@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/api.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Public authoring surface for rpiv workflows — a BARREL since the M9 split.
2
+ * Public authoring surface for rpiv workflows — a BARREL.
3
3
  * Users import everything they need (`defineWorkflow`, `produces`, `acts`,
4
4
  * `defineRoute`, `gate`, `STOP`, `marksReadsData`, schema adapters, plus the
5
5
  * type vocabulary `Workflow` / `StageDef` / `EdgeFn` / `EdgeTarget` /
package/audit-ctx.ts ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Audit ctx + identity — the pure half of the audit layer.
3
+ *
4
+ * Moved out of `audit.ts` so the ctx construction this layer shares with the
5
+ * runner + sessions has its own module, decoupled from the impure
6
+ * terminal-outcome orchestration (`terminate`, the row writers, the notify
7
+ * + lifecycle fires) that stayed behind in `audit.ts`. `audit.ts` re-exports
8
+ * every symbol below, so existing `from "../audit.js"` import sites are
9
+ * unchanged; new code imports directly from `audit-ctx.ts`.
10
+ *
11
+ * Depends on events (value: `skillStageRef`) + types + state (type-only).
12
+ * Neither events nor the orchestrator imports back — one-way edges only.
13
+ */
14
+
15
+ import { skillStageRef } from "./events.js";
16
+ import type { SessionRef } from "./state/index.js";
17
+ import type { RunContext, SessionContext, UnitRef } from "./types.js";
18
+
19
+ /**
20
+ * Minimal bookkeeping ctx. Structurally derived from `SessionContext` so any
21
+ * future field added to the base lands here too — no duplicate
22
+ * maintenance. Every `StageSession` (single stage or loop unit) collapses to this.
23
+ *
24
+ * `isScript` toggles the `onStageError` ref construction in
25
+ * `recordTerminalFailure` from `skillStageRef` to `scriptStageRef` (the
26
+ * script branch carries no `skill` field). Defaulting to `undefined`
27
+ * preserves the skill-path behaviour for every existing caller.
28
+ *
29
+ * `unit` is present iff the failure/cancellation belongs to a loop unit — its
30
+ * identity is spread into the JSONL row so failed trailers carry the
31
+ * structured fields the resume guard consumes.
32
+ *
33
+ * `session` is REQUIRED (`null` = explicitly sessionless) — the compiler
34
+ * forces every audit-row writer to make the provenance decision; the value
35
+ * lands verbatim on the JSONL row (`WorkflowStage.session`), which is what
36
+ * session-backed resume dispatches on.
37
+ */
38
+ export type AuditCtx = Pick<
39
+ SessionContext,
40
+ "cwd" | "runId" | "state" | "stageName" | "skill" | "lifecycle" | "runIdentity" | "allocatedStageNumber"
41
+ > & {
42
+ session: SessionRef | null;
43
+ isScript?: boolean;
44
+ unit?: UnitRef;
45
+ };
46
+
47
+ /**
48
+ * The read-only run identity (`workflow` name + `totalStages` + `trigger`)
49
+ * threaded onto every `SessionContext` and `AuditCtx`. Single source for the
50
+ * `runIdentity` sub-literal that session/audit constructions across the runner
51
+ * would otherwise re-spell by hand.
52
+ */
53
+ export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
54
+ return { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger };
55
+ }
56
+
57
+ /**
58
+ * Build the `AuditCtx` `recordTerminalFailure` needs for a stage failure that
59
+ * escaped a session (preflight halts, downstream throws, routing errors,
60
+ * resume-time refusals). One source for the shape so every halt path records
61
+ * a uniform row. `isScript: true` drops the `skill` field from the JSONL row
62
+ * and switches `onStageError` to `scriptStageRef`.
63
+ *
64
+ * `session` is pinned to `null` here BY CONSTRUCTION: every caller of this
65
+ * builder records a failure that escaped (or never reached) a session —
66
+ * preflight halts, seam aborts, entry throws, routing errors, resume drift,
67
+ * script halts. In-session writers build their `AuditCtx` via `auditFor`
68
+ * (sessions/sessions.ts), which threads the captured `SessionRef`.
69
+ */
70
+ export function auditCtxFor(
71
+ run: RunContext,
72
+ stageName: string,
73
+ skill: string,
74
+ opts?: { isScript?: boolean; unit?: UnitRef; allocatedStageNumber?: number },
75
+ ): AuditCtx {
76
+ return {
77
+ cwd: run.cwd,
78
+ runId: run.runId,
79
+ state: run.state,
80
+ stageName,
81
+ skill,
82
+ session: null,
83
+ lifecycle: run.lifecycle,
84
+ runIdentity: runIdentityOf(run),
85
+ ...(opts?.isScript ? { isScript: true } : {}),
86
+ ...(opts?.unit ? { unit: opts.unit } : {}),
87
+ ...(opts?.allocatedStageNumber !== undefined ? { allocatedStageNumber: opts.allocatedStageNumber } : {}),
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Lifecycle ref for the CURRENT activation — ONE numbering base (the
93
+ * allocator value) for every event of one execution, so a listener can
94
+ * correlate a retry ref with the end/error ref it belongs to. Valid once the
95
+ * activation allocated its number (`allocatedStageNumber`); falls back to the
96
+ * last allocated number for record-time allocators (failure paths that never
97
+ * reached output production).
98
+ */
99
+ export function currentStageRef(
100
+ s: Pick<SessionContext, "stageName" | "skill" | "state" | "allocatedStageNumber">,
101
+ ): ReturnType<typeof skillStageRef> {
102
+ return skillStageRef(s.stageName, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill);
103
+ }
package/audit-rows.ts CHANGED
@@ -86,6 +86,24 @@ export function applyStageSuccess(state: RunState, def: StageDef, stageName: str
86
86
  applyCompletedStage(state, def, stageName, output);
87
87
  }
88
88
 
89
+ /**
90
+ * Roll the predecessor session forward after a single-stage success so a
91
+ * downstream `continue` stage forks it. THE single authority for this slot's
92
+ * write rule — the live success path (`recordStageSuccess`, sessions.ts) and the
93
+ * resume fold (`foldKnownStage`, resume.ts) both call it, so the null-handling
94
+ * can't drift between them.
95
+ *
96
+ * A `null` session (sessionless paths — script + side-effect stages persist
97
+ * `session: null`) LEAVES the slot untouched: those stages are transparent to
98
+ * the continuation chain, so a `continue` after one forks the most recent
99
+ * SESSION-BEARING predecessor on both live and resume. Loop-unit rows never
100
+ * reach here (they take the `s.unit` / `foldUnitRow` branch and never seed a
101
+ * continuation).
102
+ */
103
+ export function rollLastSession(state: RunState, session: SessionRef | null | undefined): void {
104
+ if (session != null) state.lastSession = session;
105
+ }
106
+
89
107
  /**
90
108
  * Persist a completed stage's success row, then apply its state effects —
91
109
  * the ONE live-path success persistence (skill sessions + script stages).
package/audit.ts CHANGED
@@ -5,37 +5,55 @@
5
5
  * status-line clear, the notify toast, the `terminate()` state write, and
6
6
  * the `onStageError` lifecycle fire.
7
7
  *
8
- * Depends on audit-rows + state + messages + events + handle. Shared by
9
- * the runner + sessions; neither imports back. Pure row persistence (the
10
- * allocator, `recordStage`, success persistence) lives in `audit-rows.ts`.
8
+ * Depends on audit-rows + audit-ctx + state + messages + events + handle.
9
+ * The pure ctx half (`AuditCtx`, `runIdentityOf`, `auditCtxFor`,
10
+ * `currentStageRef`) now lives in `audit-ctx.ts`; the terminal-args builders
11
+ * (`failedArgs`/`abortedArgs`/`TerminalFailureArgs`) live in `messages.ts`.
12
+ * Both are re-exported below so existing audit-layer consumers keep one
13
+ * import site; new code may import `audit-ctx.ts` / `messages.ts` directly.
14
+ * Shared by the runner + sessions; neither imports back. Pure row
15
+ * persistence (the allocator, `recordStage`, success persistence) lives in
16
+ * `audit-rows.ts`.
11
17
  */
12
18
 
19
+ import type { AuditCtx } from "./audit-ctx.js";
13
20
  import { recordStage, unitRowFields } from "./audit-rows.js";
14
21
  import { lifecycleCtxFromSession, scriptStageRef, skillStageRef } from "./events.js";
15
22
  import { handleToString } from "./handle.js";
16
23
  import { assertNever, nowIso } from "./internal-utils.js";
17
24
  import {
25
+ abortedArgs,
26
+ FAIL_AUDIT_WRITE,
18
27
  FAIL_STAGE_ABORTED,
19
28
  FAIL_STAGE_NO_RESPONSE,
20
29
  FAIL_STAGE_TOOL_STALLED,
21
30
  FAIL_STAGE_TRUNCATED,
22
- type FailureText,
31
+ failedArgs,
23
32
  MSG_FAILURE_ROW_DROPPED,
24
33
  MSG_PARTIAL_ARTIFACTS,
25
34
  MSG_STAGE_FAILED,
26
35
  MSG_WORKFLOW_CANCELLED,
27
- STATUS_KEY,
36
+ type TerminalFailureArgs,
28
37
  } from "./messages.js";
29
- import { listArtifacts, type SessionRef } from "./state/index.js";
38
+ import { listArtifacts } from "./state/index.js";
30
39
  import type { StopSignal } from "./transcript.js";
31
- import type { RunContext, RunState, RunTermination, SessionContext, UnitRef, WorkflowHostContext } from "./types.js";
40
+ import type { RunState, RunTermination, WorkflowHostContext } from "./types.js";
32
41
 
42
+ // Preserving barrel — the pre-split import surface is unchanged. Consumers
43
+ // (`sessions/`, `runner/`, `loop-kinds`, `loop-parallel`, `internal.ts`,
44
+ // `audit.test.ts`) keep importing `AuditCtx`/`runIdentityOf`/`auditCtxFor`/
45
+ // `currentStageRef`/`failedArgs`/`abortedArgs`/`TerminalFailureArgs` from
46
+ // "./audit.js" with no edit. Symbols now live in their post-split homes:
47
+ export type { AuditCtx } from "./audit-ctx.js";
48
+ export { auditCtxFor, currentStageRef, runIdentityOf } from "./audit-ctx.js";
33
49
  // Re-export the persistence half so existing audit-layer consumers keep one
34
50
  // import site; new code may import audit-rows.js directly.
35
51
  export { allocateStageNumber, decorateStage, recordStage, unitRowFields } from "./audit-rows.js";
52
+ export type { TerminalFailureArgs } from "./messages.js";
53
+ export { abortedArgs, failedArgs } from "./messages.js";
36
54
 
37
55
  /**
38
- * THE one `state.termination` mutator. Every terminal path — completion
56
+ * `state.termination` mutator. Every terminal path — completion
39
57
  * (`finalizeWorkflow`), failure/abort (`recordTerminalFailure`), cancellation
40
58
  * (`recordCancellation`), audit-write halts — lands its outcome through here,
41
59
  * so the union can never be half-set and a new outcome variant has one
@@ -47,89 +65,18 @@ export function terminate(state: RunState, outcome: Exclude<RunTermination, { st
47
65
  }
48
66
 
49
67
  /**
50
- * Minimal bookkeeping ctx. Structurally derived from `SessionContext` so any
51
- * future field added to the base lands here too — no duplicate
52
- * maintenance. Every `StageSession` (single stage or loop unit) collapses to this.
53
- *
54
- * `isScript` toggles the `onStageError` ref construction in
55
- * `recordTerminalFailure` from `skillStageRef` to `scriptStageRef` (the
56
- * script branch carries no `skill` field). Defaulting to `undefined`
57
- * preserves the skill-path behaviour for every existing caller.
58
- *
59
- * `unit` is present iff the failure/cancellation belongs to a loop unit — its
60
- * identity is spread into the JSONL row so failed trailers carry the
61
- * structured fields the resume guard consumes.
62
- *
63
- * `session` is REQUIRED (`null` = explicitly sessionless) — the compiler
64
- * forces every audit-row writer to make the provenance decision; the value
65
- * lands verbatim on the JSONL row (`WorkflowStage.session`), which is what
66
- * session-backed resume dispatches on.
67
- */
68
- export type AuditCtx = Pick<
69
- SessionContext,
70
- "cwd" | "runId" | "state" | "stageName" | "skill" | "lifecycle" | "runIdentity" | "allocatedStageNumber"
71
- > & {
72
- session: SessionRef | null;
73
- isScript?: boolean;
74
- unit?: UnitRef;
75
- };
76
-
77
- /**
78
- * The read-only run identity (`workflow` name + `totalStages` + `trigger`)
79
- * threaded onto every `SessionContext` and `AuditCtx`. Single source for the
80
- * `runIdentity` sub-literal that session/audit constructions across the runner
81
- * would otherwise re-spell by hand.
82
- */
83
- export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
84
- return { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger };
85
- }
86
-
87
- /**
88
- * Build the `AuditCtx` `recordTerminalFailure` needs for a stage failure that
89
- * escaped a session (preflight halts, downstream throws, routing errors,
90
- * resume-time refusals). One source for the shape so every halt path records
91
- * a uniform row. `isScript: true` drops the `skill` field from the JSONL row
92
- * and switches `onStageError` to `scriptStageRef`.
93
- *
94
- * `session` is pinned to `null` here BY CONSTRUCTION: every caller of this
95
- * builder records a failure that escaped (or never reached) a session —
96
- * preflight halts, seam aborts, entry throws, routing errors, resume drift,
97
- * script halts. In-session writers build their `AuditCtx` via `auditFor`
98
- * (sessions/sessions.ts), which threads the captured `SessionRef`.
68
+ * Terminal halt for "the success row failed to persist." The audit JSONL is the
69
+ * run's system of record, so a dropped append leaves state un-advanced and ends
70
+ * the run. Notify+terminate idiom shared by the skill/unit success
71
+ * path (`recordStageSuccess`, sessions.ts) and the script path
72
+ * (`runScript`, script-stage.ts); each caller maps the void return to its own
73
+ * halt token (`false` / `"halted"`). `subject` is the skill (or stage) the
74
+ * failure message names.
99
75
  */
100
- export function auditCtxFor(
101
- run: RunContext,
102
- stageName: string,
103
- skill: string,
104
- opts?: { isScript?: boolean; unit?: UnitRef; allocatedStageNumber?: number },
105
- ): AuditCtx {
106
- return {
107
- cwd: run.cwd,
108
- runId: run.runId,
109
- state: run.state,
110
- stageName,
111
- skill,
112
- session: null,
113
- lifecycle: run.lifecycle,
114
- runIdentity: runIdentityOf(run),
115
- ...(opts?.isScript ? { isScript: true } : {}),
116
- ...(opts?.unit ? { unit: opts.unit } : {}),
117
- ...(opts?.allocatedStageNumber !== undefined ? { allocatedStageNumber: opts.allocatedStageNumber } : {}),
118
- };
119
- }
120
-
121
- /**
122
- * Lifecycle ref for the CURRENT activation — ONE numbering base (the
123
- * allocator value) for every event of one execution, so a listener can
124
- * correlate a retry ref with the end/error ref it belongs to. Valid once the
125
- * activation allocated its number (`allocatedStageNumber`); falls back to the
126
- * last allocated number for record-time allocators (failure paths that never
127
- * reached output production).
128
- */
129
- export function currentStageRef(
130
- s: Pick<SessionContext, "stageName" | "skill" | "state" | "allocatedStageNumber">,
131
- ): ReturnType<typeof skillStageRef> {
132
- return skillStageRef(s.stageName, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill);
76
+ export function failAuditWrite(ctx: WorkflowHostContext, state: RunState, subject: string): void {
77
+ const failure = FAIL_AUDIT_WRITE(subject);
78
+ ctx.ui.notify(failure.toast, "error");
79
+ terminate(state, { status: "failed", error: failure.error });
133
80
  }
134
81
 
135
82
  /** Surface every artifact recorded so far — recap on stage failure. */
@@ -141,36 +88,33 @@ export function notifyPartialArtifacts(ctx: WorkflowHostContext, cwd: string, ru
141
88
  }
142
89
 
143
90
  /**
144
- * The toast + JSONL halves of a terminal failure, paired by construction.
145
- * Build via `failedArgs` / `abortedArgs` (or `stopFailureArgs`' switch) so a
146
- * halt site can't mismatch status and notify level.
147
- */
148
- export interface TerminalFailureArgs {
149
- status: "failed" | "aborted";
150
- notifyMsg: string;
151
- notifyLevel: "warning" | "error";
152
- errMsg: string;
153
- }
154
-
155
- /**
156
- * Argument constructors for `recordTerminalFailure` — the
157
- * `{status, notifyMsg, notifyLevel, errMsg}` quadruple every halt site used
158
- * to spell by hand. One per terminal status: failures notify at `"error"`,
159
- * aborts at `"warning"` (cooperative cancellation is expected, not
160
- * exceptional).
91
+ * Terminal/halt/cancellation row-write authority. `recordStage` + the
92
+ * dropped-row guard (notify + telemetry) — the side effects the three writers
93
+ * (`recordTerminalFailure` / `recordUnitHalt` / `recordCancellation`) share.
94
+ * Each caller builds its row fields (terminal `args.status`; halt
95
+ * `collected:true`; cancellation `status:"skipped"`) and delegates the write +
96
+ * guard here, so the dropped-failure-row invariant — a dropped row corrupts
97
+ * resume: the trail's last row reads "completed" and a later resume routes
98
+ * onward past the stage — is enforced ONCE (parity contract, precedent
99
+ * `advanceCursor` at loop.ts). Returns the assigned stageNumber on success
100
+ * (undefined on drop), matching `audit-rows.ts:recordStage`'s contract.
101
+ *
102
+ * "terminal" here is the RUN-OUTCOME sense (a failure/cancellation that ends
103
+ * the run) — distinct from the `terminal()` stage factory (stage-def.ts) and
104
+ * the graph-sink `edge.mode: "terminal"` (loop-constructors.ts). See the
105
+ * glossary on `stage-def.ts`'s `terminal` export.
161
106
  */
162
- export function failedArgs(failure: FailureText): TerminalFailureArgs;
163
- export function failedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
164
- export function failedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
165
- const f = typeof a === "string" ? { toast: a, error: b as string } : a;
166
- return { status: "failed", notifyMsg: f.toast, notifyLevel: "error", errMsg: f.error };
167
- }
168
-
169
- export function abortedArgs(failure: FailureText): TerminalFailureArgs;
170
- export function abortedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
171
- export function abortedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
172
- const f = typeof a === "string" ? { toast: a, error: b as string } : a;
173
- return { status: "aborted", notifyMsg: f.toast, notifyLevel: "warning", errMsg: f.error };
107
+ function writeFailureRow(
108
+ ctx: WorkflowHostContext,
109
+ audit: AuditCtx,
110
+ row: Parameters<typeof recordStage>[2],
111
+ ): number | undefined {
112
+ const written = recordStage(audit.cwd, audit.runId, row, audit.state, audit.allocatedStageNumber);
113
+ if (written === undefined) {
114
+ ctx.ui.notify(MSG_FAILURE_ROW_DROPPED(audit.stageName), "warning");
115
+ audit.state.telemetry.droppedFailureRows.push(audit.stageName);
116
+ }
117
+ return written;
174
118
  }
175
119
 
176
120
  export async function recordTerminalFailure(
@@ -179,37 +123,27 @@ export async function recordTerminalFailure(
179
123
  args: TerminalFailureArgs,
180
124
  onFailure?: (ctx: WorkflowHostContext) => void,
181
125
  ): Promise<void> {
182
- const written = recordStage(
183
- audit.cwd,
184
- audit.runId,
126
+ // First-failure-wins: under parallel fanout dispatch with
127
+ // `failFast`, two siblings can fail near-simultaneously and BOTH reach here.
128
+ // This writer is NOT status-gated, so without this guard it would write two
129
+ // terminal rows + fire `onStageError` twice + `terminate()` twice. Skip the
130
+ // duplicate so the trail records the ONE original failure.
131
+ // Harmless on the sequential path (always `"running"` at the
132
+ // first and only terminal failure).
133
+ if (audit.state.termination.status !== "running") return;
134
+ writeFailureRow(ctx, audit, {
135
+ stage: audit.stageName,
185
136
  // Script-stage failure rows omit `skill` (the row split landed in A.0);
186
137
  // skill rows continue to carry it. `undefined` is dropped by JSON.stringify.
187
138
  // `errMsg` mirrors `state.termination.error` so the failure reason
188
139
  // survives in JSONL even when the `ctx.ui.notify` toast is missed.
189
- {
190
- stage: audit.stageName,
191
- skill: audit.isScript ? undefined : audit.skill,
192
- status: args.status,
193
- ts: nowIso(),
194
- errMsg: args.errMsg,
195
- session: audit.session,
196
- ...unitRowFields(audit.unit),
197
- },
198
- audit.state,
199
- // Reuse the activation's pre-allocated number when output production
200
- // already burned one — the failure row carries the SAME stage number
201
- // the activation's output/lifecycle refs used (no gap, no skew).
202
- audit.allocatedStageNumber,
203
- );
204
- if (written === undefined) {
205
- // A dropped FAILURE row corrupts resume: the trail's last row reads
206
- // "completed" and a resume would route onward past this stage. The run
207
- // is already halting — surface loudly + flag the envelope so callers
208
- // know the trail is unsafe to resume from.
209
- ctx.ui.notify(MSG_FAILURE_ROW_DROPPED(audit.stageName), "warning");
210
- audit.state.telemetry.droppedFailureRows.push(audit.stageName);
211
- }
212
- ctx.ui.setStatus(STATUS_KEY, undefined);
140
+ skill: audit.isScript ? undefined : audit.skill,
141
+ status: args.status,
142
+ ts: nowIso(),
143
+ errMsg: args.errMsg,
144
+ session: audit.session,
145
+ ...unitRowFields(audit.unit),
146
+ });
213
147
  ctx.ui.notify(args.notifyMsg, args.notifyLevel);
214
148
  onFailure?.(ctx);
215
149
  terminate(audit.state, { status: args.status, error: args.errMsg });
@@ -219,6 +153,29 @@ export async function recordTerminalFailure(
219
153
  await audit.lifecycle.fire(ctx, "onStageError", ref, args.errMsg, lifecycleCtxFromSession(audit));
220
154
  }
221
155
 
156
+ /**
157
+ * Persist a NON-TERMINAL failed unit row (collect-all fanout): the unit halted,
158
+ * but the run survives and the synthesis stage sees a failed slot. Mirrors
159
+ * `recordTerminalFailure`'s `recordStage` write (same unit fields, same
160
+ * pre-allocated number) WITHOUT `terminate()` (the only state mutation it skips)
161
+ * and WITHOUT the `onStageError` fire (this is not a hard fail). The row carries
162
+ * `collected: true` so the resume fold can tell it apart from a hard
163
+ * `recordTerminalFailure` row (byte-identical otherwise) and rebuild the
164
+ * `failedOutput` sentinel by `unitIndex` instead of re-dispatching it.
165
+ */
166
+ export function recordUnitHalt(ctx: WorkflowHostContext, audit: AuditCtx, errMsg: string): void {
167
+ writeFailureRow(ctx, audit, {
168
+ stage: audit.stageName,
169
+ skill: audit.isScript ? undefined : audit.skill,
170
+ status: "failed",
171
+ collected: true, // distinguishes a soft collect-all halt from a hard terminal failure on resume
172
+ ts: nowIso(),
173
+ errMsg,
174
+ session: audit.session,
175
+ ...unitRowFields(audit.unit),
176
+ });
177
+ }
178
+
222
179
  /**
223
180
  * One arm per StopSignal variant (minus `"stop"`, the success path).
224
181
  * JSONL `status` stays `"aborted" | "failed"` for downstream-reader
@@ -253,25 +210,23 @@ function stopFailureArgs(skill: string, stop: Exclude<StopSignal, "stop">, error
253
210
  }
254
211
 
255
212
  export function recordCancellation(ctx: WorkflowHostContext, audit: AuditCtx): void {
256
- // Cancellation is a first-class termination outcome (`status: "cancelled"`);
257
- // `errMsg` is mirrored into the JSONL row so post-mortems work from the
258
- // trail alone (same posture as `recordTerminalFailure`).
213
+ // Cancellation is a first-class termination outcome: the canonical in-memory
214
+ // name is `RunTermination.status: "cancelled"` (types.ts), but the JSONL row
215
+ // is written with the FROZEN `StageStatus: "skipped"` (state/state.ts) — a
216
+ // deliberate split (the row value is a versioned on-disk contract; renaming
217
+ // it would break resume + every past-run reader). THIS is the sole writer of
218
+ // a `"skipped"` row. `errMsg` is mirrored into the row so post-mortems work
219
+ // from the trail alone (same posture as `recordTerminalFailure`).
259
220
  const errMsg = `${audit.skill} cancelled by user`;
260
- recordStage(
261
- audit.cwd,
262
- audit.runId,
263
- {
264
- stage: audit.stageName,
265
- skill: audit.skill,
266
- status: "skipped",
267
- ts: nowIso(),
268
- errMsg,
269
- session: audit.session,
270
- ...unitRowFields(audit.unit),
271
- },
272
- audit.state,
273
- );
274
- ctx.ui.setStatus(STATUS_KEY, undefined);
221
+ writeFailureRow(ctx, audit, {
222
+ stage: audit.stageName,
223
+ skill: audit.skill,
224
+ status: "skipped",
225
+ ts: nowIso(),
226
+ errMsg,
227
+ session: audit.session,
228
+ ...unitRowFields(audit.unit),
229
+ });
275
230
  ctx.ui.notify(MSG_WORKFLOW_CANCELLED, "info");
276
231
  terminate(audit.state, { status: "cancelled", error: errMsg });
277
232
  }
package/built-ins.ts CHANGED
@@ -24,16 +24,24 @@ import type { Workflow } from "./api.js";
24
24
  import { globalSlot, lazyProviderRegistry } from "./internal-utils.js";
25
25
 
26
26
  const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-ins");
27
+ const FAILURES_KEY = Symbol.for("@juicesharp/rpiv-workflow:built-in-provider-failures");
27
28
 
28
29
  const getRegistry = globalSlot(REGISTRY_KEY, () => [] as Workflow[]);
29
- // Provider lifecycle (register / flush-on-demand; each provider runs once,
30
- // post-flush registrations run on the next flush — `/reload` re-registration
31
- // refreshes) via the shared `lazyProviderRegistry` helper — same global-slot
30
+ const getFailures = globalSlot(FAILURES_KEY, () => [] as unknown[]);
31
+ // Provider lifecycle via the shared `lazyProviderRegistry` — same global-slot
32
32
  // strategy as the registry, so a duplicate module load shares one
33
33
  // process-wide state. Safe to re-flush: `registerBuiltIns` replaces by name.
34
- // No `onError`: built-in providers are trusted in-process code, a throw
35
- // propagates to the awaiting `loadWorkflows` caller.
36
- const providers = lazyProviderRegistry("@juicesharp/rpiv-workflow:built-in-providers");
34
+ // `onError` RECORDS each provider throw (drained by `drainBuiltInProviderErrors`)
35
+ // instead of propagating, so `loadWorkflows` honors its never-throws contract: a
36
+ // throwing provider degrades to a partial/empty registry instead of crashing
37
+ // `/wf`, but the error is NOT swallowed silently — `loadWorkflows` surfaces it as
38
+ // a LoadIssue so a buggy provider is debuggable. Same posture as the
39
+ // skill-contracts registry.
40
+ const providers = lazyProviderRegistry("@juicesharp/rpiv-workflow:built-in-providers", {
41
+ onError: (err) => {
42
+ getFailures().push(err);
43
+ },
44
+ });
37
45
 
38
46
  /**
39
47
  * Register one or more workflows into the `built-in` layer. Idempotent on
@@ -69,6 +77,17 @@ export function flushBuiltInProviders(): Promise<void> {
69
77
  return providers.flush();
70
78
  }
71
79
 
80
+ /**
81
+ * Drain (return + clear) the errors recorded by failed built-in providers since
82
+ * the last drain. `loadWorkflows` calls this right after the flush and maps each
83
+ * into a `LoadIssue`, so a provider bug surfaces in `loaded.issues` instead of
84
+ * vanishing. Internal — not on the public barrel (mirrors
85
+ * `drainSkillContractProviderErrors`).
86
+ */
87
+ export function drainBuiltInProviderErrors(): unknown[] {
88
+ return getFailures().splice(0);
89
+ }
90
+
72
91
  /** Read-only view of the registry — consumed by `load.ts`. */
73
92
  export function getBuiltIns(): readonly Workflow[] {
74
93
  return getRegistry();
@@ -81,4 +100,5 @@ export function getBuiltIns(): readonly Workflow[] {
81
100
  export function __resetBuiltIns(): void {
82
101
  getRegistry().length = 0;
83
102
  providers.reset();
103
+ getFailures().length = 0;
84
104
  }