@juicesharp/rpiv-workflow 1.19.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
package/state/reads.ts CHANGED
@@ -16,12 +16,12 @@
16
16
  * header-only or projection-only reads sized for inspect UIs.
17
17
  */
18
18
 
19
- import { existsSync, readdirSync, readFileSync } from "node:fs";
20
- import { basename } from "node:path";
19
+ import { existsSync, readFileSync } from "node:fs";
21
20
  import type { Artifact } from "../handle.js";
22
- import { readNamesIndex } from "./names.js";
23
- import { runsDir, stateFilePath } from "./paths.js";
24
- import type { RoutingDecision, RunSummary, WorkflowHeader, WorkflowStage } from "./state.js";
21
+ import { formatError } from "../internal-utils.js";
22
+ import { stateFilePath } from "./paths.js";
23
+ import { enumerateRunIds, readFirstJsonlLine } from "./raw.js";
24
+ import type { LoopCapRow, RoutingDecision, RunSummary, WorkflowHeader, WorkflowStage } from "./state.js";
25
25
 
26
26
  /**
27
27
  * Reads every line, filters by shape (not position). Header has no
@@ -36,6 +36,15 @@ import type { RoutingDecision, RunSummary, WorkflowHeader, WorkflowStage } from
36
36
  * skipped; readers see every well-formed row that landed on disk.
37
37
  */
38
38
  function readJsonlRows<T>(cwd: string, runId: string, match: (row: unknown) => row is T): T[] {
39
+ const rows: T[] = [];
40
+ for (const parsed of readParsedRows(cwd, runId)) {
41
+ if (match(parsed)) rows.push(parsed);
42
+ }
43
+ return rows;
44
+ }
45
+
46
+ /** Every well-formed JSON row, unfiltered — the shared base under `readJsonlRows` + the strict resume reader. */
47
+ function readParsedRows(cwd: string, runId: string): unknown[] {
39
48
  let lines: string[];
40
49
  try {
41
50
  const filePath = stateFilePath(cwd, runId);
@@ -44,34 +53,69 @@ function readJsonlRows<T>(cwd: string, runId: string, match: (row: unknown) => r
44
53
  if (!content) return [];
45
54
  lines = content.split("\n");
46
55
  } catch (e) {
47
- console.warn(`[rpiv-workflow] workflow state: ${e instanceof Error ? e.message : String(e)}`);
56
+ console.warn(`[rpiv-workflow] workflow state: ${formatError(e)}`);
48
57
  return [];
49
58
  }
50
59
 
51
- const rows: T[] = [];
60
+ const rows: unknown[] = [];
52
61
  for (const line of lines) {
53
- let parsed: unknown;
54
62
  try {
55
- parsed = JSON.parse(line);
63
+ rows.push(JSON.parse(line));
56
64
  } catch (e) {
57
- console.warn(
58
- `[rpiv-workflow] workflow state: skipping malformed JSONL row — ${e instanceof Error ? e.message : String(e)}`,
59
- );
60
- continue;
65
+ console.warn(`[rpiv-workflow] workflow state: skipping malformed JSONL row — ${formatError(e)}`);
61
66
  }
62
- if (match(parsed)) rows.push(parsed);
63
67
  }
64
68
  return rows;
65
69
  }
66
70
 
67
- const isWorkflowStage = (row: unknown): row is WorkflowStage =>
68
- !!row &&
69
- typeof (row as { stageNumber?: unknown }).stageNumber === "number" &&
70
- typeof (row as { stage?: unknown }).stage === "string";
71
+ const STAGE_STATUSES: ReadonlySet<string> = new Set(["completed", "failed", "skipped", "aborted"]);
72
+
73
+ /**
74
+ * Stage-SHAPED: carries a numeric `stageNumber` (no other row kind does).
75
+ * Pre-filter for the strict resume reader — a stage-shaped row failing the
76
+ * deep `isWorkflowStage` guard is a MALFORMED stage row, not a foreign kind.
77
+ */
78
+ const isStageShaped = (row: unknown): row is { stageNumber: number; stage?: unknown } =>
79
+ !!row && typeof (row as { stageNumber?: unknown }).stageNumber === "number";
80
+
81
+ /**
82
+ * Deep guard for the fields downstream consumers actually depend on —
83
+ * not just "has a stageNumber": `status` must be a member of the enum
84
+ * (the resume fold branches on it), `output.artifacts` must be an array
85
+ * when `output` is present (`applyCompletedStage` indexes it), and a
86
+ * loop-unit row (`parent` set) must carry a numeric `unitIndex` (the
87
+ * resume drift guard compares it).
88
+ */
89
+ const isWorkflowStage = (row: unknown): row is WorkflowStage => {
90
+ const r = row as Partial<WorkflowStage> | null;
91
+ if (!r || typeof r.stageNumber !== "number" || typeof r.stage !== "string") return false;
92
+ if (typeof r.status !== "string" || !STAGE_STATUSES.has(r.status)) return false;
93
+ if (r.output !== undefined && !Array.isArray((r.output as { artifacts?: unknown } | null)?.artifacts)) return false;
94
+ if (r.parent !== undefined && typeof r.unitIndex !== "number") return false;
95
+ return true;
96
+ };
97
+
98
+ /**
99
+ * Resume-only `session` guard: the key must be PRESENT and be either `null`
100
+ * (explicit "no session involved") or an object carrying `id: string`.
101
+ * Lives apart from `isWorkflowStage` so DISPLAY readers stay lenient —
102
+ * pre-feature rows (no `session` key) still render in lists/inspect UIs;
103
+ * only the resume fold refuses them (`malformed-row`; the dev remedy is
104
+ * wiping `.rpiv/workflows/runs/` — v1 never shipped).
105
+ */
106
+ const hasValidSessionRef = (row: object): boolean => {
107
+ if (!("session" in row)) return false;
108
+ const s = (row as { session: unknown }).session;
109
+ if (s === null) return true;
110
+ return typeof s === "object" && typeof (s as { id?: unknown }).id === "string";
111
+ };
71
112
 
72
113
  const isRoutingDecision = (row: unknown): row is RoutingDecision =>
73
114
  !!row && (row as { type?: unknown }).type === "routing";
74
115
 
116
+ /** Shape guard for loop-cap telemetry rows. */
117
+ const isLoopCapRow = (r: unknown): r is LoopCapRow => (r as { type?: unknown } | undefined)?.type === "loop-cap";
118
+
75
119
  const isWorkflowHeader = (row: unknown): row is WorkflowHeader =>
76
120
  !!row &&
77
121
  typeof (row as { runId?: unknown }).runId === "string" &&
@@ -92,10 +136,41 @@ export function readAllStages(cwd: string, runId: string): WorkflowStage[] {
92
136
  return readJsonlRows(cwd, runId, isWorkflowStage);
93
137
  }
94
138
 
139
+ /**
140
+ * Resume-grade reader: same projection as `readAllStages`, but a row that is
141
+ * stage-SHAPED while failing the deep stage guard REFUSES instead of being
142
+ * skipped. Display readers may shrug off a malformed row; the resume fold
143
+ * replays the trail as its system of record, and silently dropping a row
144
+ * would replay a hole ("this stage never ran") — e.g. route onward past a
145
+ * stage whose failure row lost its `status`.
146
+ */
147
+ export function readAllStagesForResume(
148
+ cwd: string,
149
+ runId: string,
150
+ ): { ok: true; rows: WorkflowStage[] } | { ok: false; detail: string } {
151
+ const rows: WorkflowStage[] = [];
152
+ for (const parsed of readParsedRows(cwd, runId)) {
153
+ if (isWorkflowStage(parsed) && hasValidSessionRef(parsed)) {
154
+ rows.push(parsed);
155
+ continue;
156
+ }
157
+ if (isStageShaped(parsed)) {
158
+ const label = typeof parsed.stage === "string" ? ` ("${parsed.stage}")` : "";
159
+ return { ok: false, detail: `stage row ${parsed.stageNumber}${label} failed the shape guard` };
160
+ }
161
+ }
162
+ return { ok: true, rows };
163
+ }
164
+
95
165
  export function readRoutingDecisions(cwd: string, runId: string): RoutingDecision[] {
96
166
  return readJsonlRows(cwd, runId, isRoutingDecision);
97
167
  }
98
168
 
169
+ /** All loop-cap telemetry rows for a run, in trail order. */
170
+ export function readLoopCaps(cwd: string, runId: string): LoopCapRow[] {
171
+ return readJsonlRows(cwd, runId, isLoopCapRow);
172
+ }
173
+
99
174
  /**
100
175
  * Project a run's stage rows to the (stage, artifact) pairs that
101
176
  * actually carried at least one artifact. One entry per artifact —
@@ -128,68 +203,21 @@ export function listArtifacts(
128
203
  // ---------------------------------------------------------------------------
129
204
 
130
205
  /**
131
- * Read only the first JSONL line and parse it as a `WorkflowHeader`. Used
132
- * by `listRuns` so enumerating N past runs reads N first-lines instead
133
- * of fully parsing every row in every file. Returns undefined when the
134
- * file is missing, empty, or the first line doesn't match the header
135
- * shape.
206
+ * Read only the first JSONL line (a BOUNDED prefix read via
207
+ * `readFirstJsonlLine` — the file's stage rows are never loaded) and parse
208
+ * it as a `WorkflowHeader`. Used by `listRuns` so enumerating N past runs
209
+ * costs N small reads. Returns undefined when the file is missing, empty,
210
+ * or the first line doesn't match the header shape.
136
211
  *
137
212
  * Fail-soft like every other reader — never throws.
138
213
  *
139
214
  * Takes a concrete `runId`. For a user-supplied reference that may later need
140
- * symbolic resolution (`@latest`, relative), call `resolveRun` instead.
215
+ * symbolic resolution (`@latest`, relative), call `resolveRun` (resolve.ts)
216
+ * instead.
141
217
  */
142
218
  export function readHeader(cwd: string, runId: string): WorkflowHeader | undefined {
143
- try {
144
- const filePath = stateFilePath(cwd, runId);
145
- if (!existsSync(filePath)) return undefined;
146
- const content = readFileSync(filePath, "utf-8");
147
- const firstLine = content.split("\n", 1)[0] ?? "";
148
- if (!firstLine) return undefined;
149
- const parsed = JSON.parse(firstLine);
150
- return isWorkflowHeader(parsed) ? parsed : undefined;
151
- } catch {
152
- // Malformed JSON or I/O error — caller treats as "header unreadable".
153
- return undefined;
154
- }
155
- }
156
-
157
- /**
158
- * Resolve a run *reference* to its header — the ref-resolution seam.
159
- *
160
- * Which to call: reach for `resolveRun` when the ref is **user-supplied** (the
161
- * `/wf @<ref>` token, a CLI arg); reach for `readHeader` when you already hold
162
- * a concrete `runId` (e.g. straight off `RunSummary.runId`). The split is
163
- * intent, not behaviour.
164
- *
165
- * Resolution order:
166
- * 1. Check the names index (`names.json`) for a name → runId mapping on the
167
- * RAW ref. If found and the target JSONL exists, return its header.
168
- * 2. Fall back to runId lookup via `readHeader`, on the ref normalized to a
169
- * slug — a trailing `.jsonl` is stripped and any directory prefix is
170
- * dropped (`basename`). This lets `/wf @<path>` accept an editor's
171
- * file-autosuggested path to the run's JSONL (`.../runs/<id>.jsonl`),
172
- * a bare `<id>.jsonl`, or the plain `<id>` slug interchangeably.
173
- *
174
- * Name lookup stays on the raw ref: a run name is never a path, so a name like
175
- * `auth.jsonl` (were it ever claimed) must match verbatim, not as a slug.
176
- *
177
- * Fail-soft like every reader — returns undefined when the ref doesn't resolve.
178
- * A missing or corrupt `names.json` degrades gracefully: the index lookup
179
- * returns `undefined` and the literal fallback runs.
180
- */
181
- export function resolveRun(cwd: string, ref: string): WorkflowHeader | undefined {
182
- // Try the names index first — O(1) lookup for human-readable aliases.
183
- // Matched on the raw ref: a name is never a path/`.jsonl` file.
184
- const index = readNamesIndex(cwd);
185
- if (index?.[ref]) {
186
- const resolved = readHeader(cwd, index[ref]!);
187
- if (resolved) return resolved;
188
- }
189
- // Fall back to runId lookup, tolerating a pasted/autosuggested path:
190
- // reduce to the bare slug (drop dir prefix + trailing `.jsonl`).
191
- const slug = basename(ref).replace(/\.jsonl$/, "");
192
- return readHeader(cwd, slug);
219
+ const parsed = readFirstJsonlLine(cwd, runId);
220
+ return parsed !== undefined && isWorkflowHeader(parsed) ? parsed : undefined;
193
221
  }
194
222
 
195
223
  /**
@@ -207,18 +235,8 @@ export function resolveRun(cwd: string, ref: string): WorkflowHeader | undefined
207
235
  * `runId` is monotonic for runs created on the same host).
208
236
  */
209
237
  export function listRuns(cwd: string): RunSummary[] {
210
- const dir = runsDir(cwd);
211
- let entries: string[];
212
- try {
213
- entries = readdirSync(dir);
214
- } catch {
215
- // Directory doesn't exist (no runs yet) or unreadable — treat as empty.
216
- return [];
217
- }
218
238
  const summaries: RunSummary[] = [];
219
- for (const name of entries) {
220
- if (!name.endsWith(".jsonl")) continue;
221
- const runId = name.slice(0, -".jsonl".length);
239
+ for (const runId of enumerateRunIds(cwd)) {
222
240
  const header = readHeader(cwd, runId);
223
241
  if (header)
224
242
  summaries.push({
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Run-reference resolution — the one composer that sits ABOVE both the raw
3
+ * readers (`reads.ts`) and the names index (`names.ts`). A name-aware
4
+ * resolver doesn't belong in the raw-reads module, and housing it there
5
+ * would force `reads.ts` to import `names.ts`.
6
+ */
7
+
8
+ import { basename } from "node:path";
9
+ import { isValidName, readNamesIndex, rebuildIndex } from "./names.js";
10
+ import { readHeader } from "./reads.js";
11
+ import type { WorkflowHeader } from "./state.js";
12
+
13
+ /**
14
+ * Resolve a run *reference* to its header — the ref-resolution seam.
15
+ *
16
+ * Which to call: reach for `resolveRun` when the ref is **user-supplied** (the
17
+ * `/wf @<ref>` token, a CLI arg); reach for `readHeader` when you already hold
18
+ * a concrete `runId` (e.g. straight off `RunSummary.runId`). The split is
19
+ * intent, not behaviour.
20
+ *
21
+ * Resolution order:
22
+ * 1. Check the names index (`names.json`) for a name → runId mapping on the
23
+ * RAW ref. If found and the target JSONL exists, return its header.
24
+ * If found but the target JSONL is GONE (stale-present entry — a failed
25
+ * `releaseName` rollback or a hand-deleted run file), that hit is
26
+ * positive evidence the index is stale: rebuild `names.json` from the
27
+ * JSONL headers and retry the name lookup once. The rebuild also prunes
28
+ * the dead entry, freeing the name for re-claim.
29
+ * 2. Fall back to runId lookup via `readHeader`, on the ref normalized to a
30
+ * slug — a trailing `.jsonl` is stripped and any directory prefix is
31
+ * dropped (`basename`). This lets `/wf @<path>` accept an editor's
32
+ * file-autosuggested path to the run's JSONL (`.../runs/<id>.jsonl`),
33
+ * a bare `<id>.jsonl`, or the plain `<id>` slug interchangeably.
34
+ * 3. Index-miss recovery: if both lookups failed AND the ref is a
35
+ * well-formed run name absent from the index, rebuild `names.json` from
36
+ * the JSONL headers (`rebuildIndex`) and retry the name lookup once —
37
+ * a deleted/corrupt `names.json` no longer orphans named runs. (Gated on
38
+ * ABSENCE, so it can never fire for the stale-present case — that
39
+ * recovery lives in step 1.)
40
+ *
41
+ * Name lookup stays on the raw ref: a run name is never a path, so a name like
42
+ * `auth.jsonl` (were it ever claimed) must match verbatim, not as a slug.
43
+ *
44
+ * Fail-soft like every reader — returns undefined when the ref doesn't resolve.
45
+ */
46
+ export function resolveRun(cwd: string, ref: string): WorkflowHeader | undefined {
47
+ // Try the names index first — O(1) lookup for human-readable aliases.
48
+ // Matched on the raw ref: a name is never a path/`.jsonl` file.
49
+ const index = readNamesIndex(cwd);
50
+ if (index?.[ref]) {
51
+ const resolved = readHeader(cwd, index[ref]!);
52
+ if (resolved) return resolved;
53
+ // Stale-present entry: the index maps this name to a runId whose header
54
+ // is unreadable. Rebuild + retry once — and even when the retry misses,
55
+ // the rebuild has pruned the dead entry, so the name is re-claimable.
56
+ const recovered = rebuildIndex(cwd)?.[ref];
57
+ if (recovered) return readHeader(cwd, recovered);
58
+ }
59
+ // Fall back to runId lookup, tolerating a pasted/autosuggested path:
60
+ // reduce to the bare slug (drop dir prefix + trailing `.jsonl`).
61
+ const slug = basename(ref).replace(/\.jsonl$/, "");
62
+ const bySlug = readHeader(cwd, slug);
63
+ if (bySlug) return bySlug;
64
+ // Recovery: a lost/corrupt names.json silently orphans named runs. Rebuild
65
+ // from headers only when the ref LOOKS like a name the index should have
66
+ // carried (valid shape, not present) — an unresolvable runId slug never
67
+ // triggers the O(runs) rescan.
68
+ if (isValidName(ref) && !index?.[ref]) {
69
+ const runId = rebuildIndex(cwd)?.[ref];
70
+ if (runId) return readHeader(cwd, runId);
71
+ }
72
+ return undefined;
73
+ }
package/state/state.ts CHANGED
@@ -4,6 +4,12 @@
4
4
  * fail-soft (logs via console.warn with `[rpiv-workflow]` prefix, never
5
5
  * throws).
6
6
  *
7
+ * The trail is resume's SYSTEM OF RECORD — `runner/resume.ts` folds the rows
8
+ * back into a `RunState`, so the on-disk shape is a versioned contract, not a
9
+ * debug artifact. The header carries `v` (see `STATE_SCHEMA_VERSION`); resume
10
+ * refuses files written under a different version rather than mis-replaying
11
+ * them. Display readers stay lenient (shape-filtered, skip-on-mismatch).
12
+ *
7
13
  * Internally split into three modules:
8
14
  * - paths.ts — runsDir + stateFilePath + generateRunId
9
15
  * - writes.ts — tryAppendJsonl + writeHeader + appendStage +
@@ -15,6 +21,7 @@
15
21
  * else lives in a focused module.
16
22
  */
17
23
 
24
+ import type { UnitRole } from "../api.js";
18
25
  import type { Output } from "../output.js";
19
26
  import type { RunTrigger } from "../triggers.js";
20
27
 
@@ -22,21 +29,66 @@ import type { RunTrigger } from "../triggers.js";
22
29
  // Row shapes
23
30
  // ---------------------------------------------------------------------------
24
31
 
32
+ /**
33
+ * On-disk status stamped on every `WorkflowStage` row. `"skipped"` is the
34
+ * FROZEN on-disk marker for a user-cancellation: the canonical in-memory name
35
+ * is `RunTermination.status: "cancelled"` (../types.ts), and the sole writer of
36
+ * a `"skipped"` row is `recordCancellation` (../audit.ts). The split is
37
+ * deliberate — the row value is a versioned on-disk contract (see
38
+ * `STATE_SCHEMA_VERSION`), so it keeps its long-standing spelling even though
39
+ * the in-memory outcome reads "cancelled". Literal unchanged.
40
+ */
25
41
  export type StageStatus = "completed" | "failed" | "skipped" | "aborted";
26
42
 
27
43
  /**
28
- * Audit files are debug artifacts — no migration provided. Readers
29
- * shape-filter on `stageNumber`, so any rows that don't satisfy the
30
- * current shape are silently skipped.
44
+ * The Pi session that backed a stage activation — a value object the row
45
+ * serializes verbatim (wire shape = domain shape). Produced by
46
+ * `readSessionRef` (transcript.ts — the reader produces the value the row
47
+ * stores; one definition, no parallel type).
48
+ *
49
+ * - `id` — session identity. Forever.
50
+ * - `file` — `getSessionFile()` at capture time; a location HINT.
51
+ * Absent for non-persisting (in-memory) sessions. A stale
52
+ * path is recoverable: resume falls back to searching its
53
+ * dirname for `*_<id>.jsonl`, then to a header scan, then
54
+ * to cold re-run (see `sessions/locate.ts`).
55
+ * - `branchOffset` — the offset the activation ran under (continue-policy
56
+ * stages only); promotion/reattach scope extraction with
57
+ * it, exactly as the live path did.
58
+ *
59
+ * Nested deliberately — unlike `parent`/`role`/`unitId`/`unitIndex`
60
+ * (independent dispatch keys, hence flat), `file`/`branchOffset` are
61
+ * meaningless without `id` and are always consumed together; nesting makes
62
+ * the invalid states unrepresentable.
63
+ */
64
+ export interface SessionRef {
65
+ id: string;
66
+ file?: string;
67
+ branchOffset?: number;
68
+ }
69
+
70
+ /**
71
+ * One stage activation's row. DISPLAY readers shape-filter on `stageNumber`
72
+ * and silently skip rows that don't satisfy the current shape; the RESUME
73
+ * reader (`readAllStagesForResume`) refuses instead — the fold replays these
74
+ * rows as the run's system of record (see the module header).
31
75
  *
32
- * Two identity fields:
33
- * - `stage` — the workflow stage's record key. Always present. The
34
- * audit row's "which step ran" answer; stable across skill-body
35
- * overrides and aliased stages.
36
- * - `skill?` — the Pi skill body invoked, when this row records a
37
- * skill stage. Absent for script stages (`StageDef.run`); equal to
38
- * `stage` in the common case where `produces()` / `acts()` defaults
39
- * the skill body to the record key.
76
+ * Identity fields:
77
+ * - `stage` — DISPLAY identity. For single stages this is the workflow
78
+ * record key; for loop-unit rows it is the decorated human string
79
+ * (`"implement (phase-2)"`, `"breakdown (r0·judge)"`). Machine readers
80
+ * must NOT parse it — the structured fields below are the only machine
81
+ * channel.
82
+ * - `skill?` — the Pi skill body invoked. Absent for script stages; the
83
+ * judge's own skill on judge-unit rows.
84
+ * - `parent?` / `role?` / `unitId?` / `unitIndex?` — present iff the row
85
+ * records a loop unit. `parent` is the loop stage's record key (the
86
+ * resume fold + dispatch key on it); `role` says produce vs judge;
87
+ * `unitIndex` is the 0-based cursor within the generation (== the round
88
+ * for assess loops); `unitId` is the author-stable unit identity
89
+ * (`unit.id ?? unit.label`) for fanout/iterate, absent for assess
90
+ * (identity there is `(role, unitIndex)`). Present on FAILURE rows too —
91
+ * the resume drift guard consumes failed-trailer identity.
40
92
  *
41
93
  * The row no longer carries a top-level `artifact` field — discovery
42
94
  * moved into the collector, and the canonical artifact list lives on
@@ -57,14 +109,74 @@ export interface WorkflowStage {
57
109
  * JSONL alone, without depending on a transient `ctx.ui.notify` toast.
58
110
  */
59
111
  errMsg?: string;
112
+ /**
113
+ * REQUIRED: the Pi session that backed this activation, or `null` as an
114
+ * explicit statement that no session was involved (script stages,
115
+ * preflight halts, seam aborts, drift failures, pre-open cancellations) —
116
+ * writers cannot forget the decision, and an orphan `file`/`branchOffset`
117
+ * without an `id` is unrepresentable. The resume reader refuses rows
118
+ * missing the key (pre-feature files land in the `malformed-row` arm);
119
+ * display readers stay lenient and never touch it.
120
+ */
121
+ session: SessionRef | null;
122
+ parent?: string;
123
+ role?: UnitRole;
124
+ unitId?: string;
125
+ unitIndex?: number;
126
+ /**
127
+ * Marks a NON-terminal collect-all fanout unit halt (`recordUnitHalt`):
128
+ * the unit failed but the run survives and a `failedOutput` sentinel fills its
129
+ * declared slot. Distinguishes a SOFT halt from a hard `recordTerminalFailure`
130
+ * row (byte-identical otherwise) so the resume fold rebuilds the
131
+ * sentinel by `unitIndex` rather than re-dispatching the unit. Absent on every
132
+ * other row (`undefined` is dropped by `JSON.stringify`).
133
+ */
134
+ collected?: true;
60
135
  }
61
136
 
137
+ /**
138
+ * Telemetry row appended when a loop's `onCap: "advance"` trips — makes the
139
+ * soft-stop durable (post-hoc readers can distinguish "judge said done" from
140
+ * "cap tripped"). Shape-discriminated like RoutingDecision; stage readers and
141
+ * the resume fold skip it untouched. `count` is units run for fanout/iterate,
142
+ * rounds run for assess; `max` is the effective cap that tripped.
143
+ */
144
+ export interface LoopCapRow {
145
+ type: "loop-cap";
146
+ stage: string;
147
+ count: number;
148
+ max: number;
149
+ ts: string;
150
+ }
151
+
152
+ /**
153
+ * On-disk schema version stamped into every new header's `v`. Bump when a
154
+ * row/envelope shape changes in a way the resume fold cannot replay —
155
+ * `reconstructState` refuses headers carrying any other version
156
+ * (`reason: "version-mismatch"`) instead of silently mis-replaying.
157
+ *
158
+ * v2 = parallel-fanout trails: completion rows are placed by `unitIndex` (not
159
+ * trail order), and a `collected:true` failed row's `errMsg` rebuilds a
160
+ * `failedOutput` sentinel. A v1 trail (sequential fold) — and an absent
161
+ * `v`, which resolves to 1 — is rejected by `reconstructState`'s header version
162
+ * gate with `version-mismatch` ("start a fresh run"): there is no in-place
163
+ * migration (sole consumer rpiv-pi; no back-compat). Tested in
164
+ * `runner/resume.test.ts`.
165
+ */
166
+ export const STATE_SCHEMA_VERSION = 2;
167
+
62
168
  /** First line of the JSONL file. */
63
169
  export interface WorkflowHeader {
64
170
  runId: string;
65
171
  workflow: string;
66
172
  input: string;
67
173
  ts: string;
174
+ /**
175
+ * On-disk schema version — see `STATE_SCHEMA_VERSION`. Optional so headers
176
+ * written before the field existed still parse; readers treat `undefined`
177
+ * as version 1.
178
+ */
179
+ v?: number;
68
180
  /**
69
181
  * What triggered the run. Optional so older JSONL files (written
70
182
  * before the trigger field was added) still parse — readers treat
@@ -101,6 +213,12 @@ export interface RoutingDecision {
101
213
  fromStageIndex: number;
102
214
  fromStage: string;
103
215
  decision: string;
216
+ /**
217
+ * Diagnostic the deciding `EdgeFn` attached to this pick (via the
218
+ * `ROUTE_NOTE` channel) — e.g. `gate`'s "no branch matched, fallback
219
+ * fired." Absent for ordinary matched decisions.
220
+ */
221
+ note?: string;
104
222
  ts: string;
105
223
  }
106
224
 
@@ -109,23 +227,25 @@ export interface RoutingDecision {
109
227
  // ---------------------------------------------------------------------------
110
228
 
111
229
  export {
112
- addNameToIndex,
113
230
  type ClaimResult,
114
231
  claimName,
115
232
  isValidName,
116
233
  type NamesIndex,
117
234
  readNamesIndex,
118
235
  rebuildIndex,
236
+ releaseName,
119
237
  VALID_NAME,
120
238
  } from "./names.js";
121
- export { generateRunId, namesFilePath, runsDir, stateFilePath } from "./paths.js";
239
+ export { generateRunId, namesFilePath, runFileFor, runsDir, stateFilePath } from "./paths.js";
122
240
  export {
123
241
  listArtifacts,
124
242
  listRuns,
125
243
  readAllStages,
244
+ readAllStagesForResume,
126
245
  readHeader,
127
246
  readLastStage,
247
+ readLoopCaps,
128
248
  readRoutingDecisions,
129
- resolveRun,
130
249
  } from "./reads.js";
131
- export { appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
250
+ export { resolveRun } from "./resolve.js";
251
+ export { appendLoopCap, appendRoutingDecision, appendStage, writeHeader } from "./writes.js";
package/state/writes.ts CHANGED
@@ -1,25 +1,27 @@
1
1
  /**
2
2
  * Fail-soft JSONL appends. Every public helper here is a thin wrapper
3
- * around `tryAppendJsonl` so the write protocol (mkdirSync + append +
4
- * stderr warn on throw) lives in one place — changes to atomicity,
5
- * checksums, or alternative storage backends touch this file and this
6
- * file only.
3
+ * around `tryAppendJsonl` so the WRITE protocol (mkdirSync + append +
4
+ * stderr warn on throw) lives in one place — changes to append atomicity
5
+ * or checksums touch this file only. This is NOT a full storage-backend
6
+ * seam: `reads.ts`, `raw.ts`, and `names.ts` hit `node:fs` directly, so
7
+ * swapping the backend means touching all of `state/` (a `RunStore` port
8
+ * is a known possible follow-up, deliberately deferred).
7
9
  *
8
- * writeHeader — best-effort; discards the return.
10
+ * writeHeader — boolean; the runner refuses the run start on failure.
9
11
  * appendStage — boolean; allocator gates monotonic counters on it.
10
12
  * appendRoutingDecision — boolean; telemetry-not-state, dropped rows surface up.
11
13
  */
12
14
 
13
15
  import { appendFileSync, mkdirSync } from "node:fs";
16
+ import { formatError } from "../internal-utils.js";
14
17
  import { runsDir, stateFilePath } from "./paths.js";
15
- import type { RoutingDecision, WorkflowHeader, WorkflowStage } from "./state.js";
18
+ import type { LoopCapRow, RoutingDecision, WorkflowHeader, WorkflowStage } from "./state.js";
16
19
 
17
20
  /**
18
21
  * Shared append primitive: ensure the runs directory exists, then
19
22
  * append one JSON-serialised row + newline. Returns true on success;
20
- * on any throw, warns to stderr and returns false. The three public
21
- * append helpers below are thin wrappers — `writeHeader` discards the
22
- * return (best-effort), the others gate counters / telemetry on it.
23
+ * on any throw, warns to stderr and returns false. The public append
24
+ * helpers below are thin wrappers — every caller gates on the boolean.
23
25
  */
24
26
  function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
25
27
  try {
@@ -29,13 +31,19 @@ function tryAppendJsonl(cwd: string, runId: string, row: unknown): boolean {
29
31
  appendFileSync(filePath, `${JSON.stringify(row)}\n`, "utf-8");
30
32
  return true;
31
33
  } catch (e) {
32
- console.warn(`[rpiv-workflow] workflow state: ${e instanceof Error ? e.message : String(e)}`);
34
+ console.warn(`[rpiv-workflow] workflow state: ${formatError(e)}`);
33
35
  return false;
34
36
  }
35
37
  }
36
38
 
37
- export function writeHeader(cwd: string, header: WorkflowHeader): void {
38
- tryAppendJsonl(cwd, header.runId, header);
39
+ /**
40
+ * Returns true on successful write. A lost header makes the run unlistable
41
+ * (`listRuns` keys on line one) and unresumable (`resolveRun` can't find it)
42
+ * while stage rows still land — so `runWorkflow` refuses the run start on
43
+ * false, before anything has executed.
44
+ */
45
+ export function writeHeader(cwd: string, header: WorkflowHeader): boolean {
46
+ return tryAppendJsonl(cwd, header.runId, header);
39
47
  }
40
48
 
41
49
  /** Returns true on successful write — callers gate counters on this. */
@@ -56,3 +64,12 @@ export function appendStage(cwd: string, runId: string, stage: WorkflowStage): b
56
64
  export function appendRoutingDecision(cwd: string, runId: string, row: RoutingDecision): boolean {
57
65
  return tryAppendJsonl(cwd, runId, row);
58
66
  }
67
+
68
+ /**
69
+ * Append a loop-cap telemetry row (an `onCap: "advance"` trip). Telemetry,
70
+ * not a reconstruction input — a dropped write degrades the trail but never
71
+ * gates the chain (the live soft-stop toast is the user-facing signal).
72
+ */
73
+ export function appendLoopCap(cwd: string, runId: string, row: LoopCapRow): boolean {
74
+ return tryAppendJsonl(cwd, runId, row);
75
+ }
package/transcript.ts CHANGED
@@ -12,6 +12,8 @@
12
12
  * "find the last regex match in assistant text" helper they reuse.
13
13
  */
14
14
 
15
+ import type { SessionRef } from "./state/index.js";
16
+
15
17
  /** Mirror of pi-ai's StopReason union — values pi attaches to AssistantMessage. */
16
18
  export type StopReason = "stop" | "length" | "toolUse" | "error" | "aborted";
17
19
 
@@ -69,6 +71,28 @@ export function readBranch(ctx: { sessionManager: { getBranch(): unknown } }): B
69
71
  return ctx.sessionManager.getBranch() as unknown as BranchEntry[];
70
72
  }
71
73
 
74
+ /**
75
+ * Capture the active Pi session's identity as the `SessionRef` value object
76
+ * stage rows store (`WorkflowStage.session`). Lives here, next to
77
+ * `readBranch` — the module that owns narrow structural host reads.
78
+ *
79
+ * `branchOffset` is the policy-derived offset the activation ran under
80
+ * (continue-policy stages); omitted/undefined for fresh sessions so the key
81
+ * is dropped from the serialized row. `file` is likewise dropped for
82
+ * non-persisting sessions (`getSessionFile()` returns `undefined`).
83
+ */
84
+ export function readSessionRef(
85
+ ctx: { sessionManager: { getSessionId(): string; getSessionFile(): string | undefined } },
86
+ branchOffset?: number,
87
+ ): SessionRef {
88
+ const file = ctx.sessionManager.getSessionFile();
89
+ return {
90
+ id: ctx.sessionManager.getSessionId(),
91
+ ...(file !== undefined ? { file } : {}),
92
+ ...(branchOffset !== undefined ? { branchOffset } : {}),
93
+ };
94
+ }
95
+
72
96
  export function hasAssistantMessage(branch: BranchEntry[], offsetStart?: number): boolean {
73
97
  const start = Math.max(offsetStart ?? 0, 0);
74
98
  for (let i = start; i < branch.length; i++) {