@juicesharp/rpiv-workflow 1.19.0 → 1.20.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 (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/routing.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { type EdgeContext, type EdgeFn, STOP, type Workflow } from "./api.js";
17
+ import { formatError } from "./internal-utils.js";
17
18
 
18
19
  /**
19
20
  * Three-way return from `nextStage`. Matches the convention established by
@@ -62,10 +63,9 @@ function invokeEdgeFn(
62
63
  try {
63
64
  return { kind: "ok", value: fn(ctx) };
64
65
  } catch (e) {
65
- const msg = e instanceof Error ? e.message : String(e);
66
66
  return {
67
67
  kind: "err",
68
- reason: `workflow edge function at "${current}" threw: ${msg}`,
68
+ reason: `workflow edge function at "${current}" threw: ${formatError(e)}`,
69
69
  };
70
70
  }
71
71
  }
package/runner/by-name.ts CHANGED
@@ -21,7 +21,8 @@
21
21
 
22
22
  import type { WorkflowHostContext } from "../host.js";
23
23
  import { findWorkflow, loadWorkflows } from "../load/index.js";
24
- import { type RunWorkflowOptions, type RunWorkflowResult, runWorkflow } from "./runner.js";
24
+ import type { RunWorkflowOptions, RunWorkflowResult } from "../types.js";
25
+ import { runWorkflow } from "./runner.js";
25
26
 
26
27
  /**
27
28
  * Options for `runWorkflowByName` — the full `RunWorkflowOptions` surface
@@ -36,7 +36,8 @@ import type { WorkflowHostContext } from "../host.js";
36
36
  import { findWorkflow, loadWorkflows } from "../load/index.js";
37
37
  import { MSG_LOAD_ABORTED, MSG_RESUME_WORKFLOW_GONE, MSG_RUN_NOT_FOUND } from "../messages.js";
38
38
  import { resolveRun } from "../state/index.js";
39
- import { type ResumeWorkflowOptions, type RunWorkflowResult, resumeWorkflow } from "./runner.js";
39
+ import type { RunWorkflowResult } from "../types.js";
40
+ import { type ResumeWorkflowOptions, resumeWorkflow } from "./runner.js";
40
41
 
41
42
  /**
42
43
  * Options for `resumeWorkflowByRunId` — the full `ResumeWorkflowOptions` surface
@@ -1,26 +1,36 @@
1
1
  /**
2
2
  * Routing layer after a stage completes successfully: pick the next stage,
3
3
  * audit predicate-mediated decisions, enforce the backward-jump guard,
4
- * then recurse via `runStageOrRecordFailure`.
4
+ * then recurse via the injected `deps.runNext`.
5
5
  *
6
6
  * `nextStage` returns a tagged union; `advanceChain` switches on `kind`
7
- * instead of catching. `runStageOrRecordFailure` owns the catch for
8
- * downstream-stage throws.
7
+ * instead of catching. The injected runner owns the catch for
8
+ * downstream-stage throws — the `ChainDeps` injection (the `LoopDeps`
9
+ * pattern) keeps this module's imports strictly downward: the chain walk's
10
+ * runStage ↔ advanceChain recursion is composed in run-stage.ts, not
11
+ * spelled as a module cycle.
9
12
  */
10
13
 
11
- import { auditCtxFor, nowIso, recordTerminalFailure } from "../audit.js";
12
- import { resolveSkill } from "../internal-utils.js";
13
- import { skillStageRef } from "../lifecycle.js";
14
- import {
15
- ERR_BACKWARD_JUMP_EXHAUSTED,
16
- MSG_BACKWARD_JUMP_EXHAUSTED,
17
- MSG_CHAIN_ADVANCE_FAILED,
18
- MSG_ROUTING_AUDIT_DROPPED,
19
- } from "../messages.js";
14
+ import { takeRouteNote } from "../api.js";
15
+ import { auditCtxFor, failedArgs, recordTerminalFailure } from "../audit.js";
16
+ import { resolveSkill } from "../chain-state.js";
17
+ import { lifecycleCtxFor, skillStageRef } from "../events.js";
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
20
  import { edgeIsDecision, nextStage } from "../routing.js";
21
21
  import { appendRoutingDecision } from "../state/index.js";
22
22
  import type { RunContext, WorkflowHostContext } from "../types.js";
23
- import { finalizeWorkflow, lifecycleCtxFor, runStageOrRecordFailure } from "./runner.js";
23
+ import { type ChainOutcome, finalizeWorkflow } from "./failure.js";
24
+
25
+ /**
26
+ * The walk continuation injected by the composition site
27
+ * (run-stage.ts): run the routed next stage through the single catch
28
+ * site. Injected so this module never imports the per-stage pipeline back —
29
+ * the mutual recursion of the chain walk lives in ONE composing module.
30
+ */
31
+ export interface ChainDeps {
32
+ runNext: (curCtx: WorkflowHostContext, name: string, idx: number, run: RunContext) => Promise<ChainOutcome>;
33
+ }
24
34
 
25
35
  /**
26
36
  * Decomposed into three helpers — `auditRoutingDecision`,
@@ -32,7 +42,8 @@ export async function advanceChain(
32
42
  currentName: string,
33
43
  idx: number,
34
44
  run: RunContext,
35
- ): Promise<void> {
45
+ deps: ChainDeps,
46
+ ): Promise<ChainOutcome> {
36
47
  // Mark the just-completed stage as visited BEFORE consulting the next edge.
37
48
  // A thrown EdgeFn would otherwise leave currentName un-marked, opening a
38
49
  // (narrow) window where a recovery path could under-count revisits.
@@ -42,22 +53,21 @@ export async function advanceChain(
42
53
  const result = nextStage(run.workflow, currentName, { output: run.state.output, state: run.state });
43
54
 
44
55
  if (result.kind === "err") {
45
- await haltOnRoutingError(curCtx, run, currentName, result.reason);
46
- return;
56
+ return haltOnRoutingError(curCtx, run, currentName, result.reason);
47
57
  }
48
58
 
49
59
  const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
50
60
 
51
61
  if (result.kind === "stop") {
52
62
  await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
53
- finalizeWorkflow(curCtx, run);
54
- return;
63
+ return finalizeWorkflow(curCtx, run);
55
64
  }
56
65
 
57
66
  const nextName = result.stage;
58
67
  if (wasDecision) {
59
68
  auditRoutingDecision(curCtx, run, idx, currentName, nextName);
60
- if (!(await checkBackwardJumpGuard(curCtx, run, nextName))) return;
69
+ const guard = await checkBackwardJumpGuard(curCtx, run, nextName);
70
+ if (guard !== "continue") return guard;
61
71
  }
62
72
 
63
73
  // Fire onRoute after the routing decision has been audited (when applicable),
@@ -65,11 +75,11 @@ export async function advanceChain(
65
75
  // listeners see every transition.
66
76
  await run.lifecycle.fire(curCtx, "onRoute", fromRef, nextName, lifecycleCtxFor(run));
67
77
 
68
- // runStageOrRecordFailure owns the catch for throws out of the *next* stage,
69
- // so the JSONL row records `nextName` (the stage that actually threw)
70
- // rather than `currentName` (which would mis-attribute the failure to
71
- // the prior stage that already completed successfully).
72
- await runStageOrRecordFailure(curCtx, nextName, idx + 1, run);
78
+ // deps.runNext owns the catch for throws out of the *next* stage, so the
79
+ // JSONL row records `nextName` (the stage that actually threw) rather than
80
+ // `currentName` (which would mis-attribute the failure to the prior stage
81
+ // that already completed successfully).
82
+ return deps.runNext(curCtx, nextName, idx + 1, run);
73
83
  }
74
84
 
75
85
  /**
@@ -90,12 +100,18 @@ function auditRoutingDecision(
90
100
  currentName: string,
91
101
  nextName: string,
92
102
  ): void {
103
+ // Read-and-clear any note the edge attached to THIS pick (e.g. gate's
104
+ // fallback-fired diagnostic). Same tick as the invocation — no other
105
+ // decision can interleave. `undefined` is dropped by JSON.stringify.
106
+ const edge = run.workflow.edges[currentName];
107
+ const note = typeof edge === "function" ? takeRouteNote(edge) : undefined;
93
108
  const fromStageIndex = idx + 1;
94
109
  const wrote = appendRoutingDecision(run.cwd, run.runId, {
95
110
  type: "routing",
96
111
  fromStageIndex,
97
112
  fromStage: currentName,
98
113
  decision: nextName,
114
+ note,
99
115
  ts: nowIso(),
100
116
  });
101
117
  if (!wrote) {
@@ -105,9 +121,9 @@ function auditRoutingDecision(
105
121
  }
106
122
 
107
123
  /**
108
- * Per-loop cap on decision-edge retries. Returns `true` when the run may
109
- * continue, `false` when the cap tripped (and the terminal failure has
110
- * been recorded).
124
+ * Per-loop cap on decision-edge retries. Returns `"continue"` when the run
125
+ * may proceed, or the `"halted"` outcome when the cap tripped (and the
126
+ * terminal failure has been recorded).
111
127
  *
112
128
  * A "backward jump" is a *decision-edge* resolving to an already-visited
113
129
  * stage — i.e. a deliberate retry choice. Deterministic forward edges that
@@ -129,21 +145,20 @@ async function checkBackwardJumpGuard(
129
145
  curCtx: WorkflowHostContext,
130
146
  run: RunContext,
131
147
  nextName: string,
132
- ): Promise<boolean> {
148
+ ): Promise<"continue" | ChainOutcome> {
133
149
  const { state } = run;
134
150
  if (!run.visited.has(nextName)) {
135
151
  state.telemetry.backwardJumps = 0;
136
- return true;
152
+ return "continue";
137
153
  }
138
154
  state.telemetry.backwardJumps++;
139
- if (state.telemetry.backwardJumps <= run.maxBackwardJumps) return true;
140
- await recordTerminalFailure(curCtx, auditCtxFor(run, nextName, nextName), {
141
- status: "failed",
142
- notifyMsg: MSG_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
143
- notifyLevel: "error",
144
- errMsg: ERR_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps),
145
- });
146
- return false;
155
+ if (state.telemetry.backwardJumps <= run.maxBackwardJumps) return "continue";
156
+ await recordTerminalFailure(
157
+ curCtx,
158
+ auditCtxFor(run, nextName, nextName),
159
+ failedArgs(FAIL_BACKWARD_JUMP_EXHAUSTED(state.telemetry.backwardJumps, run.maxBackwardJumps)),
160
+ );
161
+ return "halted";
147
162
  }
148
163
 
149
164
  /**
@@ -156,11 +171,11 @@ async function haltOnRoutingError(
156
171
  run: RunContext,
157
172
  currentName: string,
158
173
  reason: string,
159
- ): Promise<void> {
160
- await recordTerminalFailure(curCtx, auditCtxFor(run, currentName, currentName), {
161
- status: "failed",
162
- notifyMsg: MSG_CHAIN_ADVANCE_FAILED(currentName, reason),
163
- notifyLevel: "error",
164
- errMsg: reason,
165
- });
174
+ ): Promise<ChainOutcome> {
175
+ await recordTerminalFailure(
176
+ curCtx,
177
+ auditCtxFor(run, currentName, currentName),
178
+ failedArgs(MSG_CHAIN_ADVANCE_FAILED(currentName, reason), reason),
179
+ );
180
+ return "halted";
166
181
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The runner's typed-throw vocabulary — a leaf module so every layer of the
3
+ * per-stage pipeline (preflights, input validation, the loop shortcut) can
4
+ * throw it and the single catch site (`runStageOrRecordFailure`,
5
+ * run-stage.ts) can catch it without any module importing back up.
6
+ */
7
+
8
+ /**
9
+ * Thrown by a preflight check on failure; carries the recorded-row
10
+ * attribution + notify/err messages so `runStageOrRecordFailure` can land
11
+ * a uniform JSONL row regardless of which slot tripped.
12
+ *
13
+ * `kind` annotates the violation class for diagnostics only — control
14
+ * flow at the catch site is uniform:
15
+ * - `"halt"` — runtime-state failure (skill not registered, missing
16
+ * upstream artifact, schema mismatch).
17
+ * - `"invariant"` — authoring-time-knowable violation that
18
+ * `validateWorkflow` should reject at load. A throw
19
+ * here means validation was bypassed or the rule lives
20
+ * only in the runner (continue-without-pi).
21
+ */
22
+ export class StagePreflightError extends Error {
23
+ constructor(
24
+ public readonly kind: "halt" | "invariant",
25
+ public readonly skill: string,
26
+ public readonly notifyMsg: string,
27
+ public readonly errMsg: string,
28
+ public readonly notifyPartial: boolean,
29
+ ) {
30
+ super(errMsg);
31
+ this.name = "StagePreflightError";
32
+ }
33
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Terminal-outcome translation for the chain walk — a LEAF imported downward
3
+ * by runner.ts, chain-advance.ts, and run-stage.ts. Owns the ONE
4
+ * "entry threw" → failure-row translation and the run-completion finalizer,
5
+ * plus the `ChainOutcome` vocabulary the whole walk returns.
6
+ */
7
+
8
+ import {
9
+ abortedArgs,
10
+ auditCtxFor,
11
+ failedArgs,
12
+ notifyPartialArtifacts,
13
+ recordTerminalFailure,
14
+ terminate,
15
+ } from "../audit.js";
16
+ import { formatError } from "../internal-utils.js";
17
+ import { FAIL_WORKFLOW_ABORTED, MSG_STAGE_THREW, MSG_WORKFLOW_COMPLETE, STATUS_KEY } from "../messages.js";
18
+ import type { RunContext, WorkflowHostContext } from "../types.js";
19
+ import { StagePreflightError } from "./errors.js";
20
+
21
+ /**
22
+ * Explicit result of one chain-walk step, threaded up through
23
+ * `advanceChain` / `runStage` / `runStageOrRecordFailure`. The walk's halt
24
+ * protocol used to be record-then-quietly-unwind by convention — every halt
25
+ * site had to remember a bare `return` after `recordTerminalFailure`. With a
26
+ * non-void return type, a branch that records a failure but forgets to stop
27
+ * the walk no longer typechecks: every arm must RETURN an outcome, and halts
28
+ * read `return haltChain(...)`.
29
+ *
30
+ * - `"halted"` — a terminal failure/abort row was recorded; the walk
31
+ * stops here and unwinds.
32
+ * - `"completed"` — the chain reached `stop`; `finalizeWorkflow` ran.
33
+ * - `"dispatched"` — the walk handed off to a session/loop continuation
34
+ * (Pi owns the live session; the eventual outcome
35
+ * resolves inside the continuation's own walk frames).
36
+ */
37
+ export type ChainOutcome = "halted" | "completed" | "dispatched";
38
+
39
+ /**
40
+ * The composed chain-advance continuation (run-stage.ts wires it) —
41
+ * injected into stage runners that advance the chain themselves (the script
42
+ * path) so they never import the composition site back.
43
+ */
44
+ export type AdvanceFn = (
45
+ curCtx: WorkflowHostContext,
46
+ completedName: string,
47
+ completedIdx: number,
48
+ run: RunContext,
49
+ ) => Promise<ChainOutcome>;
50
+
51
+ /**
52
+ * Record a terminal failure and yield the `"halted"` outcome — the standard
53
+ * halt idiom for walk arms: `return haltChain(...)`.
54
+ */
55
+ export async function haltChain(
56
+ curCtx: WorkflowHostContext,
57
+ run: RunContext,
58
+ stageName: string,
59
+ skill: string,
60
+ args: Parameters<typeof recordTerminalFailure>[2],
61
+ onFailure?: (ctx: WorkflowHostContext) => void,
62
+ ): Promise<ChainOutcome> {
63
+ await recordTerminalFailure(curCtx, auditCtxFor(run, stageName, skill), args, onFailure);
64
+ return "halted";
65
+ }
66
+
67
+ /**
68
+ * The ONE "entry threw" → terminal-failure-row translation (live + resume
69
+ * entries). Two flavours of throw land here:
70
+ *
71
+ * - `StagePreflightError` — a known preflight failure carrying its own
72
+ * attribution + messages. Recorded with the carried payload exactly.
73
+ * - Any other `Error` — unexpected machinery failure; recorded with the
74
+ * generic `MSG_STAGE_THREW` shape attributed to the stage id.
75
+ */
76
+ export async function recordEntryThrow(
77
+ curCtx: WorkflowHostContext,
78
+ name: string,
79
+ run: RunContext,
80
+ e: unknown,
81
+ ): Promise<ChainOutcome> {
82
+ if (e instanceof StagePreflightError) {
83
+ return haltChain(
84
+ curCtx,
85
+ run,
86
+ name,
87
+ e.skill,
88
+ failedArgs(e.notifyMsg, e.errMsg),
89
+ e.notifyPartial ? (ctx) => notifyPartialArtifacts(ctx, run.cwd, run.runId) : undefined,
90
+ );
91
+ }
92
+ const reason = formatError(e);
93
+ return haltChain(curCtx, run, name, name, failedArgs(MSG_STAGE_THREW(name, reason), reason));
94
+ }
95
+
96
+ /**
97
+ * Record the `"aborted"` terminal row for a cooperative-cancellation stop at
98
+ * the between-stage seam (`run.signal` aborted before `name` ran).
99
+ */
100
+ export function recordAbortedAtSeam(curCtx: WorkflowHostContext, name: string, run: RunContext): Promise<ChainOutcome> {
101
+ return haltChain(curCtx, run, name, name, abortedArgs(FAIL_WORKFLOW_ABORTED(name)));
102
+ }
103
+
104
+ export function finalizeWorkflow(curCtx: WorkflowHostContext, run: RunContext): ChainOutcome {
105
+ curCtx.ui.setStatus(STATUS_KEY, undefined);
106
+ curCtx.ui.notify(MSG_WORKFLOW_COMPLETE(run.state.stagesCompleted), "info");
107
+ terminate(run.state, { status: "completed" });
108
+ return "completed";
109
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * C7 regression: a failed run-header append refuses the run start. A lost
3
+ * header makes the run unlistable and unresumable while its stage rows land,
4
+ * and the name claim has already burned the name — so `runWorkflow` must
5
+ * reject BEFORE any stage executes and roll the claim back.
6
+ *
7
+ * Lives in its own file because `vi.mock` is module-scoped: every test here
8
+ * runs with `writeHeader` forced to fail.
9
+ */
10
+
11
+ import { mkdtempSync, rmSync } from "node:fs";
12
+ import { tmpdir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { createMockSessionChain } from "@juicesharp/rpiv-test-utils";
15
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
16
+ import type { Workflow } from "../api.js";
17
+ import { readNamesIndex } from "../state/index.js";
18
+ import { runWorkflow } from "./runner.js";
19
+
20
+ vi.mock("../state/writes.js", async (importOriginal) => {
21
+ const actual = await importOriginal<typeof import("../state/writes.js")>();
22
+ return { ...actual, writeHeader: vi.fn(() => false) };
23
+ });
24
+
25
+ const tinyWorkflow: Workflow = {
26
+ name: "tiny",
27
+ start: "research",
28
+ stages: { research: { kind: "produces", sessionPolicy: "fresh" } },
29
+ edges: { research: "stop" },
30
+ };
31
+
32
+ let tmpDir: string;
33
+
34
+ beforeEach(() => {
35
+ tmpDir = mkdtempSync(join(tmpdir(), "rpiv-workflow-header-fail-"));
36
+ });
37
+
38
+ afterEach(() => {
39
+ rmSync(tmpDir, { recursive: true, force: true });
40
+ });
41
+
42
+ describe("runWorkflow — header write failure (C7)", () => {
43
+ it("refuses the run start with no runId and zero stages executed", async () => {
44
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
45
+ const result = await runWorkflow(chain.ctx, { workflow: tinyWorkflow, input: "x" });
46
+
47
+ expect(result.success).toBe(false);
48
+ expect(result.runId).toBeUndefined(); // pre-flight rejection — no JSONL exists
49
+ expect(result.stagesCompleted).toBe(0);
50
+ expect(result.error).toContain("could not write the run header");
51
+ expect(chain.remaining()).toBe(0); // no session was ever opened
52
+ });
53
+
54
+ it("rolls back the name claim so the index never points at a run that doesn't exist", async () => {
55
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
56
+ const result = await runWorkflow(chain.ctx, { workflow: tinyWorkflow, input: "x", name: "auth" });
57
+
58
+ expect(result.success).toBe(false);
59
+ expect(result.error).toMatch(/could not write the run header/);
60
+ // claimName persisted the entry before writeHeader ran; the refusal
61
+ // must have released it.
62
+ expect(readNamesIndex(tmpDir) ?? {}).toEqual({});
63
+ });
64
+ });
package/runner/index.ts CHANGED
@@ -1,18 +1,12 @@
1
1
  /**
2
- * Workflow runner public surface. The runner is internally split into
3
- * three files (see `runner.ts`'s header for the module map); this barrel
4
- * re-exports only the symbols the package itself needs to publish.
2
+ * Workflow runner public surface. The runner is internally split by concern
3
+ * (see `runner.ts`'s header for the module map); this barrel re-exports only
4
+ * the symbols the package itself needs to publish.
5
5
  */
6
6
 
7
+ export type { RunWorkflowOptions, RunWorkflowResult } from "../types.js";
7
8
  export { type RunWorkflowByNameOptions, runWorkflowByName } from "./by-name.js";
8
9
  export { type ResumeWorkflowByRunIdOptions, resumeWorkflowByRunId } from "./by-run-id.js";
9
- export {
10
- MAX_BACKWARD_JUMPS,
11
- type ResumeWorkflowOptions,
12
- type RunWorkflowOptions,
13
- type RunWorkflowResult,
14
- resumeWorkflow,
15
- runWorkflow,
16
- } from "./runner.js";
17
-
18
- export { StagePreflightError } from "./stage-lifecycle.js";
10
+ export { StagePreflightError } from "./errors.js";
11
+ export { MAX_BACKWARD_JUMPS } from "./run-context.js";
12
+ export { type ResumeWorkflowOptions, resumeWorkflow, runWorkflow } from "./runner.js";
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Input-validation preflights for the runner's per-stage pipeline.
3
3
  *
4
- * Two validators run as `POST_PROMPT_CHECKS` in `stage-lifecycle.ts`:
4
+ * Two validators run after prompt prep in the single-stage pipeline
5
+ * (`runSingleStage`, run-stage.ts):
5
6
  * - `ensureInputValid` — validates upstream output against the stage's
6
7
  * declared `inputSchema`.
7
8
  * - `ensureContractInputValid` — validates upstream output against the
@@ -15,20 +16,21 @@
15
16
  * halting only on timeouts.
16
17
  */
17
18
 
18
- import { SchemaTimeoutError, withTimeout } from "../internal-utils.js";
19
+ import { formatError, withTimeout } from "../internal-utils.js";
19
20
  import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
20
- import { ERR_INPUT_VALIDATION_FAILED, ERR_SCHEMA_TIMEOUT, MSG_INPUT_VALIDATION_FAILED } from "../messages.js";
21
+ import { ERR_SCHEMA_TIMEOUT, FAIL_INPUT_VALIDATION } from "../messages.js";
21
22
  import type { RunContext } from "../types.js";
22
23
  import {
23
24
  DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
24
25
  describeFailure,
25
26
  MAX_VALIDATION_RETRY_TIMEOUT_MS,
26
27
  MIN_VALIDATION_RETRY_TIMEOUT_MS,
28
+ SchemaTimeoutError,
27
29
  type ValidationResult,
28
30
  validateOutputData,
29
31
  } from "../validate-output.js";
30
- import type { ResolvedStage } from "./stage-lifecycle.js";
31
- import { StagePreflightError } from "./stage-lifecycle.js";
32
+ import { StagePreflightError } from "./errors.js";
33
+ import type { ResolvedStage } from "./resolve-stage.js";
32
34
 
33
35
  // ---------------------------------------------------------------------------
34
36
  // Shared helper
@@ -75,26 +77,14 @@ async function validateOrThrow(
75
77
  result = await withTimeout(Promise.resolve(validateOutputData(schema, data)), timeoutMs, timeoutError);
76
78
  } catch (e) {
77
79
  if (errorPolicy === "degrade-on-non-timeout" && !(e instanceof SchemaTimeoutError)) return;
78
- const reason = e instanceof Error ? e.message : String(e);
79
- throw new StagePreflightError(
80
- "halt",
81
- stage.skill,
82
- MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
83
- ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, reason),
84
- true,
85
- );
80
+ const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, formatError(e));
81
+ throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
86
82
  }
87
83
 
88
84
  if (result.valid) return;
89
85
 
90
- const failureSummary = result.failures.map(describeFailure).join("; ");
91
- throw new StagePreflightError(
92
- "halt",
93
- stage.skill,
94
- MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
95
- ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, failureSummary),
96
- true,
97
- );
86
+ const f = FAIL_INPUT_VALIDATION(stage.skill, prevSkill, result.failures.map(describeFailure).join("; "));
87
+ throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
98
88
  }
99
89
 
100
90
  // ---------------------------------------------------------------------------