@juicesharp/rpiv-workflow 1.20.0 → 2.0.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 (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
@@ -3,205 +3,140 @@
3
3
  * `runStageSession` is the only public entry (loop units run through it too,
4
4
  * threading their identity via `StageSession.unit`).
5
5
  *
6
- * The fresh-vs-continue policy split is owned by `SessionPolicyHandler`
7
- * (see `spawn.ts`): `FRESH_HANDLER` and `CONTINUE_HANDLER` implement
8
- * the three policy-specific decisions. Everything in this file —
9
- * post-processing, halt routing, success persistence, outcome reading
10
- * — is policy-agnostic.
6
+ * Every stage runs in its own detached child session (`spawnChildAndRun`,
7
+ * spawn.ts); the only surviving policy divergence is the branch offset
8
+ * (`branchOffsetFor`). Everything in this file — post-processing, halt routing,
9
+ * success persistence, outcome reading — is policy-agnostic.
11
10
  *
12
11
  * Companion modules:
13
- * - extraction.ts — produceAndValidateOutput + retry loop +
14
- * outcome helpers (collector → parser pipeline).
15
- * - spawn.ts — SessionPolicyHandler + FRESH/CONTINUE handlers +
16
- * handlerFor.
17
- * - reattach.ts — session-backed resume (promotion + reattach); reuses
18
- * postStage / recordStageSuccess / the halt helpers
19
- * exported below instead of duplicating them.
12
+ * - extraction.ts — produceAndValidateOutput + retry loop +
13
+ * outcome helpers (collector → parser pipeline).
14
+ * - spawn.ts — the child-spawn primitives (`spawnChildAndRun`,
15
+ * `reattachChildSession`, `resendIntoChild`) + `branchOffsetFor`.
16
+ * - halt-routing.ts — the halt pipeline (`haltStageOrSoftHalt` gate +
17
+ * the per-arm halt helpers + `auditFor`); consumed by
18
+ * `postStage` below and `reattach.ts`.
19
+ * - success-persist.ts — `recordStageSuccess` + `unitEventOf`; consumed by
20
+ * `postStage` below and `reattach.ts`.
21
+ * - reattach.ts — session-backed resume (promotion + reattach); reuses
22
+ * postStage / recordStageSuccess / the halt helpers
23
+ * exported below instead of duplicating them.
20
24
  */
21
25
 
22
- import {
23
- type AuditCtx,
24
- currentStageRef,
25
- failedArgs,
26
- recordCancellation,
27
- recordStopFailure,
28
- recordTerminalFailure,
29
- terminate,
30
- } from "../audit.js";
31
- import { persistStageSuccess } from "../audit-rows.js";
32
- import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
33
- import {
34
- FAIL_AUDIT_WRITE,
35
- FAIL_VALIDATION_EXHAUSTED,
36
- MSG_STAGE_COMPLETE,
37
- MSG_STAGE_FAILED,
38
- MSG_UNIT_COMPLETE,
39
- } from "../messages.js";
40
- import type { Output } from "../output.js";
41
- import type { SessionRef } from "../state/index.js";
26
+ import { WorkflowAbortError } from "../internal-utils.js";
42
27
  import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
43
- import type { StageSession, WorkflowHostContext } from "../types.js";
28
+ import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
44
29
  import { produceAndValidateOutput } from "./extraction.js";
45
- import { handlerFor } from "./spawn.js";
30
+ import { haltStageOrSoftHalt } from "./halt-routing.js";
31
+ import { branchOffsetFor, resendIntoChild, spawnChildAndRun } from "./spawn.js";
32
+ import { recordStageSuccess } from "./success-persist.js";
46
33
 
47
34
  // ===========================================================================
48
35
  // PUBLIC ENTRIES — what the orchestrator calls
49
36
  // ===========================================================================
50
37
 
51
- /** Execute one DAG stage (or loop unit) in its own session. */
38
+ /** Execute one DAG stage (or loop unit) in its own detached child session. */
52
39
  export async function runStageSession(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
53
- const handler = handlerFor(s.stage.sessionPolicy);
54
- const { cancelled } = await handler.spawn(ctx, s.prompt, (sessionCtx) => postStage(sessionCtx, s), s.continueHost);
55
- // Pre-open cancellation — no session ever backed this activation.
56
- if (cancelled) recordCancellation(ctx, auditFor(s, null));
40
+ await spawnChildAndRun(ctx, s, (child) => postStage(ctx, child, s));
57
41
  }
58
42
 
59
- // ===========================================================================
60
- // POST-PROCESSING — runs after the agent loop settles
61
- // ===========================================================================
62
-
63
43
  /**
64
- * Stage post-processing: classify outcome → produce & validate output →
65
- * persist → chain. Exported to the `reattach.ts` companion — a reattached
66
- * session's continuation runs this exact pipeline, byte-identical to live.
44
+ * Continue body — runs inside a FORKED child (`forkChildSession`, spawn.ts)
45
+ * carrying the predecessor's full transcript. Re-derive the inherited-prefix
46
+ * offset from the actual forked branch BEFORE the continuation turn is sent
47
+ * (the boundary past which only this stage's own output lives), send the turn
48
+ * via `resendIntoChild` (`/skill:` and templates expand through the rpiv-args
49
+ * input hook exactly as a fresh prompt would), then run the standard `postStage`
50
+ * scoped by that offset. From there the flow is byte-identical to a fresh stage —
51
+ * stop classification, extraction, persistence — only sliced past the prefix.
67
52
  *
68
- * The backing `SessionRef` is captured ONCE at entry — every row this
69
- * pipeline can write (success, stop-failure, extraction/validation failure)
70
- * carries the same provenance value.
53
+ * The re-derived offset (not a launcher-branch read) flows into `postStage` →
54
+ * `readSessionRef`, so the continue stage's own row records the offset its forked
55
+ * branch ran under; resume re-applies that persisted value verbatim.
71
56
  */
72
- export async function postStage(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
73
- const handler = handlerFor(s.stage.sessionPolicy);
74
- const offset = handler.branchOffset(s.branchOffset);
75
- const session = readSessionRef(ctx, offset);
76
- const outcome = readSessionOutcome(ctx, offset);
77
- if (outcome.stop !== "stop") return haltStage(ctx, s, outcome.stop, session);
78
-
79
- const result = await produceAndValidateOutput(ctx, s, outcome.branch, offset);
80
- if (result.kind === "fatal") return haltStageWithExtractionError(ctx, s, result.message, session);
81
- if (result.kind === "validation-exhausted")
82
- return haltStageWithValidationFailure(ctx, s, result.failureSummary, session);
83
-
84
- if (!(await recordStageSuccess(ctx, s, result.output, session))) return;
85
- // The validated Output goes to the continuation directly — loop drivers
86
- // thread it into accumulated / feedForward without state back-reads.
87
- await s.onSuccess(ctx, result.output);
88
- }
89
-
90
- // ===========================================================================
91
- // HALT HELPERS — turn a halt reason into the right audit-layer call
92
- // ===========================================================================
93
-
94
- async function haltStage(
95
- ctx: WorkflowHostContext,
96
- s: StageSession,
97
- stop: Exclude<StopSignal, "stop">,
98
- session: SessionRef | null,
99
- ): Promise<void> {
100
- await recordStopFailure(ctx, auditFor(s, session), stop, `${s.skill} failed`, s.onFailure);
101
- }
102
-
103
- async function haltStageWithExtractionError(
104
- ctx: WorkflowHostContext,
105
- s: StageSession,
106
- message: string,
107
- session: SessionRef | null,
108
- ): Promise<void> {
109
- await recordTerminalFailure(
110
- ctx,
111
- auditFor(s, session),
112
- { status: "failed", notifyMsg: MSG_STAGE_FAILED(s.skill), notifyLevel: "error", errMsg: message },
113
- s.onFailure,
114
- );
115
- }
116
-
117
- /** Exported to the `reattach.ts` companion — a promotion's validation-exhausted halt is identical to live. */
118
- export async function haltStageWithValidationFailure(
119
- ctx: WorkflowHostContext,
57
+ export async function continueStageSession(
58
+ obsCtx: WorkflowHostContext,
59
+ child: WorkflowSessionContext,
120
60
  s: StageSession,
121
- failureSummary: string,
122
- session: SessionRef | null,
123
61
  ): Promise<void> {
124
- await recordTerminalFailure(
125
- ctx,
126
- auditFor(s, session),
127
- failedArgs(FAIL_VALIDATION_EXHAUSTED(s.skill, failureSummary)),
128
- s.onFailure,
129
- );
62
+ const offset = readBranch(child).length;
63
+ await resendIntoChild(child, s.prompt);
64
+ await postStage(obsCtx, child, s, offset);
130
65
  }
131
66
 
132
67
  // ===========================================================================
133
- // SUCCESS-PERSISTENCE HELPERS
68
+ // POST-PROCESSING — runs after the agent loop settles
134
69
  // ===========================================================================
135
70
 
136
71
  /**
137
- * Returns true on successful write — caller gates `onSuccess` on this so the
138
- * chain advances only when the audit row landed. On failure, leaves
139
- * `state.output` / `state.primaryArtifact` at their prior values ("output is
140
- * set iff the row that carried it landed") and sets `state.termination.error`
141
- * to halt the run. Persistence + state apply run through
142
- * `persistStageSuccess` (audit-rows.ts) — the ONE success pipeline shared
143
- * with the script path: the row reuses the activation's pre-allocated number
144
- * so `output.meta.stageNumber` and the row agree, and unit rows carry the
145
- * structured identity fields alongside the decorated display `stage`.
72
+ * Stage post-processing: classify outcome → produce & validate output →
73
+ * persist → chain. Exported to the `reattach.ts` companion — a reattached
74
+ * session's continuation runs this exact pipeline, byte-identical to live.
146
75
  *
147
- * Single stages keep the `onStageEnd` + `MSG_STAGE_COMPLETE` contract
148
- * verbatim. Loop units fire `onUnitEnd` (NEVER `onStageEnd` — that's reserved
149
- * for single-stage and loop-level semantics) with a labeled toast, the ref
150
- * carrying the PARENT stage name so listeners key on graph identity, not the
151
- * display decoration.
76
+ * TWO ctxs (detachment): `obsCtx` is the long-lived LAUNCHER/observer ctx the
77
+ * walk threads — it stays valid across every stage, so the user-facing recording
78
+ * (success/halt rows + notifications + lifecycle) AND the chain continuation
79
+ * (`onSuccess` → advance/step, which spawns the NEXT stage's child) all run on
80
+ * it, NOT on the per-stage child (whose UI is the lane binding — noOp in the
81
+ * background lane — and which is disposed when the stage ends). `child` is the
82
+ * in-session ctx: the agent transcript (`readBranch`/`readSessionRef`) and the
83
+ * validation-retry re-prompt (`produceAndValidateOutput` → `resendIntoChild`)
84
+ * read/write through it. Spawning the next stage off `obsCtx` is what keeps the
85
+ * launcher the single spawner (no nested-child chain).
152
86
  *
153
- * Exported to the `reattach.ts` companion — promotion persists through this
154
- * exact pipeline (one success path, live and adopted alike).
87
+ * The backing `SessionRef` is captured ONCE at entry — every row this
88
+ * pipeline can write (success, stop-failure, extraction/validation failure)
89
+ * carries the same provenance value.
155
90
  */
156
- export async function recordStageSuccess(
157
- ctx: WorkflowHostContext,
91
+ export async function postStage(
92
+ obsCtx: WorkflowHostContext,
93
+ child: WorkflowSessionContext,
158
94
  s: StageSession,
159
- output: Output,
160
- session: SessionRef | null,
161
- ): Promise<boolean> {
162
- const persisted = persistStageSuccess(
163
- s.state,
164
- {
165
- cwd: s.cwd,
166
- runId: s.runId,
167
- stage: s.stageName,
168
- skill: s.skill,
169
- output,
170
- session,
171
- unit: s.unit,
172
- preAllocated: s.allocatedStageNumber,
173
- },
174
- s.stage,
175
- );
176
- if (persisted) {
177
- if (s.unit) {
178
- ctx.ui.notify(MSG_UNIT_COMPLETE(s.skill, s.unit.label), "info");
179
- await s.lifecycle.fire(
180
- ctx,
181
- "onUnitEnd",
182
- // Same allocator base as every other ref of this activation; the
183
- // ref's NAME stays the parent stage key (graph identity).
184
- skillStageRef(s.unit.parent, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill),
185
- unitEventOf(s),
186
- output,
187
- lifecycleCtxFromSession(s),
188
- );
189
- } else {
190
- ctx.ui.notify(MSG_STAGE_COMPLETE(s.skill), "info");
191
- await s.lifecycle.fire(ctx, "onStageEnd", currentStageRef(s), output, lifecycleCtxFromSession(s));
192
- }
193
- return true;
95
+ // Defaults to the policy-derived offset (fresh ⇒ undefined; resume continue ⇒
96
+ // the persisted row's value). The live continue body passes the value it
97
+ // re-derived from the forked branch, which is authoritative there.
98
+ offset: number | undefined = branchOffsetFor(s.stage.sessionPolicy, s.branchOffset),
99
+ ): Promise<void> {
100
+ const session = readSessionRef(child, offset);
101
+ const outcome = readSessionOutcome(child, offset);
102
+ // Abort surfaces as a STOP CLASSIFICATION, not a promise rejection:
103
+ // `session.abort()` makes the SDK RESOLVE `prompt()` with a
104
+ // `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
105
+ // straight into here. Throw BEFORE haltStage/softHaltUnit/any row write so:
106
+ // (a) no `collected:true` row is written (else the resume fold marks the unit
107
+ // "don't re-dispatch" → permanent work loss), (b) the parallel fold's
108
+ // `isAbortError` branch leaves the slot unfilled, and (c) resume re-dispatches
109
+ // the unit cleanly.
110
+ //
111
+ // A genuine run/user abort (`s.signal` fired) ALWAYS re-dispatches on resume, so it
112
+ // takes the throw unconditionally. An `aborted` stop with the signal cold is examined
113
+ // for a watchdog tool-timeout (`child.toolTimeout`): the host aborted a runaway bash,
114
+ // which must route to the soft-halt gate (collect-all unit survives; else terminal
115
+ // fail) — NOT WorkflowAbortError, which would re-run the same runaway command on resume.
116
+ if (s.signal?.aborted) throw new WorkflowAbortError();
117
+ if (outcome.stop === "aborted") {
118
+ const timeout = child.toolTimeout?.();
119
+ if (timeout) return haltStageOrSoftHalt(obsCtx, s, { kind: "timeout", reason: timeout.reason }, session);
120
+ throw new WorkflowAbortError();
194
121
  }
195
- const auditFailure = FAIL_AUDIT_WRITE(s.skill);
196
- ctx.ui.notify(auditFailure.toast, "error");
197
- terminate(s.state, { status: "failed", error: auditFailure.error });
198
- return false;
199
- }
122
+ // Every halt below routes through the single `haltStageOrSoftHalt` gate: a
123
+ // fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
124
+ // slot instead of halting the run; everything else takes the arm's fail-fast
125
+ // halt. Recording + the continuation run on obsCtx (the launcher) — the per-stage
126
+ // child is disposed when the stage ends.
127
+ if (outcome.stop !== "stop") return haltStageOrSoftHalt(obsCtx, s, { kind: "stop", stop: outcome.stop }, session);
128
+
129
+ const result = await produceAndValidateOutput(child, s, outcome.branch, offset);
130
+ if (result.kind === "fatal")
131
+ return haltStageOrSoftHalt(obsCtx, s, { kind: "extraction", message: result.message }, session);
132
+ if (result.kind === "validation-exhausted")
133
+ return haltStageOrSoftHalt(obsCtx, s, { kind: "validation", failureSummary: result.failureSummary }, session);
200
134
 
201
- /** Public `UnitEvent` payload from the session's `UnitRef` + dispatched skill. */
202
- function unitEventOf(s: StageSession): UnitEvent {
203
- const u = s.unit!;
204
- return { role: u.role, index: u.index, unitId: u.id, label: u.label, skill: s.skill };
135
+ if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
136
+ // The validated Output goes to the continuation directly — loop drivers
137
+ // thread it into accumulated / feedForward without state back-reads. Runs on
138
+ // obsCtx so the next stage's child is spawned off the launcher.
139
+ await s.onSuccess(obsCtx, result.output);
205
140
  }
206
141
 
207
142
  // ===========================================================================
@@ -229,26 +164,3 @@ function readSessionOutcome(ctx: WorkflowHostContext, branchOffset: number | und
229
164
  stop: classifyStop(branch, branchOffset),
230
165
  };
231
166
  }
232
-
233
- // ===========================================================================
234
- // Helpers
235
- // ===========================================================================
236
-
237
- const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
238
- cwd: s.cwd,
239
- runId: s.runId,
240
- state: s.state,
241
- stageName: s.stageName,
242
- skill: s.skill,
243
- // The Pi session backing this activation — `null` only for pre-open
244
- // cancellation (the one writer here that never entered a session).
245
- session,
246
- lifecycle: s.lifecycle,
247
- runIdentity: s.runIdentity,
248
- // The activation's pre-allocated stage number (set once output production
249
- // began) — a failure row reuses it instead of burning a second number.
250
- allocatedStageNumber: s.allocatedStageNumber,
251
- // Loop units thread their identity onto failure/cancellation rows so failed
252
- // trailers carry the structured fields the resume drift guard consumes.
253
- ...(s.unit ? { unit: s.unit } : {}),
254
- });
package/sessions/spawn.ts CHANGED
@@ -1,139 +1,152 @@
1
1
  /**
2
- * Session policy dispatch. Owns the three policy-specific decisions the
3
- * stage / phase machinery has to make per session: which branch offset
4
- * the outcome sees, how the session is opened, and how an
5
- * already-established session is sent to.
2
+ * Session opening — the child-spawn primitives every stage and loop unit runs
3
+ * through. With every stage isolated in its own child session, "send into an
4
+ * existing session" doesn't exist, so there's no stale-ctx fallback ladder,
5
+ * no registry-host fallback param, and no defensive `sendUserMessage` guards.
6
6
  *
7
- * Two handlers — `FRESH_HANDLER` and `CONTINUE_HANDLER` — implement the
8
- * interface; `handlerFor(policy)` picks. Everything else in the
9
- * `sessions/` directory is policy-agnostic.
7
+ * Three open modes, all routed through `ctx.spawnChild`:
8
+ * - FRESH (`spawnChildAndRun`) — a brand-new child; the host sends the prompt.
9
+ * - REATTACH (`reattachChildSession`) — open a persisted file IN PLACE
10
+ * (session-backed resume); the host skips the prompt, the body promotes/nudges.
11
+ * - FORK (`forkChildSession`) — copy a PREDECESSOR's persisted session into a
12
+ * NEW file carrying its full transcript (`sessionPolicy: "continue"`); the host
13
+ * skips the prompt, the body re-derives the inherited-prefix offset and sends
14
+ * the continuation turn. This is the detached continuation mechanism — prior-
15
+ * session lineage survives detachment via `SessionManager.forkFrom`, resolving
16
+ * the original OQ1 (which assumed it could not). The source file is never
17
+ * mutated, so DAG forks are safe and the continue child has its own resumable
18
+ * identity.
10
19
  */
11
20
 
12
21
  import type { SessionPolicy } from "../api.js";
13
- import type { WorkflowHost } from "../host.js";
14
- import type { WorkflowHostContext } from "../types.js";
22
+ import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
15
23
 
16
24
  /**
17
- * Three policy-specific decisions that used to live as five ternaries
18
- * scattered across sessions.ts:
25
+ * The per-policy branch offset — fresh ignores the stage-captured value;
26
+ * continue flows it through so a continue stage's outcome still skips the prior
27
+ * transcript its forked child inherited (trail / replay symmetry). The sole
28
+ * surviving policy divergence.
19
29
  *
20
- * - `branchOffset(captured)` — the offset outcomes apply to skip
21
- * the prior-stage prefix in continue sessions. Fresh ignores the
22
- * stage-side captured value (it's `undefined` from
23
- * `computeBranchOffset` for fresh stages anyway); continue returns
24
- * it as-is.
25
- * - `spawn(ctx, prompt, body, host?)` — open the session and run `body`
26
- * on whichever ctx is valid for that policy (fresh → freshCtx
27
- * inside `withSession`; continue → the supplied ctx, after a
28
- * send+waitForIdle settles the existing session). `cancelled: true`
29
- * means a fresh session was cancelled before `withSession` ran.
30
- * - `send(ctx, msg, host?)` — send into an already-established session
31
- * and wait for it to settle (used by the validation-retry path).
32
- *
33
- * `host` is the registry-level fallback for continue stages — used only
34
- * when `ctx.sendUserMessage` is absent (the outer command ctx at the
35
- * very start of a workflow whose first stage is continue-policy).
36
- * Everywhere else (continue stages following any other stage),
37
- * `ctx.sendUserMessage` is present and preferred because Pi marks the
38
- * captured host stale after `ctx.newSession()`. `enforceSessionInvariants`
39
- * still requires a host whenever any stage is continue-policy so the
40
- * start-stage path has a working fallback. Fresh ignores `host` entirely.
30
+ * The `captured` value is sourced from the continuation's ACTUAL branch:
31
+ * - live (`continueStageSession`) re-derives it from the forked child's branch
32
+ * length before the continuation turn is sent, and threads it through `postStage`;
33
+ * - resume takes it from the persisted row (`SessionRef.branchOffset`) of the
34
+ * continue stage's own forked session.
35
+ * Never the launcher's branch (the bug the fork redesign removed).
41
36
  */
42
- export interface SessionPolicyHandler {
43
- branchOffset(capturedOffset: number | undefined): number | undefined;
44
- spawn(
45
- ctx: WorkflowHostContext,
46
- prompt: string,
47
- body: (sessionCtx: WorkflowHostContext) => Promise<void>,
48
- host?: WorkflowHost,
49
- ): Promise<{ cancelled: boolean }>;
50
- send(ctx: WorkflowHostContext, msg: string, host?: WorkflowHost): Promise<void>;
37
+ export function branchOffsetFor(policy: SessionPolicy | undefined, captured: number | undefined): number | undefined {
38
+ return policy === "continue" ? captured : undefined;
51
39
  }
52
40
 
53
- export const FRESH_HANDLER: SessionPolicyHandler = {
54
- branchOffset: () => undefined,
55
- async spawn(ctx, prompt, body) {
56
- const { cancelled } = await ctx.newSession({
57
- // `freshCtx` is a `WorkflowSessionContext` — the port guarantees
58
- // `sendUserMessage` on the replacement ctx, so no runtime guard.
59
- withSession: async (freshCtx) => {
60
- await freshCtx.sendUserMessage(prompt);
61
- await body(freshCtx);
62
- },
63
- });
64
- return { cancelled };
65
- },
66
- async send(ctx, msg) {
67
- // At runtime ctx is the in-session replacement (a
68
- // `WorkflowSessionContext`), but the shared `SessionPolicyHandler`
69
- // types it as the base `WorkflowHostContext` (continue's send may run
70
- // on the senderless start ctx), so this seam keeps a defensive guard.
71
- if (!ctx.sendUserMessage) {
72
- throw new Error("FRESH_HANDLER.send: replacement ctx missing sendUserMessage");
73
- }
74
- await ctx.sendUserMessage(msg);
75
- },
76
- };
41
+ /** Optional open mode — absent ⇒ FRESH; `reattach` opens a persisted file in
42
+ * place; `fork` copies a predecessor's session into a new file. The two carry
43
+ * the same `{ sessionFile }` shape; only the host's open semantics differ. */
44
+ type OpenMode = { reattach: { sessionFile: string } } | { fork: { sessionFile: string } };
77
45
 
78
- export const CONTINUE_HANDLER: SessionPolicyHandler = {
79
- branchOffset: (captured) => captured,
80
- async spawn(ctx, prompt, body, host) {
81
- // Prefer the live `ctx.sendUserMessage` over the captured `host`.
82
- // Pi marks the registry-level host handle stale after the first
83
- // `ctx.newSession()`, so a continue stage that follows a fresh
84
- // stage would throw "extension ctx is stale" if we called
85
- // `host.sendUserMessage` here. The inner replacement ctx delivered
86
- // to `withSession` always exposes `sendUserMessage` (the port
87
- // marks it optional because only the outer command ctx lacks it).
88
- // `host` remains the fallback for the workflow-start-with-continue
89
- // case where there is no inner ctx yet — `enforceSessionInvariants`
90
- // requires a host whenever any stage is continue-policy, so the
91
- // fallback can be taken safely.
92
- //
93
- // Awaiting the send (vs fire-and-forget) lands transport errors on
94
- // this stage's halt path; pre-I5b we discarded the promise and the
95
- // runner walked the chain blind on rejection.
96
- await sendIntoExistingSession(ctx, host, prompt);
97
- await ctx.waitForIdle();
98
- await body(ctx);
99
- return { cancelled: false };
100
- },
101
- async send(ctx, msg, host) {
102
- // Same precedence as spawn: live ctx first, captured host as
103
- // fallback. Validation-retry sends always run inside a stage's
104
- // session, so `ctx.sendUserMessage` is present in practice; the
105
- // host branch is there for symmetry with spawn.
106
- await sendIntoExistingSession(ctx, host, msg);
107
- await ctx.waitForIdle();
108
- },
109
- };
46
+ /**
47
+ * THE child-spawn primitive every mode below reduces to. Open an isolated child
48
+ * (parent stays valid) in the requested `mode`, let the host apply the
49
+ * prompt/model/signal (+ reattach/fork), wait for the agent to settle, then run
50
+ * `body` on the guaranteed-in-session child ctx. The await-idle-then-body
51
+ * sequence — load-bearing for the IDLE-BEFORE-REPROMPT invariant — lives here
52
+ * once, so the three named entries can't drift on it. Up to `ctx.maxConcurrency`
53
+ * may be in flight (the loop's semaphore bounds fanout; single stages run one).
54
+ */
55
+ function openChild(
56
+ ctx: WorkflowHostContext,
57
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
58
+ body: (child: WorkflowSessionContext) => Promise<void>,
59
+ mode?: OpenMode,
60
+ ): Promise<void> {
61
+ return ctx.spawnChild({
62
+ prompt: s.prompt, // FRESH: host sends it. REATTACH/FORK: carried for parity; host skips auto-replay.
63
+ model: s.model,
64
+ signal: s.signal,
65
+ // The lane key for a lane-aware host's per-unit slot — set only for fan-out units.
66
+ // Undefined for sequential loop units / single stages / reattach / fork, all
67
+ // of which map to the host's reserved single-unit slot so the lane row keeps
68
+ // showing the one live session. Inert on a non-lane host.
69
+ unitIndex: s.laneUnitIndex,
70
+ ...mode,
71
+ withSession: async (child) => {
72
+ await child.waitForIdle();
73
+ await body(child);
74
+ },
75
+ });
76
+ }
110
77
 
111
78
  /**
112
- * Send a message into the already-active session. Prefers the live
113
- * `ctx.sendUserMessage`; falls back to the captured registry-level
114
- * `host.sendUserMessage` only when ctx doesn't expose one (workflow start
115
- * with a continue-first-stage). Throws if neither path is available —
116
- * `enforceSessionInvariants` should have rejected the workflow before
117
- * we land here.
79
+ * FRESH open. Open a brand-new isolated child session; the host sends the prompt
80
+ * and applies the model. The default stage/loop-unit entry.
118
81
  */
119
- async function sendIntoExistingSession(
82
+ export function spawnChildAndRun(
120
83
  ctx: WorkflowHostContext,
121
- host: WorkflowHost | undefined,
122
- msg: string,
84
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
85
+ body: (child: WorkflowSessionContext) => Promise<void>,
123
86
  ): Promise<void> {
124
- if (ctx.sendUserMessage) {
125
- await ctx.sendUserMessage(msg);
126
- return;
127
- }
128
- if (host) {
129
- await host.sendUserMessage(msg);
130
- return;
131
- }
132
- throw new Error(
133
- "CONTINUE_HANDLER: neither ctx.sendUserMessage nor a workflow host available — continue policy requires one of them",
134
- );
87
+ return openChild(ctx, s, body);
135
88
  }
136
89
 
137
- export function handlerFor(policy: SessionPolicy | undefined): SessionPolicyHandler {
138
- return policy === "continue" ? CONTINUE_HANDLER : FRESH_HANDLER;
90
+ /**
91
+ * THE reattach primitive — the detached replacement for the deleted
92
+ * live-session swap (`ctx.switchSession`). Spawn a child bound to the PERSISTED
93
+ * session at `sessionFile` (the host opens it, no fresh creation, no initial `prompt`),
94
+ * then run `body` on the in-session child ctx whose `getBranch` reflects the
95
+ * prior transcript. `body` is `reattachStageSession` (sessions/reattach.ts),
96
+ * which promotes from the loaded branch or nudges via `resendIntoChild`.
97
+ *
98
+ * `sessionFile` is supplied by the resume entry (a `locateSessionFile` hit), so
99
+ * the host always has a real file; a missing/in-memory case is gated upstream.
100
+ * There is NO `{ cancelled }` arm — a detached reattach has no live-session swap
101
+ * for the user to dismiss.
102
+ */
103
+ export function reattachChildSession(
104
+ ctx: WorkflowHostContext,
105
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
106
+ sessionFile: string,
107
+ body: (child: WorkflowSessionContext) => Promise<void>,
108
+ ): Promise<void> {
109
+ return openChild(ctx, s, body, { reattach: { sessionFile } });
110
+ }
111
+
112
+ /**
113
+ * THE fork primitive — the detached continuation mechanism for
114
+ * `sessionPolicy: "continue"`. Spawn a child by FORKING the PREDECESSOR's
115
+ * persisted session at `sessionFile` (`SessionManager.forkFrom`: a new file +
116
+ * new id carrying the predecessor's full transcript, source left intact), then
117
+ * run `body` on the in-session child ctx whose `getBranch` reflects that prior
118
+ * transcript. The host opens the fork and does NOT send the carried `prompt` —
119
+ * `body` (`continueStageSession`, sessions.ts) measures the inherited prefix and
120
+ * sends the continuation turn via `resendIntoChild`.
121
+ *
122
+ * `sessionFile` is the predecessor stage's persisted session (a
123
+ * `locateSessionFile` hit gated by the caller, from `run.state.lastSession`), so
124
+ * the host always has a real file. Distinct from `reattachChildSession` (which
125
+ * opens the SAME file IN PLACE for resume): a fork must not mutate the
126
+ * predecessor's file and gives the continue stage its own resumable identity.
127
+ */
128
+ export function forkChildSession(
129
+ ctx: WorkflowHostContext,
130
+ s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
131
+ sessionFile: string,
132
+ body: (child: WorkflowSessionContext) => Promise<void>,
133
+ ): Promise<void> {
134
+ return openChild(ctx, s, body, { fork: { sessionFile } });
135
+ }
136
+
137
+ /**
138
+ * Re-prompt an already-open child and wait for it to settle — the
139
+ * validation-retry path (`askAgentToFix`) and the resume reattach nudge.
140
+ * The child ctx always exposes `sendUserMessage`, so no guard.
141
+ *
142
+ * IDLE-BEFORE-REPROMPT INVARIANT: uses `sendUserMessage` (which QUEUES, safe
143
+ * mid-stream), NOT `prompt()` — the SDK THROWS "Agent is already processing" if
144
+ * `prompt()` is called while streaming. Every entry point honors this:
145
+ * `spawnChildAndRun` calls `waitForIdle()` before `body`, and the host's
146
+ * `prompt()` is only the single initial send. Callers must never call a child's
147
+ * `prompt()` again after the first; re-prompts go through `sendUserMessage` here.
148
+ */
149
+ export async function resendIntoChild(child: WorkflowSessionContext, msg: string): Promise<void> {
150
+ await child.sendUserMessage(msg);
151
+ await child.waitForIdle();
139
152
  }