@juicesharp/rpiv-workflow 2.2.0 → 2.3.1

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 (50) hide show
  1. package/audit-ctx.ts +7 -7
  2. package/audit.ts +29 -29
  3. package/chain-state.ts +14 -3
  4. package/death-scene.ts +9 -9
  5. package/docs/workflow-authoring.md +2 -2
  6. package/events.ts +1 -1
  7. package/failure-memos.ts +4 -4
  8. package/handle.ts +16 -1
  9. package/host.ts +1 -1
  10. package/loop-def.ts +1 -1
  11. package/loop-kinds.ts +134 -91
  12. package/loop-parallel.ts +15 -15
  13. package/loop-waves.ts +3 -3
  14. package/loop.ts +54 -35
  15. package/messages.ts +30 -17
  16. package/outcomes/collectors/workspace-diff.ts +3 -3
  17. package/outcomes/git-commit.ts +11 -4
  18. package/output-spec.ts +7 -7
  19. package/package.json +2 -2
  20. package/preview.ts +8 -1
  21. package/registration.ts +3 -3
  22. package/routing.ts +1 -1
  23. package/runner/chain-advance.ts +66 -26
  24. package/runner/errors.ts +1 -1
  25. package/runner/failure.ts +22 -23
  26. package/runner/preflight.ts +20 -20
  27. package/runner/resolve-stage.ts +3 -3
  28. package/runner/resume-entry.ts +5 -5
  29. package/runner/resume-loop.ts +5 -5
  30. package/runner/resume.ts +198 -133
  31. package/runner/run-stage.ts +111 -88
  32. package/runner/runner.ts +4 -4
  33. package/runner/script-stage.ts +17 -17
  34. package/sessions/bash-strikes.ts +9 -9
  35. package/sessions/extraction.ts +135 -77
  36. package/sessions/halt-routing.ts +14 -14
  37. package/sessions/index.ts +1 -1
  38. package/sessions/reattach.ts +10 -10
  39. package/sessions/sessions.ts +93 -53
  40. package/sessions/spawn.ts +5 -5
  41. package/sessions/success-persist.ts +3 -3
  42. package/stage-def.ts +2 -2
  43. package/stage-errors.ts +1 -1
  44. package/state/index.ts +1 -1
  45. package/state/names.ts +1 -1
  46. package/state/reads.ts +1 -1
  47. package/state/state.ts +4 -4
  48. package/state/writes.ts +2 -2
  49. package/types.ts +16 -16
  50. package/validate/stage-rules.ts +42 -17
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Session execution — one Pi session per workflow stage / loop unit.
3
- * `runStageSession` is the only public entry (loop units run through it too,
4
- * threading their identity via `StageSession.unit`).
3
+ * `executeStageSession` is the only public entry (loop units run through it too,
4
+ * threading their identity via `StageSessionContext.unit`).
5
5
  *
6
6
  * Every stage runs in its own detached child session (`spawnChildAndRun`,
7
7
  * spawn.ts); the only surviving policy divergence is the branch offset
@@ -24,8 +24,9 @@
24
24
  */
25
25
 
26
26
  import { WorkflowAbortError } from "../internal-utils.js";
27
+ import type { SessionRef } from "../state/index.js";
27
28
  import { type BranchEntry, classifyStop, readBranch, readSessionRef, type StopSignal } from "../transcript.js";
28
- import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
29
+ import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
29
30
  import { bashStrikesRemaining, bashTimeoutSteeringMessage, consumeBashStrike } from "./bash-strikes.js";
30
31
  import { produceAndValidateOutput } from "./extraction.js";
31
32
  import { haltStageOrSoftHalt } from "./halt-routing.js";
@@ -37,7 +38,7 @@ import { recordStageSuccess } from "./success-persist.js";
37
38
  // ===========================================================================
38
39
 
39
40
  /** Execute one DAG stage (or loop unit) in its own detached child session. */
40
- export async function runStageSession(ctx: WorkflowHostContext, s: StageSession): Promise<void> {
41
+ export async function executeStageSession(ctx: WorkflowHostContext, s: StageSessionContext): Promise<void> {
41
42
  await spawnChildAndRun(ctx, s, (child) => postStage(ctx, child, s));
42
43
  }
43
44
 
@@ -56,13 +57,13 @@ export async function runStageSession(ctx: WorkflowHostContext, s: StageSession)
56
57
  * branch ran under; resume re-applies that persisted value verbatim.
57
58
  */
58
59
  export async function continueStageSession(
59
- obsCtx: WorkflowHostContext,
60
+ observerCtx: WorkflowHostContext,
60
61
  child: WorkflowSessionContext,
61
- s: StageSession,
62
+ s: StageSessionContext,
62
63
  ): Promise<void> {
63
64
  const offset = readBranch(child).length;
64
65
  await resendIntoChild(child, s.prompt);
65
- await postStage(obsCtx, child, s, offset);
66
+ await postStage(observerCtx, child, s, offset);
66
67
  }
67
68
 
68
69
  // ===========================================================================
@@ -74,7 +75,7 @@ export async function continueStageSession(
74
75
  * persist → chain. Exported to the `reattach.ts` companion — a reattached
75
76
  * session's continuation runs this exact pipeline, byte-identical to live.
76
77
  *
77
- * TWO ctxs (detachment): `obsCtx` is the long-lived LAUNCHER/observer ctx the
78
+ * TWO ctxs (detachment): `observerCtx` is the long-lived LAUNCHER/observer ctx the
78
79
  * walk threads — it stays valid across every stage, so the user-facing recording
79
80
  * (success/halt rows + notifications + lifecycle) AND the chain continuation
80
81
  * (`onSuccess` → advance/step, which spawns the NEXT stage's child) all run on
@@ -82,7 +83,7 @@ export async function continueStageSession(
82
83
  * background lane — and which is disposed when the stage ends). `child` is the
83
84
  * in-session ctx: the agent transcript (`readBranch`/`readSessionRef`) and the
84
85
  * validation-retry re-prompt (`produceAndValidateOutput` → `resendIntoChild`)
85
- * read/write through it. Spawning the next stage off `obsCtx` is what keeps the
86
+ * read/write through it. Spawning the next stage off `observerCtx` is what keeps the
86
87
  * launcher the single spawner (no nested-child chain).
87
88
  *
88
89
  * The backing `SessionRef` is captured ONCE at entry — every row this
@@ -90,9 +91,9 @@ export async function continueStageSession(
90
91
  * carries the same provenance value.
91
92
  */
92
93
  export async function postStage(
93
- obsCtx: WorkflowHostContext,
94
+ observerCtx: WorkflowHostContext,
94
95
  child: WorkflowSessionContext,
95
- s: StageSession,
96
+ s: StageSessionContext,
96
97
  // Defaults to the policy-derived offset (fresh ⇒ undefined; resume continue ⇒
97
98
  // the persisted row's value). The live continue body passes the value it
98
99
  // re-derived from the forked branch, which is authoritative there.
@@ -100,58 +101,97 @@ export async function postStage(
100
101
  ): Promise<void> {
101
102
  const session = readSessionRef(child, offset);
102
103
  const outcome = readSessionOutcome(child, offset);
103
- // Abort surfaces as a STOP CLASSIFICATION, not a promise rejection:
104
- // `session.abort()` makes the SDK RESOLVE `prompt()` with a
105
- // `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
106
- // straight into here. Throw BEFORE haltStage/softHaltUnit/any row write so:
107
- // (a) no `collected:true` row is written (else the resume fold marks the unit
108
- // "don't re-dispatch" → permanent work loss), (b) the parallel fold's
109
- // `isAbortError` branch leaves the slot unfilled, and (c) resume re-dispatches
110
- // the unit cleanly.
111
- //
112
- // A genuine run/user abort (`s.signal` fired) ALWAYS re-dispatches on resume, so it
113
- // takes the throw unconditionally. An `aborted` stop with the signal cold is examined
114
- // for a watchdog tool-timeout (`child.toolTimeout`): the host aborted a runaway bash,
115
- // which must route to the soft-halt gate (collect-all unit survives; else terminal
116
- // fail) — NOT WorkflowAbortError, which would re-run the same runaway command on resume.
117
- if (s.signal?.aborted) throw new WorkflowAbortError();
118
- if (outcome.stop === "aborted") {
119
- const timeout = child.toolTimeout?.();
120
- if (timeout) {
121
- // Strike-based recovery: a watchdog tool-timeout is a recoverable tool
122
- // event INSIDE the live child. While strikes remain, the single-caller
123
- // helper resets → re-prompts → tail-recurses postStage (offset threaded
124
- // verbatim); exhaustion falls through to the UNCHANGED soft-halt/terminal
125
- // seam below, where the failure-row writers (memo + death-scene) fire for free.
126
- if (consumeBashStrike(s, timeout.reason)) {
127
- return retryStageAfterBashStrike(obsCtx, child, s, offset, timeout.reason);
128
- }
129
- return haltStageOrSoftHalt(obsCtx, s, { kind: "timeout", reason: timeout.reason }, session);
130
- }
131
- throw new WorkflowAbortError();
132
- }
104
+ // Abort classification and strike recovery are owned by a single helper that
105
+ // returns "continue" when it has handled the turn (strike retry or soft-halt),
106
+ // so postStage reaches its happy-path switch only for a clean stop.
107
+ if ((await classifyAndHandleAbort(observerCtx, child, s, outcome, session, offset)) === "continue") return;
133
108
  // Every halt below routes through the single `haltStageOrSoftHalt` gate: a
134
109
  // fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
135
110
  // slot instead of halting the run; everything else takes the arm's fail-fast
136
- // halt. Recording + the continuation run on obsCtx (the launcher) — the per-stage
111
+ // halt. Recording + the continuation run on observerCtx (the launcher) — the per-stage
137
112
  // child is disposed when the stage ends.
138
- if (outcome.stop !== "stop") return haltStageOrSoftHalt(obsCtx, s, { kind: "stop", stop: outcome.stop }, session);
113
+ if (outcome.stop !== "stop")
114
+ return haltStageOrSoftHalt(observerCtx, s, { kind: "stop", stop: outcome.stop }, session);
139
115
 
140
116
  const result = await produceAndValidateOutput(child, s, outcome.branch, offset);
141
117
  if (result.kind === "fatal")
142
- return haltStageOrSoftHalt(obsCtx, s, { kind: "extraction", message: result.message }, session);
118
+ return haltStageOrSoftHalt(observerCtx, s, { kind: "extraction", message: result.message }, session);
143
119
  if (result.kind === "validation-exhausted")
144
- return haltStageOrSoftHalt(obsCtx, s, { kind: "validation", failureSummary: result.failureSummary }, session);
120
+ return haltStageOrSoftHalt(
121
+ observerCtx,
122
+ s,
123
+ { kind: "validation", failureSummary: result.failureSummary },
124
+ session,
125
+ );
145
126
 
146
- if (!(await recordStageSuccess(obsCtx, s, result.output, session))) return;
127
+ if (!(await recordStageSuccess(observerCtx, s, result.output, session))) return;
147
128
  // The validated Output goes to the continuation directly — loop drivers
148
129
  // thread it into accumulated / feedForward without state back-reads. Runs on
149
- // obsCtx so the next stage's child is spawned off the launcher.
150
- await s.onSuccess(obsCtx, result.output);
130
+ // observerCtx so the next stage's child is spawned off the launcher.
131
+ await s.onSuccess(observerCtx, result.output);
132
+ }
133
+
134
+ // ===========================================================================
135
+ // ABORT CLASSIFIER — postStage's single abort dispatch + its predicates
136
+ // ===========================================================================
137
+
138
+ /** An `aborted` stop classification (the SDK resolves `prompt()` with `stopReason:"aborted"`). */
139
+ const isAbortedStop = (outcome: SessionOutcome): boolean => outcome.stop === "aborted";
140
+
141
+ /**
142
+ * The watchdog tool-timeout verdict, if any. Read ONCE and returned so the
143
+ * `reason` threads through without a second read (the strike arm clears the
144
+ * verdict, so a re-read would see `undefined`).
145
+ */
146
+ const watchdogTimeoutOf = (child: WorkflowSessionContext): { reason: string } | undefined => child.toolTimeout?.();
147
+
148
+ /**
149
+ * Classify and route an abort. Abort surfaces as a STOP CLASSIFICATION, not a
150
+ * promise rejection: `session.abort()` makes the SDK RESOLVE `prompt()` with a
151
+ * `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
152
+ * straight into here. A genuine abort throws BEFORE haltStage/softHaltUnit/any
153
+ * row write so: (a) no `collected:true` row is written (else the resume fold
154
+ * marks the unit "don't re-dispatch" → permanent work loss), (b) the parallel
155
+ * fold's `isAbortError` branch leaves the slot unfilled, and (c) resume
156
+ * re-dispatches the unit cleanly.
157
+ *
158
+ * Returns `"continue"` once the turn is owned (strike retry or soft-halt),
159
+ * telling the caller to stop; returns `void` (no abort) so the caller proceeds
160
+ * to the happy-path switch.
161
+ *
162
+ * Exported ONLY for the co-located direct tests (`sessions/sessions.test.ts` —
163
+ * a non-exported member cannot be imported there; the `extraction.ts` retry
164
+ * hooks set the precedent). Absent from the `sessions/index.ts` barrel, so the
165
+ * package surface is unchanged.
166
+ */
167
+ export async function classifyAndHandleAbort(
168
+ observerCtx: WorkflowHostContext,
169
+ child: WorkflowSessionContext,
170
+ s: StageSessionContext,
171
+ outcome: SessionOutcome,
172
+ session: SessionRef | null,
173
+ offset: number | undefined,
174
+ ): Promise<"continue" | undefined> {
175
+ // Level 1 — genuine run/user abort: the signal fired, so always re-dispatch on resume.
176
+ if (s.signal?.aborted) throw new WorkflowAbortError();
177
+ // Level 2 — not an abort stop: hand back to the caller's happy-path switch.
178
+ if (!isAbortedStop(outcome)) return;
179
+ // Level 3 — examine a watchdog tool-timeout; an aborted stop with the signal cold
180
+ // and no watchdog is a genuine abort that re-dispatches on resume.
181
+ const timeout = watchdogTimeoutOf(child);
182
+ if (!timeout) throw new WorkflowAbortError();
183
+ // Level 4 — a watchdog tool-timeout is recoverable: consume a strike and retry, or
184
+ // route exhaustion through the soft-halt gate (collect-all survives; else terminal).
185
+ if (consumeBashStrike(s, timeout.reason)) {
186
+ await retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
187
+ } else {
188
+ await haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
189
+ }
190
+ return "continue";
151
191
  }
152
192
 
153
193
  // ===========================================================================
154
- // STRIKE-ARM RECOVERY — single-caller helper for postStage's watchdog arm
194
+ // STRIKE-ARM RECOVERY — single-caller helper for the abort classifier's watchdog arm
155
195
  // ===========================================================================
156
196
 
157
197
  /**
@@ -160,21 +200,21 @@ export async function postStage(
160
200
  * verbatim — the exact shape the continue body uses). Called ONLY when
161
201
  * `consumeBashStrike(s, reason)` returned true, so this helper performs the
162
202
  * reset → re-prompt → tail-recurse sequence byte-identically to the inline arm
163
- * it replaces; strike exhaustion stays routed by the caller (`postStage`) to
203
+ * it replaces; strike exhaustion stays routed by the caller (`classifyAndHandleAbort`) to
164
204
  * the UNCHANGED `haltStageOrSoftHalt({ kind: "timeout" })` seam, where the
165
205
  * failure-row writers (memo + death-scene artifact) fire for free.
166
206
  */
167
207
  async function retryStageAfterBashStrike(
168
- obsCtx: WorkflowHostContext,
208
+ observerCtx: WorkflowHostContext,
169
209
  child: WorkflowSessionContext,
170
- s: StageSession,
210
+ s: StageSessionContext,
171
211
  offset: number | undefined,
172
212
  reason: string,
173
213
  ): Promise<void> {
174
214
  child.resetToolTimeout?.();
175
215
  const remaining = bashStrikesRemaining(s);
176
216
  await resendIntoChild(child, bashTimeoutSteeringMessage(reason, remaining, remaining === 0));
177
- return postStage(obsCtx, child, s, offset);
217
+ return postStage(observerCtx, child, s, offset);
178
218
  }
179
219
 
180
220
  // ===========================================================================
package/sessions/spawn.ts CHANGED
@@ -19,7 +19,7 @@
19
19
  */
20
20
 
21
21
  import type { SessionPolicy } from "../api.js";
22
- import type { StageSession, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
22
+ import type { StageSessionContext, WorkflowHostContext, WorkflowSessionContext } from "../types.js";
23
23
 
24
24
  /**
25
25
  * The per-policy branch offset — fresh ignores the stage-captured value;
@@ -54,7 +54,7 @@ type OpenMode = { reattach: { sessionFile: string } } | { fork: { sessionFile: s
54
54
  */
55
55
  function openChild(
56
56
  ctx: WorkflowHostContext,
57
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
57
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
58
58
  body: (child: WorkflowSessionContext) => Promise<void>,
59
59
  mode?: OpenMode,
60
60
  ): Promise<void> {
@@ -81,7 +81,7 @@ function openChild(
81
81
  */
82
82
  export function spawnChildAndRun(
83
83
  ctx: WorkflowHostContext,
84
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
84
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
85
85
  body: (child: WorkflowSessionContext) => Promise<void>,
86
86
  ): Promise<void> {
87
87
  return openChild(ctx, s, body);
@@ -102,7 +102,7 @@ export function spawnChildAndRun(
102
102
  */
103
103
  export function reattachChildSession(
104
104
  ctx: WorkflowHostContext,
105
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
105
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
106
106
  sessionFile: string,
107
107
  body: (child: WorkflowSessionContext) => Promise<void>,
108
108
  ): Promise<void> {
@@ -127,7 +127,7 @@ export function reattachChildSession(
127
127
  */
128
128
  export function forkChildSession(
129
129
  ctx: WorkflowHostContext,
130
- s: Pick<StageSession, "prompt" | "model" | "signal" | "laneUnitIndex">,
130
+ s: Pick<StageSessionContext, "prompt" | "model" | "signal" | "laneUnitIndex">,
131
131
  sessionFile: string,
132
132
  body: (child: WorkflowSessionContext) => Promise<void>,
133
133
  ): Promise<void> {
@@ -14,7 +14,7 @@ import { persistStageSuccess, rollLastSession } from "../audit-rows.js";
14
14
  import { lifecycleCtxFromSession, skillStageRef, type UnitEvent } from "../events.js";
15
15
  import type { Output } from "../output.js";
16
16
  import type { SessionRef } from "../state/index.js";
17
- import type { StageSession, WorkflowHostContext } from "../types.js";
17
+ import type { StageSessionContext, WorkflowHostContext } from "../types.js";
18
18
  import { bashTimeoutStrikeHistory } from "./bash-strikes.js";
19
19
 
20
20
  /**
@@ -39,7 +39,7 @@ import { bashTimeoutStrikeHistory } from "./bash-strikes.js";
39
39
  */
40
40
  export async function recordStageSuccess(
41
41
  ctx: WorkflowHostContext,
42
- s: StageSession,
42
+ s: StageSessionContext,
43
43
  output: Output,
44
44
  session: SessionRef | null,
45
45
  ): Promise<boolean> {
@@ -89,7 +89,7 @@ export async function recordStageSuccess(
89
89
  }
90
90
 
91
91
  /** Public `UnitEvent` payload from the session's `UnitRef` + dispatched skill. */
92
- export function unitEventOf(s: StageSession): UnitEvent {
92
+ export function unitEventOf(s: StageSessionContext): UnitEvent {
93
93
  const u = s.unit!;
94
94
  return { role: u.role, index: u.index, unitId: u.id, label: u.label, skill: s.skill };
95
95
  }
package/stage-def.ts CHANGED
@@ -515,7 +515,7 @@ function actsScript<TIn = unknown>(opts: ActsScriptOptions<TIn>): StageDef<TIn,
515
515
  // / `{ kind: "stop" }` in routing.ts: no outgoing edge OR explicit `STOP`;
516
516
  // orthogonal to this factory — a `terminal()` stage can route onward, and a
517
517
  // plain stage can be a sink) and SENSE 3 (run-outcome prose — "terminal
518
- // failure/outcome" = a halt that ends the run, e.g. audit.ts `writeFailureRow`).
518
+ // failure/outcome" = a halt that ends the run, e.g. audit.ts `recordFailureRow`).
519
519
  // See the `terminal` export doc below for the full glossary.
520
520
  function terminalFn(overrides: Partial<StageDef> = {}): StageDef {
521
521
  return withDefaults("side-effect", { ...overrides, inheritsArtifacts: false });
@@ -589,7 +589,7 @@ export const acts = Object.assign(actsFn, { script: actsScript, prompt: actsProm
589
589
  * factory — a `terminal()` stage can route onward, a plain stage can be a
590
590
  * sink.
591
591
  * 3. RUN OUTCOME ("terminal failure/outcome" prose, e.g. audit.ts
592
- * `writeFailureRow` / `recordTerminalFailure`): a failure/cancellation/
592
+ * `recordFailureRow` / `recordFatalFailure`): a failure/cancellation/
593
593
  * abort that ends the run.
594
594
  */
595
595
  export const terminal = Object.assign(terminalFn, { script: terminalScript });
package/stage-errors.ts CHANGED
@@ -14,7 +14,7 @@ import type { FailureText } from "./messages.js";
14
14
 
15
15
  /**
16
16
  * Thrown by a preflight check on failure; carries the recorded-row
17
- * attribution + notify/err messages so `runStageOrRecordFailure` can land
17
+ * attribution + notify/err messages so `dispatchStageOrRecordFailure` can land
18
18
  * a uniform JSONL row regardless of which slot tripped.
19
19
  *
20
20
  * `kind` annotates the violation class for diagnostics only — control
package/state/index.ts CHANGED
@@ -16,6 +16,7 @@ export type {
16
16
  WorkflowStage,
17
17
  } from "./state.js";
18
18
  export {
19
+ appendHeader,
19
20
  appendLoopCap,
20
21
  appendRoutingDecision,
21
22
  appendStage,
@@ -40,5 +41,4 @@ export {
40
41
  STATE_SCHEMA_VERSION,
41
42
  stateFilePath,
42
43
  VALID_NAME,
43
- writeHeader,
44
44
  } from "./state.js";
package/state/names.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * Internal module — not re-exported from registration.ts. The runner reserves
7
7
  * names through `claimName` (the single in-process door: validate →
8
- * collision-check → persist) BEFORE `writeHeader`. External consumers resolve
8
+ * collision-check → persist) BEFORE `appendHeader`. External consumers resolve
9
9
  * names through `resolveRun`.
10
10
  *
11
11
  * Durability: every write goes through `writeNamesIndex` — temp file +
package/state/reads.ts CHANGED
@@ -27,7 +27,7 @@ import type { LoopCapRow, RoutingDecision, RunSummary, WorkflowHeader, WorkflowS
27
27
  * Reads every line, filters by shape (not position). Header has no
28
28
  * `stageNumber`; routing rows carry `type: "routing"`; stage rows have
29
29
  * `stageNumber: number` and no `type`. Starting at line 0 keeps the first
30
- * stage row recoverable even if a transient writeHeader failure left the
30
+ * stage row recoverable even if a transient appendHeader failure left the
31
31
  * file without its header.
32
32
  *
33
33
  * Each line's `JSON.parse` runs in its own try/catch — a truncated trailing
package/state/state.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * Internally split into three modules:
14
14
  * - paths.ts — runsDir + stateFilePath + generateRunId
15
- * - writes.ts — tryAppendJsonl + writeHeader + appendStage +
15
+ * - writes.ts — tryAppendJsonl + appendHeader + appendStage +
16
16
  * appendRoutingDecision
17
17
  * - reads.ts — readLastStage + readAllStages + readRoutingDecisions +
18
18
  * listArtifacts + readHeader + listRuns
@@ -103,7 +103,7 @@ export interface WorkflowStage {
103
103
  output?: Output;
104
104
  /**
105
105
  * Reason a terminal-failure row was written — mirrors the
106
- * `state.termination.error` set by `recordTerminalFailure`. Present
106
+ * `state.termination.error` set by `recordFatalFailure`. Present
107
107
  * only on `status: "failed" | "aborted"` rows; absent on completed /
108
108
  * skipped rows. Persisting it here means post-mortems work from
109
109
  * JSONL alone, without depending on a transient `ctx.ui.notify` toast.
@@ -136,7 +136,7 @@ export interface WorkflowStage {
136
136
  /**
137
137
  * Marks a NON-terminal collect-all fanout unit halt (`recordUnitHalt`):
138
138
  * the unit failed but the run survives and a `failedOutput` sentinel fills its
139
- * declared slot. Distinguishes a SOFT halt from a hard `recordTerminalFailure`
139
+ * declared slot. Distinguishes a SOFT halt from a hard `recordFatalFailure`
140
140
  * row (byte-identical otherwise) so the resume fold rebuilds the
141
141
  * sentinel by `unitIndex` rather than re-dispatching the unit. Absent on every
142
142
  * other row (`undefined` is dropped by `JSON.stringify`).
@@ -258,4 +258,4 @@ export {
258
258
  readRoutingDecisions,
259
259
  } from "./reads.js";
260
260
  export { resolveRun } from "./resolve.js";
261
- export { appendLoopCap, appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
261
+ export { appendHeader, appendLoopCap, appendRoutingDecision, appendStage } from "./writes.js";
package/state/writes.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  * swapping the backend means touching all of `state/` (a `RunStore` port
8
8
  * is a known possible follow-up, deliberately deferred).
9
9
  *
10
- * writeHeader — boolean; the runner refuses the run start on failure.
10
+ * appendHeader — boolean; the runner refuses the run start on failure.
11
11
  * appendStage — boolean; allocator gates monotonic counters on it.
12
12
  * appendRoutingDecision — boolean; telemetry-not-state, dropped rows surface up.
13
13
  */
@@ -42,7 +42,7 @@ function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
42
42
  * while stage rows still land — so `runWorkflow` refuses the run start on
43
43
  * false, before anything has executed.
44
44
  */
45
- export function writeHeader(cwd: string, header: WorkflowHeader): boolean {
45
+ export function appendHeader(cwd: string, header: WorkflowHeader): boolean {
46
46
  return tryAppendJsonl(cwd, header.runId, header);
47
47
  }
48
48
 
package/types.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  *
17
17
  * Per-stage / per-phase sessions extend a shared `SessionContext` base
18
18
  * (cwd, runId, state, prompt, skill). The audit layer pins its dependency
19
- * on this base structurally via `AuditCtx = Pick<SessionContext, ...>`.
19
+ * on this base structurally via `AuditContext = Pick<SessionContext, ...>`.
20
20
  *
21
21
  * Lives apart from runner.ts / sessions.ts so both can reference the same
22
22
  * shapes without a runtime import cycle (type-only refs back via this
@@ -239,13 +239,13 @@ export interface RunWorkflowOptions {
239
239
  signal?: AbortSignal;
240
240
  /**
241
241
  * Per-stage model-override resolver, injected by the embedder. Threaded onto
242
- * `RunContext.resolveModel` → every `StageSession.model`; the host applies it
242
+ * `RunContext.resolveModel` → every `StageSessionContext.model`; the host applies it
243
243
  * at child-session creation. Undefined ⇒ host default for every stage.
244
244
  */
245
245
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
246
246
  /**
247
247
  * Worktree-digest override for the validation-retry gate — threaded
248
- * onto `RunContext.worktreeDigest` → every `StageSession.worktreeDigest`.
248
+ * onto `RunContext.worktreeDigest` → every `StageSessionContext.worktreeDigest`.
249
249
  * Undefined ⇒ the built-in `computeWorktreeDigest` (git + artifacts).
250
250
  */
251
251
  worktreeDigest?: (cwd: string) => string | undefined;
@@ -361,7 +361,7 @@ export interface RunContext {
361
361
  * lacks a stage `inputSchema` (a harvested `consumes.data` is the
362
362
  * stage's own `inputSchema` re-derived, already covered by
363
363
  * `ensureInputValid`);
364
- * - `effectiveOutputSchema` (threaded onto `StageSession`) sources a
364
+ * - `effectiveOutputSchema` (threaded onto `StageSessionContext`) sources a
365
365
  * declared `produces.data` as the output schema when the stage carries
366
366
  * no `outputSchema` of its own.
367
367
  * Fail-soft: both degrade (no validation, never throw) when absent.
@@ -370,7 +370,7 @@ export interface RunContext {
370
370
  /**
371
371
  * Resolve a per-stage model override, injected by the embedder (rpiv-pi maps
372
372
  * each `{ stage, skill }` to its model/effort override). The runner threads
373
- * the result onto every `StageSession.model`; the host applies it at child
373
+ * the result onto every `StageSessionContext.model`; the host applies it at child
374
374
  * creation (NOT via global mutation). Undefined ⇒ host default.
375
375
  */
376
376
  resolveModel?: (id: { stage: string; skill: string }) => ModelSelection | undefined;
@@ -381,13 +381,13 @@ export interface RunContext {
381
381
  * writer at failure time (death-scene.ts) — the ONLY reader. Undefined for
382
382
  * programmatic embedders / no provider, in which case the writer degrades
383
383
  * silently (no artifact, no warning). Threaded provider → executor →
384
- * `RunContext` → `SessionContext` → `AuditCtx` → `auditFor`.
384
+ * `RunContext` → `SessionContext` → `AuditContext` → `auditFor`.
385
385
  */
386
386
  readSessionBranch?: (file: string) => BranchEntry[] | undefined;
387
387
  /**
388
388
  * Worktree-digest resolver injected by the embedder (tests / programmatic
389
389
  * embedders that want to stub the filesystem). Threaded onto every
390
- * `StageSession.worktreeDigest` and read by the validation-retry gate
390
+ * `StageSessionContext.worktreeDigest` and read by the validation-retry gate
391
391
  * (`packages/rpiv-workflow/sessions/extraction.ts` mechanism-1 +
392
392
  * `packages/rpiv-workflow/runner/run-stage.ts` mechanism-2) via
393
393
  * `resolveDigest` (`worktree-digest.ts`). Undefined ⇒ the built-in
@@ -409,7 +409,7 @@ export interface RunContext {
409
409
  lifecycle: LifecycleDispatcher;
410
410
  /**
411
411
  * Optional cooperative-cancellation signal from `RunWorkflowOptions.signal`.
412
- * Checked at the between-stage seam (top of `runStageOrRecordFailure`, before
412
+ * Checked at the between-stage seam (top of `dispatchStageOrRecordFailure`, before
413
413
  * the start stage and before every routed next stage). An aborted signal
414
414
  * records an `"aborted"` terminal row and unwinds — it does NOT interrupt a
415
415
  * stage already streaming (Pi owns the live session).
@@ -418,9 +418,9 @@ export interface RunContext {
418
418
  }
419
419
 
420
420
  /**
421
- * Per-stage / per-unit common base. Extended by `StageSession` (loop units
422
- * thread their identity through `StageSession.unit`); consumed in pick form by
423
- * `AuditCtx` (audit.ts) so the audit layer pins its dependency on this shape
421
+ * Per-stage / per-unit common base. Extended by `StageSessionContext` (loop units
422
+ * thread their identity through `StageSessionContext.unit`); consumed in pick form by
423
+ * `AuditContext` (audit.ts) so the audit layer pins its dependency on this shape
424
424
  * structurally instead of duplicating the field list.
425
425
  *
426
426
  * `stageName` is the workflow stage's record key — the value that lands
@@ -464,10 +464,10 @@ export interface SessionContext {
464
464
  /**
465
465
  * Host-injected persisted-session branch reader, threaded from
466
466
  * `RunContext.readSessionBranch`. Read by the death-scene artifact writer
467
- * (`writeDeathSceneArtifact`) via `AuditCtx`; absent for programmatic
467
+ * (`writeDeathSceneArtifact`) via `AuditContext`; absent for programmatic
468
468
  * embedders (the writer degrades silently). Travels FURTHER than
469
- * `resolveModel` — into `SessionContext` → `AuditCtx` → `auditFor` —
470
- * because the writer reads it from `AuditCtx` at failure time.
469
+ * `resolveModel` — into `SessionContext` → `AuditContext` → `auditFor` —
470
+ * because the writer reads it from `AuditContext` at failure time.
471
471
  */
472
472
  readSessionBranch?: (file: string) => BranchEntry[] | undefined;
473
473
  }
@@ -490,7 +490,7 @@ export interface UnitRef {
490
490
  label: string;
491
491
  }
492
492
 
493
- export interface StageSession extends SessionContext {
493
+ export interface StageSessionContext extends SessionContext {
494
494
  stage: StageDef;
495
495
  /**
496
496
  * Registered skill-contract registry, threaded from
@@ -549,7 +549,7 @@ export interface StageSession extends SessionContext {
549
549
  * `undefined` ⇒ the `BASH_TIMEOUT_STRIKES` module default. Pin to `0` in a
550
550
  * watchdog-contract test to force immediate exhaustion; pin to `N` to drive
551
551
  * a multi-strike recovery without mutating env. Now the SOLE strike surface
552
- * on `StageSession`: the mutable accounting (used counter + reasons
552
+ * on `StageSessionContext`: the mutable accounting (used counter + reasons
553
553
  * accumulator) lives in the private `StrikeBudget` value object held in
554
554
  * `sessions/bash-strikes.ts`, keyed off this session (read once at first
555
555
  * consume to resolve the budget's ceiling). Immutable per-activation.
@@ -11,7 +11,16 @@
11
11
  * (different dependency footprint entirely).
12
12
  */
13
13
 
14
- import { LOOP_KINDS, ON_INVALID_VALUES, SESSION_POLICIES, STAGE_KINDS, type StageDef, type Workflow } from "../api.js";
14
+ import {
15
+ type FanoutLoop,
16
+ LOOP_KINDS,
17
+ type LoopDef,
18
+ ON_INVALID_VALUES,
19
+ SESSION_POLICIES,
20
+ STAGE_KINDS,
21
+ type StageDef,
22
+ type Workflow,
23
+ } from "../api.js";
15
24
  import { type AnyJudge, isPanel } from "../judge.js";
16
25
  import {
17
26
  forEachJudgeChannel,
@@ -70,30 +79,17 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
70
79
  if (loop.max !== undefined && (!Number.isInteger(loop.max) || loop.max < 1)) {
71
80
  report("loop-max-invalid", { max: loop.max });
72
81
  }
73
- if (
74
- loop.kind === "fanout" &&
75
- loop.concurrency !== undefined &&
76
- (!Number.isInteger(loop.concurrency) || loop.concurrency < 1)
77
- ) {
82
+ if (isInvalidConcurrency(loop)) {
78
83
  report("loop-concurrency-invalid", { concurrency: loop.concurrency });
79
84
  }
80
- if (
81
- loop.kind === "fanout" &&
82
- loop.depArtifactFlag !== undefined &&
83
- (typeof loop.depArtifactFlag !== "string" || loop.depArtifactFlag.trim().length === 0)
84
- ) {
85
+ if (isInvalidDepArtifactFlag(loop)) {
85
86
  report("loop-dep-flag-invalid", { depArtifactFlag: loop.depArtifactFlag });
86
87
  }
87
88
  // Pull loops + assess run the stage's outcome collector per unit.
88
89
  if ((loop.kind === "iterate" || loop.kind === "assess") && stage.kind !== "produces") {
89
90
  report("loop-requires-produces", { kind: loop.kind });
90
91
  }
91
- // A stable named slot: iterate and assess always (every unit/round runs the
92
- // produces collector), fanout when COLLECTING (produces kind) — the decorated
93
- // display string must never split the accumulation slot.
94
- const needsName =
95
- loop.kind === "iterate" || loop.kind === "assess" || (loop.kind === "fanout" && stage.kind === "produces");
96
- if (needsName && !stage.outcome?.name) {
92
+ if (requiresOutcomeName(loop, stage) && !stage.outcome?.name) {
97
93
  report("loop-outcome-name-required");
98
94
  }
99
95
 
@@ -129,6 +125,35 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
129
125
  checkVerdictChannels(slot, name, stage, "assess-verdict-channel-collision", report);
130
126
  }
131
127
 
128
+ /**
129
+ * A fanout's `concurrency` ceiling is present and out of range — not an
130
+ * integer or below 1. The type guard narrows to `FanoutLoop &
131
+ * { concurrency: number }` so the report call reads the field without a cast
132
+ * or non-null assertion.
133
+ */
134
+ const isInvalidConcurrency = (loop: LoopDef): loop is FanoutLoop & { concurrency: number } =>
135
+ loop.kind === "fanout" &&
136
+ loop.concurrency !== undefined &&
137
+ (!Number.isInteger(loop.concurrency) || loop.concurrency < 1);
138
+
139
+ /**
140
+ * A fanout's `depArtifactFlag` is present but not a non-empty string. The type
141
+ * guard narrows to `FanoutLoop & { depArtifactFlag: string }` so the report
142
+ * call reads the field without a cast or non-null assertion.
143
+ */
144
+ const isInvalidDepArtifactFlag = (loop: LoopDef): loop is FanoutLoop & { depArtifactFlag: string } =>
145
+ loop.kind === "fanout" &&
146
+ loop.depArtifactFlag !== undefined &&
147
+ (typeof loop.depArtifactFlag !== "string" || loop.depArtifactFlag.trim().length === 0);
148
+
149
+ /**
150
+ * A stable named slot: iterate and assess always (every unit/round runs the
151
+ * produces collector), fanout when COLLECTING (produces kind) — the decorated
152
+ * display string must never split the accumulation slot.
153
+ */
154
+ const requiresOutcomeName = (loop: LoopDef, stage: StageDef): boolean =>
155
+ loop.kind === "iterate" || loop.kind === "assess" || (loop.kind === "fanout" && stage.kind === "produces");
156
+
132
157
  /**
133
158
  * Verdict-channel collisions for a judge SLOT (`AnyJudge`) — workflow-level
134
159
  * because it needs the producer's publish identity