@juicesharp/rpiv-workflow 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
package/events.ts CHANGED
@@ -47,21 +47,6 @@ export interface LifecycleContext {
47
47
  /** What triggered this run; defaulted at `runWorkflow` entry if `options.trigger` was omitted. */
48
48
  trigger: RunTrigger;
49
49
  state: RunView;
50
- /**
51
- * Distinct stage names already executed in this run — the engine's
52
- * authoritative `RunContext.visited`, RECONSTRUCTED from the JSONL trail on a
53
- * resume. Populated only on the run-level projection (`lifecycleCtxFor`, which
54
- * backs `onWorkflowStart`/`onWorkflowEnd`, script-stage `onStageStart`, and the
55
- * loop/route fires); UNDEFINED on session-fired events (`lifecycleCtxFromSession`
56
- * carries `runIdentity` only, never the live visited set).
57
- *
58
- * Exists so a status-line bridge can SEED its own distinct-visited accumulator
59
- * at `onWorkflowStart`: a resumed run kicks the chain at its reconstructed walk
60
- * position (a deep `stageNumber`), but only re-fires per-stage events from that
61
- * point forward — without this, the bridge would recount `visited` from zero and
62
- * a near-done resume would render a misleadingly tiny `visited/totalStages`.
63
- */
64
- visited?: readonly string[];
65
50
  }
66
51
 
67
52
  /**
@@ -185,13 +170,9 @@ export interface LifecycleListeners {
185
170
 
186
171
  /**
187
172
  * After an `EdgeFn` picks and its routing-decision row lands. `to` may be the
188
- * `STOP` sentinel literal `"stop"`. `bypassed` lists the decision edge's
189
- * not-taken RECOVERY arms — failure loops the chosen arm skipped for good (see
190
- * `bypassedRecoveryArms` in routing.ts). A progress listener credits them so
191
- * the bar reaches full while the terminal stage runs; empty for deterministic
192
- * (string) edges and gates with no loop-back alternative.
173
+ * `STOP` sentinel literal `"stop"`.
193
174
  */
194
- onRoute?(from: StageRef, to: string, ctx: LifecycleContext, bypassed?: readonly string[]): void | Promise<void>;
175
+ onRoute?(from: StageRef, to: string, ctx: LifecycleContext): void | Promise<void>;
195
176
 
196
177
  /** After `onStageStart`, before unit 1's session (after the unit list is computed for fanout). */
197
178
  onLoopStart?(stage: StageRef, info: LoopStartInfo, ctx: LifecycleContext): void | Promise<void>;
@@ -330,7 +311,6 @@ export function buildLifecycleContext(args: {
330
311
  totalStages: number;
331
312
  trigger: RunTrigger;
332
313
  state: RunView;
333
- visited?: readonly string[];
334
314
  }): LifecycleContext {
335
315
  return args;
336
316
  }
@@ -350,7 +330,6 @@ export function lifecycleCtxFor(run: {
350
330
  totalStages: number;
351
331
  trigger: RunTrigger;
352
332
  state: RunView;
353
- visited: ReadonlySet<string>;
354
333
  }): LifecycleContext {
355
334
  return buildLifecycleContext({
356
335
  cwd: run.cwd,
@@ -359,14 +338,11 @@ export function lifecycleCtxFor(run: {
359
338
  totalStages: run.totalStages,
360
339
  trigger: run.trigger,
361
340
  state: run.state,
362
- // Snapshot the live set — listeners must not mutate the engine's accumulator,
363
- // and a fired ctx is captured per fire so a later `visited.add` is irrelevant.
364
- visited: [...run.visited],
365
341
  });
366
342
  }
367
343
 
368
344
  /**
369
- * Build a `LifecycleContext` from any SessionContext/AuditCtx-shaped object
345
+ * Build a `LifecycleContext` from any SessionContext/AuditContext-shaped object
370
346
  * (cwd + runId + the frozen `runIdentity` + live state). The session, audit,
371
347
  * and extraction layers all fire through this projection instead of
372
348
  * re-spelling the six-field literal.
package/execution-host.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import type { ModelSelection, WorkflowHostContext } from "./host.js";
10
10
  import { globalSlot } from "./internal-utils.js";
11
+ import type { BranchEntry } from "./transcript.js";
11
12
 
12
13
  /** What the provider hands back per run: the detached executor, an optional
13
14
  * cancellation `signal` (rpiv-pi wires it from `ctx.ui.onTerminalInput`),
@@ -42,6 +43,14 @@ export interface WorkflowExecutionProvider {
42
43
  /** Per-stage model resolution (rpiv-pi's resolveStageModel) — threaded onto
43
44
  * RunContext.resolveModel so the dispatcher fills each child's ModelSelection. */
44
45
  resolveModel?(id: { stage: string; skill: string }): ModelSelection | undefined;
46
+ /** Re-open a persisted child-session JSONL and return its branch
47
+ * (`SessionManager.open(file).getBranch()` on the rpiv-pi side), narrowed
48
+ * to `BranchEntry[]`. Threaded onto `RunContext.readSessionBranch` so the
49
+ * death-scene artifact writer can read the just-failed session's transcript
50
+ * WITHOUT re-querying the live child (which is already torn down). Returns
51
+ * `undefined` on any open/read failure (fail-soft). Absent for programmatic
52
+ * embedders / no provider ⇒ the writer degrades silently. */
53
+ readSessionBranch?(file: string): BranchEntry[] | undefined;
45
54
  }
46
55
 
47
56
  // Use the SAME globalThis[Symbol.for(...)] slot mechanism as
@@ -0,0 +1,74 @@
1
+ /**
2
+ * failure-memos.ts — bounded log of stage/unit failures, surfaced as an
3
+ * additive prompt suffix on every subsequently-built stage/unit session.
4
+ *
5
+ * Two writers feed it: `recordFatalFailure` (the terminal path — first
6
+ * failure wins) and `recordUnitHalt` (a collect-all fanout soft-halt). The
7
+ * suffix is appended at the two session-construction chokepoints
8
+ * (`buildSingleStageSession` + `buildUnitSession`). Zero memos ⇒ the suffix
9
+ * is `""` ⇒ byte-identical prompt to a clean run.
10
+ *
11
+ * Leaf module: type-only imports of `RunState`/`FailureMemo` (types.js) and
12
+ * `AuditContext` (audit-ctx.js), value import of `nowIso` (internal-utils.js).
13
+ * No back-edges — the value-import DAG stays acyclic.
14
+ */
15
+
16
+ import type { AuditContext } from "./audit-ctx.js";
17
+ import { nowIso } from "./internal-utils.js";
18
+ import type { FailureMemo, RunState } from "./types.js";
19
+
20
+ /**
21
+ * Maximum number of memos retained on `RunState.failureMemos`. The array is
22
+ * bounded so a long collect-all fanout with many failing units does not grow
23
+ * the suffix without limit; the OLDEST entry is dropped when the cap is
24
+ * exceeded. The rendered block lists at most this many, newest-first.
25
+ */
26
+ export const MAX_FAILURE_MEMOS = 3;
27
+
28
+ /**
29
+ * Maximum character length of a single memo's `errMsg`. Longer messages are
30
+ * truncated to this length with a trailing ellipsis so the prompt suffix stays
31
+ * bounded even when the failure reason is a multi-KB stack trace.
32
+ */
33
+ export const MAX_FAILURE_MEMO_ERR_LEN = 500;
34
+
35
+ /**
36
+ * Append a failure memo to `state.failureMemos`, bounded by `MAX_FAILURE_MEMOS`
37
+ * (oldest dropped) and with `errMsg` length-bounded by `MAX_FAILURE_MEMO_ERR_LEN`.
38
+ *
39
+ * `stage` resolves to the unit's PARENT (machine identity) for a loop-unit
40
+ * failure and to the audit `stageName` for a non-unit failure. `unitId` is set
41
+ * only for a loop-unit failure (the unit's stable audit id).
42
+ */
43
+ export function appendFailureMemo(state: RunState, audit: AuditContext, errMsg: string): void {
44
+ const memo: FailureMemo = {
45
+ stage: audit.unit?.parent ?? audit.stageName,
46
+ ...(audit.unit?.id ? { unitId: audit.unit.id } : {}),
47
+ errMsg: truncateErr(errMsg),
48
+ ts: nowIso(),
49
+ };
50
+ state.failureMemos.push(memo);
51
+ if (state.failureMemos.length > MAX_FAILURE_MEMOS) {
52
+ state.failureMemos.shift(); // drop oldest — newest memos win the bounded slot
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Render the additive prompt suffix for `state.failureMemos`, newest-first.
58
+ * Returns `""` when there are no memos so the host prompt is byte-identical to
59
+ * a clean run (no separator, no fence, no newline).
60
+ */
61
+ export function failureMemoSuffix(state: RunState): string {
62
+ const memos = state.failureMemos;
63
+ if (memos.length === 0) return "";
64
+ const lines = [...memos]
65
+ .reverse()
66
+ .map((m) => `- ${m.unitId ? `${m.stage} (unit ${m.unitId})` : m.stage}: ${m.errMsg}`);
67
+ return `\n\nPrior failures in this run (do not repeat these — the run already tried them and they failed):\n${lines.join("\n")}`;
68
+ }
69
+
70
+ /** Truncate `errMsg` to `MAX_FAILURE_MEMO_ERR_LEN` with a trailing ellipsis when longer. */
71
+ function truncateErr(errMsg: string): string {
72
+ if (errMsg.length <= MAX_FAILURE_MEMO_ERR_LEN) return errMsg;
73
+ return `${errMsg.slice(0, MAX_FAILURE_MEMO_ERR_LEN)}…`;
74
+ }
package/handle.ts CHANGED
@@ -49,6 +49,21 @@ export const opaque = (id: string): ArtifactHandle => ({ kind: "opaque", id });
49
49
  export const inline = (bytes: Uint8Array, mime?: string): ArtifactHandle =>
50
50
  mime !== undefined ? { kind: "inline", bytes, mime } : { kind: "inline", bytes };
51
51
 
52
+ /**
53
+ * Inline-handle wire format — the lossy placeholder `handleToString`
54
+ * emits for inline artifact bytes. Inline content is gathered directly
55
+ * by the collector and is not meaningfully promptable, so the serialised
56
+ * form reports only its byte length (plus an optional mime suffix).
57
+ *
58
+ * `inline:` — kind discriminator (mirrors the `kind` literal)
59
+ * <byteLength> — number of bytes the collector gathered
60
+ * `b` — unit marking the preceding number as a byte length
61
+ * `;` <mime> — delimiter + optional mime type, emitted when present
62
+ */
63
+ const INLINE_HANDLE_PREFIX = "inline:";
64
+ const INLINE_HANDLE_BYTE_UNIT = "b";
65
+ const INLINE_HANDLE_MIME_SEPARATOR = ";";
66
+
52
67
  /**
53
68
  * Serialise a handle to a human-readable string — used by the runner
54
69
  * when threading the primary artifact into a downstream stage's prompt
@@ -65,6 +80,6 @@ export function handleToString(h: ArtifactHandle): string {
65
80
  case "opaque":
66
81
  return h.id;
67
82
  case "inline":
68
- return `inline:${h.bytes.byteLength}b${h.mime ? `;${h.mime}` : ""}`;
83
+ return `${INLINE_HANDLE_PREFIX}${h.bytes.byteLength}${INLINE_HANDLE_BYTE_UNIT}${h.mime ? `${INLINE_HANDLE_MIME_SEPARATOR}${h.mime}` : ""}`;
69
84
  }
70
85
  }
package/host.ts CHANGED
@@ -157,7 +157,7 @@ export interface WorkflowHostContext {
157
157
  /**
158
158
  * The fan-out unit index for this spawn, surfaced so a lane-aware host can
159
159
  * publish the child under a per-unit registry slot (rpiv-pi's lane dock/viewer).
160
- * Set by `openChild` from `StageSession.unit?.index`; undefined for a non-fan-out
160
+ * Set by `openChild` from `StageSessionContext.unit?.index`; undefined for a non-fan-out
161
161
  * single stage (and for reattach/fork), which the host maps to its reserved
162
162
  * single-unit slot. Purely an observability hint — a non-lane host ignores it and
163
163
  * it NEVER affects execution.
@@ -192,4 +192,16 @@ export interface WorkflowSessionContext extends WorkflowHostContext {
192
192
  * watchdog omits it and every abort stays a plain abort.
193
193
  */
194
194
  toolTimeout?(): { reason: string } | undefined;
195
+
196
+ /**
197
+ * Recovery-side twin of `toolTimeout`: clears the recorded verdict so the runner can
198
+ * re-arm the watchdog for the resumed turn's next bash call. Set by a watchdog-equipped
199
+ * host (rpiv-pi) alongside `toolTimeout`. The strike-recovery branch consumes a strike
200
+ * BEFORE calling this, then re-prompts the SAME child; omitting it on a watchdog host
201
+ * would leave a stale verdict that re-halts immediately. Optional + safe to widen: only
202
+ * two implementors of this port exist (the SDK host + the test mock), and a host without
203
+ * a watchdog still routes every abort as a plain abort (the strike branch never fires
204
+ * because `toolTimeout()` returns `undefined`).
205
+ */
206
+ resetToolTimeout?(): void;
195
207
  }
package/internal.ts CHANGED
@@ -35,6 +35,7 @@ export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins
35
35
  export { __resetLifecycleRegistry } from "./events.js";
36
36
  export { __resetWorkflowExecutionHost } from "./execution-host.js";
37
37
  export { __resetLoadCache } from "./load/cache.js";
38
+ export { __resetStrikeBudgets } from "./sessions/bash-strikes.js";
38
39
  export {
39
40
  __resetSkillContracts,
40
41
  buildEffectiveContracts,
package/loop-def.ts CHANGED
@@ -30,7 +30,7 @@ export interface Unit {
30
30
  * edges: a unit dispatches only after every unit it lists here has completed
31
31
  * (its slot filled). Absent/empty ⇒ a root (wave 0). A reference that matches
32
32
  * no unit's `id ?? label`, or any cycle, halts the stage at the live entry
33
- * (`validateUnitDeps`). Ignored by the sequential kinds (iterate/assess
33
+ * (`ensureUnitDeps`). Ignored by the sequential kinds (iterate/assess
34
34
  * consume the prior unit, so ordering is implicit).
35
35
  */
36
36
  deps?: readonly string[];
@@ -216,10 +216,14 @@ export interface FanoutLoop extends LoopCommon {
216
216
  units: FanoutFn;
217
217
  /** Per-fanout concurrency ceiling. Caps in-flight units to
218
218
  * `min(concurrency, host maxConcurrency)`; `1` SERIALIZES the loop — the safe
219
- * model for a stage that mutates SHARED state (e.g. `implement` applying a plan
220
- * to one working tree, where parallel phases race on a shared file and a
221
- * dependent phase can run before its prerequisite has landed). Absent ⇒ the host
222
- * cap governs. Must be an integer ≥ 1 (validated at construction + load). */
219
+ * model for a fanout whose units mutate SHARED state AND whose write-sets are
220
+ * unknown (so the scheduler cannot derive dep edges and no lane-level scope
221
+ * floor guards the declared set). Absent ⇒ the host cap governs. A fanout
222
+ * whose units carry a declared write-set (`files:`) AND derived `deps` edges
223
+ * AND a lane-level scope floor MAY omit `concurrency`: disjoint-write units run
224
+ * concurrently, a write-overlap edge orders the waves, and the scope floor
225
+ * guards the declared set. Must be an integer ≥ 1 (validated at construction +
226
+ * load). */
223
227
  concurrency?: number;
224
228
  /** Opt out of collect-all: any unit failure halts the run. Default (absent) ⇒
225
229
  * collect-all. Under parallel dispatch, the first failing unit halts the
package/loop-kinds.ts CHANGED
@@ -30,12 +30,13 @@ import { decorateStage, runIdentityOf } from "./audit.js";
30
30
  // reconstruct byte-identical declared-order state regardless of
31
31
  // completion/resume order. iterate/assess keep advanceCursor (sequential).
32
32
  import { placeFanoutOutput, resolveStagePrompt } from "./chain-state.js";
33
+ import { failureMemoSuffix } from "./failure-memos.js";
33
34
  import { type Artifact, handleToString } from "./handle.js";
34
35
  import { isPanel, type Judge, type PanelJudge, panelMembers, resolveJudgePrompt } from "./judge.js";
35
36
  import { MSG_LOOP_CURSOR_CORRUPT } from "./messages.js";
36
37
  import { finalizeOutput, isFailedOutput, type Output, type OutputMeta } from "./output.js";
37
38
  import { invariantPreflight } from "./stage-errors.js";
38
- import type { RunContext, RunState, StageSession, UnitRef, WorkflowHostContext } from "./types.js";
39
+ import type { RunContext, RunState, StageSessionContext, UnitRef, WorkflowHostContext } from "./types.js";
39
40
 
40
41
  // ---------------------------------------------------------------------------
41
42
  // Cursor + entry vocabulary (kind-agnostic, shared live + fold)
@@ -95,21 +96,21 @@ export function buildLoopEntry(
95
96
  */
96
97
  export interface LoopDeps {
97
98
  /** Dispatch one unit through the standard stage-session path. */
98
- runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
99
+ executeStageSession: (ctx: WorkflowHostContext, s: StageSessionContext) => Promise<void>;
99
100
  /**
100
101
  * Resume the chain after the loop finishes — receives the loop node's REAL
101
102
  * name. `Promise<unknown>` so the walk's `ChainOutcome`-returning composed
102
103
  * advance plugs in directly (the driver only awaits settlement).
103
104
  */
104
105
  advanceAfter: (
105
- curCtx: WorkflowHostContext,
106
+ hostCtx: WorkflowHostContext,
106
107
  completedName: string,
107
108
  completedIdx: number,
108
109
  run: RunContext,
109
110
  ) => Promise<unknown>;
110
111
  /** Re-capture the outcome's pre-stage snapshot per unit (ctx + stage name for the fail-soft warning). */
111
112
  captureSnapshot: (
112
- curCtx: WorkflowHostContext,
113
+ hostCtx: WorkflowHostContext,
113
114
  stageName: string,
114
115
  def: StageDef,
115
116
  idx: number,
@@ -117,7 +118,7 @@ export interface LoopDeps {
117
118
  ) => Promise<unknown>;
118
119
  /** Record the terminal failure when `onCap: "halt"` trips — verify-worded for verify stages. */
119
120
  haltLoop: (
120
- curCtx: WorkflowHostContext,
121
+ hostCtx: WorkflowHostContext,
121
122
  run: RunContext,
122
123
  e: Pick<LoopEntry, "name" | "def">,
123
124
  count: number,
@@ -125,14 +126,14 @@ export interface LoopDeps {
125
126
  ) => Promise<void>;
126
127
  /** Record a mid-flight run abort at the loop seam (FAIL_WORKFLOW_ABORTED).
127
128
  * Keeps the drivers free of engine imports; wired to `recordAbortedAtSeam`. */
128
- recordAborted: (curCtx: WorkflowHostContext, name: string, run: RunContext) => Promise<void>;
129
+ recordAborted: (hostCtx: WorkflowHostContext, name: string, run: RunContext) => Promise<void>;
129
130
  /** Funnel an UNEXPECTED worker rejection (not a workflow halt) to a
130
131
  * terminal-failure row + onStageError, terminating state WITHOUT re-throwing,
131
132
  * so entry() resolves and onWorkflowEnd still fires. Wraps recordEntryThrow.
132
133
  * The unit's identity (`unit` + its `skill`) lands as STRUCTURED row fields —
133
134
  * the row's `stage` stays the parent graph identity. */
134
135
  recordWorkerThrow: (
135
- curCtx: WorkflowHostContext,
136
+ hostCtx: WorkflowHostContext,
136
137
  unit: UnitRef,
137
138
  skill: string,
138
139
  run: RunContext,
@@ -352,7 +353,7 @@ export type NextStep =
352
353
  * key to `(index, memberIndex)` for assess panels — within one round all member
353
354
  * rows share `index`, so the member dimension is what tells them apart.
354
355
  */
355
- export interface GenerationGuardCtx {
356
+ export interface GenerationGuardContext {
356
357
  loop: LoopDef;
357
358
  entryArtifact: Artifact | undefined;
358
359
  cursor: LoopCursor;
@@ -413,7 +414,7 @@ export interface SequentialStrategy extends LoopKindStrategy {
413
414
  * (role, unitIndex) arithmetic matched. Returns false on drift. May invoke
414
415
  * user fns — a throw becomes drift in the caller (`guarded`).
415
416
  */
416
- guardExpectation(gen: GenerationGuardCtx, row: UnitRowFacts, cwd: string, state: RunState): Promise<boolean>;
417
+ guardExpectation(gen: GenerationGuardContext, row: UnitRowFacts, cwd: string, state: RunState): Promise<boolean>;
417
418
  /**
418
419
  * Resume re-entry pending-work probe — never dispatches; gates the
419
420
  * announce only. The iterate arm re-pulls `next()` at the cursor (the
@@ -474,7 +475,7 @@ const shouldCollectAll = (loop: LoopDef): boolean => loop.kind === "fanout" && !
474
475
  * fan-out index (the same value `unit.index` carries). */
475
476
  const laneIndexFor = (loop: LoopDef, index: number): number | undefined => (loop.kind === "fanout" ? index : undefined);
476
477
 
477
- /** Factored unit StageSession — shared by the sequential `dispatchUnit` (loop.ts)
478
+ /** Factored unit StageSessionContext — shared by the sequential `dispatchUnit` (loop.ts)
478
479
  * and the parallel `dispatchUnitDetached` (loop-parallel.ts); differs only in
479
480
  * `onSuccess` and the threaded `signal`. Populates the per-child execution
480
481
  * controls (lane/model/signal). The sequential path passes `run.signal`
@@ -487,13 +488,13 @@ export function buildUnitSession(
487
488
  run: RunContext,
488
489
  snapshot: unknown,
489
490
  signal: AbortSignal | undefined,
490
- onSuccess: StageSession["onSuccess"],
491
- ): StageSession {
491
+ onSuccess: StageSessionContext["onSuccess"],
492
+ ): StageSessionContext {
492
493
  return {
493
494
  cwd: run.cwd,
494
495
  runId: run.runId,
495
496
  state: run.state,
496
- prompt: u.prompt,
497
+ prompt: u.prompt + failureMemoSuffix(run.state),
497
498
  stageName: decorateStage(e.name, u.tag), // DISPLAY only — machine identity is `unit`
498
499
  skill: u.skill,
499
500
  lifecycle: run.lifecycle,
@@ -506,6 +507,8 @@ export function buildUnitSession(
506
507
  unit: { parent: e.name, role: u.role, index, id: u.id, label: u.label },
507
508
  model: run.resolveModel?.({ stage: e.name, skill: u.skill }),
508
509
  signal,
510
+ readSessionBranch: run.readSessionBranch,
511
+ worktreeDigest: run.worktreeDigest,
509
512
  collectAll: shouldCollectAll(e.loop),
510
513
  laneUnitIndex: laneIndexFor(e.loop, index),
511
514
  onFailure: undefined,