@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
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Stage-identity derivations — the pure projections off a `StageDef` that the
3
+ * runtime and the load-time validators must agree on (effective skill, publish
4
+ * name, dispatch-vs-body classification).
5
+ *
6
+ * A dependency-free LEAF (imports only `StageDef`/`SkillStage` TYPES): so the
7
+ * definition/compile-time context (`load/`, `validate/`, `skill-contracts/harvest`)
8
+ * can consume these without importing `chain-state.ts` — a RUNTIME-STATE module
9
+ * (it imports `RunState` and houses `applyCompletedStage(state, …)` mutators).
10
+ * Co-locating these projections there forced a structural edge from the loader +
11
+ * validators into the execution context, enforced by nothing but convention.
12
+ * `chain-state.ts` re-exports them so its own runtime callers keep one import.
13
+ */
14
+
15
+ import type { SkillStage, StageDef } from "./api.js";
16
+
17
+ /**
18
+ * Resolve the `state.named` key a produces stage appends its `Output`
19
+ * envelope onto. Two layers of fallback, in priority order:
20
+ * 1. `stage.outcome?.name` — categorical name carried by the outcome.
21
+ * 2. The stage's record key — always defined.
22
+ *
23
+ * Single source of truth for the key derivation so the skill-stage path
24
+ * and the script-stage path stay in lockstep, and so `validateWorkflow`
25
+ * can compute the same key set at load time.
26
+ */
27
+ export function resolvePublishName(def: StageDef, stageName: string): string {
28
+ return def.outcome?.name ?? stageName;
29
+ }
30
+
31
+ /**
32
+ * Resolve a stage's effective skill — the contract-registry key. Twin of
33
+ * `resolvePublishName`. Single source of truth so the runtime resolution
34
+ * (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
35
+ * registry identically and can't drift.
36
+ */
37
+ export function resolveSkill(def: StageDef, stageName: string): string {
38
+ return def.skill ?? stageName;
39
+ }
40
+
41
+ /**
42
+ * A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
43
+ * (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
44
+ * neither, so they ARE dispatching stages. The shared predicate for every site
45
+ * that treats `resolveSkill`'s result as a REAL skill identity — the alias
46
+ * remap + its no-op warning, contract harvest, and the validator's contract
47
+ * lookups must all agree, or a script/prompt stage whose record key matches a
48
+ * registered skill inherits that skill's contract by accident.
49
+ *
50
+ * A TYPE GUARD since the StageDef union: a positive narrows to
51
+ * `SkillStage`, so callers that wire skill-derived data onto the stage
52
+ * (the alias remap, outcome derivers) get the writable arm.
53
+ */
54
+ export function isDispatchingStage(stage: StageDef): stage is SkillStage {
55
+ return stage.run == null && stage.prompt == null;
56
+ }
package/startup.ts CHANGED
@@ -6,8 +6,11 @@
6
6
  */
7
7
 
8
8
  export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
9
- export { registerLifecycle } from "./lifecycle.js";
9
+ export { registerLifecycle } from "./events.js";
10
+ export { registerWorkflowExecutionHost } from "./execution-host.js";
10
11
  export {
12
+ getBucketKindMappings,
13
+ registerBucketKindMapping,
11
14
  registerCompositionComparator,
12
15
  registerOutcomeDeriver,
13
16
  registerSkillContracts,
package/state/index.ts CHANGED
@@ -6,15 +6,17 @@
6
6
 
7
7
  export type {
8
8
  ClaimResult,
9
+ LoopCapRow,
9
10
  NamesIndex,
10
11
  RoutingDecision,
11
12
  RunSummary,
13
+ SessionRef,
12
14
  StageStatus,
13
15
  WorkflowHeader,
14
16
  WorkflowStage,
15
17
  } from "./state.js";
16
18
  export {
17
- addNameToIndex,
19
+ appendLoopCap,
18
20
  appendRoutingDecision,
19
21
  appendStage,
20
22
  claimName,
@@ -24,13 +26,18 @@ export {
24
26
  listRuns,
25
27
  namesFilePath,
26
28
  readAllStages,
29
+ readAllStagesForResume,
27
30
  readHeader,
28
31
  readLastStage,
32
+ readLoopCaps,
29
33
  readNamesIndex,
30
34
  readRoutingDecisions,
31
35
  rebuildIndex,
36
+ releaseName,
32
37
  resolveRun,
38
+ runFileFor,
33
39
  runsDir,
40
+ STATE_SCHEMA_VERSION,
34
41
  stateFilePath,
35
42
  VALID_NAME,
36
43
  writeHeader,
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,23 @@ 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
+ /** Per-run directory holding each detached child's persisted session file,
53
+ * keyed by SessionRef.id — `.rpiv/workflows/runs/<runId>/sessions/`. The flat
54
+ * `<runId>.jsonl` trail stays a sibling under `runsDir`. INTERNAL — not on the
55
+ * public barrel (same encapsulation rule as runsDir/stateFilePath). */
56
+ export function childSessionsDir(cwd: string, runId: string): string {
57
+ return join(runsDir(cwd), runId, "sessions");
58
+ }
59
+
60
+ /**
61
+ * OPAQUE display path of a run's JSONL file — the only layout projection on
62
+ * the public surface (exposing `runsDir`/`stateFilePath` invites external code
63
+ * to parse and synthesize run paths, freezing the on-disk layout into the public
64
+ * contract). Takes a `RunSummary`/`WorkflowHeader` (anything carrying
65
+ * `runId`). Consumers show or open the returned path; they MUST NOT derive
66
+ * sibling paths from it — the layout may change between versions.
67
+ */
68
+ export function runFileFor(cwd: string, run: { runId: string }): string {
69
+ return stateFilePath(cwd, run.runId);
70
+ }
package/state/raw.ts ADDED
@@ -0,0 +1,77 @@
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.
5
+ *
6
+ * Fail-soft like the rest of `state/`: both helpers return empty/undefined
7
+ * on any I/O or parse failure, never throw.
8
+ */
9
+
10
+ import { closeSync, openSync, readdirSync, readSync } from "node:fs";
11
+ import { runsDir, stateFilePath } from "./paths.js";
12
+
13
+ /** Read chunk for the first-line scan. Headers are one short JSON object — one chunk almost always suffices. */
14
+ const FIRST_LINE_CHUNK = 8192;
15
+ /** Defensive cap: a "first line" longer than this is not a header we'd accept anyway. */
16
+ const FIRST_LINE_MAX = 256 * 1024;
17
+
18
+ /**
19
+ * Parse ONLY the first JSONL line of a run file — a BOUNDED prefix read
20
+ * (open + chunked `readSync` until the first newline), not a whole-file
21
+ * `readFileSync`. `listRuns` calls this once per run file, so enumerating N
22
+ * past runs costs N small reads regardless of how many stage rows each run
23
+ * accumulated.
24
+ *
25
+ * Returns the parsed value (caller shape-checks it), or `undefined` when the
26
+ * file is missing/empty/unparseable. The newline search is byte-level
27
+ * (0x0A), so a multi-byte character split across chunks can't mangle the
28
+ * line.
29
+ */
30
+ export function readFirstJsonlLine(cwd: string, runId: string): unknown {
31
+ let fd: number;
32
+ try {
33
+ fd = openSync(stateFilePath(cwd, runId), "r");
34
+ } catch {
35
+ return undefined;
36
+ }
37
+ try {
38
+ const chunks: Buffer[] = [];
39
+ let total = 0;
40
+ while (total < FIRST_LINE_MAX) {
41
+ const chunk = Buffer.alloc(FIRST_LINE_CHUNK);
42
+ const n = readSync(fd, chunk, 0, FIRST_LINE_CHUNK, total);
43
+ if (n <= 0) break;
44
+ const read = chunk.subarray(0, n);
45
+ const nl = read.indexOf(0x0a);
46
+ if (nl >= 0) {
47
+ chunks.push(read.subarray(0, nl));
48
+ break;
49
+ }
50
+ chunks.push(read);
51
+ total += n;
52
+ if (n < FIRST_LINE_CHUNK) break; // EOF before any newline
53
+ }
54
+ const line = Buffer.concat(chunks).toString("utf-8").trim();
55
+ if (!line) return undefined;
56
+ return JSON.parse(line);
57
+ } catch {
58
+ return undefined;
59
+ } finally {
60
+ closeSync(fd);
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Every run id with a `<id>.jsonl` file under the runs directory, in
66
+ * filesystem order. Empty array when the directory doesn't exist (no runs
67
+ * yet) or is unreadable.
68
+ */
69
+ export function enumerateRunIds(cwd: string): string[] {
70
+ let entries: string[];
71
+ try {
72
+ entries = readdirSync(runsDir(cwd));
73
+ } catch {
74
+ return [];
75
+ }
76
+ return entries.filter((name) => name.endsWith(".jsonl")).map((name) => name.slice(0, -".jsonl".length));
77
+ }