@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
package/runner/runner.ts CHANGED
@@ -4,35 +4,15 @@
4
4
  * run's JSONL trail and re-enters the chain at the right seam. Per-stage
5
5
  * work (sessions, extraction, validation, audit row writes) lives in
6
6
  * sessions.ts + audit.ts; this directory owns graph traversal, per-stage
7
- * prerequisites, and routing.
7
+ * prerequisites, and routing; imports point strictly downward — the walk's
8
+ * mutual recursion is composed by injection in run-stage.ts, never as a
9
+ * module cycle.
8
10
  *
9
- * Modules (imports point strictly downward — the walk's mutual recursion is
10
- * composed by injection in run-stage.ts, never as a module cycle):
11
- * - runner.ts — runWorkflow + resumeWorkflow + executeRun (shared
12
- * tail).
13
- * - run-stage.ts — runStage (mode dispatch) + runStageOrRecordFailure
14
- * (single catch site) + the walk composition.
15
- * - chain-advance.ts — advanceChain + routing audit + backward-jump
16
- * guard + halt-on-error (ChainDeps-injected).
17
- * - resolve-stage.ts — ResolvedStage: mode/dispatch derived once.
18
- * - preflight.ts — runtime preflights (throw StagePreflightError).
19
- * - input-validation.ts— schema-backed input preflights.
20
- * - script-stage.ts — skillless TS-stage runtime (no session/collector).
21
- * - failure.ts — ChainOutcome + entry-throw → failure-row + finalize.
22
- * - run-context.ts — RunContext/RunState construction + policy caps.
23
- * - errors.ts — StagePreflightError.
24
- * - resume.ts — reconstructState: pure RunState rebuild from a
25
- * past run's JSONL trail (consumed by resumeWorkflow).
26
- * - resume-entry.ts — trail trailer → chain re-entry thunk + refusal text.
27
- * - resume-loop.ts — loop-trailer re-entry + drift refusals.
28
- *
29
- * Ctx lifecycle: every level only touches the ctx it was handed.
30
- * - `newSession({cancelled: false})` invalidates the outer ctx; all
31
- * further work runs on `freshCtx` inside `withSession`, and the
32
- * outer function simply unwinds.
33
- * - `cancelled: true` means no replacement happened — outer ctx remains
34
- * valid.
35
- * - Continue policy has no newSession — same ctx throughout.
11
+ * Ctx lifecycle: the launcher ctx threaded into `runWorkflow`/`resumeWorkflow`
12
+ * STAYS VALID for the whole run — it is never swapped. Every stage runs in its
13
+ * own detached child session opened via `ctx.spawnChild({ withSession })`; the
14
+ * parent ctx only observes (progress, status). Continue policy spawns a child
15
+ * like any other stage — its only divergence is the preserved branch offset.
36
16
  *
37
17
  * Vocabulary: "stage" = one stage activation in this run; "phase" = one
38
18
  * `## Phase N:` subdivision inside an implement plan artifact.
@@ -41,8 +21,9 @@
41
21
  import type { Workflow } from "../api.js";
42
22
  import { currentPrimaryArtifact } from "../chain-state.js";
43
23
  import { type LifecycleListeners, lifecycleCtxFor } from "../events.js";
24
+ import { getWorkflowExecutionProvider } from "../execution-host.js";
44
25
  import { handleToString } from "../handle.js";
45
- import type { WorkflowHost, WorkflowHostContext } from "../host.js";
26
+ import type { ModelSelection, WorkflowHost, WorkflowHostContext } from "../host.js";
46
27
  import { nowIso } from "../internal-utils.js";
47
28
  import {
48
29
  MSG_HEADER_WRITE_FAILED,
@@ -50,15 +31,18 @@ import {
50
31
  MSG_NAME_INDEX_WRITE_FAILED,
51
32
  MSG_NAME_INVALID,
52
33
  } from "../messages.js";
34
+ import { pruneOrphanedChildSessions } from "../sessions/index.js";
53
35
  import {
54
36
  type ClaimResult,
55
37
  claimName,
56
38
  generateRunId,
39
+ readAllStages,
57
40
  releaseName,
58
41
  STATE_SCHEMA_VERSION,
59
42
  type WorkflowHeader,
60
43
  writeHeader,
61
44
  } from "../state/index.js";
45
+ import { childSessionsDir } from "../state/paths.js";
62
46
  import { DEFAULT_TRIGGER } from "../triggers.js";
63
47
  import type { RunContext, RunWorkflowOptions, RunWorkflowResult } from "../types.js";
64
48
  import { reconstructState } from "./resume.js";
@@ -85,6 +69,12 @@ async function executeRun(
85
69
 
86
70
  await entry();
87
71
 
72
+ // Run settled — every child torn down, every row persisted. Sweep child-session
73
+ // files no row references (chiefly a `continue` fork whose stage threw before its
74
+ // first row write — the failure row pins session:null, orphaning the fork). Safe:
75
+ // resume only reattaches/forks files a persisted row references. Best-effort.
76
+ pruneOrphanedChildSessions(run.cwd, run.runId, referencedSessionIds(run));
77
+
88
78
  const { state } = run;
89
79
  const result: RunWorkflowResult = {
90
80
  runId: run.runId,
@@ -108,6 +98,83 @@ async function executeRun(
108
98
  return result;
109
99
  }
110
100
 
101
+ /**
102
+ * The keep-set for the run-end orphan sweep. Failed/aborted rows that carry a
103
+ * session are reattach targets on resume, so every row's `session.id` is read
104
+ * from the durable trail (success OR failure) and unioned with `lastSession`
105
+ * (the live predecessor a resumed `continue` would fork). Anything NOT here is
106
+ * a child-session file no row points at — safe to delete.
107
+ */
108
+ function referencedSessionIds(run: RunContext): Set<string> {
109
+ const ids = new Set<string>();
110
+ for (const row of readAllStages(run.cwd, run.runId)) {
111
+ if (row.session) ids.add(row.session.id);
112
+ }
113
+ if (run.state.lastSession) ids.add(run.state.lastSession.id);
114
+ return ids;
115
+ }
116
+
117
+ /** What `detachExecutor` resolves: the executor ctx to run against, the
118
+ * per-stage model resolver + abort signal to thread onto `RunContext`, and the
119
+ * teardown the caller invokes in `finally`. */
120
+ interface DetachedExecutor {
121
+ execCtx: WorkflowHostContext;
122
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
123
+ signal?: AbortSignal;
124
+ dispose?: () => void;
125
+ }
126
+
127
+ /**
128
+ * Detach to the executor host — the SHARED detach BOTH entry points run through,
129
+ * so a resumed stage's `spawnChild` / reattach / fork runs against the SAME real
130
+ * executor as a live run. Building the host HERE for both paths keeps resume
131
+ * off the bare launcher ctx (a `WorkflowLauncherContext` with no
132
+ * `spawnChild`/`maxConcurrency`) — the only place such a gap could hide is a
133
+ * test injecting a `spawnChild` directly.
134
+ *
135
+ * Threads the provider's `resolveModel` + abort `signal` too, so resumed children
136
+ * get per-stage models and cooperative cancellation exactly like live. The
137
+ * `childSessionsDir` is keyed by `runId`, so a resume reuses the SAME run-scoped
138
+ * dir the original run persisted its children into — what reattach/fork resolve
139
+ * against.
140
+ *
141
+ * No provider ⇒ execute on the live `ctx` (graceful degrade for non-Pi embedders
142
+ * / tests — the caller is contracted to pass an executor-capable ctx there).
143
+ * `dispose` unsubscribes the keystroke tap; the caller MUST call it in `finally`.
144
+ */
145
+ async function detachExecutor(
146
+ ctx: WorkflowHostContext,
147
+ cwd: string,
148
+ runId: string,
149
+ options: {
150
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
151
+ signal?: AbortSignal;
152
+ name?: string; // lane display name (run --name ?? workflow name)
153
+ /** Workflow name (the dock's dim `workflow:` tag); threaded from workflow.name / header.workflow. */
154
+ workflow?: string;
155
+ /** The run's original input (user prompt); threaded from options.input / header.input. */
156
+ input?: string;
157
+ },
158
+ ): Promise<DetachedExecutor> {
159
+ const provider = getWorkflowExecutionProvider();
160
+ if (!provider) return { execCtx: ctx, resolveModel: options.resolveModel, signal: options.signal };
161
+ // Resolve the run-scoped session dir here (internal layout helper) and hand the
162
+ // provider a concrete string; rpiv-pi never imports childSessionsDir.
163
+ const exec = await provider.createHost(ctx, {
164
+ runId,
165
+ childSessionsDir: childSessionsDir(cwd, runId),
166
+ name: options.name, // rpiv-pi records the lane under this name
167
+ workflow: options.workflow, // dock tag (the workflow name)
168
+ input: options.input, // dock descriptor (the user prompt)
169
+ });
170
+ return {
171
+ execCtx: exec.host,
172
+ dispose: exec.dispose,
173
+ resolveModel: options.resolveModel ?? provider.resolveModel,
174
+ signal: options.signal ?? exec.signal, // provider-owned abort handle
175
+ };
176
+ }
177
+
111
178
  // ---------------------------------------------------------------------------
112
179
  // runWorkflow — workflow entry point
113
180
  // ---------------------------------------------------------------------------
@@ -125,9 +192,9 @@ function nameClaimError(name: string, claim: Extract<ClaimResult, { ok: false }>
125
192
  }
126
193
 
127
194
  /**
128
- * Each subsequent `newSession()` is invoked on the freshCtx returned by the
129
- * previous withSession — never on a captured outer ctx (which Pi invalidates
130
- * as soon as the session is replaced).
195
+ * Walks the workflow's edge graph from `workflow.start`. The launcher `ctx`
196
+ * stays valid throughout — each stage opens (and disposes) its own detached
197
+ * child session via `spawnChild`, so the outer ctx is never swapped.
131
198
  */
132
199
  export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflowOptions): Promise<RunWorkflowResult> {
133
200
  const { workflow } = options;
@@ -139,9 +206,6 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
139
206
  };
140
207
  }
141
208
 
142
- const continueGuard = hostMissingForContinueStages(workflow, options.host);
143
- if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
144
-
145
209
  const cwd = ctx.cwd;
146
210
  const runId = generateRunId();
147
211
  const trigger = options.trigger ?? DEFAULT_TRIGGER;
@@ -172,14 +236,33 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
172
236
  return { stagesCompleted: 0, success: false, error: MSG_HEADER_WRITE_FAILED(runId) };
173
237
  }
174
238
 
175
- const run = buildRunContext(cwd, workflow, options, {
176
- runId,
177
- state: freshRunState(options.input),
178
- visited: new Set(),
179
- trigger,
239
+ // Detach to the executor host (the executor relays UI back to the live session).
240
+ const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, runId, {
241
+ ...options,
242
+ name: options.name ?? workflow.name,
243
+ workflow: workflow.name,
244
+ input: options.input,
180
245
  });
181
246
 
182
- return executeRun(ctx, run, () => runStageOrRecordFailure(ctx, workflow.start, 0, run));
247
+ // `buildRunContext` is INSIDE the try so a throw there (e.g. countReachableStages
248
+ // on a malformed EdgeFn that bypassed load-time validation) still runs `dispose`
249
+ // — otherwise the onTerminalInput tap leaks, accumulating one per failed run.
250
+ try {
251
+ const run = buildRunContext(
252
+ cwd,
253
+ workflow,
254
+ { ...options, resolveModel, signal },
255
+ {
256
+ runId,
257
+ state: freshRunState(options.input),
258
+ visited: new Set(),
259
+ trigger,
260
+ },
261
+ );
262
+ return await executeRun(execCtx, run, () => runStageOrRecordFailure(execCtx, workflow.start, 0, run));
263
+ } finally {
264
+ dispose?.(); // unsubscribe the onTerminalInput tap — leaks accumulate on the TUI otherwise
265
+ }
183
266
  }
184
267
 
185
268
  export interface ResumeWorkflowOptions {
@@ -187,9 +270,9 @@ export interface ResumeWorkflowOptions {
187
270
  workflow: Workflow;
188
271
  /** Header of the run to resume — caller resolves via `resolveRun`. */
189
272
  header: WorkflowHeader;
190
- /** Required for "continue"-policy stages (host.sendUserMessage). */
273
+ /** Registry-level host — enumerated once for the skill-registration snapshot. */
191
274
  host?: WorkflowHost;
192
- /** Defaults to MAX_BACKWARD_JUMPS. */
275
+ /** Per-destination decision-edge re-entry cap. Defaults to MAX_BACKWARD_JUMPS. */
193
276
  maxBackwardJumps?: number;
194
277
  /** Run-wide safety cap on loop units (all kinds). Defaults to MAX_ITERATIONS. */
195
278
  maxIterations?: number;
@@ -199,6 +282,14 @@ export interface ResumeWorkflowOptions {
199
282
  lifecycle?: LifecycleListeners;
200
283
  /** Cooperative cancellation — see `RunWorkflowOptions.signal`. */
201
284
  signal?: AbortSignal;
285
+ /**
286
+ * Per-stage model-override resolver — see `RunWorkflowOptions.resolveModel`.
287
+ * Resumed stages resolve per-child models exactly like live; when omitted the
288
+ * detached executor's own `provider.resolveModel` is used (so a resume from the
289
+ * Pi launcher still honors per-skill overrides without the caller re-threading
290
+ * it). Undefined + no provider ⇒ host default for every resumed stage.
291
+ */
292
+ resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
202
293
  }
203
294
 
204
295
  /**
@@ -227,32 +318,35 @@ export async function resumeWorkflow(
227
318
  return { stagesCompleted: 0, success: false, error: resumeRefusalError(recon, header.workflow) };
228
319
  }
229
320
 
230
- const continueGuard = hostMissingForContinueStages(workflow, options.host);
231
- if (continueGuard) return { stagesCompleted: 0, success: false, error: continueGuard };
232
-
233
- const run = buildRunContext(cwd, workflow, options, {
234
- runId: header.runId, // SAME run — new rows append to the same file
235
- state: recon.state,
236
- visited: recon.visited,
237
- trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
321
+ // Detach to the executor host — the SAME wiring as live (L4-01). After the
322
+ // reconstruct refusal so a refused resume builds no host, but BEFORE
323
+ // `buildRunContext`/`executeRun` so every resumed stage (single-stage reattach,
324
+ // pending-fanout re-dispatch, or a cold-routed continue fork) runs against the
325
+ // real executor, not the bare launcher ctx. Same run id ⇒ same childSessionsDir,
326
+ // so reattach/fork resolve the original run's persisted child sessions.
327
+ const { execCtx, resolveModel, signal, dispose } = await detachExecutor(ctx, cwd, header.runId, {
328
+ ...options,
329
+ name: header.name ?? header.workflow,
330
+ workflow: header.workflow,
331
+ input: header.input,
238
332
  });
239
333
 
240
- return executeRun(ctx, run, selectResumeEntry(ctx, recon, run));
241
- }
242
-
243
- // ---------------------------------------------------------------------------
244
- // Entry helpers
245
- // ---------------------------------------------------------------------------
246
-
247
- /**
248
- * Continue-policy stages thread the prior session via the host's
249
- * `sendUserMessage`; with no host, `enforceSessionInvariants` would throw at
250
- * the first such stage. Reject at workflow entry so embedders get a clean
251
- * envelope instead of a throw. Returns the error message, or undefined if the
252
- * workflow is safe to run.
253
- */
254
- function hostMissingForContinueStages(workflow: Workflow, host: WorkflowHost | undefined): string | undefined {
255
- if (host !== undefined) return undefined;
256
- if (!Object.values(workflow.stages).some((s) => s.sessionPolicy === "continue")) return undefined;
257
- return "workflow contains continue-policy stages which require a workflow host";
334
+ // `buildRunContext` + `selectResumeEntry` are INSIDE the try so a throw in either
335
+ // still runs `dispose` (tap-leak parity with `runWorkflow`).
336
+ try {
337
+ const run = buildRunContext(
338
+ cwd,
339
+ workflow,
340
+ { ...options, resolveModel, signal },
341
+ {
342
+ runId: header.runId, // SAME run — new rows append to the same file
343
+ state: recon.state,
344
+ visited: recon.visited,
345
+ trigger: { kind: "command", name: "wf", meta: { resumedFrom: options.ref } },
346
+ },
347
+ );
348
+ return await executeRun(execCtx, run, selectResumeEntry(execCtx, recon, run));
349
+ } finally {
350
+ dispose?.(); // unsubscribe the onTerminalInput tap — parity with runWorkflow
351
+ }
258
352
  }
@@ -29,20 +29,13 @@
29
29
  */
30
30
 
31
31
  import type { ScriptContext } from "../api.js";
32
- import { auditCtxFor, failedArgs, recordTerminalFailure, terminate } from "../audit.js";
32
+ import { auditCtxFor, failAuditWrite, failedArgs, recordTerminalFailure } from "../audit.js";
33
33
  import { allocateStageNumber, persistStageSuccess } from "../audit-rows.js";
34
34
  import { lifecycleCtxFor, scriptStageRef } from "../events.js";
35
35
  import type { Artifact } from "../handle.js";
36
36
  import { formatError, nowIso } from "../internal-utils.js";
37
- import {
38
- FAIL_AUDIT_WRITE,
39
- FAIL_SCRIPT_THREW,
40
- FAIL_VALIDATION_EXHAUSTED,
41
- MSG_STAGE_COMPLETE,
42
- STATUS_KEY,
43
- STATUS_STAGE,
44
- } from "../messages.js";
45
- import { finalizeOutput, type Output } from "../output.js";
37
+ import { FAIL_SCRIPT_THREW, FAIL_VALIDATION_EXHAUSTED } from "../messages.js";
38
+ import { finalizeOutput, type Output, outputMeta } from "../output.js";
46
39
  import type { RunContext, WorkflowHostContext } from "../types.js";
47
40
  import {
48
41
  DEFAULT_VALIDATION_RETRIES,
@@ -70,8 +63,6 @@ export async function runScript(
70
63
  run: RunContext,
71
64
  advance: AdvanceFn,
72
65
  ): Promise<ChainOutcome> {
73
- curCtx.ui.setStatus(STATUS_KEY, STATUS_STAGE(stage.stageNumber, run.totalStages, stage.name));
74
-
75
66
  const ref = scriptStageRef(stage.name, stage.stageNumber);
76
67
  await run.lifecycle.fire(curCtx, "onStageStart", ref, lifecycleCtxFor(run));
77
68
 
@@ -90,36 +81,42 @@ export async function runScript(
90
81
  const result = await runValidationRetryLoop<Output, "recorded">(
91
82
  {
92
83
  maxRetries: stage.def.maxRetries ?? DEFAULT_VALIDATION_RETRIES,
93
- haltOnInvalid: (stage.def.onInvalid ?? "retry") === "halt",
84
+ failFast: (stage.def.onInvalid ?? "retry") === "halt",
94
85
  },
95
86
  {
96
87
  produce: async () => {
97
88
  const invocation = await invokeRun(curCtx, stage, scriptCtx, run, stageNumber);
98
- if (!invocation.ok) return { ok: false, halt: "recorded" };
99
- const output = finalizeOutput(invocation.raw, {
100
- stage: stage.name,
101
- stageNumber,
102
- ts: nowIso(),
103
- runId: run.runId,
104
- });
105
- return { ok: true, value: output };
89
+ if (!invocation.ok) return { kind: "aborted", abort: "recorded" };
90
+ const output = finalizeOutput(
91
+ invocation.raw,
92
+ outputMeta({
93
+ stage: stage.name,
94
+ stageNumber,
95
+ ts: nowIso(),
96
+ runId: run.runId,
97
+ }),
98
+ );
99
+ return { kind: "ok", value: output };
106
100
  },
107
101
  validate: async (output) => {
108
102
  if (!(stage.def.kind === "produces" && stage.def.outputSchema)) {
109
- return { ok: true, result: { valid: true, failures: [] } };
103
+ return { kind: "ok", result: { valid: true, failures: [] } };
110
104
  }
111
105
  // No catch: a throwing author schema propagates to the runner's
112
106
  // single catch site (today's contract).
113
- return { ok: true, result: await Promise.resolve(validateOutputData(stage.def.outputSchema, output.data)) };
107
+ return {
108
+ kind: "ok",
109
+ result: await Promise.resolve(validateOutputData(stage.def.outputSchema, output.data)),
110
+ };
114
111
  },
115
112
  onRetry: async (attempt) => {
116
113
  await run.lifecycle.fire(curCtx, "onStageRetry", ref, attempt, lifecycleCtxFor(run));
117
- return { ok: true };
114
+ return { kind: "ok" };
118
115
  },
119
116
  },
120
117
  );
121
118
 
122
- if (result.kind === "halt") return "halted";
119
+ if (result.kind === "aborted") return "halted";
123
120
  if (result.kind === "exhausted") {
124
121
  const failureSummary = result.failures.map(describeFailure).join("; ");
125
122
  await recordTerminalFailure(
@@ -140,12 +137,9 @@ export async function runScript(
140
137
  stage.def,
141
138
  );
142
139
  if (!persisted) {
143
- const auditFailure = FAIL_AUDIT_WRITE(stage.name);
144
- curCtx.ui.notify(auditFailure.toast, "error");
145
- terminate(run.state, { status: "failed", error: auditFailure.error });
140
+ failAuditWrite(curCtx, run.state, stage.name);
146
141
  return "halted";
147
142
  }
148
- curCtx.ui.notify(MSG_STAGE_COMPLETE(stage.name), "info");
149
143
 
150
144
  await run.lifecycle.fire(curCtx, "onStageEnd", ref, output, lifecycleCtxFor(run));
151
145
  return advance(curCtx, stage.name, idx, run);
package/schema-compat.ts CHANGED
@@ -20,8 +20,7 @@ import type { JsonSchemaObject } from "./json-schema.js";
20
20
  * producer's output schema and a consumer's input schema. Owned by the
21
21
  * engine that defines its semantics (this module); the contract domain
22
22
  * (`skill-contract.ts`) re-exports it so `CompositionComparator` consumers
23
- * stay self-contained (G7 — the old direction was a utility→domain
24
- * inversion).
23
+ * stay self-contained.
25
24
  */
26
25
  export interface SchemaCompatResult {
27
26
  ok: boolean;
package/semaphore.ts ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * semaphore.ts — bounded-concurrency gate for the parallel fanout dispatcher.
3
+ *
4
+ * `run(fn)` acquires a slot (queuing FIFO if `limit` are already in flight),
5
+ * runs `fn`, and releases on settle. When `signal` aborts, every QUEUED waiter
6
+ * rejects with a `WorkflowAbortError` so not-yet-started units never run;
7
+ * already-active children are aborted by the host (the dispatcher threads
8
+ * `signal` into each `spawnChild`). A fresh `acquire` after abort rejects
9
+ * immediately. `Semaphore(1)` serializes — the cursor/`state.named`
10
+ * representation is then identical to the sequential path.
11
+ */
12
+
13
+ import { WorkflowAbortError, WorkflowConfigError } from "./internal-utils.js";
14
+
15
+ export class Semaphore {
16
+ private active = 0;
17
+ private readonly queue: Array<{ resolve: () => void; reject: (e: unknown) => void }> = [];
18
+
19
+ constructor(
20
+ private readonly limit: number,
21
+ private readonly signal?: AbortSignal,
22
+ ) {
23
+ if (limit < 1) throw new WorkflowConfigError(`Semaphore limit must be ≥ 1, got ${limit}`);
24
+ signal?.addEventListener("abort", () => this.drain(), { once: true });
25
+ }
26
+
27
+ async run<T>(fn: () => Promise<T>): Promise<T> {
28
+ await this.acquire();
29
+ try {
30
+ return await fn();
31
+ } finally {
32
+ this.release();
33
+ }
34
+ }
35
+
36
+ private acquire(): Promise<void> {
37
+ if (this.signal?.aborted) return Promise.reject(new WorkflowAbortError());
38
+ if (this.active < this.limit) {
39
+ this.active++;
40
+ return Promise.resolve();
41
+ }
42
+ return new Promise<void>((resolve, reject) => this.queue.push({ resolve, reject }));
43
+ }
44
+
45
+ private release(): void {
46
+ const next = this.queue.shift();
47
+ if (next)
48
+ next.resolve(); // transfer the slot to the next waiter (active unchanged)
49
+ else this.active--;
50
+ }
51
+
52
+ private drain(): void {
53
+ while (this.queue.length > 0) this.queue.shift()?.reject(new WorkflowAbortError());
54
+ }
55
+ }