@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/state/names.ts CHANGED
@@ -3,16 +3,27 @@
3
3
  * O(1) resolution. Lives in `<cwd>/.rpiv/workflows/runs/names.json`, alongside
4
4
  * the JSONL audit files.
5
5
  *
6
- * Internal module — not re-exported from registration.ts. The runner calls
7
- * `readNamesIndex` for collision pre-flight and `addNameToIndex` after
8
- * `writeHeader`. External consumers resolve names through `resolveRun`.
6
+ * Internal module — not re-exported from registration.ts. The runner reserves
7
+ * names through `claimName` (the single in-process door: validate →
8
+ * collision-check → persist) BEFORE `writeHeader`. External consumers resolve
9
+ * names through `resolveRun`.
10
+ *
11
+ * Durability: every write goes through `writeNamesIndex` — temp file +
12
+ * `renameSync`, so a crash mid-write can never tear the index. Concurrency:
13
+ * there is NO cross-process lock — two `/wf` processes claiming names
14
+ * simultaneously can race the read-modify-write (lost update / duplicate
15
+ * claim). Accepted for now: the index is recoverable via `rebuildIndex`, and
16
+ * a lock file is deferred (see the trigger-source concurrency note in
17
+ * triggers.ts).
9
18
  *
10
19
  * Fail-soft like every state-layer module: readers return `undefined` or empty
11
20
  * on failure; writers warn via `console.warn` with `[rpiv-workflow]` prefix.
12
21
  */
13
22
 
14
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
24
+ import { formatError } from "../internal-utils.js";
15
25
  import { namesFilePath, runsDir, stateFilePath } from "./paths.js";
26
+ import { enumerateRunIds, readFirstJsonlLine } from "./raw.js";
16
27
 
17
28
  // ---------------------------------------------------------------------------
18
29
  // Types
@@ -57,7 +68,7 @@ export function readNamesIndex(cwd: string): NamesIndex | undefined {
57
68
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
58
69
  return parsed as NamesIndex;
59
70
  } catch (e) {
60
- console.warn(`[rpiv-workflow] names index: ${e instanceof Error ? e.message : String(e)}`);
71
+ console.warn(`[rpiv-workflow] names index: ${formatError(e)}`);
61
72
  return undefined;
62
73
  }
63
74
  }
@@ -67,37 +78,87 @@ export function readNamesIndex(cwd: string): NamesIndex | undefined {
67
78
  // ---------------------------------------------------------------------------
68
79
 
69
80
  /**
70
- * Add a name → runId mapping to the index. Reads the current index, adds the
71
- * entry, and writes back. Creates the file if it doesn't exist. Returns `true`
72
- * on success, `false` on failure (warns to stderr).
81
+ * THE single write path for `names.json` — temp file + `renameSync` so a
82
+ * crash mid-write tears the temp file, never the index (rename is atomic on
83
+ * POSIX filesystems). Throws on failure; callers own the fail-soft warn.
84
+ */
85
+ function writeNamesIndex(cwd: string, index: NamesIndex): void {
86
+ const dir = runsDir(cwd);
87
+ mkdirSync(dir, { recursive: true });
88
+ const target = namesFilePath(cwd);
89
+ const tmp = `${target}.${process.pid}.tmp`;
90
+ writeFileSync(tmp, `${JSON.stringify(index)}\n`, "utf-8");
91
+ renameSync(tmp, target);
92
+ }
93
+
94
+ /**
95
+ * Add a name → runId mapping to the index and write it back atomically.
96
+ * `current` is the index the caller already read (`claimName` reads it once
97
+ * for the collision check — no second read widening the race window);
98
+ * defaults to a fresh read for direct callers. Returns `true` on success,
99
+ * `false` on failure (warns to stderr).
73
100
  *
74
- * Does NOT check for collisions — callers handle that before calling.
101
+ * Does NOT check for collisions — `claimName` (the only production caller)
102
+ * handles that first. Deliberately NOT re-exported from the state barrels:
103
+ * writing the index without the claim protocol would bypass the collision
104
+ * guard. The module-level export exists for direct unit tests only.
75
105
  */
76
- export function addNameToIndex(cwd: string, name: string, runId: string): boolean {
106
+ export function addNameToIndex(cwd: string, name: string, runId: string, current?: NamesIndex): boolean {
77
107
  try {
78
- const current = readNamesIndex(cwd) ?? {};
79
- current[name] = runId;
80
- const dir = runsDir(cwd);
81
- mkdirSync(dir, { recursive: true });
82
- writeFileSync(namesFilePath(cwd), `${JSON.stringify(current)}\n`, "utf-8");
108
+ const index = current ?? readNamesIndex(cwd) ?? {};
109
+ index[name] = runId;
110
+ writeNamesIndex(cwd, index);
83
111
  return true;
84
112
  } catch (e) {
85
- console.warn(`[rpiv-workflow] names index: ${e instanceof Error ? e.message : String(e)}`);
113
+ console.warn(`[rpiv-workflow] names index: ${formatError(e)}`);
86
114
  return false;
87
115
  }
88
116
  }
89
117
 
90
118
  /**
91
- * Claim a name for a run: validate → collision-check → persist, in that order.
92
- * The single transactional door for reserving a name; callers must claim
93
- * BEFORE writing the JSONL header so the collision guard's truth-source (the
94
- * index) can never lag the header. On any non-`ok` result nothing is written.
119
+ * Roll back a claim made by `claimName` — for when the run start fails AFTER
120
+ * the claim (the JSONL header append failed), so the index never points at a
121
+ * run that doesn't exist on disk. Removes the entry only while it still maps
122
+ * to `runId` (never clobbers a re-claim by another run). Fail-soft: a failed
123
+ * rollback warns and leaves a stale entry, recoverable via `rebuildIndex`.
124
+ */
125
+ export function releaseName(cwd: string, name: string, runId: string): void {
126
+ try {
127
+ const current = readNamesIndex(cwd);
128
+ if (!current || current[name] !== runId) return;
129
+ delete current[name];
130
+ writeNamesIndex(cwd, current);
131
+ } catch (e) {
132
+ console.warn(`[rpiv-workflow] names index: ${formatError(e)}`);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Claim a name for a run: validate → collision-check → persist, in that
138
+ * order, against ONE read of the index. The single in-process door for
139
+ * reserving a name; callers must claim BEFORE writing the JSONL header so the
140
+ * collision guard's truth-source (the index) can never lag the header. On any
141
+ * non-`ok` result nothing is written.
142
+ *
143
+ * Not transactional ACROSS processes — see the module header's concurrency
144
+ * note. Within one process the read→check→write sequence is atomic by
145
+ * single-threadedness, and the rename-based write can't tear the file.
95
146
  */
96
147
  export function claimName(cwd: string, name: string, runId: string): ClaimResult {
97
148
  if (!isValidName(name)) return { ok: false, reason: "invalid" };
98
- const existing = readNamesIndex(cwd)?.[name];
99
- if (existing) return { ok: false, reason: "collision", runId: existing };
100
- if (!addNameToIndex(cwd, name, runId)) return { ok: false, reason: "write-failed" };
149
+ const current = readNamesIndex(cwd) ?? {};
150
+ const existing = current[name];
151
+ // Collision only when the holder actually exists on disk: a mapping whose
152
+ // run file is gone is a stale entry (failed `releaseName` rollback,
153
+ // hand-deleted run), so the name is re-claimable — `addNameToIndex` simply
154
+ // overwrites it. A concurrent claimant inside its own claim→header window
155
+ // could be misread as stale, but that window is two consecutive
156
+ // synchronous calls and falls under the module header's accepted
157
+ // cross-process race.
158
+ if (existing && existsSync(stateFilePath(cwd, existing))) {
159
+ return { ok: false, reason: "collision", runId: existing };
160
+ }
161
+ if (!addNameToIndex(cwd, name, runId, current)) return { ok: false, reason: "write-failed" };
101
162
  return { ok: true };
102
163
  }
103
164
 
@@ -112,22 +173,12 @@ export function claimName(cwd: string, name: string, runId: string): ClaimResult
112
173
  */
113
174
  export function rebuildIndex(cwd: string): NamesIndex | undefined {
114
175
  try {
115
- const dir = runsDir(cwd);
116
- let entries: string[];
117
- try {
118
- entries = readdirSync(dir);
119
- } catch {
120
- return undefined;
121
- }
122
-
123
176
  const index: NamesIndex = {};
124
- for (const fileName of entries) {
125
- if (!fileName.endsWith(".jsonl")) continue;
126
- const runId = fileName.slice(0, -".jsonl".length);
127
- // Read only the name field from the JSONL header — avoids importing
128
- // readHeader from reads.ts (which would create a circular dependency
129
- // since reads.ts imports readNamesIndex from this module).
130
- const name = readNameFromJsonlHeader(cwd, runId);
177
+ for (const runId of enumerateRunIds(cwd)) {
178
+ // Read only the name field off the raw first line (shared `raw.ts`
179
+ // leaf) — the full typed WorkflowHeader isn't needed here.
180
+ const header = readFirstJsonlLine(cwd, runId) as Record<string, unknown> | undefined;
181
+ const name = typeof header?.name === "string" ? header.name : undefined;
131
182
  if (name) {
132
183
  // readdirSync order is filesystem-dependent — surface duplicate
133
184
  // claims instead of silently picking a winner.
@@ -140,35 +191,10 @@ export function rebuildIndex(cwd: string): NamesIndex | undefined {
140
191
  }
141
192
  }
142
193
 
143
- mkdirSync(dir, { recursive: true });
144
- writeFileSync(namesFilePath(cwd), `${JSON.stringify(index)}\n`, "utf-8");
194
+ writeNamesIndex(cwd, index);
145
195
  return index;
146
196
  } catch (e) {
147
- console.warn(`[rpiv-workflow] names index rebuild: ${e instanceof Error ? e.message : String(e)}`);
148
- return undefined;
149
- }
150
- }
151
-
152
- /**
153
- * Read only the `name` field from a JSONL run file's header line. Returns
154
- * `undefined` when the file is missing, the first line isn't valid JSON, or
155
- * the header has no `name` field. Intentionally does not validate the full
156
- * header shape — rebuildIndex only needs the name, not the typed WorkflowHeader.
157
- *
158
- * Internal helper — not exported. Keeps names.ts acyclic with reads.ts.
159
- */
160
- function readNameFromJsonlHeader(cwd: string, runId: string): string | undefined {
161
- try {
162
- const filePath = stateFilePath(cwd, runId);
163
- if (!existsSync(filePath)) return undefined;
164
- const content = readFileSync(filePath, "utf-8");
165
- const firstLine = content.split("\n", 1)[0] ?? "";
166
- if (!firstLine) return undefined;
167
- const parsed: unknown = JSON.parse(firstLine);
168
- return typeof (parsed as Record<string, unknown>)?.name === "string"
169
- ? ((parsed as Record<string, unknown>).name as string)
170
- : undefined;
171
- } catch {
197
+ console.warn(`[rpiv-workflow] names index rebuild: ${formatError(e)}`);
172
198
  return undefined;
173
199
  }
174
200
  }
package/state/paths.ts CHANGED
@@ -48,3 +48,15 @@ export function namesFilePath(cwd: string): string {
48
48
  export function stateFilePath(cwd: string, runId: string): string {
49
49
  return join(runsDir(cwd), `${runId}.jsonl`);
50
50
  }
51
+
52
+ /**
53
+ * OPAQUE display path of a run's JSONL file — the only layout projection on
54
+ * the public surface (`runsDir`/`stateFilePath` previously invited external
55
+ * code to parse and synthesize run paths, freezing the on-disk layout into the
56
+ * public contract). Takes a `RunSummary`/`WorkflowHeader` (anything carrying
57
+ * `runId`). Consumers show or open the returned path; they MUST NOT derive
58
+ * sibling paths from it — the layout may change between versions.
59
+ */
60
+ export function runFileFor(cwd: string, run: { runId: string }): string {
61
+ return stateFilePath(cwd, run.runId);
62
+ }
package/state/raw.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Raw file-level primitives shared by the readers (`reads.ts`) and the names
3
+ * index (`names.ts`) — a LEAF under both, so neither re-implements the other
4
+ * to dodge a cycle (D9: `names.ts` used to carry its own header-line parse
5
+ * and dir scan).
6
+ *
7
+ * Fail-soft like the rest of `state/`: both helpers return empty/undefined
8
+ * on any I/O or parse failure, never throw.
9
+ */
10
+
11
+ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
12
+ import { runsDir, stateFilePath } from "./paths.js";
13
+
14
+ /** Read chunk for the first-line scan. Headers are one short JSON object — one chunk almost always suffices. */
15
+ const FIRST_LINE_CHUNK = 8192;
16
+ /** Defensive cap: a "first line" longer than this is not a header we'd accept anyway. */
17
+ const FIRST_LINE_MAX = 256 * 1024;
18
+
19
+ /**
20
+ * Parse ONLY the first JSONL line of a run file — a BOUNDED prefix read
21
+ * (open + chunked `readSync` until the first newline), not a whole-file
22
+ * `readFileSync`. `listRuns` calls this once per run file, so enumerating N
23
+ * past runs costs N small reads regardless of how many stage rows each run
24
+ * accumulated (the perf wart the old whole-file read had).
25
+ *
26
+ * Returns the parsed value (caller shape-checks it), or `undefined` when the
27
+ * file is missing/empty/unparseable. The newline search is byte-level
28
+ * (0x0A), so a multi-byte character split across chunks can't mangle the
29
+ * line.
30
+ */
31
+ export function readFirstJsonlLine(cwd: string, runId: string): unknown {
32
+ let fd: number;
33
+ try {
34
+ fd = openSync(stateFilePath(cwd, runId), "r");
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ try {
39
+ const chunks: Buffer[] = [];
40
+ let total = 0;
41
+ while (total < FIRST_LINE_MAX) {
42
+ const chunk = Buffer.alloc(FIRST_LINE_CHUNK);
43
+ const n = readSync(fd, chunk, 0, FIRST_LINE_CHUNK, total);
44
+ if (n <= 0) break;
45
+ const read = chunk.subarray(0, n);
46
+ const nl = read.indexOf(0x0a);
47
+ if (nl >= 0) {
48
+ chunks.push(read.subarray(0, nl));
49
+ break;
50
+ }
51
+ chunks.push(read);
52
+ total += n;
53
+ if (n < FIRST_LINE_CHUNK) break; // EOF before any newline
54
+ }
55
+ const line = Buffer.concat(chunks).toString("utf-8").trim();
56
+ if (!line) return undefined;
57
+ return JSON.parse(line);
58
+ } catch {
59
+ return undefined;
60
+ } finally {
61
+ closeSync(fd);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Every run id with a `<id>.jsonl` file under the runs directory, in
67
+ * filesystem order. Empty array when the directory doesn't exist (no runs
68
+ * yet) or is unreadable.
69
+ */
70
+ export function enumerateRunIds(cwd: string): string[] {
71
+ let entries: string[];
72
+ try {
73
+ entries = readdirSync(runsDir(cwd));
74
+ } catch {
75
+ return [];
76
+ }
77
+ return entries.filter((name) => name.endsWith(".jsonl")).map((name) => name.slice(0, -".jsonl".length));
78
+ }
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`). Moved out of
4
+ * `reads.ts` (D9): a name-aware resolver doesn't belong in the raw-reads
5
+ * module, and housing it there forced `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
+ }