@juicesharp/rpiv-workflow 2.1.0 → 2.3.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 (57) hide show
  1. package/audit-ctx.ts +16 -8
  2. package/audit-rows.ts +10 -0
  3. package/audit.ts +48 -26
  4. package/chain-state.ts +26 -1
  5. package/death-scene.ts +232 -0
  6. package/docs/embedding.md +1 -1
  7. package/docs/workflow-authoring.md +2 -2
  8. package/events.ts +3 -27
  9. package/execution-host.ts +9 -0
  10. package/failure-memos.ts +74 -0
  11. package/handle.ts +16 -1
  12. package/host.ts +13 -1
  13. package/internal.ts +1 -0
  14. package/loop-def.ts +9 -5
  15. package/loop-kinds.ts +16 -13
  16. package/loop-parallel.ts +116 -95
  17. package/loop-waves.ts +3 -3
  18. package/loop.ts +46 -43
  19. package/messages.ts +53 -14
  20. package/outcomes/collectors/workspace-diff.ts +3 -3
  21. package/outcomes/git-commit.ts +11 -4
  22. package/output-spec.ts +7 -7
  23. package/package.json +5 -2
  24. package/preview.ts +8 -1
  25. package/registration.ts +8 -3
  26. package/routing.ts +1 -41
  27. package/runner/chain-advance.ts +50 -32
  28. package/runner/errors.ts +1 -1
  29. package/runner/failure.ts +22 -23
  30. package/runner/preflight.ts +3 -6
  31. package/runner/resolve-stage.ts +3 -3
  32. package/runner/resume-entry.ts +5 -5
  33. package/runner/resume-loop.ts +5 -5
  34. package/runner/resume.ts +1 -1
  35. package/runner/run-context.ts +13 -3
  36. package/runner/run-stage.ts +134 -60
  37. package/runner/runner.ts +19 -9
  38. package/runner/script-stage.ts +17 -17
  39. package/sessions/bash-strikes.ts +182 -0
  40. package/sessions/extraction.ts +51 -37
  41. package/sessions/halt-routing.ts +18 -13
  42. package/sessions/index.ts +1 -1
  43. package/sessions/reattach.ts +10 -10
  44. package/sessions/sessions.ts +63 -19
  45. package/sessions/spawn.ts +5 -5
  46. package/sessions/success-persist.ts +9 -3
  47. package/stage-def.ts +2 -2
  48. package/stage-errors.ts +1 -1
  49. package/stage-identity.ts +43 -4
  50. package/state/index.ts +1 -1
  51. package/state/names.ts +1 -1
  52. package/state/reads.ts +1 -1
  53. package/state/state.ts +14 -4
  54. package/state/writes.ts +2 -2
  55. package/transcript.ts +30 -0
  56. package/types.ts +105 -15
  57. package/worktree-digest.ts +148 -0
package/messages.ts CHANGED
@@ -56,6 +56,32 @@ export const FAIL_VALIDATION_EXHAUSTED = (skill: string, failures: string): Fail
56
56
  error: `${skill} output validation failed after retries: ${failures}`,
57
57
  });
58
58
 
59
+ /**
60
+ * Validation-retry mechanism-1 — the agent was asked to fix the artifact but changed nothing
61
+ * observable in the worktree, so the `produce(attempt)` re-read + re-validate
62
+ * cycle would just re-run the same failing validation. Routed as the extraction
63
+ * retry loop's `Fatal.message` (the `{ kind: "aborted"; abort: { kind: "fatal" } }`
64
+ * arm of `onRetry` in `packages/rpiv-workflow/sessions/extraction.ts`), so the
65
+ * stage halts through the existing extraction-fatal path. Lands in
66
+ * `state.termination.error` + the JSONL row's `errMsg` via `haltStageOrSoftHalt`.
67
+ */
68
+ export const ERR_VALIDATE_RETRY_UNCHANGED = (skill: string) =>
69
+ `${skill}: validation retry halted — the working tree was unchanged after the fix prompt (no observable edit detected to tracked files or .rpiv/artifacts/); refusing to re-run the same failing validation`;
70
+
71
+ /**
72
+ * Validation-retry mechanism-2 — a schema-validated `produces` stage was re-dispatched against
73
+ * a worktree unchanged since its last validation failure at the same progress
74
+ * point (`stagesCompleted` unchanged). A `FailureText` consumed by `failedArgs`
75
+ * (the sessionless `recordFatalFailure` descriptor, mirroring
76
+ * `ensureBackwardJumpGuard` in `packages/rpiv-workflow/runner/chain-advance.ts`).
77
+ * The terminal skip carries the failure memo for free through the shared
78
+ * `recordFatalFailure` writer hooks at `packages/rpiv-workflow/audit.ts:134`.
79
+ */
80
+ export const FAIL_VALIDATE_GATE_SKIPPED = (skill: string): FailureText => ({
81
+ toast: `✗ ${skill} re-dispatched with no observable change since its last validation failure — stopping workflow`,
82
+ error: `${skill} re-dispatched with an unchanged worktree since its last schema-validation failure (no observable fix detected); halting to avoid a no-op retry loop`,
83
+ });
84
+
59
85
  export const FAIL_INPUT_VALIDATION = (currentSkill: string, prevSkill: string, failures: string): FailureText => ({
60
86
  toast: `✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`,
61
87
  error: `Input validation failed for '${currentSkill}': upstream '${prevSkill}' produced invalid data: ${failures}`,
@@ -95,6 +121,19 @@ export const FAIL_BACKWARD_JUMP_EXHAUSTED = (stage: string, revisits: number, ma
95
121
  error: `Backward-jump limit exceeded: stage "${stage}" re-entered ${revisits} times (max ${max})`,
96
122
  });
97
123
 
124
+ /**
125
+ * A decision edge terminated the chain because no branch matched — `match`
126
+ * without a fallback saw an unexpected value (typically a failed verdict on a
127
+ * gate whose only routes are pass arms). The run is blocked awaiting
128
+ * intervention, not complete; `note` is the edge's own no-match diagnostic
129
+ * (the ROUTE_NOTE `match` attaches), so the toast names the value that failed
130
+ * to route. The stage's own output (its verdict) holds the findings.
131
+ */
132
+ export const FAIL_GATE_STOP = (stage: string, note: string): FailureText => ({
133
+ toast: `✗ workflow stopped at "${stage}" — its routing gate matched no branch (${note}); see the stage's verdict for findings, then fix and re-run`,
134
+ error: `Routing gate after "${stage}" matched no branch: ${note}`,
135
+ });
136
+
98
137
  /**
99
138
  * A loop produced zero units (push: empty array handled upstream as
100
139
  * single-stage fall-through, so this fires only for a pull loop whose FIRST
@@ -154,8 +193,8 @@ export const MSG_CHAIN_ADVANCE_FAILED = (fromStage: string, reason: string) =>
154
193
 
155
194
  /**
156
195
  * Stage threw before it could record its own audit row — covers
157
- * `enforceSessionInvariants` violations, session-machinery errors, and any
158
- * other path that escapes `runStage` directly. Distinguished from
196
+ * `ensureLoopNotContinue` violations, session-machinery errors, and any
197
+ * other path that escapes `dispatchStage` directly. Distinguished from
159
198
  * `MSG_CHAIN_ADVANCE_FAILED` (which is about an edge throwing AFTER a stage
160
199
  * succeeded) — the user needs to see *which* stage failed, not which one
161
200
  * preceded the failure. Wording is deliberately neutral ("failed", not
@@ -363,7 +402,7 @@ export const MSG_NO_WORKFLOWS_REGISTERED =
363
402
  * Build via `failedArgs` / `abortedArgs` (or `stopFailureArgs`' switch, in
364
403
  * audit.ts) so a halt site can't mismatch status and notify level.
365
404
  */
366
- export interface TerminalFailureArgs {
405
+ export interface FatalFailureArgs {
367
406
  status: "failed" | "aborted";
368
407
  notifyMsg: string;
369
408
  notifyLevel: "warning" | "error";
@@ -376,27 +415,27 @@ export interface TerminalFailureArgs {
376
415
  * overload-resolution body for `failedArgs`/`abortedArgs` lives here once.
377
416
  * Modeled after `stopFailureArgs` (parameterize by status).
378
417
  */
379
- function terminalArgsOf(status: "failed" | "aborted", a: FailureText | string, b?: string): TerminalFailureArgs {
418
+ function fatalArgsOf(status: "failed" | "aborted", a: FailureText | string, b?: string): FatalFailureArgs {
380
419
  const f = typeof a === "string" ? { toast: a, error: b as string } : a;
381
420
  return { status, notifyMsg: f.toast, notifyLevel: status === "failed" ? "error" : "warning", errMsg: f.error };
382
421
  }
383
422
 
384
423
  /**
385
- * Argument constructors for `recordTerminalFailure` — the
424
+ * Argument constructors for `recordFatalFailure` — the
386
425
  * `{status, notifyMsg, notifyLevel, errMsg}` quadruple every halt site used
387
426
  * to spell by hand. One per terminal status: failures notify at `"error"`,
388
427
  * aborts at `"warning"` (cooperative cancellation is expected, not
389
- * exceptional). 1-line facades over `terminalArgsOf` so the status/level
428
+ * exceptional). 1-line facades over `fatalArgsOf` so the status/level
390
429
  * pairing lives once.
391
430
  */
392
- export function failedArgs(failure: FailureText): TerminalFailureArgs;
393
- export function failedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
394
- export function failedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
395
- return terminalArgsOf("failed", a, b);
431
+ export function failedArgs(failure: FailureText): FatalFailureArgs;
432
+ export function failedArgs(notifyMsg: string, errMsg: string): FatalFailureArgs;
433
+ export function failedArgs(a: FailureText | string, b?: string): FatalFailureArgs {
434
+ return fatalArgsOf("failed", a, b);
396
435
  }
397
436
 
398
- export function abortedArgs(failure: FailureText): TerminalFailureArgs;
399
- export function abortedArgs(notifyMsg: string, errMsg: string): TerminalFailureArgs;
400
- export function abortedArgs(a: FailureText | string, b?: string): TerminalFailureArgs {
401
- return terminalArgsOf("aborted", a, b);
437
+ export function abortedArgs(failure: FailureText): FatalFailureArgs;
438
+ export function abortedArgs(notifyMsg: string, errMsg: string): FatalFailureArgs;
439
+ export function abortedArgs(a: FailureText | string, b?: string): FatalFailureArgs {
440
+ return fatalArgsOf("aborted", a, b);
402
441
  }
@@ -23,7 +23,7 @@
23
23
  */
24
24
 
25
25
  import { type Artifact, fs as fsHandle } from "../../handle.js";
26
- import type { ArtifactCollector, CollectCtx, CollectResult, SnapshotCtx } from "../../output-spec.js";
26
+ import type { ArtifactCollector, CollectContext, CollectResult, SnapshotContext } from "../../output-spec.js";
27
27
  import { defineCollector } from "../../output-spec.js";
28
28
  import { execFileAsync, GIT_EXEC_TIMEOUT_MS } from "../exec.js";
29
29
 
@@ -53,14 +53,14 @@ export const workspaceDiffCollector = (
53
53
  // Snapshot + diff implementation
54
54
  // ---------------------------------------------------------------------------
55
55
 
56
- async function capturePorcelainSnapshot(ctx: SnapshotCtx): Promise<WorkspaceDiffSnapshot | undefined> {
56
+ async function capturePorcelainSnapshot(ctx: SnapshotContext): Promise<WorkspaceDiffSnapshot | undefined> {
57
57
  const status = await runGitStatus(ctx.cwd);
58
58
  if (status === undefined) return undefined;
59
59
  return { statusByPath: parsePorcelain(status) };
60
60
  }
61
61
 
62
62
  async function collectDiffArtifacts(
63
- ctx: CollectCtx<WorkspaceDiffSnapshot | undefined>,
63
+ ctx: CollectContext<WorkspaceDiffSnapshot | undefined>,
64
64
  filter: ((path: string) => boolean) | undefined,
65
65
  ): Promise<CollectResult> {
66
66
  const snapshot = ctx.snapshot;
@@ -27,7 +27,14 @@
27
27
 
28
28
  import { type Artifact, opaque } from "../handle.js";
29
29
  import type { Output } from "../output.js";
30
- import type { ArtifactCollector, ArtifactParser, CollectCtx, Outcome, ParseCtx, SnapshotCtx } from "../output-spec.js";
30
+ import type {
31
+ ArtifactCollector,
32
+ ArtifactParser,
33
+ CollectContext,
34
+ Outcome,
35
+ ParseContext,
36
+ SnapshotContext,
37
+ } from "../output-spec.js";
31
38
  import { execFileAsync, GIT_EXEC_TIMEOUT_MS } from "./exec.js";
32
39
 
33
40
  /**
@@ -104,7 +111,7 @@ async function git(cwd: string, ...args: string[]): Promise<string> {
104
111
  * `gitCommitCollector` handles `undefined` snapshot gracefully by
105
112
  * emitting an artifact carrying a `noOp: true` payload.
106
113
  */
107
- export async function gitHeadSnapshot(ctx: SnapshotCtx): Promise<GitHeadSnapshot | undefined> {
114
+ export async function gitHeadSnapshot(ctx: SnapshotContext): Promise<GitHeadSnapshot | undefined> {
108
115
  try {
109
116
  const sha = await git(ctx.cwd, "rev-parse", "HEAD");
110
117
  return sha ? { baselineSha: sha } : undefined;
@@ -126,7 +133,7 @@ export async function gitHeadSnapshot(ctx: SnapshotCtx): Promise<GitHeadSnapshot
126
133
  */
127
134
  export const gitCommitCollector: ArtifactCollector<GitHeadSnapshot | undefined> = {
128
135
  snapshot: gitHeadSnapshot,
129
- async collect(ctx: CollectCtx<GitHeadSnapshot | undefined>) {
136
+ async collect(ctx: CollectContext<GitHeadSnapshot | undefined>) {
130
137
  const baselineSha = ctx.snapshot?.baselineSha;
131
138
  if (!baselineSha) {
132
139
  // Deliberate degrade: the stage ran outside a (working) git repo.
@@ -236,7 +243,7 @@ function isGitCommitRecord(r: unknown): r is GitCommitRecord {
236
243
  * commit data) and projects it into `GitCommitData`. No I/O.
237
244
  */
238
245
  export const gitCommitParser: ArtifactParser<GitHeadSnapshot | undefined, "git-commit", GitCommitData> = {
239
- parse(ctx: ParseCtx<GitHeadSnapshot | undefined>) {
246
+ parse(ctx: ParseContext<GitHeadSnapshot | undefined>) {
240
247
  const artifact = ctx.artifacts[0];
241
248
  const meta = artifact?.meta;
242
249
  if (!isGitCommitMeta(meta)) {
package/output-spec.ts CHANGED
@@ -27,7 +27,7 @@ import type { BranchEntry } from "./transcript.js";
27
27
  // Snapshot — pre-stage reference capture (shared by collector + parser)
28
28
  // ---------------------------------------------------------------------------
29
29
 
30
- export interface SnapshotCtx {
30
+ export interface SnapshotContext {
31
31
  cwd: string;
32
32
  runId: string;
33
33
  stageIndex: number;
@@ -45,7 +45,7 @@ export interface SnapshotCtx {
45
45
  * prefix without re-materialising a slice. `snapshot` is whatever the
46
46
  * collector's optional `snapshot` hook returned.
47
47
  */
48
- export interface CollectCtx<Snapshot = unknown> extends SnapshotCtx {
48
+ export interface CollectContext<Snapshot = unknown> extends SnapshotContext {
49
49
  branch: BranchEntry[];
50
50
  branchOffset?: number;
51
51
  snapshot: Snapshot;
@@ -97,8 +97,8 @@ export type CollectResult = { kind: "ok"; artifacts: readonly Artifact[] } | { k
97
97
  * widening at every call site.
98
98
  */
99
99
  export interface ArtifactCollector<Snapshot = unknown> {
100
- snapshot?(ctx: SnapshotCtx): Promise<Snapshot> | Snapshot;
101
- collect(ctx: CollectCtx<Snapshot>): Promise<CollectResult> | CollectResult;
100
+ snapshot?(ctx: SnapshotContext): Promise<Snapshot> | Snapshot;
101
+ collect(ctx: CollectContext<Snapshot>): Promise<CollectResult> | CollectResult;
102
102
  }
103
103
 
104
104
  // ---------------------------------------------------------------------------
@@ -106,12 +106,12 @@ export interface ArtifactCollector<Snapshot = unknown> {
106
106
  // ---------------------------------------------------------------------------
107
107
 
108
108
  /**
109
- * Context handed to a parser's `parse`. Extends `CollectCtx` with the
109
+ * Context handed to a parser's `parse`. Extends `CollectContext` with the
110
110
  * `artifacts` the matching collector just returned, so parsers can
111
111
  * narrow on `artifacts[0].handle.kind` and inspect any `meta` the
112
112
  * collector attached. `snapshot` flows through unchanged.
113
113
  */
114
- export interface ParseCtx<Snapshot = unknown> extends CollectCtx<Snapshot> {
114
+ export interface ParseContext<Snapshot = unknown> extends CollectContext<Snapshot> {
115
115
  artifacts: readonly Artifact[];
116
116
  }
117
117
 
@@ -133,7 +133,7 @@ export type ParseResult<Kind extends string = string, Data = unknown> =
133
133
  * Method shorthand for the same bivariance reason as `ArtifactCollector`.
134
134
  */
135
135
  export interface ArtifactParser<Snapshot = unknown, Kind extends string = string, Data = unknown> {
136
- parse(ctx: ParseCtx<Snapshot>): Promise<ParseResult<Kind, Data>> | ParseResult<Kind, Data>;
136
+ parse(ctx: ParseContext<Snapshot>): Promise<ParseResult<Kind, Data>> | ParseResult<Kind, Data>;
137
137
  }
138
138
 
139
139
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -46,7 +46,9 @@
46
46
  "chain-state.ts",
47
47
  "command.ts",
48
48
  "command-run.ts",
49
+ "death-scene.ts",
49
50
  "execution-host.ts",
51
+ "failure-memos.ts",
50
52
  "loop-constructors.ts",
51
53
  "loops/",
52
54
  "extension.ts",
@@ -86,6 +88,7 @@
86
88
  "validation-bounds.ts",
87
89
  "validate-workflow.ts",
88
90
  "validate/",
91
+ "worktree-digest.ts",
89
92
  "docs-protocol.ts",
90
93
  "docs/",
91
94
  "!docs/*.png",
@@ -108,7 +111,7 @@
108
111
  ]
109
112
  },
110
113
  "dependencies": {
111
- "@juicesharp/rpiv-config": "^2.1.0",
114
+ "@juicesharp/rpiv-config": "^2.3.0",
112
115
  "jiti": "^2.7.0",
113
116
  "typebox": "^1.1.24"
114
117
  },
package/preview.ts CHANGED
@@ -24,8 +24,15 @@ export const CMD_USAGE_RUN = (name: string) => `Usage: /wf ${name} <description>
24
24
  // Public formatters
25
25
  // ===========================================================================
26
26
 
27
+ /**
28
+ * Description-truncation cap (characters) for the workflow-list view. Test-pinned
29
+ * at `preview.test.ts` ("truncates long descriptions at 50 characters with
30
+ * ellipsis"); the body reserves 3 chars for the trailing "...".
31
+ */
32
+ const DESC_TRUNCATE_LEN = 50;
33
+
27
34
  /** Truncate a description to `maxLen` characters, appending "..." if truncated. */
28
- function truncateDescription(desc: string, maxLen = 50): string {
35
+ function truncateDescription(desc: string, maxLen = DESC_TRUNCATE_LEN): string {
29
36
  if (desc.length <= maxLen) return desc;
30
37
  return `${desc.slice(0, maxLen - 3)}...`;
31
38
  }
package/registration.ts CHANGED
@@ -170,15 +170,15 @@ export type { Output, OutputMeta, RunView, Verdict } from "./output.js";
170
170
  export {
171
171
  type ArtifactCollector,
172
172
  type ArtifactParser,
173
- type CollectCtx,
173
+ type CollectContext,
174
174
  type CollectResult,
175
175
  defineCollector,
176
176
  defineParser,
177
177
  type Outcome,
178
178
  type OutputSpec,
179
- type ParseCtx,
179
+ type ParseContext,
180
180
  type ParseResult,
181
- type SnapshotCtx,
181
+ type SnapshotContext,
182
182
  } from "./output-spec.js";
183
183
  export { eq, gt, gte, lt, lte, type NumericPredicate, type Predicate } from "./predicates.js";
184
184
  export type {
@@ -219,6 +219,11 @@ export {
219
219
  type WorkflowHeader,
220
220
  type WorkflowStage,
221
221
  } from "./state/index.js";
222
+ // The persisted-session branch shape the host-injected `readSessionBranch`
223
+ // reader returns (`WorkflowExecutionProvider.readSessionBranch` /
224
+ // `RunContext.readSessionBranch`). Re-exported so the rpiv-pi host can name the
225
+ // return type when it narrows `SessionManager.open(file).getBranch()`.
226
+ export type { BranchEntry } from "./transcript.js";
222
227
  export { DEFAULT_TRIGGER, type RunTrigger } from "./triggers.js";
223
228
  export { typeboxSchema } from "./typebox-adapter.js";
224
229
  // `RunState` is deliberately NOT here — it is runner-private; user contexts
package/routing.ts CHANGED
@@ -15,7 +15,7 @@
15
15
  * `terminal` export. The `kind: "stop"` literal is untouched.
16
16
  *
17
17
  * Errors are returned, not thrown. The caller (runner) switches on
18
- * `kind` and routes `"err"` through `recordTerminalFailure` — same as
18
+ * `kind` and routes `"err"` through `recordFatalFailure` — same as
19
19
  * any other halt site.
20
20
  */
21
21
 
@@ -57,46 +57,6 @@ export function edgeIsDecision(workflow: Workflow, current: string): boolean {
57
57
  return typeof workflow.edges[current] === "function";
58
58
  }
59
59
 
60
- /**
61
- * The not-taken targets of a DECISION edge that are pure RECOVERY arms — a
62
- * stage whose own out-edge is a STRING edge pointing at an already-visited
63
- * stage, i.e. taking it would loop BACK into covered territory rather than make
64
- * forward progress.
65
- *
66
- * Used by the progress bridge (`rpiv-pi` lane-progress): when a gate takes its
67
- * pass arm, the failure arm (build's `slice-fix` / `plan-fix` / `code-fix`) is bypassed for good
68
- * on this path, so it counts toward "distinct nodes covered" — the bar reaches
69
- * full WHILE the terminal stage runs instead of freezing one-below until the
70
- * `onWorkflowEnd` snap. Surfaced as the `onRoute` lifecycle event's `bypassed`
71
- * argument.
72
- *
73
- * Deliberately narrow: a not-taken target is credited ONLY when its successor
74
- * is a string edge to an already-visited stage. A FORWARD arm (its successor
75
- * not yet visited) is merely deferred, not bypassed — crediting it would push
76
- * the numerator AHEAD of the stages actually reached. An arm with a gate/
77
- * terminal out-edge is left uncredited (conservative; never over-counts).
78
- *
79
- * Returns distinct names; `chosen`, `STOP`, and already-visited arms are
80
- * excluded, so the credited set never inflates the numerator past the reachable
81
- * total.
82
- */
83
- export function bypassedRecoveryArms(
84
- workflow: Workflow,
85
- from: string,
86
- chosen: string,
87
- visited: ReadonlySet<string>,
88
- ): string[] {
89
- const edge = workflow.edges[from];
90
- if (typeof edge !== "function" || !Array.isArray(edge.targets)) return [];
91
- const out: string[] = [];
92
- for (const t of edge.targets) {
93
- if (t === chosen || t === STOP || visited.has(t)) continue;
94
- const succ = workflow.edges[t]; // one-hop loop-back test
95
- if (typeof succ === "string" && visited.has(succ)) out.push(t);
96
- }
97
- return out;
98
- }
99
-
100
60
  // ---------------------------------------------------------------------------
101
61
  // Internals
102
62
  // ---------------------------------------------------------------------------
@@ -7,20 +7,25 @@
7
7
  * instead of catching. The injected runner owns the catch for
8
8
  * downstream-stage throws — the `ChainDeps` injection (the `LoopDeps`
9
9
  * pattern) keeps this module's imports strictly downward: the chain walk's
10
- * runStage ↔ advanceChain recursion is composed in run-stage.ts, not
10
+ * dispatchStage ↔ advanceChain recursion is composed in run-stage.ts, not
11
11
  * spelled as a module cycle.
12
12
  */
13
13
 
14
14
  import { takeRouteNote } from "../api.js";
15
- import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
15
+ import { auditCtxFor, failedArgs, recordFatalFailure } from "../audit.js";
16
16
  import { resolveSkill } from "../chain-state.js";
17
17
  import { lifecycleCtxFor, skillStageRef } from "../events.js";
18
18
  import { nowIso } from "../internal-utils.js";
19
- import { FAIL_BACKWARD_JUMP_EXHAUSTED, MSG_CHAIN_ADVANCE_FAILED, MSG_ROUTING_AUDIT_DROPPED } from "../messages.js";
20
- import { bypassedRecoveryArms, edgeIsDecision, nextStage } from "../routing.js";
19
+ import {
20
+ FAIL_BACKWARD_JUMP_EXHAUSTED,
21
+ FAIL_GATE_STOP,
22
+ MSG_CHAIN_ADVANCE_FAILED,
23
+ MSG_ROUTING_AUDIT_DROPPED,
24
+ } from "../messages.js";
25
+ import { edgeIsDecision, nextStage } from "../routing.js";
21
26
  import { appendRoutingDecision } from "../state/index.js";
22
27
  import type { RunContext, WorkflowHostContext } from "../types.js";
23
- import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
28
+ import { type ChainOutcome, finalizeWorkflow, haltChain } from "./failure.js";
24
29
 
25
30
  /**
26
31
  * The walk continuation injected by the composition site
@@ -29,16 +34,16 @@ import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
29
34
  * the mutual recursion of the chain walk lives in ONE composing module.
30
35
  */
31
36
  export interface ChainDeps {
32
- runNext: (curCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
37
+ runNext: (hostCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
33
38
  }
34
39
 
35
40
  /**
36
41
  * Decomposed into three helpers — `auditRoutingDecision`,
37
- * `checkBackwardJumpGuard`, `haltOnRoutingError` — each owning one
42
+ * `ensureBackwardJumpGuard`, `haltOnRoutingError` — each owning one
38
43
  * structural concern.
39
44
  */
40
45
  export async function advanceChain(
41
- curCtx: WorkflowHostContext,
46
+ hostCtx: WorkflowHostContext,
42
47
  currentName: string,
43
48
  idx: number,
44
49
  run: RunContext,
@@ -53,39 +58,48 @@ export async function advanceChain(
53
58
  const result = nextStage(run.workflow, currentName, { output: run.state.output, state: run.state });
54
59
 
55
60
  if (result.kind === "err") {
56
- return haltOnRoutingError(curCtx, run, currentName, result.reason);
61
+ return haltOnRoutingError(hostCtx, run, currentName, result.reason);
57
62
  }
58
63
 
59
- const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
60
-
61
- // Recovery arms this decision passed over for good — credited toward progress
62
- // "coverage" by the bridge so a clean run's bar isn't frozen one-below until the
63
- // end (build's slice-fix/plan-fix/code-fix). Empty for deterministic edges (no alternatives).
64
- const chosen = result.kind === "stop" ? "stop" : result.stage;
65
- const bypassed = wasDecision ? bypassedRecoveryArms(run.workflow, currentName, chosen, run.visited) : [];
64
+ const skill = resolveSkill(run.workflow.stages[currentName]!, currentName);
65
+ const fromRef = skillStageRef(currentName, idx + 1, skill);
66
66
 
67
67
  if (result.kind === "stop") {
68
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run), bypassed);
69
- return finalizeWorkflow(curCtx, run);
68
+ // A decision edge stopping the chain is audited like any forward pick,
69
+ // and a stop carrying a ROUTE_NOTE is `match`'s no-fallback termination:
70
+ // the gate found no branch for the value it read (typically a failed
71
+ // verdict on a pass-only gate). That run is BLOCKED awaiting
72
+ // intervention, not complete — record a terminal failure row so the
73
+ // trail and the lane show a stopped run instead of a silent ✓. A
74
+ // noteless decision stop (a custom edge deliberately returning STOP)
75
+ // and the ordinary end-of-chain stop remain completions.
76
+ const edge = run.workflow.edges[currentName];
77
+ const note = wasDecision && typeof edge === "function" ? takeRouteNote(edge) : undefined;
78
+ if (wasDecision) auditRoutingDecision(hostCtx, run, idx, currentName, "stop", note);
79
+ await run.lifecycle.fire(hostCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
80
+ if (note !== undefined) {
81
+ return haltChain(hostCtx, run, currentName, skill, failedArgs(FAIL_GATE_STOP(currentName, note)));
82
+ }
83
+ return finalizeWorkflow(hostCtx, run);
70
84
  }
71
85
 
72
86
  const nextName = result.stage;
73
87
  if (wasDecision) {
74
- auditRoutingDecision(curCtx, run, idx, currentName, nextName);
75
- const guard = await checkBackwardJumpGuard(curCtx, run, nextName);
88
+ auditRoutingDecision(hostCtx, run, idx, currentName, nextName);
89
+ const guard = await ensureBackwardJumpGuard(hostCtx, run, nextName);
76
90
  if (guard !== "continue") return guard;
77
91
  }
78
92
 
79
93
  // Fire onRoute after the routing decision has been audited (when applicable),
80
94
  // before the next stage runs. Deterministic auto-edges still fire so
81
95
  // listeners see every transition.
82
- await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run), bypassed);
96
+ await run.lifecycle.fire(hostCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
83
97
 
84
98
  // deps.runNext owns the catch for throws out of the *next* stage, so the
85
99
  // JSONL row records `nextName` (the stage that actually threw) rather than
86
100
  // `currentName` (which would mis-attribute the failure to the prior stage
87
101
  // that already completed successfully).
88
- return deps.runNext(curCtx, nextName, idx + 1, run);
102
+ return deps.runNext(hostCtx, nextName, idx + 1, run);
89
103
  }
90
104
 
91
105
  /**
@@ -100,17 +114,21 @@ export async function advanceChain(
100
114
  * routing rows are pure telemetry).
101
115
  */
102
116
  function auditRoutingDecision(
103
- curCtx: WorkflowHostContext,
117
+ hostCtx: WorkflowHostContext,
104
118
  run: RunContext,
105
119
  idx: number,
106
120
  currentName: string,
107
121
  nextName: string,
122
+ noteOverride?: string,
108
123
  ): void {
109
124
  // Read-and-clear any note the edge attached to THIS pick (e.g. gate's
110
125
  // fallback-fired diagnostic). Same tick as the invocation — no other
111
126
  // decision can interleave. `undefined` is dropped by JSON.stringify.
127
+ // The stop branch reads the note BEFORE calling here (it decides
128
+ // halt-vs-finalize on it) and passes it as `noteOverride` — takeRouteNote
129
+ // is read-and-clear, so a second read would see nothing.
112
130
  const edge = run.workflow.edges[currentName];
113
- const note = typeof edge === "function" ? takeRouteNote(edge) : undefined;
131
+ const note = noteOverride ?? (typeof edge === "function" ? takeRouteNote(edge) : undefined);
114
132
  const fromStageIndex = idx + 1;
115
133
  const wrote = appendRoutingDecision(run.cwd, run.runId, {
116
134
  type: "routing",
@@ -122,7 +140,7 @@ function auditRoutingDecision(
122
140
  });
123
141
  if (!wrote) {
124
142
  run.state.telemetry.droppedRoutingRows.push({ fromStageIndex, fromStage: currentName, decision: nextName });
125
- curCtx.ui.notify(MSG_ROUTING_AUDIT_DROPPED(currentName, nextName), "warning");
143
+ hostCtx.ui.notify(MSG_ROUTING_AUDIT_DROPPED(currentName, nextName), "warning");
126
144
  }
127
145
  }
128
146
 
@@ -156,8 +174,8 @@ function auditRoutingDecision(
156
174
  * Trip attribution targets `nextName` (the stage the guard refused to
157
175
  * re-enter), not the just-completed stage.
158
176
  */
159
- async function checkBackwardJumpGuard(
160
- curCtx: WorkflowHostContext,
177
+ async function ensureBackwardJumpGuard(
178
+ hostCtx: WorkflowHostContext,
161
179
  run: RunContext,
162
180
  nextName: string,
163
181
  ): Promise<"continue" | ChainOutcome> {
@@ -166,8 +184,8 @@ async function checkBackwardJumpGuard(
166
184
  run.revisits.set(nextName, revisits);
167
185
  run.state.telemetry.backwardJumps++;
168
186
  if (revisits <= run.maxBackwardJumps) return "continue";
169
- await recordTerminalFailure(
170
- curCtx,
187
+ await recordFatalFailure(
188
+ hostCtx,
171
189
  auditCtxFor(run, nextName, nextName),
172
190
  failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(nextName, revisits, run.maxBackwardJumps)),
173
191
  );
@@ -180,13 +198,13 @@ async function checkBackwardJumpGuard(
180
198
  * `currentName` (the edge belongs to the just-completed stage).
181
199
  */
182
200
  async function haltOnRoutingError(
183
- curCtx: WorkflowHostContext,
201
+ hostCtx: WorkflowHostContext,
184
202
  run: RunContext,
185
203
  currentName: string,
186
204
  reason: string,
187
205
  ): Promise<ChainOutcome> {
188
- await recordTerminalFailure(
189
- curCtx,
206
+ await recordFatalFailure(
207
+ hostCtx,
190
208
  auditCtxFor(run, currentName, currentName),
191
209
  failedArgs(MSG_CHAIN_ADVANCE_FAILED(currentName, reason), reason),
192
210
  );
package/runner/errors.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * without importing into `runner/`; this module re-exports it so every layer of
5
5
  * the per-stage pipeline (preflights, input validation, the loop shortcut) keeps
6
6
  * its local `./errors.js` spelling and the single catch site
7
- * (`runStageOrRecordFailure`, run-stage.ts) catches it as before.
7
+ * (`dispatchStageOrRecordFailure`, run-stage.ts) catches it as before.
8
8
  */
9
9
 
10
10
  export { haltPreflight, invariantPreflight, StagePreflightError } from "../stage-errors.js";