@juicesharp/rpiv-workflow 1.19.1 → 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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
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 ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Audit-row persistence — the pure half of the audit layer. Owns the
3
+ * monotonic stage-number allocator, JSONL stage-row appends, the structured
4
+ * unit-row projection, and the shared success persistence/apply pair the
5
+ * skill path, the script path, and the resume fold all run through.
6
+ *
7
+ * Depends only on state, chain-state, and generic utils — NO UI, NO
8
+ * lifecycle dispatch. Terminal-outcome orchestration (notify + status-line
9
+ * + lifecycle events + `terminate`) lives in `audit.ts`.
10
+ */
11
+
12
+ import type { StageDef } from "./api.js";
13
+ import { applyCompletedStage } from "./chain-state.js";
14
+ import { nowIso } from "./internal-utils.js";
15
+ import type { Output } from "./output.js";
16
+ import { appendStage, type SessionRef, type WorkflowStage } from "./state/index.js";
17
+ import type { RunState, UnitRef } from "./types.js";
18
+
19
+ /**
20
+ * Advance the monotonic stage-number allocator and return the assigned
21
+ * number. Call ONCE per stage activation, BEFORE the activation's output
22
+ * envelope is built — the envelope's `meta.stageNumber`, the JSONL row, and
23
+ * every lifecycle ref for the activation then share one explicit value
24
+ * instead of peeking `lastAllocatedStageNumber + 1` and relying on a
25
+ * "no record in between" convention.
26
+ */
27
+ export function allocateStageNumber(state: RunState): number {
28
+ state.lastAllocatedStageNumber += 1;
29
+ return state.lastAllocatedStageNumber;
30
+ }
31
+
32
+ /**
33
+ * Attempts the append and returns the assigned `stageNumber` on success (or
34
+ * undefined on I/O failure). The number comes from `preAllocated` when the
35
+ * activation already ran `allocateStageNumber` (output-producing paths), or
36
+ * is allocated here (pre-output halts). Either way the allocator advances
37
+ * monotonically — once per activation — so a transient failure doesn't cause
38
+ * the next stage to reuse the lost row's number. Higher-level counters
39
+ * (e.g. `stagesCompleted`) gate on the returned value being defined.
40
+ */
41
+ export function recordStage(
42
+ cwd: string,
43
+ runId: string,
44
+ stage: Omit<WorkflowStage, "stageNumber">,
45
+ state: RunState,
46
+ preAllocated?: number,
47
+ ): number | undefined {
48
+ const stageNumber = preAllocated ?? allocateStageNumber(state);
49
+ return appendStage(cwd, runId, { stageNumber, ...stage }) ? stageNumber : undefined;
50
+ }
51
+
52
+ /**
53
+ * DISPLAY decoration for a loop-unit row's `stage` value —
54
+ * `"implement (phase-2)"`, `"breakdown (r0·judge)"`. Pure human label: the
55
+ * machine channel is the structured `parent`/`role`/`unitId`/`unitIndex`
56
+ * fields (`unitRowFields`); nothing may parse this string back. The driver
57
+ * builds the tag (`unit.id ?? unit.label` for fanout/iterate;
58
+ * `r{round}·{phase}` for assess) and decorates once at session construction.
59
+ */
60
+ export const decorateStage = (parent: string, tag: string): string => `${parent} (${tag})`;
61
+
62
+ /**
63
+ * Project a session's unit identity into the structured row fields. Returns
64
+ * `{}` for single stages so call sites spread unconditionally —
65
+ * `JSON.stringify` drops nothing because nothing is added.
66
+ */
67
+ export function unitRowFields(
68
+ unit: UnitRef | undefined,
69
+ ): Pick<WorkflowStage, "parent" | "role" | "unitId" | "unitIndex"> {
70
+ if (!unit) return {};
71
+ return { parent: unit.parent, role: unit.role, unitId: unit.id, unitIndex: unit.index };
72
+ }
73
+
74
+ /**
75
+ * Apply a completed stage's effects to `RunState` — the I/O-free half of
76
+ * success persistence, and exactly what the resume fold replays per
77
+ * completed row: advance the completion counter, roll `state.output`, and
78
+ * advance the artifact slots via the `applyCompletedStage` authority.
79
+ * `output` may be absent (defensive — completed rows normally carry one);
80
+ * the counter still advances, matching the fold's semantics.
81
+ */
82
+ export function applyStageSuccess(state: RunState, def: StageDef, stageName: string, output: Output | undefined): void {
83
+ state.stagesCompleted++;
84
+ if (!output) return;
85
+ state.output = output;
86
+ applyCompletedStage(state, def, stageName, output);
87
+ }
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
+
107
+ /**
108
+ * Persist a completed stage's success row, then apply its state effects —
109
+ * the ONE live-path success persistence (skill sessions + script stages).
110
+ * Returns `true` iff the JSONL row landed; on `false` the state is left at
111
+ * its prior values (output is set iff the row that carried it landed) and
112
+ * the CALLER owns the halt (notify + `terminate` — the wording differs per
113
+ * path). The resume fold runs `applyStageSuccess` directly (its rows are
114
+ * already on disk).
115
+ */
116
+ export function persistStageSuccess(
117
+ state: RunState,
118
+ row: {
119
+ cwd: string;
120
+ runId: string;
121
+ stage: string;
122
+ /** Omitted on script-stage rows — JSON.stringify drops `undefined`. */
123
+ skill?: string;
124
+ output: Output;
125
+ /**
126
+ * REQUIRED: the Pi session that backed the activation, or `null` for
127
+ * sessionless paths (script stages) — the row serializes it verbatim.
128
+ */
129
+ session: SessionRef | null;
130
+ unit?: UnitRef;
131
+ /** The activation's pre-allocated number (output-producing paths). */
132
+ preAllocated?: number;
133
+ },
134
+ def: StageDef,
135
+ ): boolean {
136
+ const assigned = recordStage(
137
+ row.cwd,
138
+ row.runId,
139
+ {
140
+ stage: row.stage,
141
+ skill: row.skill,
142
+ status: "completed",
143
+ ts: nowIso(),
144
+ output: row.output,
145
+ session: row.session,
146
+ ...unitRowFields(row.unit),
147
+ },
148
+ state,
149
+ row.preAllocated,
150
+ );
151
+ if (assigned === undefined) return false;
152
+ applyStageSuccess(state, def, row.stage, row.output);
153
+ return true;
154
+ }
package/audit.ts CHANGED
@@ -1,127 +1,82 @@
1
1
  /**
2
- * Audit / bookkeeping — JSONL writes, status-line clears, notify, and
3
- * `state.termination.error` for terminal outcomes. Shared by runner.ts + sessions.ts;
4
- * neither imports back. Depends only on state + messages.
2
+ * Terminal-outcome orchestration — the impure half of the audit layer.
3
+ * Turns a halt reason into the full bundle a terminal outcome owes the
4
+ * user and the system: the JSONL failure row (via `audit-rows.ts`), the
5
+ * status-line clear, the notify toast, the `terminate()` state write, and
6
+ * the `onStageError` lifecycle fire.
7
+ *
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`.
5
17
  */
6
18
 
19
+ import type { AuditCtx } from "./audit-ctx.js";
20
+ import { recordStage, unitRowFields } from "./audit-rows.js";
21
+ import { lifecycleCtxFromSession, scriptStageRef, skillStageRef } from "./events.js";
7
22
  import { handleToString } from "./handle.js";
8
- import { assertNever } from "./internal-utils.js";
9
- import { buildLifecycleContext, scriptStageRef, skillStageRef } from "./lifecycle.js";
23
+ import { assertNever, nowIso } from "./internal-utils.js";
10
24
  import {
11
- ERR_STAGE_ABORTED,
12
- ERR_STAGE_NO_RESPONSE,
13
- ERR_STAGE_TOOL_STALLED,
14
- ERR_STAGE_TRUNCATED,
25
+ abortedArgs,
26
+ FAIL_AUDIT_WRITE,
27
+ FAIL_STAGE_ABORTED,
28
+ FAIL_STAGE_NO_RESPONSE,
29
+ FAIL_STAGE_TOOL_STALLED,
30
+ FAIL_STAGE_TRUNCATED,
31
+ failedArgs,
32
+ MSG_FAILURE_ROW_DROPPED,
15
33
  MSG_PARTIAL_ARTIFACTS,
16
- MSG_STAGE_ABORTED,
17
34
  MSG_STAGE_FAILED,
18
- MSG_STAGE_NO_RESPONSE,
19
- MSG_STAGE_TOOL_STALLED,
20
- MSG_STAGE_TRUNCATED,
21
35
  MSG_WORKFLOW_CANCELLED,
22
- STATUS_KEY,
36
+ type TerminalFailureArgs,
23
37
  } from "./messages.js";
24
- import { appendStage, listArtifacts, type WorkflowStage } from "./state/index.js";
38
+ import { listArtifacts } from "./state/index.js";
25
39
  import type { StopSignal } from "./transcript.js";
26
- import type { FanoutSession, RunContext, RunState, SessionContext, WorkflowHostContext } from "./types.js";
27
-
28
- /** Single source of ISO-8601 timestamps for audit rows + output meta. */
29
- export const nowIso = (): string => new Date().toISOString();
30
-
31
- /**
32
- * Minimal bookkeeping ctx. Structurally derived from `SessionContext` so any
33
- * future field added to the base lands here too — no duplicate
34
- * maintenance. Both `StageSession` and `FanoutSession` collapse to this.
35
- *
36
- * `isScript` toggles the `onStageError` ref construction in
37
- * `recordTerminalFailure` from `skillStageRef` to `scriptStageRef` (the
38
- * script branch carries no `skill` field). Defaulting to `undefined`
39
- * preserves the skill-path behaviour for every existing caller.
40
- */
41
- export type AuditCtx = Pick<
42
- SessionContext,
43
- "cwd" | "runId" | "state" | "stageName" | "skill" | "lifecycle" | "runIdentity"
44
- > & {
45
- isScript?: boolean;
46
- };
40
+ import type { RunState, RunTermination, WorkflowHostContext } from "./types.js";
47
41
 
48
- /**
49
- * The read-only run identity (`workflow` name + `totalStages` + `trigger`)
50
- * threaded onto every `SessionContext` and `AuditCtx`. Single source for the
51
- * `runIdentity` sub-literal that session/audit constructions across the runner
52
- * would otherwise re-spell by hand.
53
- */
54
- export function runIdentityOf(run: RunContext): SessionContext["runIdentity"] {
55
- return { workflow: run.workflow.name, totalStages: run.totalStages, trigger: run.trigger };
56
- }
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";
49
+ // Re-export the persistence half so existing audit-layer consumers keep one
50
+ // import site; new code may import audit-rows.js directly.
51
+ export { allocateStageNumber, decorateStage, recordStage, unitRowFields } from "./audit-rows.js";
52
+ export type { TerminalFailureArgs } from "./messages.js";
53
+ export { abortedArgs, failedArgs } from "./messages.js";
57
54
 
58
55
  /**
59
- * Build the `AuditCtx` `recordTerminalFailure` needs for a stage failure that
60
- * escaped a session (preflight halts, downstream throws, routing errors,
61
- * resume-time refusals). One source for the shape so every halt path records
62
- * a uniform row. `isScript: true` drops the `skill` field from the JSONL row
63
- * and switches `onStageError` to `scriptStageRef`.
56
+ * `state.termination` mutator. Every terminal path — completion
57
+ * (`finalizeWorkflow`), failure/abort (`recordTerminalFailure`), cancellation
58
+ * (`recordCancellation`), audit-write halts — lands its outcome through here,
59
+ * so the union can never be half-set and a new outcome variant has one
60
+ * write-site to thread through. Last write wins (a failure recorded after an
61
+ * earlier failure on the same unwind keeps today's semantics).
64
62
  */
65
- export function auditCtxFor(
66
- run: RunContext,
67
- stageName: string,
68
- skill: string,
69
- opts?: { isScript?: boolean },
70
- ): AuditCtx {
71
- return {
72
- cwd: run.cwd,
73
- runId: run.runId,
74
- state: run.state,
75
- stageName,
76
- skill,
77
- lifecycle: run.lifecycle,
78
- runIdentity: runIdentityOf(run),
79
- ...(opts?.isScript ? { isScript: true } : {}),
80
- };
63
+ export function terminate(state: RunState, outcome: Exclude<RunTermination, { status: "running" }>): void {
64
+ state.termination = outcome;
81
65
  }
82
66
 
83
67
  /**
84
- * JSONL `WorkflowStage.stage` value for fanout-unit rows — built from
85
- * the parent stage's record key (`stageName`) suffixed with the
86
- * user-supplied `id` when present, falling back to `label`
87
- * (e.g. `"implement (phase-2)"` or `"implement (phase 2/4)"`) so
88
- * post-hoc readers can distinguish loop iterations. Owned by the audit
89
- * layer because the JSONL row shape is its concern; the runner stays
90
- * neutral about the wording.
91
- */
92
- export const fanoutRowStage = (s: FanoutSession): string => `${s.stageName} (${s.id ?? s.label})`;
93
-
94
- /**
95
- * JSONL `WorkflowStage.stage` value for iterate-unit rows. Same projection as
96
- * `fanoutRowStage` — the parent stage's record key suffixed with the unit's
97
- * `id ?? label` (e.g. `"blueprint (phase-2)"`) so post-hoc readers can tell
98
- * the accumulated units apart. Takes the decorated parts directly (rather than
99
- * a session) because the iterate executor synthesizes the `StageSession` after
100
- * building this label. Decoration is SAFE for named keying: iterate mandates
101
- * `outcome.name`, so `resolvePublishName` ignores the decorated `stageName`
102
- * and every unit publishes to the same `state.named` slot.
103
- */
104
- export const iterateRowStage = (stageName: string, tag: string): string => `${stageName} (${tag})`;
105
-
106
- /**
107
- * Allocates the next `stageNumber`, attempts the append, and returns the
108
- * assigned number on success (or undefined on I/O failure). `lastAllocatedStageNumber`
109
- * advances monotonically — once per call — so a transient failure doesn't
110
- * cause the next stage to reuse the lost row's number. Higher-level counters
111
- * (e.g. `stagesCompleted`) gate on the returned value being defined.
112
- *
113
- * `wrapOutput`'s `state.lastAllocatedStageNumber + 1` peek aligns with this allocation
114
- * because the output is built BEFORE recordStage is called.
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.
115
75
  */
116
- export function recordStage(
117
- cwd: string,
118
- runId: string,
119
- stage: Omit<WorkflowStage, "stageNumber">,
120
- state: RunState,
121
- ): number | undefined {
122
- state.lastAllocatedStageNumber += 1;
123
- const stageNumber = state.lastAllocatedStageNumber;
124
- return appendStage(cwd, runId, { stageNumber, ...stage }) ? stageNumber : undefined;
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 });
125
80
  }
126
81
 
127
82
  /** Surface every artifact recorded so far — recap on stage failure. */
@@ -132,54 +87,93 @@ export function notifyPartialArtifacts(ctx: WorkflowHostContext, cwd: string, ru
132
87
  ctx.ui.notify(MSG_PARTIAL_ARTIFACTS(artifactList), "info");
133
88
  }
134
89
 
90
+ /**
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.
106
+ */
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;
118
+ }
119
+
135
120
  export async function recordTerminalFailure(
136
121
  ctx: WorkflowHostContext,
137
122
  audit: AuditCtx,
138
- args: {
139
- status: "failed" | "aborted";
140
- notifyMsg: string;
141
- notifyLevel: "warning" | "error";
142
- errMsg: string;
143
- },
123
+ args: TerminalFailureArgs,
144
124
  onFailure?: (ctx: WorkflowHostContext) => void,
145
125
  ): Promise<void> {
146
- recordStage(
147
- audit.cwd,
148
- 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,
149
136
  // Script-stage failure rows omit `skill` (the row split landed in A.0);
150
137
  // skill rows continue to carry it. `undefined` is dropped by JSON.stringify.
151
138
  // `errMsg` mirrors `state.termination.error` so the failure reason
152
139
  // survives in JSONL even when the `ctx.ui.notify` toast is missed.
153
- {
154
- stage: audit.stageName,
155
- skill: audit.isScript ? undefined : audit.skill,
156
- status: args.status,
157
- ts: nowIso(),
158
- errMsg: args.errMsg,
159
- },
160
- audit.state,
161
- );
162
- 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
+ });
163
147
  ctx.ui.notify(args.notifyMsg, args.notifyLevel);
164
148
  onFailure?.(ctx);
165
- audit.state.termination.error = args.errMsg;
149
+ terminate(audit.state, { status: args.status, error: args.errMsg });
166
150
  const ref = audit.isScript
167
151
  ? scriptStageRef(audit.stageName, audit.state.lastAllocatedStageNumber)
168
152
  : skillStageRef(audit.stageName, audit.state.lastAllocatedStageNumber, audit.skill);
169
- await audit.lifecycle.fire(
170
- ctx,
171
- "onStageError",
172
- ref,
173
- args.errMsg,
174
- buildLifecycleContext({
175
- cwd: audit.cwd,
176
- runId: audit.runId,
177
- workflow: audit.runIdentity.workflow,
178
- totalStages: audit.runIdentity.totalStages,
179
- trigger: audit.runIdentity.trigger,
180
- state: audit.state,
181
- }),
182
- );
153
+ await audit.lifecycle.fire(ctx, "onStageError", ref, args.errMsg, lifecycleCtxFromSession(audit));
154
+ }
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
+ });
183
177
  }
184
178
 
185
179
  /**
@@ -198,67 +192,41 @@ export async function recordStopFailure(
198
192
  await recordTerminalFailure(ctx, audit, stopFailureArgs(audit.skill, stop, errorMessage), onFailure);
199
193
  }
200
194
 
201
- function stopFailureArgs(
202
- skill: string,
203
- stop: Exclude<StopSignal, "stop">,
204
- errorMessage: string,
205
- ): {
206
- status: "failed" | "aborted";
207
- notifyMsg: string;
208
- notifyLevel: "warning" | "error";
209
- errMsg: string;
210
- } {
195
+ function stopFailureArgs(skill: string, stop: Exclude<StopSignal, "stop">, errorMessage: string): TerminalFailureArgs {
211
196
  switch (stop) {
212
197
  case "aborted":
213
- return {
214
- status: "aborted",
215
- notifyMsg: MSG_STAGE_ABORTED(skill),
216
- notifyLevel: "warning",
217
- errMsg: ERR_STAGE_ABORTED(skill),
218
- };
198
+ return abortedArgs(FAIL_STAGE_ABORTED(skill));
219
199
  case "length":
220
- return {
221
- status: "failed",
222
- notifyMsg: MSG_STAGE_TRUNCATED(skill),
223
- notifyLevel: "error",
224
- errMsg: ERR_STAGE_TRUNCATED(skill),
225
- };
200
+ return failedArgs(FAIL_STAGE_TRUNCATED(skill));
226
201
  case "toolUse":
227
- return {
228
- status: "failed",
229
- notifyMsg: MSG_STAGE_TOOL_STALLED(skill),
230
- notifyLevel: "error",
231
- errMsg: ERR_STAGE_TOOL_STALLED(skill),
232
- };
202
+ return failedArgs(FAIL_STAGE_TOOL_STALLED(skill));
233
203
  case "noResponse":
234
- return {
235
- status: "failed",
236
- notifyMsg: MSG_STAGE_NO_RESPONSE(skill),
237
- notifyLevel: "error",
238
- errMsg: ERR_STAGE_NO_RESPONSE(skill),
239
- };
204
+ return failedArgs(FAIL_STAGE_NO_RESPONSE(skill));
240
205
  case "error":
241
- return {
242
- status: "failed",
243
- notifyMsg: MSG_STAGE_FAILED(skill),
244
- notifyLevel: "error",
245
- errMsg: errorMessage,
246
- };
206
+ return failedArgs(MSG_STAGE_FAILED(skill), errorMessage);
247
207
  default:
248
208
  return assertNever(stop);
249
209
  }
250
210
  }
251
211
 
252
212
  export function recordCancellation(ctx: WorkflowHostContext, audit: AuditCtx): void {
253
- recordStage(
254
- audit.cwd,
255
- audit.runId,
256
- { stage: audit.stageName, skill: audit.skill, status: "skipped", ts: nowIso() },
257
- audit.state,
258
- );
259
- ctx.ui.setStatus(STATUS_KEY, undefined);
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`).
220
+ const errMsg = `${audit.skill} cancelled by user`;
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
+ });
260
230
  ctx.ui.notify(MSG_WORKFLOW_CANCELLED, "info");
261
- // `success: false` alone can't distinguish "cancelled" from "never started";
262
- // the error string is the signal.
263
- audit.state.termination.error = `${audit.skill} cancelled by user`;
231
+ terminate(audit.state, { status: "cancelled", error: errMsg });
264
232
  }