@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
@@ -21,12 +21,12 @@ import { lifecycleCtxFromSession } from "../events.js";
21
21
  import type { Artifact } from "../handle.js";
22
22
  import { assertNever, formatError, nowIso, withTimeout } from "../internal-utils.js";
23
23
  import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
24
- import { ERR_COLLECTOR_THREW, ERR_PARSER_THREW, ERR_SCHEMA_TIMEOUT, MSG_VALIDATION_RETRY } from "../messages.js";
24
+ import { ERR_COLLECTOR_THREW, ERR_PARSER_THREW, ERR_SCHEMA_TIMEOUT } from "../messages.js";
25
25
  import { sideEffectOutcome } from "../outcomes/index.js";
26
- import { finalizeOutput, type Output } from "../output.js";
26
+ import { finalizeOutput, type Output, outputMeta } from "../output.js";
27
27
  import type { CollectCtx, Outcome } from "../output-spec.js";
28
28
  import { type BranchEntry, readBranch } from "../transcript.js";
29
- import type { StageSession, WorkflowHostContext } from "../types.js";
29
+ import type { StageSession, WorkflowSessionContext } from "../types.js";
30
30
  import {
31
31
  DEFAULT_VALIDATION_RETRIES,
32
32
  DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
@@ -35,20 +35,34 @@ import {
35
35
  MAX_VALIDATION_RETRY_TIMEOUT_MS,
36
36
  MIN_VALIDATION_RETRIES,
37
37
  MIN_VALIDATION_RETRY_TIMEOUT_MS,
38
+ runValidationRetryLoop,
38
39
  type SchemaValidationFailure,
39
40
  type ValidationResult,
40
41
  validateOutputData,
41
42
  } from "../validate-output.js";
42
- import { handlerFor } from "./spawn.js";
43
+ import { clampRange } from "../validation-bounds.js";
44
+ import { resendIntoChild } from "./spawn.js";
45
+
46
+ /**
47
+ * The fatal arm shared by every extraction-stage outcome — `{ kind: "fatal";
48
+ * message }`. Declared four times inline before (OutputProduction,
49
+ * RunOutcomeResult, enforceCompletionContract, validateOrFatal); the ok arms
50
+ * genuinely differ (OutputProduction carries a validation-exhausted third arm;
51
+ * validateOrFatal's ok payload is a ValidationResult under `result`, not an
52
+ * Output under `output`), so a single generic `FatalOr<T>` would force a field
53
+ * misnomer — the fatal arm is the part that's actually identical, so it's the
54
+ * thing to name once.
55
+ */
56
+ type Fatal = { kind: "fatal"; message: string };
43
57
 
44
58
  export type OutputProduction =
45
59
  | { kind: "ok"; output: Output }
46
- | { kind: "fatal"; message: string }
60
+ | Fatal
47
61
  | { kind: "validation-exhausted"; failureSummary: string };
48
62
 
49
63
  /** Retry loop re-produces against the latest branch after each fix request. */
50
64
  export async function produceAndValidateOutput(
51
- ctx: WorkflowHostContext,
65
+ ctx: WorkflowSessionContext,
52
66
  s: StageSession,
53
67
  branch: BranchEntry[],
54
68
  branchOffset: number | undefined,
@@ -118,19 +132,22 @@ function buildCollectCtx(s: StageSession, branch: BranchEntry[], branchOffset: n
118
132
  }
119
133
 
120
134
  function wrapOutput(s: StageSession, parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }): Output {
121
- return finalizeOutput(parts, {
122
- stage: s.stageName,
123
- skill: s.skill,
124
- // Pre-allocated by `produceAndValidateOutput` before any finalize runs —
125
- // no `lastAllocatedStageNumber + 1` peek, no temporal coupling with
126
- // recordStage.
127
- stageNumber: s.allocatedStageNumber!,
128
- ts: nowIso(),
129
- runId: s.runId,
130
- });
135
+ return finalizeOutput(
136
+ parts,
137
+ outputMeta({
138
+ stage: s.stageName,
139
+ skill: s.skill,
140
+ // Pre-allocated by `produceAndValidateOutput` before any finalize runs —
141
+ // no `lastAllocatedStageNumber + 1` peek, no temporal coupling with
142
+ // recordStage.
143
+ stageNumber: s.allocatedStageNumber!,
144
+ ts: nowIso(),
145
+ runId: s.runId,
146
+ }),
147
+ );
131
148
  }
132
149
 
133
- type RunOutcomeResult = { kind: "ok"; output: Output } | { kind: "fatal"; message: string };
150
+ type RunOutcomeResult = { kind: "ok"; output: Output } | Fatal;
134
151
 
135
152
  /**
136
153
  * The collector → parser pipeline. When `parser` is omitted, the
@@ -190,7 +207,7 @@ function enforceCompletionContract(
190
207
  stage: StageDef,
191
208
  skill: string,
192
209
  output: Output,
193
- ): { kind: "ok"; output: Output } | { kind: "fatal"; message: string } {
210
+ ): { kind: "ok"; output: Output } | Fatal {
194
211
  if (stage.kind === "produces" && output.artifacts.length === 0) {
195
212
  return {
196
213
  kind: "fatal",
@@ -231,55 +248,82 @@ interface RetryDeps {
231
248
  }
232
249
 
233
250
  async function retryUntilValid(
234
- ctx: WorkflowHostContext,
251
+ ctx: WorkflowSessionContext,
235
252
  s: StageSession,
236
253
  deps: RetryDeps,
237
254
  initial: Output,
238
255
  ): Promise<OutputProduction> {
239
256
  const schema = effectiveOutputSchema(s)!;
240
- const maxRetries = Math.max(
257
+ const maxRetries = clampRange(
258
+ s.stage.maxRetries,
241
259
  MIN_VALIDATION_RETRIES,
242
- Math.min(s.stage.maxRetries ?? DEFAULT_VALIDATION_RETRIES, MAX_VALIDATION_RETRIES),
260
+ DEFAULT_VALIDATION_RETRIES,
261
+ MAX_VALIDATION_RETRIES,
243
262
  );
244
- const timeoutMs = Math.max(
263
+ const timeoutMs = clampRange(
264
+ s.stage.validateTimeoutMs,
245
265
  MIN_VALIDATION_RETRY_TIMEOUT_MS,
246
- Math.min(s.stage.validateTimeoutMs ?? DEFAULT_VALIDATION_RETRY_TIMEOUT_MS, MAX_VALIDATION_RETRY_TIMEOUT_MS),
266
+ DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
267
+ MAX_VALIDATION_RETRY_TIMEOUT_MS,
247
268
  );
248
269
 
249
- let output = initial;
250
- const initialValidation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
251
- if (initialValidation.kind === "fatal") return initialValidation;
252
- let result = initialValidation.result;
253
- let attempts = 0;
254
-
255
- while (!result.valid && attempts < maxRetries && s.stage.onInvalid !== "halt") {
256
- attempts++;
257
- // onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
258
- // Ref shares the activation's ALLOCATOR number (currentStageRef) so
259
- // listeners can correlate this retry with the end/error event it
260
- // belongs to — graph position (`stageIndex + 1`) diverges past any loop.
261
- await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempts, lifecycleCtxFromSession(s));
262
- try {
263
- await askAgentToFix(ctx, s, attempts, result.failures, timeoutMs);
264
- } catch (e) {
265
- return { kind: "fatal", message: formatError(e) };
266
- }
267
-
268
- const retryBranch = readBranch(ctx);
269
- const retryCtx: CollectCtx = { ...deps.collectCtx, branch: retryBranch };
270
- const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
271
- if (reRun.kind === "fatal") return reRun;
272
- const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
273
- if (contract.kind === "fatal") return contract;
274
-
275
- output = contract.output;
276
- const reValidation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
277
- if (reValidation.kind === "fatal") return reValidation;
278
- result = reValidation.result;
279
- }
270
+ // The retry policy is the SHARED `runValidationRetryLoop` engine
271
+ // (validate-output.ts) — the same produce → validate → retry structure the
272
+ // script path runs. The four equivalence cases (invalid+failFast → exhausted;
273
+ // invalid+budget-spent → exhausted; invalid+retryable → retry; any fatal →
274
+ // Fatal) fall out of the engine's three-arm outcome:
275
+ // - `produce(0)` → the already-produced `initial` (produced + contract-
276
+ // checked before this loop opened); `produce(n>0)` → re-read the branch,
277
+ // re-run the collector/parser, re-check the completion contract.
278
+ // - `validate` → `validateOrFatal`, mapping its `Fatal` onto the engine's
279
+ // `{ kind: "aborted"; abort: Fatal }` abort arm.
280
+ // - `onRetry` → `onStageRetry` + `askAgentToFix`; a throw becomes an abort.
281
+ // `failFast` mirrors the script path's stop-flag polarity —
282
+ // `(onInvalid ?? "retry") === "halt"` is byte-identical to today's
283
+ // `onInvalid !== "halt"` loop-continue condition, just expressed as the
284
+ // engine's stop flag. Total productions stay bounded by `maxRetries + 1`.
285
+ const outcome = await runValidationRetryLoop<Output, Fatal>(
286
+ {
287
+ maxRetries,
288
+ failFast: (s.stage.onInvalid ?? "retry") === "halt",
289
+ },
290
+ {
291
+ produce: async (attempt) => {
292
+ // `produce(0)` returns the already-produced initial — no re-collection,
293
+ // no contract re-check (both ran before the loop opened).
294
+ if (attempt === 0) return { kind: "ok", value: initial };
295
+ const retryBranch = readBranch(ctx);
296
+ const retryCtx: CollectCtx = { ...deps.collectCtx, branch: retryBranch };
297
+ const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
298
+ if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
299
+ const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
300
+ if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
301
+ return { kind: "ok", value: contract.output };
302
+ },
303
+ validate: async (output) => {
304
+ const validation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
305
+ if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
306
+ return { kind: "ok", result: validation.result };
307
+ },
308
+ onRetry: async (attempt, failures) => {
309
+ // onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
310
+ // Ref shares the activation's ALLOCATOR number (currentStageRef) so
311
+ // listeners can correlate this retry with the end/error event it
312
+ // belongs to — graph position (`stageIndex + 1`) diverges past any loop.
313
+ await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
314
+ try {
315
+ await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
316
+ return { kind: "ok" };
317
+ } catch (e) {
318
+ return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
319
+ }
320
+ },
321
+ },
322
+ );
280
323
 
281
- if (!result.valid) return validationExhausted(result.failures);
282
- return { kind: "ok", output };
324
+ if (outcome.kind === "aborted") return outcome.abort;
325
+ if (outcome.kind === "exhausted") return validationExhausted(outcome.failures);
326
+ return { kind: "ok", output: outcome.value };
283
327
  }
284
328
 
285
329
  /**
@@ -306,7 +350,7 @@ async function validateOrFatal(
306
350
  data: unknown,
307
351
  skill: string,
308
352
  timeoutMs: number,
309
- ): Promise<{ kind: "ok"; result: ValidationResult } | { kind: "fatal"; message: string }> {
353
+ ): Promise<{ kind: "ok"; result: ValidationResult } | Fatal> {
310
354
  try {
311
355
  const result = await withTimeout(
312
356
  Promise.resolve(validateOutputData(schema, data)),
@@ -320,16 +364,15 @@ async function validateOrFatal(
320
364
  }
321
365
 
322
366
  async function askAgentToFix(
323
- ctx: WorkflowHostContext,
367
+ ctx: WorkflowSessionContext,
324
368
  s: StageSession,
325
369
  attempt: number,
326
370
  failures: SchemaValidationFailure[],
327
371
  timeoutMs: number,
328
372
  ): Promise<void> {
329
- ctx.ui.notify(MSG_VALIDATION_RETRY(s.skill, attempt), "warning");
330
373
  const errorLines = failures.map((f) => ` • ${describeFailure(f)}`).join("\n");
331
374
  await withTimeout(
332
- handlerFor(s.stage.sessionPolicy).send(ctx, MSG_VALIDATION_RETRY_PROMPT(s.skill, errorLines), s.continueHost),
375
+ resendIntoChild(ctx, MSG_VALIDATION_RETRY_PROMPT(s.skill, errorLines)),
333
376
  timeoutMs,
334
377
  `${s.skill}: validation retry attempt ${attempt} exceeded ${timeoutMs}ms — agent did not settle`,
335
378
  );
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Halt-routing facet — extracted from `sessions.ts`'s HALT HELPERS. Turns a
3
+ * halt reason into the right audit-layer call. `haltStageOrSoftHalt` is the
4
+ * single gate `postStage` dispatches through (a `collectAll` fanout unit
5
+ * soft-halts; everything else fail-fast halts). `haltStageWithValidationFailure`
6
+ * is also exported for the `reattach.ts` companion.
7
+ *
8
+ * `auditFor` lives here (moved from `sessions.ts`) — its only callers are the
9
+ * halt helpers below; relocating it keeps the value-import DAG acyclic (the
10
+ * success-persistence facet in `success-persist.ts` does not use `auditFor`,
11
+ * so no edge from there back here).
12
+ *
13
+ * Companion modules (see `sessions.ts`'s header for the full map):
14
+ * - success-persist.ts — `recordStageSuccess` + `unitEventOf` (the soft-halt
15
+ * lifecycle signal borrows `unitEventOf` from here).
16
+ */
17
+
18
+ import { type AuditCtx, failedArgs, recordStopFailure, recordTerminalFailure, recordUnitHalt } from "../audit.js";
19
+ import { allocateStageNumber } from "../audit-rows.js";
20
+ import { lifecycleCtxFromSession, skillStageRef } from "../events.js";
21
+ import { nowIso } from "../internal-utils.js";
22
+ import { FAIL_VALIDATION_EXHAUSTED, MSG_STAGE_FAILED } from "../messages.js";
23
+ import { failedOutput, type OutputMeta, outputMeta } from "../output.js";
24
+ import type { SessionRef } from "../state/index.js";
25
+ import type { StopSignal } from "../transcript.js";
26
+ import type { StageSession, WorkflowHostContext } from "../types.js";
27
+ import { unitEventOf } from "./success-persist.js";
28
+
29
+ /**
30
+ * A stage's reason-to-halt, tagged by the post-processing arm that produced it.
31
+ * Carries BOTH the fail-fast halt shape (the per-arm record call) and the
32
+ * collect-all soft-halt reason string, so ONE gate decides between them.
33
+ */
34
+ type HaltReason =
35
+ | { kind: "stop"; stop: Exclude<StopSignal, "stop"> }
36
+ | { kind: "extraction"; message: string }
37
+ | { kind: "validation"; failureSummary: string }
38
+ // A watchdog aborted a runaway tool call (bash) past its per-command timeout. The
39
+ // host surfaces it via `WorkflowSessionContext.toolTimeout`; carries the operator-grade
40
+ // reason string written to the failed row (soft-halt errMsg / terminal errMsg).
41
+ | { kind: "timeout"; reason: string };
42
+
43
+ /**
44
+ * The single collect-all fork. A `collectAll` fanout unit soft-halts (a
45
+ * NON-terminal `collected:true` row + a `failedOutput` sentinel the parallel fold
46
+ * places by index); every other stage takes the arm's fail-fast terminal halt.
47
+ * Replaces the `if (s.collectAll)` that was inlined at all three halt sites.
48
+ */
49
+ export async function haltStageOrSoftHalt(
50
+ ctx: WorkflowHostContext,
51
+ s: StageSession,
52
+ reason: HaltReason,
53
+ session: SessionRef | null,
54
+ ): Promise<void> {
55
+ if (s.collectAll) return softHaltUnit(ctx, s, softHaltReason(s, reason), session);
56
+ return failFastHalt(ctx, s, reason, session);
57
+ }
58
+
59
+ /** Collect-all reason text per arm — byte-identical to the prior inline strings. */
60
+ function softHaltReason(s: StageSession, reason: HaltReason): string {
61
+ switch (reason.kind) {
62
+ case "stop":
63
+ return `${s.skill} stopped (${reason.stop})`;
64
+ case "extraction":
65
+ return reason.message;
66
+ case "validation":
67
+ return reason.failureSummary;
68
+ case "timeout":
69
+ return reason.reason;
70
+ }
71
+ }
72
+
73
+ /** Fail-fast terminal halt per arm — dispatches to the existing helpers, unchanged. */
74
+ function failFastHalt(
75
+ ctx: WorkflowHostContext,
76
+ s: StageSession,
77
+ reason: HaltReason,
78
+ session: SessionRef | null,
79
+ ): Promise<void> {
80
+ switch (reason.kind) {
81
+ case "stop":
82
+ return haltStage(ctx, s, reason.stop, session);
83
+ case "extraction":
84
+ return haltStageWithExtractionError(ctx, s, reason.message, session);
85
+ case "validation":
86
+ return haltStageWithValidationFailure(ctx, s, reason.failureSummary, session);
87
+ case "timeout":
88
+ // A non-fan-out stage whose bash overran the watchdog: terminal "failed" row whose
89
+ // errMsg carries the timeout reason (same shape as an extraction-fatal halt).
90
+ return haltStageWithExtractionError(ctx, s, reason.reason, session);
91
+ }
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
+ /**
118
+ * Collect-all fanout unit halt: write a NON-terminal failed row, then hand a
119
+ * `failedOutput` sentinel to the continuation (`onSuccess`) so the parallel fold
120
+ * places it by declared index (`foldFanoutCompletion` → `placeFanoutOutput`) and
121
+ * `fanin(...).filter(Boolean)` skips it. The run survives — no `terminate()`. No
122
+ * direct `applyCompletedStage` here (the fold owns the single channel-write — a
123
+ * push here would double-write the slot). Recording + `onSuccess` run on the
124
+ * launcher/observer `ctx` (the same posture as `postStage`).
125
+ */
126
+ async function softHaltUnit(
127
+ ctx: WorkflowHostContext,
128
+ s: StageSession,
129
+ reason: string,
130
+ session: SessionRef | null,
131
+ ): Promise<void> {
132
+ s.allocatedStageNumber ??= allocateStageNumber(s.state);
133
+ recordUnitHalt(ctx, auditFor(s, session), reason); // status:"failed" collected:true row (resume reads errMsg)
134
+ // Fire the soft-halt lifecycle signal (mirrors recordStageSuccess's onUnitEnd) AFTER the row
135
+ // lands. Without it this unit emits NO terminal lifecycle event — recordUnitHalt deliberately
136
+ // skips onStageError ("not a hard fail") and the success-only onUnitEnd never runs — so a lane
137
+ // bridge would leave the sub-row spinning until onWorkflowEnd, where a completed run's sweep
138
+ // paints it ✓ (a failed-but-collected unit mis-rendered as success). The ref carries the PARENT
139
+ // stage name (graph identity), same allocator base as every other ref of this activation.
140
+ await s.lifecycle.fire(
141
+ ctx,
142
+ "onUnitHalt",
143
+ skillStageRef(s.unit!.parent, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill),
144
+ unitEventOf(s),
145
+ reason,
146
+ lifecycleCtxFromSession(s),
147
+ );
148
+ await s.onSuccess(ctx, failedOutput(outputMetaFor(s), reason));
149
+ }
150
+
151
+ /** OutputMeta for a sentinel — same stage number the failed row carries, so the
152
+ * live sentinel and the resume-rebuilt one are byte-identical. */
153
+ function outputMetaFor(s: StageSession): OutputMeta {
154
+ return outputMeta({
155
+ stage: s.stageName,
156
+ skill: s.skill,
157
+ stageNumber: s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber,
158
+ ts: nowIso(),
159
+ runId: s.runId,
160
+ });
161
+ }
162
+
163
+ /** Exported to the `reattach.ts` companion — a promotion's validation-exhausted halt is identical to live. */
164
+ export async function haltStageWithValidationFailure(
165
+ ctx: WorkflowHostContext,
166
+ s: StageSession,
167
+ failureSummary: string,
168
+ session: SessionRef | null,
169
+ ): Promise<void> {
170
+ await recordTerminalFailure(
171
+ ctx,
172
+ auditFor(s, session),
173
+ failedArgs(FAIL_VALIDATION_EXHAUSTED(s.skill, failureSummary)),
174
+ s.onFailure,
175
+ );
176
+ }
177
+
178
+ const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
179
+ cwd: s.cwd,
180
+ runId: s.runId,
181
+ state: s.state,
182
+ stageName: s.stageName,
183
+ skill: s.skill,
184
+ // The Pi session backing this activation — `null` only for pre-open
185
+ // cancellation (the one writer here that never entered a session).
186
+ session,
187
+ lifecycle: s.lifecycle,
188
+ runIdentity: s.runIdentity,
189
+ // The activation's pre-allocated stage number (set once output production
190
+ // began) — a failure row reuses it instead of burning a second number.
191
+ allocatedStageNumber: s.allocatedStageNumber,
192
+ // Loop units thread their identity onto failure/cancellation rows so failed
193
+ // trailers carry the structured fields the resume drift guard consumes.
194
+ ...(s.unit ? { unit: s.unit } : {}),
195
+ });
package/sessions/index.ts CHANGED
@@ -4,6 +4,6 @@
4
4
  * barrel re-exports only the symbols the rest of the package consumes.
5
5
  */
6
6
 
7
- export { locateSessionFile } from "./locate.js";
7
+ export { locateSessionFile, pruneOrphanedChildSessions } from "./locate.js";
8
8
  export { reattachStageSession } from "./reattach.js";
9
- export { runStageSession } from "./sessions.js";
9
+ export { continueStageSession, runStageSession } from "./sessions.js";
@@ -1,22 +1,29 @@
1
1
  /**
2
- * Session-file location for session-backed resume. `SessionRef.file` is a
3
- * HINT captured at activation time — sessions move (Pi renames on label
4
- * change), get cleaned up, or live on another machine. `locateSessionFile`
5
- * resolves id → on-disk path with a three-rung fallback; `null` means
6
- * "fall back to cold re-run" (the caller's ladder notifies).
2
+ * Child-session file layout — the two operations keyed off `childSessionsDir`:
3
+ * LOCATE one session by id (session-backed resume) and PRUNE the orphans (the
4
+ * run-end sweep). `SessionRef.file` is a HINT captured at activation time —
5
+ * sessions move (Pi renames on label change), get cleaned up, or live on another
6
+ * machine. `locateSessionFile` resolves id → on-disk path with a three-rung
7
+ * fallback; `null` means "fall back to cold re-run" (the caller's ladder
8
+ * notifies). `pruneOrphanedChildSessions` removes files no persisted row points
9
+ * at.
7
10
  *
8
11
  * `node:fs` only — no Pi import; unit-testable with temp dirs. Fail-soft
9
12
  * throughout: any fs error degrades to the next rung, never throws.
10
13
  */
11
14
 
12
- import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from "node:fs";
15
+ import { closeSync, existsSync, openSync, readdirSync, readSync, rmSync, statSync } from "node:fs";
13
16
  import { dirname, join } from "node:path";
14
17
  import type { SessionRef } from "../state/index.js";
18
+ import { childSessionsDir } from "../state/paths.js";
15
19
 
16
20
  /**
17
21
  * id → on-disk session file. Fail-soft: `null` means "fall back to cold
18
22
  * re-run".
19
23
  *
24
+ * 0. When a `runId`+`cwd` are known, try the run-scoped child dir by id
25
+ * FIRST (`childSessionsDir(cwd, runId)/<id>.jsonl`, O(1)) — detached
26
+ * children persist there keyed by `SessionRef.id`.
20
27
  * 1. `ref.file` exists on disk → use it (fast path).
21
28
  * 2. Else search `dirname(ref.file)` for `*_<id>.jsonl` (Pi's filename
22
29
  * convention embeds the session id).
@@ -24,10 +31,14 @@ import type { SessionRef } from "../state/index.js";
24
31
  * (robust against filename-convention drift).
25
32
  * 4. Else `null`.
26
33
  *
27
- * No `file` hint at all (in-memory session) → `null` immediately: without
28
- * the hint there is no directory to search.
34
+ * No `file` hint at all (in-memory session) → `null` immediately AFTER the
35
+ * id-first rung: without the hint there is no directory to search.
29
36
  */
30
- export function locateSessionFile(ref: SessionRef): string | null {
37
+ export function locateSessionFile(ref: SessionRef, runId?: string, cwd?: string): string | null {
38
+ if (runId && cwd) {
39
+ const candidate = join(childSessionsDir(cwd, runId), `${ref.id}.jsonl`);
40
+ if (isFile(candidate)) return candidate;
41
+ }
31
42
  if (!ref.file) return null;
32
43
  try {
33
44
  if (existsSync(ref.file) && statSync(ref.file).isFile()) return ref.file;
@@ -59,6 +70,46 @@ export function locateSessionFile(ref: SessionRef): string | null {
59
70
  return null;
60
71
  }
61
72
 
73
+ /**
74
+ * Orphan sweep — delete every persisted child-session file under the run's
75
+ * `childSessionsDir` whose session id NO entry in `referenced` carries. Run ONCE
76
+ * at run end (`executeRun`), after every child is torn down and every row is
77
+ * written, so the keep-set is complete.
78
+ *
79
+ * The orphan source today is a `continue` fork whose stage threw between
80
+ * `SessionManager.forkFrom` (which wrote the fork file) and its first audit-row
81
+ * write: `recordEntryThrow` pins `session: null` on the failure row, so no row
82
+ * references the fork (an aborted fresh child is the same shape). Deleting it is
83
+ * SAFE because resume only ever reattaches/forks a file some persisted row
84
+ * references — or `lastSession`, itself a referenced session — so an unreferenced
85
+ * file is never consulted; removing it cannot strand a resumable session.
86
+ *
87
+ * CONSERVATIVE by construction: a file is removed ONLY when its header id is
88
+ * positively read AND absent from `referenced`. An unreadable header keeps the
89
+ * file (a leftover orphan is the harmless status quo; deleting a referenced file
90
+ * is not). Best-effort — a missing dir or an unlink race never throws.
91
+ */
92
+ export function pruneOrphanedChildSessions(cwd: string, runId: string, referenced: ReadonlySet<string>): void {
93
+ const dir = childSessionsDir(cwd, runId);
94
+ let entries: string[];
95
+ try {
96
+ entries = readdirSync(dir);
97
+ } catch {
98
+ return; // no child-sessions dir (no detached child ran) — nothing to sweep
99
+ }
100
+ for (const entry of entries) {
101
+ if (!entry.endsWith(".jsonl")) continue;
102
+ const path = join(dir, entry);
103
+ const id = headerIdOf(path);
104
+ if (id === undefined || referenced.has(id)) continue; // unidentifiable / referenced → keep
105
+ try {
106
+ rmSync(path);
107
+ } catch {
108
+ // best-effort — an already-removed file / concurrent reader is fine
109
+ }
110
+ }
111
+ }
112
+
62
113
  function isFile(path: string): boolean {
63
114
  try {
64
115
  return statSync(path).isFile();
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Session-backed resume continuation — runs INSIDE the interrupted stage's
3
- * adopted session (the `withSession` callback of `ctx.switchSession`, wired
4
- * by `resumeStageWithSession` in runner/run-stage.ts). Companion to
5
- * `sessions.ts`, reusing its exported pipeline pieces instead of
6
- * duplicating them.
3
+ * reopened child session (the `withSession` callback of `reattachChildSession`,
4
+ * which the host opens from the persisted session file; wired by
5
+ * `resumeWithSessionLadder` in runner/run-stage.ts). Companion to `sessions.ts`,
6
+ * reusing its exported pipeline pieces instead of duplicating them.
7
7
  *
8
8
  * Two arms, tried in order:
9
9
  *
@@ -27,37 +27,45 @@
27
27
  * Validation-exhausted from promotion halts exactly as live does.
28
28
  */
29
29
 
30
- import type { WorkflowSessionContext } from "../host.js";
31
30
  import { MSG_RESUME_PROMOTED, MSG_RESUME_REATTACHED, REATTACH_PROMPT } from "../messages.js";
32
31
  import { readBranch, readSessionRef } from "../transcript.js";
33
- import type { StageSession } from "../types.js";
32
+ import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
34
33
  import { produceAndValidateOutput } from "./extraction.js";
35
- import { haltStageWithValidationFailure, postStage, recordStageSuccess } from "./sessions.js";
36
- import { handlerFor } from "./spawn.js";
34
+ import { haltStageWithValidationFailure } from "./halt-routing.js";
35
+ import { postStage } from "./sessions.js";
36
+ import { branchOffsetFor, resendIntoChild } from "./spawn.js";
37
+ import { recordStageSuccess } from "./success-persist.js";
37
38
 
38
- export async function reattachStageSession(ctx: WorkflowSessionContext, s: StageSession): Promise<void> {
39
+ // Same two-ctx split as `postStage`: `obsCtx` is the long-lived launcher/observer
40
+ // (user-facing notifications + record + the chain continuation that spawns the
41
+ // next stage); `child` is the reopened persisted session (branch reads + the
42
+ // reattach nudge).
43
+ export async function reattachStageSession(
44
+ obsCtx: WorkflowHostContext,
45
+ child: WorkflowSessionContext,
46
+ s: StageSession,
47
+ ): Promise<void> {
39
48
  // Promotion: extraction over the adopted branch, scoped by the SAME
40
49
  // offset the interrupted activation ran under (persisted on its row and
41
50
  // threaded back via `s.branchOffset`; fresh stages scan the whole branch).
42
- const offset = handlerFor(s.stage.sessionPolicy).branchOffset(s.branchOffset);
43
- const session = readSessionRef(ctx, offset);
44
- const result = await produceAndValidateOutput(ctx, s, readBranch(ctx), offset);
51
+ const offset = branchOffsetFor(s.stage.sessionPolicy, s.branchOffset);
52
+ const session = readSessionRef(child, offset);
53
+ const result = await produceAndValidateOutput(child, s, readBranch(child), offset);
45
54
 
46
55
  if (result.kind === "ok") {
47
- ctx.ui.notify(MSG_RESUME_PROMOTED(s.skill), "info");
48
- if (!(await recordStageSuccess(ctx, s, result.output, session))) return;
49
- await s.onSuccess(ctx, result.output);
56
+ obsCtx.ui.notify(MSG_RESUME_PROMOTED(s.skill), "info");
57
+ if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
58
+ await s.onSuccess(obsCtx, result.output);
50
59
  return;
51
60
  }
52
61
  if (result.kind === "validation-exhausted") {
53
- return haltStageWithValidationFailure(ctx, s, result.failureSummary, session);
62
+ return haltStageWithValidationFailure(obsCtx, s, result.failureSummary, session);
54
63
  }
55
64
 
56
65
  // Promotion missed (collector-fatal) — reattach: nudge the session from
57
66
  // its leaf, let the agent finish with full prior context, then run the
58
67
  // standard post-session pipeline.
59
- ctx.ui.notify(MSG_RESUME_REATTACHED(s.skill), "info");
60
- await ctx.sendUserMessage(REATTACH_PROMPT(s.skill));
61
- await ctx.waitForIdle();
62
- await postStage(ctx, s);
68
+ obsCtx.ui.notify(MSG_RESUME_REATTACHED(s.skill), "info");
69
+ await resendIntoChild(child, REATTACH_PROMPT(s.skill));
70
+ await postStage(obsCtx, child, s);
63
71
  }