@osolmaz/pi-workflows 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +107 -26
  2. package/dist/builtins/monitor.workflow.d.ts +71 -0
  3. package/dist/builtins/monitor.workflow.js +234 -0
  4. package/dist/builtins/monitor.workflow.js.map +1 -0
  5. package/dist/controllers/conditions.d.ts +6 -0
  6. package/dist/controllers/conditions.js +68 -0
  7. package/dist/controllers/conditions.js.map +1 -0
  8. package/dist/controllers/definition.d.ts +6 -0
  9. package/dist/controllers/definition.js +45 -0
  10. package/dist/controllers/definition.js.map +1 -0
  11. package/dist/controllers/effects.d.ts +14 -0
  12. package/dist/controllers/effects.js +104 -0
  13. package/dist/controllers/effects.js.map +1 -0
  14. package/dist/controllers/errors.d.ts +12 -0
  15. package/dist/controllers/errors.js +25 -0
  16. package/dist/controllers/errors.js.map +1 -0
  17. package/dist/controllers/index.d.ts +13 -0
  18. package/dist/controllers/index.js +13 -0
  19. package/dist/controllers/index.js.map +1 -0
  20. package/dist/controllers/json.d.ts +5 -0
  21. package/dist/controllers/json.js +57 -0
  22. package/dist/controllers/json.js.map +1 -0
  23. package/dist/controllers/loader.d.ts +23 -0
  24. package/dist/controllers/loader.js +74 -0
  25. package/dist/controllers/loader.js.map +1 -0
  26. package/dist/controllers/manager.d.ts +58 -0
  27. package/dist/controllers/manager.js +399 -0
  28. package/dist/controllers/manager.js.map +1 -0
  29. package/dist/controllers/results.d.ts +5 -0
  30. package/dist/controllers/results.js +32 -0
  31. package/dist/controllers/results.js.map +1 -0
  32. package/dist/controllers/sqlite.d.ts +212 -0
  33. package/dist/controllers/sqlite.js +1009 -0
  34. package/dist/controllers/sqlite.js.map +1 -0
  35. package/dist/controllers/store.d.ts +112 -0
  36. package/dist/controllers/store.js +32 -0
  37. package/dist/controllers/store.js.map +1 -0
  38. package/dist/controllers/types.d.ts +159 -0
  39. package/dist/controllers/types.js +2 -0
  40. package/dist/controllers/types.js.map +1 -0
  41. package/dist/controllers/workflow-engine-scheduler.d.ts +25 -0
  42. package/dist/controllers/workflow-engine-scheduler.js +93 -0
  43. package/dist/controllers/workflow-engine-scheduler.js.map +1 -0
  44. package/dist/controllers/workflows.d.ts +27 -0
  45. package/dist/controllers/workflows.js +109 -0
  46. package/dist/controllers/workflows.js.map +1 -0
  47. package/dist/extension/controller-host.d.ts +47 -0
  48. package/dist/extension/controller-host.js +110 -0
  49. package/dist/extension/controller-host.js.map +1 -0
  50. package/dist/extension/executor.d.ts +14 -1
  51. package/dist/extension/executor.js +12 -2
  52. package/dist/extension/executor.js.map +1 -1
  53. package/dist/extension/index.d.ts +7 -0
  54. package/dist/extension/index.js +1118 -89
  55. package/dist/extension/index.js.map +1 -1
  56. package/dist/extension/recorder.d.ts +91 -0
  57. package/dist/extension/recorder.js +537 -0
  58. package/dist/extension/recorder.js.map +1 -0
  59. package/dist/extension/session-events.d.ts +134 -0
  60. package/dist/extension/session-events.js +60 -0
  61. package/dist/extension/session-events.js.map +1 -0
  62. package/dist/extension/widget.js +25 -24
  63. package/dist/extension/widget.js.map +1 -1
  64. package/dist/extension/workflow-tool.d.ts +28 -0
  65. package/dist/extension/workflow-tool.js +33 -0
  66. package/dist/extension/workflow-tool.js.map +1 -0
  67. package/dist/host/processes.d.ts +24 -0
  68. package/dist/host/processes.js +114 -0
  69. package/dist/host/processes.js.map +1 -0
  70. package/dist/host/rpc-bridge.d.ts +9 -0
  71. package/dist/host/rpc-bridge.js +39 -0
  72. package/dist/host/rpc-bridge.js.map +1 -0
  73. package/dist/host/rpc-executor.d.ts +38 -0
  74. package/dist/host/rpc-executor.js +254 -0
  75. package/dist/host/rpc-executor.js.map +1 -0
  76. package/dist/host/runner.d.ts +49 -0
  77. package/dist/host/runner.js +350 -0
  78. package/dist/host/runner.js.map +1 -0
  79. package/dist/render/canvas.d.ts +1 -1
  80. package/dist/render/canvas.js +5 -0
  81. package/dist/render/canvas.js.map +1 -1
  82. package/dist/render/graph-render.d.ts +5 -0
  83. package/dist/render/graph-render.js +211 -48
  84. package/dist/render/graph-render.js.map +1 -1
  85. package/dist/viewer/cli.d.ts +7 -3
  86. package/dist/viewer/cli.js +150 -19
  87. package/dist/viewer/cli.js.map +1 -1
  88. package/dist/viewer/render.js +19 -3
  89. package/dist/viewer/render.js.map +1 -1
  90. package/dist/viewer/session-reducer.d.ts +45 -0
  91. package/dist/viewer/session-reducer.js +266 -0
  92. package/dist/viewer/session-reducer.js.map +1 -0
  93. package/dist/workflows/artifacts.d.ts +40 -0
  94. package/dist/workflows/artifacts.js +155 -0
  95. package/dist/workflows/artifacts.js.map +1 -0
  96. package/dist/workflows/engine.d.ts +38 -0
  97. package/dist/workflows/engine.js +281 -20
  98. package/dist/workflows/engine.js.map +1 -1
  99. package/dist/workflows/errors.d.ts +23 -0
  100. package/dist/workflows/errors.js +38 -0
  101. package/dist/workflows/errors.js.map +1 -1
  102. package/dist/workflows/graph.js +0 -5
  103. package/dist/workflows/graph.js.map +1 -1
  104. package/dist/workflows/index.d.ts +3 -2
  105. package/dist/workflows/index.js +2 -1
  106. package/dist/workflows/index.js.map +1 -1
  107. package/dist/workflows/loader.d.ts +5 -3
  108. package/dist/workflows/loader.js +10 -1
  109. package/dist/workflows/loader.js.map +1 -1
  110. package/dist/workflows/schema.js +1 -1
  111. package/dist/workflows/schema.js.map +1 -1
  112. package/dist/workflows/store.d.ts +98 -10
  113. package/dist/workflows/store.js +921 -46
  114. package/dist/workflows/store.js.map +1 -1
  115. package/dist/workflows/types.d.ts +136 -3
  116. package/docs/CONTROLLERS.md +215 -0
  117. package/docs/development.md +51 -24
  118. package/docs/live-replay-protocol.md +155 -0
  119. package/docs/plans/2026-08-04-controller-runtime-plan.md +169 -0
  120. package/docs/plans/2026-08-05-always-on-workflows-plan.md +125 -0
  121. package/docs/plans/2026-08-10-agent-managed-monitor-workflows-plan.md +184 -0
  122. package/docs/plans/piw-viewer-experience-implementation-plan.md +674 -0
  123. package/docs/plans/replayable-run-bundles-implementation-plan.md +65 -0
  124. package/docs/plans/session-event-replay-implementation-plan.md +494 -0
  125. package/docs/plans/tui-viewer-implementation-plan.md +64 -0
  126. package/docs/run-bundles.md +359 -55
  127. package/docs/session-event-journal.md +470 -0
  128. package/docs/tui-viewer.md +218 -0
  129. package/docs/workflows.md +131 -11
  130. package/examples/controllers/pull-request.controller.ts +215 -0
  131. package/package.json +11 -2
  132. package/src/builtins/monitor.workflow.ts +278 -0
  133. package/src/controllers/conditions.ts +110 -0
  134. package/src/controllers/definition.ts +65 -0
  135. package/src/controllers/effects.ts +123 -0
  136. package/src/controllers/errors.ts +27 -0
  137. package/src/controllers/index.ts +90 -0
  138. package/src/controllers/json.ts +62 -0
  139. package/src/controllers/loader.ts +104 -0
  140. package/src/controllers/manager.ts +533 -0
  141. package/src/controllers/results.ts +46 -0
  142. package/src/controllers/sqlite.ts +1427 -0
  143. package/src/controllers/store.ts +160 -0
  144. package/src/controllers/types.ts +183 -0
  145. package/src/controllers/workflow-engine-scheduler.ts +145 -0
  146. package/src/controllers/workflows.ts +152 -0
  147. package/src/extension/controller-host.ts +163 -0
  148. package/src/extension/executor.ts +29 -2
  149. package/src/extension/index.ts +1315 -109
  150. package/src/extension/recorder.ts +662 -0
  151. package/src/extension/session-events.ts +119 -0
  152. package/src/extension/widget.ts +26 -24
  153. package/src/extension/workflow-tool.ts +59 -0
  154. package/src/host/processes.ts +119 -0
  155. package/src/host/rpc-bridge.ts +44 -0
  156. package/src/host/rpc-executor.ts +299 -0
  157. package/src/host/runner.ts +406 -0
  158. package/src/render/canvas.ts +19 -1
  159. package/src/render/graph-render.ts +277 -44
  160. package/src/viewer/cli.ts +167 -21
  161. package/src/viewer/render.ts +21 -3
  162. package/src/viewer/session-reducer.ts +347 -0
  163. package/src/workflows/artifacts.ts +188 -0
  164. package/src/workflows/engine.ts +365 -19
  165. package/src/workflows/errors.ts +45 -0
  166. package/src/workflows/graph.ts +0 -5
  167. package/src/workflows/index.ts +15 -0
  168. package/src/workflows/loader.ts +13 -3
  169. package/src/workflows/schema.ts +1 -1
  170. package/src/workflows/store.ts +1157 -48
  171. package/src/workflows/types.ts +151 -3
@@ -2,13 +2,46 @@ import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { ArtifactWriter, encodeValue } from "./artifacts.js";
5
6
  export const RUN_BUNDLE_SCHEMA = "pi-workflows.run-bundle.v1";
7
+ export const RUN_STATE_SCHEMA = "pi-workflows.run-state.v1";
6
8
  export const TRACE_EVENT_SCHEMA = "pi-workflows.trace-event.v1";
7
9
  export const DEFINITION_SNAPSHOT_SCHEMA = "pi-workflows.definition-snapshot.v1";
10
+ export const SESSION_BINDING_SCHEMA = "pi-workflows.session-binding.v1";
11
+ export const SESSION_EVENT_SCHEMA = "pi-workflows.session-event.v1";
12
+ export const SESSION_CAPTURE_SCHEMA = "pi-workflows.session-capture.v1";
13
+ export const SESSION_EVENT_MAX_BYTES = 1024 * 1024;
8
14
  const MANIFEST_PATH = "manifest.json";
9
15
  const WORKFLOW_SNAPSHOT_PATH = "workflow.json";
10
16
  const STATE_PATH = "state.json";
11
17
  const TRACE_PATH = "trace.ndjson";
18
+ const SESSION_DIR = "session";
19
+ const SESSION_BINDING_PATH = `${SESSION_DIR}/binding.json`;
20
+ const SESSION_ENTRIES_PATH = `${SESSION_DIR}/entries.ndjson`;
21
+ const SESSION_EVENTS_PATH = `${SESSION_DIR}/events.ndjson`;
22
+ const SESSION_CAPTURE_PATH = `${SESSION_DIR}/capture.json`;
23
+ const SESSION_SEGMENTS_DIR = `${SESSION_DIR}/segments`;
24
+ /** Capture file layout for one recorder attempt; "" is the legacy flat stream. */
25
+ function sessionStreamPaths(attemptId) {
26
+ if (attemptId === undefined) {
27
+ return {
28
+ dir: SESSION_DIR,
29
+ binding: SESSION_BINDING_PATH,
30
+ entries: SESSION_ENTRIES_PATH,
31
+ events: SESSION_EVENTS_PATH,
32
+ capture: SESSION_CAPTURE_PATH,
33
+ };
34
+ }
35
+ assertValidRunId(attemptId);
36
+ const dir = `${SESSION_SEGMENTS_DIR}/${attemptId}`;
37
+ return {
38
+ dir,
39
+ binding: `${dir}/binding.json`,
40
+ entries: `${dir}/entries.ndjson`,
41
+ events: `${dir}/events.ndjson`,
42
+ capture: `${dir}/capture.json`,
43
+ };
44
+ }
12
45
  /** Runs directory: `$PI_WORKFLOWS_RUNS_DIR` or `~/.pi/agent/workflows/runs`. */
13
46
  export function workflowRunsBaseDir(homeDir = os.homedir()) {
14
47
  const override = process.env.PI_WORKFLOWS_RUNS_DIR;
@@ -29,76 +62,815 @@ export function createRunId(workflowName, now = new Date()) {
29
62
  .slice(0, 40);
30
63
  return `${stamp}-${slug || "workflow"}-${randomUUID().slice(0, 8)}`;
31
64
  }
32
- /**
33
- * Persists run bundles. A bundle directory contains `manifest.json`,
34
- * `workflow.json` (definition snapshot), `state.json` (full run projection,
35
- * atomically replaced), and `trace.ndjson` (append-only event log).
36
- */
37
65
  export class WorkflowRunStore {
38
66
  outputRoot;
39
- traceSeqByRun = new Map();
40
- appendChainByPath = new Map();
41
- constructor(outputRoot = workflowRunsBaseDir()) {
67
+ fenceProvider;
68
+ contexts = new Map();
69
+ constructor(outputRoot = workflowRunsBaseDir(), options = {}) {
42
70
  this.outputRoot = outputRoot;
71
+ this.fenceProvider = options.fenceProvider;
43
72
  }
44
73
  runDirFor(runId) {
74
+ assertValidRunId(runId);
45
75
  return path.join(this.outputRoot, runId);
46
76
  }
77
+ async quarantineIncompleteRun(runId) {
78
+ const runDir = this.runDirFor(runId);
79
+ let runStat;
80
+ try {
81
+ runStat = await fs.lstat(runDir);
82
+ }
83
+ catch (error) {
84
+ if (isMissingPath(error)) {
85
+ return undefined;
86
+ }
87
+ throw error;
88
+ }
89
+ if (!runStat.isDirectory() || runStat.isSymbolicLink()) {
90
+ throw new Error(`Reserved workflow run path is not a directory: ${runDir}`);
91
+ }
92
+ try {
93
+ await fs.lstat(path.join(runDir, MANIFEST_PATH));
94
+ throw new Error(`Reserved workflow run has an unreadable manifest: ${runId}`);
95
+ }
96
+ catch (error) {
97
+ if (!isMissingPath(error)) {
98
+ throw error;
99
+ }
100
+ }
101
+ const quarantineDir = path.join(this.outputRoot, `.${runId}.incomplete-${randomUUID().slice(0, 8)}`);
102
+ await fs.rename(runDir, quarantineDir);
103
+ this.contexts.delete(runDir);
104
+ return quarantineDir;
105
+ }
106
+ contextFor(runDir) {
107
+ let context = this.contexts.get(runDir);
108
+ if (!context) {
109
+ context = {
110
+ traceSeq: 0,
111
+ artifacts: new ArtifactWriter(runDir),
112
+ lock: Promise.resolve(),
113
+ streams: new Map(),
114
+ };
115
+ this.contexts.set(runDir, context);
116
+ }
117
+ return context;
118
+ }
119
+ streamFor(runDir, attemptId) {
120
+ const context = this.contextFor(runDir);
121
+ const key = attemptId ?? "";
122
+ let stream = context.streams.get(key);
123
+ if (!stream) {
124
+ stream = {
125
+ sessionSeq: 0,
126
+ sessionEventSeq: 0,
127
+ sessionBound: false,
128
+ sessionEventsStopped: false,
129
+ lock: Promise.resolve(),
130
+ };
131
+ context.streams.set(key, stream);
132
+ }
133
+ return stream;
134
+ }
135
+ /**
136
+ * Run `task` exclusively for this bundle. Sequence numbers are assigned
137
+ * inside the lock, so physical file order always matches logical order.
138
+ */
139
+ withRunLock(runDir, task) {
140
+ const context = this.contextFor(runDir);
141
+ const result = context.lock.then(async () => {
142
+ this.fenceProvider?.(runDir)?.();
143
+ return await task();
144
+ });
145
+ context.lock = result.then(() => undefined, () => undefined);
146
+ return result;
147
+ }
148
+ withSessionEventLock(runDir, attemptId, task) {
149
+ const stream = this.streamFor(runDir, attemptId);
150
+ const result = stream.lock.then(async () => {
151
+ this.fenceProvider?.(runDir)?.();
152
+ return await task();
153
+ });
154
+ stream.lock = result.then(() => undefined, () => undefined);
155
+ return result;
156
+ }
47
157
  async initializeRunBundle(workflow, state) {
48
158
  const runDir = this.runDirFor(state.runId);
49
- await fs.mkdir(runDir, { recursive: true });
50
- this.traceSeqByRun.set(runDir, 0);
51
- await writeJsonAtomic(path.join(runDir, WORKFLOW_SNAPSHOT_PATH), createDefinitionSnapshot(workflow));
52
- await writeJsonAtomic(path.join(runDir, MANIFEST_PATH), createManifest(state));
53
- await writeJsonAtomic(path.join(runDir, STATE_PATH), state);
54
- await this.appendJsonLine(path.join(runDir, TRACE_PATH), null);
55
- return runDir;
159
+ return await this.withRunLock(runDir, async () => {
160
+ await fs.mkdir(this.outputRoot, { recursive: true, mode: 0o700 });
161
+ await fs.mkdir(runDir, { recursive: false, mode: 0o700 });
162
+ await writeJsonAtomic(path.join(runDir, WORKFLOW_SNAPSHOT_PATH), createDefinitionSnapshot(workflow));
163
+ await appendLine(path.join(runDir, TRACE_PATH), null);
164
+ await this.writeProjections(runDir, state);
165
+ return runDir;
166
+ });
167
+ }
168
+ /**
169
+ * Prepare an interrupted bundle for resume. Repairs a torn trace tail,
170
+ * drops trace events the state projection never recorded, and seeds the
171
+ * in-process context so new events continue the sequence. The caller must
172
+ * hold the run's queue claim; the fence is verified before any write.
173
+ */
174
+ async prepareRunResume(runId) {
175
+ const runDir = this.runDirFor(runId);
176
+ this.fenceProvider?.(runDir)?.();
177
+ const bundle = await readRunBundle(runDir);
178
+ if (bundle === null) {
179
+ throw new Error(`Cannot resume unreadable workflow run: ${runId}`);
180
+ }
181
+ if (bundle.state.status !== "running") {
182
+ throw new Error(`Cannot resume workflow run ${runId} with status ${bundle.state.status}`);
183
+ }
184
+ const tracePath = resolveBundlePath(runDir, bundle.manifest.paths.trace, TRACE_PATH);
185
+ await repairTraceFile(tracePath, bundle.state.traceSeq, () => {
186
+ // The repair rewrites the trace; re-verify ownership immediately
187
+ // before the rename so a stalled runner cannot truncate a new claim
188
+ // holder's appended events.
189
+ this.fenceProvider?.(runDir)?.();
190
+ });
191
+ // A crashed session never finalizes its capture, and resuming recorders
192
+ // always write new segments — so dangling "recording" captures end here
193
+ // instead of reporting the run capture-corrupt forever.
194
+ await this.finalizeRecordingCaptures(runDir, "Workflow host stopped before the run finished");
195
+ const counts = await this.sessionCounts(runDir);
196
+ const captureFinished = bundle.sessionCapture?.status === "complete" || bundle.sessionCapture?.status === "failed";
197
+ this.contexts.set(runDir, {
198
+ traceSeq: bundle.state.traceSeq,
199
+ artifacts: new ArtifactWriter(runDir),
200
+ lock: Promise.resolve(),
201
+ streams: seededStreams({
202
+ sessionSeq: counts.entryCount,
203
+ sessionEventSeq: counts.lastEventSeq,
204
+ sessionBound: bundle.manifest.paths.session !== undefined,
205
+ sessionEventsStopped: captureFinished,
206
+ }),
207
+ });
208
+ const prepared = await readRunBundle(runDir);
209
+ if (prepared === null) {
210
+ throw new Error(`Workflow run ${runId} became unreadable during resume preparation`);
211
+ }
212
+ return prepared;
213
+ }
214
+ /**
215
+ * Finalize captures left "recording" by a session that is gone, so they
216
+ * report failed with the reason instead of dangling forever.
217
+ */
218
+ async finalizeRecordingCaptures(runDir, reason, options = {}) {
219
+ if (options.skipFlat !== true) {
220
+ const flatCapture = await readJsonFile(path.join(runDir, SESSION_CAPTURE_PATH));
221
+ if (flatCapture?.status === "recording") {
222
+ const counts = await this.sessionCounts(runDir);
223
+ await this.writeSessionCapture(runDir, {
224
+ schema: SESSION_CAPTURE_SCHEMA,
225
+ eventSchema: SESSION_EVENT_SCHEMA,
226
+ status: "failed",
227
+ ...counts,
228
+ failure: {
229
+ failedAt: new Date().toISOString(),
230
+ code: "host_interrupted",
231
+ message: reason,
232
+ },
233
+ });
234
+ }
235
+ }
236
+ for (const segmentId of await this.listSessionSegments(runDir)) {
237
+ const segmentCapture = await readJsonFile(path.join(runDir, sessionStreamPaths(segmentId).capture));
238
+ if (segmentCapture?.status !== "recording") {
239
+ continue;
240
+ }
241
+ const segmentCounts = await this.sessionCounts(runDir, segmentId);
242
+ await this.writeSessionCapture(runDir, {
243
+ schema: SESSION_CAPTURE_SCHEMA,
244
+ eventSchema: SESSION_EVENT_SCHEMA,
245
+ status: "failed",
246
+ ...segmentCounts,
247
+ failure: {
248
+ failedAt: new Date().toISOString(),
249
+ code: "host_interrupted",
250
+ message: reason,
251
+ },
252
+ }, segmentId);
253
+ }
56
254
  }
255
+ /** Mark a nonterminal bundle failed and append an interruption event. */
256
+ async markRunInterrupted(runId, reason = "Workflow host stopped before the run finished") {
257
+ const runDir = this.runDirFor(runId);
258
+ const bundle = await readRunBundle(runDir);
259
+ if (bundle === null || bundle.state.status !== "running") {
260
+ return bundle;
261
+ }
262
+ const lastTraceEvent = await readLastTraceEvent(runDir, bundle.manifest.paths.trace);
263
+ const counts = await this.sessionCounts(runDir);
264
+ const sessionBound = bundle.manifest.paths.session !== undefined;
265
+ const captureFinished = bundle.sessionCapture?.status === "complete" || bundle.sessionCapture?.status === "failed";
266
+ this.contexts.set(runDir, {
267
+ traceSeq: Math.max(bundle.state.traceSeq, lastTraceEvent?.seq ?? 0),
268
+ artifacts: new ArtifactWriter(runDir),
269
+ lock: Promise.resolve(),
270
+ streams: seededStreams({
271
+ sessionSeq: counts.entryCount,
272
+ sessionEventSeq: counts.lastEventSeq,
273
+ sessionBound,
274
+ sessionEventsStopped: captureFinished,
275
+ }),
276
+ });
277
+ const state = bundle.state;
278
+ if (lastTraceEvent !== null && recoverTerminalProjection(state, lastTraceEvent)) {
279
+ await this.writeLoadedProjections(runDir, state);
280
+ return await readRunBundle(runDir);
281
+ }
282
+ if (sessionBound && !captureFinished) {
283
+ await this.writeSessionCapture(runDir, {
284
+ schema: SESSION_CAPTURE_SCHEMA,
285
+ eventSchema: SESSION_EVENT_SCHEMA,
286
+ status: "failed",
287
+ ...counts,
288
+ failure: {
289
+ failedAt: new Date().toISOString(),
290
+ code: "host_interrupted",
291
+ message: reason,
292
+ },
293
+ });
294
+ }
295
+ await this.finalizeRecordingCaptures(runDir, reason, { skipFlat: true });
296
+ state.status = "failed";
297
+ state.finishedAt = new Date().toISOString();
298
+ state.error = reason;
299
+ delete state.currentNode;
300
+ delete state.currentAttemptId;
301
+ delete state.currentNodeStartedAt;
302
+ delete state.statusDetail;
303
+ delete state.paused;
304
+ await this.withRunLock(runDir, async () => {
305
+ const traceEvent = await this.appendTraceEvent(runDir, state.runId, {
306
+ scope: "run",
307
+ type: "run_interrupted",
308
+ payload: { error: reason },
309
+ });
310
+ state.traceSeq = traceEvent.seq;
311
+ state.updatedAt = traceEvent.at;
312
+ await this.writeLoadedProjections(runDir, state);
313
+ });
314
+ return await readRunBundle(runDir);
315
+ }
316
+ /**
317
+ * Persist one transition: append the trace event, then rewrite the
318
+ * projections reflecting it.
319
+ */
57
320
  async writeSnapshot(runDir, state, event) {
58
- state.updatedAt = new Date().toISOString();
59
- await writeJsonAtomic(path.join(runDir, STATE_PATH), state);
60
- await writeJsonAtomic(path.join(runDir, MANIFEST_PATH), createManifest(state));
61
- return await this.appendTrace(runDir, state, event);
321
+ return await this.withRunLock(runDir, async () => {
322
+ const traceEvent = await this.appendTraceEvent(runDir, state.runId, event);
323
+ state.traceSeq = traceEvent.seq;
324
+ state.updatedAt = new Date().toISOString();
325
+ await this.writeProjections(runDir, state);
326
+ return traceEvent;
327
+ });
62
328
  }
63
- async appendTrace(runDir, state, event) {
329
+ /**
330
+ * Bind the run to a Pi conversation: write `session/binding.json` once and
331
+ * append a `session_bound` trace event. Projections catch up on the next
332
+ * snapshot.
333
+ */
334
+ /** True when a session binding already exists for this bundle. */
335
+ async hasSessionBinding(runDir) {
336
+ try {
337
+ await fs.lstat(path.join(runDir, SESSION_BINDING_PATH));
338
+ return true;
339
+ }
340
+ catch {
341
+ return false;
342
+ }
343
+ }
344
+ /** List capture segment attempt ids under `session/segments/`. */
345
+ async listSessionSegments(runDir) {
346
+ try {
347
+ const entries = await fs.readdir(path.join(runDir, SESSION_SEGMENTS_DIR), {
348
+ withFileTypes: true,
349
+ });
350
+ return entries
351
+ .filter((entry) => entry.isDirectory())
352
+ .map((entry) => entry.name)
353
+ .sort();
354
+ }
355
+ catch {
356
+ return [];
357
+ }
358
+ }
359
+ async writeSessionBinding(runDir, binding, attemptId) {
360
+ await this.withRunLock(runDir, async () => {
361
+ const stream = this.streamFor(runDir, attemptId);
362
+ if (stream.sessionBound) {
363
+ return;
364
+ }
365
+ stream.sessionBound = true;
366
+ const paths = sessionStreamPaths(attemptId);
367
+ await fs.mkdir(path.join(runDir, paths.dir), { recursive: true, mode: 0o700 });
368
+ await writeJsonAtomic(path.join(runDir, paths.binding), binding);
369
+ await this.appendTraceEvent(runDir, binding.runId, {
370
+ scope: "session",
371
+ type: "session_bound",
372
+ payload: {
373
+ piSessionId: binding.piSessionId,
374
+ ...(attemptId !== undefined ? { captureAttemptId: attemptId } : {}),
375
+ },
376
+ });
377
+ });
378
+ }
379
+ /** Append one verbatim Pi session entry to `session/entries.ndjson`. */
380
+ async appendSessionEntry(runDir, entry, attemptId) {
381
+ return await this.withRunLock(runDir, async () => {
382
+ const stream = this.streamFor(runDir, attemptId);
383
+ stream.sessionSeq += 1;
384
+ const record = {
385
+ seq: stream.sessionSeq,
386
+ at: new Date().toISOString(),
387
+ entry,
388
+ };
389
+ await appendLine(path.join(runDir, sessionStreamPaths(attemptId).entries), record);
390
+ return record.seq;
391
+ });
392
+ }
393
+ /** Append a fully stamped ordered batch to `session/events.ndjson`. */
394
+ async appendSessionEventBatch(runDir, records, attemptId) {
395
+ if (records.length === 0) {
396
+ return;
397
+ }
398
+ await this.withSessionEventLock(runDir, attemptId, async () => {
399
+ const stream = this.streamFor(runDir, attemptId);
400
+ if (stream.sessionEventsStopped) {
401
+ throw new Error("Session event capture has stopped");
402
+ }
403
+ try {
404
+ let expected = stream.sessionEventSeq + 1;
405
+ for (const record of records) {
406
+ validateSessionEventRecord(record);
407
+ if (record.seq !== expected) {
408
+ throw new Error(`Expected session event seq ${expected}, got ${record.seq}`);
409
+ }
410
+ expected += 1;
411
+ }
412
+ const encoded = await Promise.all(records.map(async (record) => ({
413
+ ...record,
414
+ payload: record.type === "tool_execution_started" ||
415
+ record.type === "tool_execution_finished" ||
416
+ (record.type === "assistant_event" && record.payload.type === "toolcall_end")
417
+ ? (await encodeValue(record.payload, this.contextFor(runDir).artifacts))
418
+ : record.payload,
419
+ })));
420
+ for (const record of encoded) {
421
+ if (Buffer.byteLength(JSON.stringify(record), "utf8") + 1 > SESSION_EVENT_MAX_BYTES) {
422
+ throw new Error(`session event exceeded ${SESSION_EVENT_MAX_BYTES} bytes`);
423
+ }
424
+ }
425
+ await appendLines(path.join(runDir, sessionStreamPaths(attemptId).events), encoded);
426
+ stream.sessionEventSeq = records.at(-1)?.seq ?? stream.sessionEventSeq;
427
+ }
428
+ catch (error) {
429
+ stream.sessionEventsStopped = true;
430
+ throw error;
431
+ }
432
+ });
433
+ }
434
+ /** Atomically replace the temporal capture integrity projection. */
435
+ async writeSessionCapture(runDir, capture, attemptId) {
436
+ validateSessionCapture(capture);
437
+ await this.withSessionEventLock(runDir, attemptId, async () => {
438
+ const stream = this.streamFor(runDir, attemptId);
439
+ if (capture.status !== "recording") {
440
+ stream.sessionEventsStopped = true;
441
+ }
442
+ await writeJsonAtomic(path.join(runDir, sessionStreamPaths(attemptId).capture), capture);
443
+ });
444
+ }
445
+ /** Count complete durable session records after both writers have drained. */
446
+ async sessionCounts(runDir, attemptId) {
447
+ const paths = sessionStreamPaths(attemptId);
448
+ const events = await readCompleteNdjson(path.join(runDir, paths.events));
449
+ const entries = await readCompleteNdjson(path.join(runDir, paths.entries));
450
+ return {
451
+ eventCount: events.length,
452
+ entryCount: entries.length,
453
+ lastEventSeq: events.at(-1)?.seq ?? 0,
454
+ };
455
+ }
456
+ async appendTraceEvent(runDir, runId, event) {
457
+ const context = this.contextFor(runDir);
64
458
  const traceEvent = {
65
- seq: this.nextTraceSeq(runDir),
459
+ seq: context.traceSeq + 1,
66
460
  at: new Date().toISOString(),
67
- runId: state.runId,
461
+ runId,
68
462
  ...event,
463
+ payload: (await encodeValue(event.payload, context.artifacts)),
69
464
  };
70
- await this.appendJsonLine(path.join(runDir, TRACE_PATH), traceEvent);
465
+ await appendLine(path.join(runDir, TRACE_PATH), traceEvent);
466
+ context.traceSeq = traceEvent.seq;
71
467
  return traceEvent;
72
468
  }
73
- nextTraceSeq(runDir) {
74
- const next = (this.traceSeqByRun.get(runDir) ?? 0) + 1;
75
- this.traceSeqByRun.set(runDir, next);
76
- return next;
469
+ async writeProjections(runDir, state) {
470
+ const context = this.contextFor(runDir);
471
+ const encoded = await encodeRunState(state, context.artifacts);
472
+ await writeJsonAtomic(path.join(runDir, STATE_PATH), encoded);
473
+ await writeJsonAtomic(path.join(runDir, MANIFEST_PATH), createManifest(state, {
474
+ session: [...context.streams.values()].some((stream) => stream.sessionBound),
475
+ }));
77
476
  }
78
- async appendJsonLine(filePath, value) {
79
- const prior = this.appendChainByPath.get(filePath) ?? Promise.resolve();
80
- const nextWrite = prior.then(async () => {
81
- await fs.mkdir(path.dirname(filePath), { recursive: true });
82
- await fs.appendFile(filePath, value === null ? "" : `${JSON.stringify(value)}\n`, "utf8");
83
- });
84
- const tracked = nextWrite.finally(() => {
85
- if (this.appendChainByPath.get(filePath) === tracked) {
86
- this.appendChainByPath.delete(filePath);
477
+ async writeLoadedProjections(runDir, state) {
478
+ const context = this.contextFor(runDir);
479
+ await writeJsonAtomic(path.join(runDir, STATE_PATH), state);
480
+ await writeJsonAtomic(path.join(runDir, MANIFEST_PATH), createManifest(state, {
481
+ session: [...context.streams.values()].some((stream) => stream.sessionBound),
482
+ }));
483
+ }
484
+ }
485
+ /**
486
+ * Truncate a trace file to the longest contiguous valid prefix, then to the
487
+ * event count the state projection recorded. A crash can leave a partial
488
+ * final line or one event appended before its projection write; the repair
489
+ * keeps state and trace consistent so resume can continue the sequence. The
490
+ * rewrite is atomic: a stale writer appending to the old inode cannot
491
+ * interleave with the repaired file.
492
+ */
493
+ async function repairTraceFile(tracePath, keepSeq, beforeWrite) {
494
+ let raw;
495
+ try {
496
+ raw = await fs.readFile(tracePath, "utf8");
497
+ }
498
+ catch {
499
+ return;
500
+ }
501
+ const lines = raw.split("\n");
502
+ if (lines.at(-1) === "") {
503
+ lines.pop();
504
+ }
505
+ const good = [];
506
+ let expectedSeq = 1;
507
+ for (const line of lines) {
508
+ if (line.trim().length === 0) {
509
+ break;
510
+ }
511
+ try {
512
+ const event = JSON.parse(line);
513
+ if (event.seq !== expectedSeq) {
514
+ break;
87
515
  }
88
- });
89
- this.appendChainByPath.set(filePath, tracked);
90
- await tracked;
516
+ good.push(line);
517
+ expectedSeq += 1;
518
+ }
519
+ catch {
520
+ break;
521
+ }
522
+ }
523
+ const kept = good.slice(0, keepSeq);
524
+ if (kept.length === lines.length) {
525
+ return;
91
526
  }
527
+ beforeWrite?.();
528
+ const tempPath = `${tracePath}.${process.pid}.${randomUUID()}.tmp`;
529
+ await fs.writeFile(tempPath, kept.length === 0 ? "" : `${kept.join("\n")}\n`, {
530
+ encoding: "utf8",
531
+ mode: 0o600,
532
+ });
533
+ await fs.rename(tempPath, tracePath);
534
+ }
535
+ function seededStreams(flat) {
536
+ return new Map([["", { ...flat, lock: Promise.resolve() }]]);
537
+ }
538
+ function recoverTerminalProjection(state, event) {
539
+ const status = terminalStatusForEvent(event.type);
540
+ if (status === undefined) {
541
+ return false;
542
+ }
543
+ state.traceSeq = event.seq;
544
+ state.status = status;
545
+ state.updatedAt = event.at;
546
+ state.finishedAt = event.at;
547
+ if (typeof event.payload.error === "string") {
548
+ state.error = event.payload.error;
549
+ }
550
+ if (typeof event.payload.waitingOn === "string") {
551
+ state.waitingOn = event.payload.waitingOn;
552
+ }
553
+ if (Object.hasOwn(event.payload, "finalOutput")) {
554
+ state.finalOutput = event.payload.finalOutput;
555
+ }
556
+ delete state.currentNode;
557
+ delete state.currentAttemptId;
558
+ delete state.currentNodeStartedAt;
559
+ return true;
560
+ }
561
+ function terminalStatusForEvent(type) {
562
+ switch (type) {
563
+ case "run_waiting":
564
+ return "waiting";
565
+ case "run_completed":
566
+ return "completed";
567
+ case "run_failed":
568
+ case "run_interrupted":
569
+ return "failed";
570
+ case "run_timed_out":
571
+ return "timed_out";
572
+ case "run_cancelled":
573
+ return "cancelled";
574
+ default:
575
+ return undefined;
576
+ }
577
+ }
578
+ function assertValidRunId(runId) {
579
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(runId)) {
580
+ throw new Error(`Invalid workflow run id: ${JSON.stringify(runId)}`);
581
+ }
582
+ }
583
+ function isMissingPath(error) {
584
+ return error instanceof Error && "code" in error && error.code === "ENOENT";
585
+ }
586
+ async function appendLine(filePath, value) {
587
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
588
+ await fs.appendFile(filePath, value === null ? "" : `${JSON.stringify(value)}\n`, {
589
+ encoding: "utf8",
590
+ mode: 0o600,
591
+ });
592
+ }
593
+ async function appendLines(filePath, values) {
594
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
595
+ const text = values.map((value) => `${JSON.stringify(value)}\n`).join("");
596
+ await fs.appendFile(filePath, text, { encoding: "utf8", mode: 0o600 });
597
+ }
598
+ function isNonEmptyString(value) {
599
+ return typeof value === "string" && value.length > 0;
600
+ }
601
+ function validateSessionEventRecord(record) {
602
+ if (!Number.isSafeInteger(record.seq) || record.seq < 1) {
603
+ throw new Error("Session event seq must be a positive safe integer");
604
+ }
605
+ if (!isNonEmptyString(record.at) ||
606
+ !isNonEmptyString(record.nodeId) ||
607
+ !isNonEmptyString(record.attemptId) ||
608
+ !isNonEmptyString(record.type) ||
609
+ typeof record.payload !== "object" ||
610
+ record.payload === null ||
611
+ Array.isArray(record.payload)) {
612
+ throw new Error("Session event is missing required envelope fields");
613
+ }
614
+ const knownType = [
615
+ "turn_started",
616
+ "turn_finished",
617
+ "message_started",
618
+ "assistant_event",
619
+ "message_finished",
620
+ "tool_execution_started",
621
+ "tool_execution_updated",
622
+ "tool_execution_finished",
623
+ ].includes(record.type);
624
+ if (!knownType) {
625
+ return;
626
+ }
627
+ if (!isNonEmptyString(record.turnId)) {
628
+ throw new Error(`${record.type} requires turnId`);
629
+ }
630
+ if (!["turn_started", "turn_finished"].includes(record.type) &&
631
+ !isNonEmptyString(record.messageId)) {
632
+ throw new Error(`${record.type} requires messageId`);
633
+ }
634
+ if (record.type.startsWith("tool_execution_") && !isNonEmptyString(record.toolCallId)) {
635
+ throw new Error(`${record.type} requires toolCallId`);
636
+ }
637
+ }
638
+ function sessionRelationshipDiagnostics(entries, events) {
639
+ const entryIds = new Set(entries.flatMap((record) => (isNonEmptyString(record.entry.id) ? [record.entry.id] : [])));
640
+ const turns = new Set();
641
+ const messages = new Set();
642
+ const tools = new Set();
643
+ const diagnostics = [];
644
+ for (const event of events) {
645
+ switch (event.type) {
646
+ case "turn_started":
647
+ if (event.turnId)
648
+ turns.add(event.turnId);
649
+ break;
650
+ case "turn_finished":
651
+ if (!event.turnId || !turns.has(event.turnId)) {
652
+ diagnostics.push(`turn_finished ${event.seq} precedes turn_started`);
653
+ }
654
+ break;
655
+ case "message_started":
656
+ if (!event.turnId || !turns.has(event.turnId)) {
657
+ diagnostics.push(`message_started ${event.seq} precedes turn_started`);
658
+ }
659
+ if (event.messageId)
660
+ messages.add(event.messageId);
661
+ break;
662
+ case "assistant_event":
663
+ if (!event.messageId || !messages.has(event.messageId)) {
664
+ diagnostics.push(`assistant_event ${event.seq} precedes message_started`);
665
+ }
666
+ break;
667
+ case "message_finished": {
668
+ if (!event.messageId || !messages.has(event.messageId)) {
669
+ diagnostics.push(`message_finished ${event.seq} precedes message_started`);
670
+ }
671
+ const settled = event.payload.settled;
672
+ const entryId = event.payload.entryId;
673
+ if (settled === true && (!isNonEmptyString(entryId) || !entryIds.has(entryId))) {
674
+ diagnostics.push(`message_finished ${event.seq} references a missing entry`);
675
+ }
676
+ else if (settled !== true && entryId !== undefined) {
677
+ diagnostics.push(`message_finished ${event.seq} has entryId while unsettled`);
678
+ }
679
+ break;
680
+ }
681
+ case "tool_execution_started":
682
+ if (!event.messageId || !messages.has(event.messageId)) {
683
+ diagnostics.push(`tool_execution_started ${event.seq} precedes message_started`);
684
+ }
685
+ if (event.toolCallId)
686
+ tools.add(event.toolCallId);
687
+ break;
688
+ case "tool_execution_updated":
689
+ case "tool_execution_finished":
690
+ if (!event.toolCallId || !tools.has(event.toolCallId)) {
691
+ diagnostics.push(`${event.type} ${event.seq} precedes tool_execution_started`);
692
+ }
693
+ break;
694
+ default:
695
+ break;
696
+ }
697
+ }
698
+ return diagnostics;
699
+ }
700
+ function validateSessionCapture(capture) {
701
+ if (capture.schema !== SESSION_CAPTURE_SCHEMA ||
702
+ capture.eventSchema !== SESSION_EVENT_SCHEMA ||
703
+ !["recording", "complete", "failed"].includes(capture.status) ||
704
+ !Number.isSafeInteger(capture.eventCount) ||
705
+ capture.eventCount < 0 ||
706
+ !Number.isSafeInteger(capture.entryCount) ||
707
+ capture.entryCount < 0 ||
708
+ !Number.isSafeInteger(capture.lastEventSeq) ||
709
+ capture.lastEventSeq < 0) {
710
+ throw new Error("Invalid session capture projection");
711
+ }
712
+ if (capture.status === "failed" && capture.failure === undefined) {
713
+ throw new Error("Failed session capture requires failure details");
714
+ }
715
+ if (capture.status !== "failed" && capture.failure !== undefined) {
716
+ throw new Error("Only failed session capture may contain failure details");
717
+ }
718
+ }
719
+ async function readCompleteNdjson(filePath) {
720
+ let raw;
721
+ try {
722
+ raw = await fs.readFile(filePath, "utf8");
723
+ }
724
+ catch {
725
+ return [];
726
+ }
727
+ const lines = raw.split("\n");
728
+ if (!raw.endsWith("\n")) {
729
+ lines.pop();
730
+ }
731
+ const records = [];
732
+ for (const line of lines) {
733
+ if (line.trim().length === 0) {
734
+ continue;
735
+ }
736
+ try {
737
+ const value = JSON.parse(line);
738
+ if (!Number.isSafeInteger(value.seq) || value.seq < 1) {
739
+ break;
740
+ }
741
+ records.push({ seq: value.seq });
742
+ }
743
+ catch {
744
+ break;
745
+ }
746
+ }
747
+ return records;
748
+ }
749
+ /**
750
+ * Encode the externalizable value positions of the state document. The
751
+ * in-memory state always holds raw values; the persisted copy may carry
752
+ * `$artifact` references instead of large strings.
753
+ */
754
+ async function encodeRunState(state, artifacts) {
755
+ const results = Object.fromEntries(await Promise.all(Object.entries(state.results).map(async ([nodeId, result]) => [
756
+ nodeId,
757
+ "output" in result
758
+ ? { ...result, output: await encodeValue(result.output, artifacts) }
759
+ : result,
760
+ ])));
761
+ return {
762
+ ...state,
763
+ input: await encodeValue(state.input, artifacts),
764
+ outputs: Object.fromEntries(await Promise.all(Object.entries(state.outputs).map(async ([nodeId, output]) => [
765
+ nodeId,
766
+ await encodeValue(output, artifacts),
767
+ ]))),
768
+ results,
769
+ steps: await Promise.all(state.steps.map(async (step) => ({
770
+ ...step,
771
+ prompt: (await encodeValue(step.prompt, artifacts)),
772
+ output: await encodeValue(step.output, artifacts),
773
+ }))),
774
+ ...(state.finalOutput !== undefined
775
+ ? { finalOutput: await encodeValue(state.finalOutput, artifacts) }
776
+ : {}),
777
+ };
778
+ }
779
+ /** Read the final trace record without loading the rest of a run bundle. */
780
+ export async function readLastTraceEvent(runDir, tracePath) {
781
+ const events = await readNdjsonFile(resolveBundlePath(runDir, tracePath, TRACE_PATH));
782
+ return events.records.at(-1) ?? null;
92
783
  }
93
784
  /** Read a run bundle from disk. Returns null when the bundle is unreadable. */
94
785
  export async function readRunBundle(runDir) {
95
786
  const manifest = await readJsonFile(path.join(runDir, MANIFEST_PATH));
96
- const state = await readJsonFile(path.join(runDir, STATE_PATH));
97
- if (!manifest || !state || manifest.schema !== RUN_BUNDLE_SCHEMA) {
787
+ if (!manifest || manifest.schema !== RUN_BUNDLE_SCHEMA) {
788
+ return null;
789
+ }
790
+ // A schema-tagged manifest may still be malformed (e.g. hand-edited);
791
+ // treat anything unexpected as an unreadable bundle rather than throwing.
792
+ const paths = typeof manifest.paths === "object" && manifest.paths !== null ? manifest.paths : {};
793
+ const state = await readJsonFile(resolveBundlePath(runDir, paths.state, STATE_PATH));
794
+ if (!state || state.schema !== RUN_STATE_SCHEMA) {
98
795
  return null;
99
796
  }
100
- const snapshot = await readJsonFile(path.join(runDir, WORKFLOW_SNAPSHOT_PATH));
101
- return { runDir, manifest, state, snapshot };
797
+ const snapshot = await readJsonFile(resolveBundlePath(runDir, paths.workflow, WORKFLOW_SNAPSHOT_PATH));
798
+ const sessionDir = resolveBundlePath(runDir, paths.session, SESSION_DIR);
799
+ const sessionBinding = await readJsonFile(path.join(sessionDir, "binding.json"));
800
+ const entries = await readNdjsonFile(path.join(sessionDir, "entries.ndjson"));
801
+ const events = await readNdjsonFile(path.join(sessionDir, "events.ndjson"));
802
+ const sessionCapture = await readJsonFile(path.join(sessionDir, "capture.json"));
803
+ const flatIntegrity = assessSessionIntegrity({
804
+ binding: sessionBinding,
805
+ entries,
806
+ events,
807
+ capture: sessionCapture,
808
+ runTerminal: state.status !== "running",
809
+ });
810
+ const sessionSegments = [];
811
+ let segmentIds = [];
812
+ try {
813
+ segmentIds = (await fs.readdir(path.join(sessionDir, "segments"), { withFileTypes: true }))
814
+ .filter((entry) => entry.isDirectory())
815
+ .map((entry) => entry.name)
816
+ .sort();
817
+ }
818
+ catch {
819
+ // No segments directory means only the flat stream can exist.
820
+ }
821
+ for (const attemptId of segmentIds) {
822
+ const segmentDir = path.join(sessionDir, "segments", attemptId);
823
+ const binding = await readJsonFile(path.join(segmentDir, "binding.json"));
824
+ const segmentEntries = await readNdjsonFile(path.join(segmentDir, "entries.ndjson"));
825
+ const segmentEvents = await readNdjsonFile(path.join(segmentDir, "events.ndjson"));
826
+ const capture = await readJsonFile(path.join(segmentDir, "capture.json"));
827
+ sessionSegments.push({
828
+ attemptId,
829
+ binding,
830
+ entries: segmentEntries.records,
831
+ events: segmentEvents.records,
832
+ capture,
833
+ integrity: assessSessionIntegrity({
834
+ binding,
835
+ entries: segmentEntries,
836
+ events: segmentEvents,
837
+ capture,
838
+ runTerminal: state.status !== "running",
839
+ }),
840
+ });
841
+ }
842
+ // The headline integrity is the flat stream's when present; otherwise the
843
+ // chronologically latest capture segment speaks for the run (segment ids
844
+ // are random, so directory order says nothing about time).
845
+ sessionSegments.sort((a, b) => (a.binding?.boundAt ?? "").localeCompare(b.binding?.boundAt ?? ""));
846
+ const sessionIntegrity = flatIntegrity.status !== "unavailable" || sessionSegments.length === 0
847
+ ? flatIntegrity
848
+ : (sessionSegments.at(-1)?.integrity ?? flatIntegrity);
849
+ return {
850
+ runDir,
851
+ manifest,
852
+ state,
853
+ snapshot,
854
+ sessionBinding,
855
+ sessionEntries: entries.records,
856
+ sessionEvents: events.records,
857
+ sessionCapture,
858
+ sessionIntegrity,
859
+ sessionSegments,
860
+ };
861
+ }
862
+ /**
863
+ * Resolve a manifest-relative path, rejecting anything that is not a string
864
+ * or escapes the bundle directory. Malformed manifests must degrade to an
865
+ * unreadable bundle, never to a thrown error that aborts a listing.
866
+ */
867
+ function resolveBundlePath(runDir, relative, fallback) {
868
+ const candidate = path.resolve(runDir, typeof relative === "string" && relative ? relative : fallback);
869
+ if (candidate !== path.resolve(runDir) &&
870
+ !candidate.startsWith(path.resolve(runDir) + path.sep)) {
871
+ return path.join(runDir, fallback);
872
+ }
873
+ return candidate;
102
874
  }
103
875
  /** List run bundles under `outputRoot`, most recently started first. */
104
876
  export async function listRunBundles(outputRoot) {
@@ -128,7 +900,102 @@ async function readJsonFile(filePath) {
128
900
  return null;
129
901
  }
130
902
  }
131
- function createManifest(state) {
903
+ async function readNdjsonFile(filePath) {
904
+ let raw;
905
+ try {
906
+ raw = await fs.readFile(filePath, "utf8");
907
+ }
908
+ catch {
909
+ return { records: [], exists: false, tornTail: false, malformed: false };
910
+ }
911
+ const tornTail = raw.length > 0 && !raw.endsWith("\n");
912
+ const lines = raw.split("\n");
913
+ if (tornTail) {
914
+ lines.pop();
915
+ }
916
+ const records = [];
917
+ let malformed = false;
918
+ for (const line of lines) {
919
+ if (line.trim().length === 0) {
920
+ continue;
921
+ }
922
+ try {
923
+ records.push(JSON.parse(line));
924
+ }
925
+ catch {
926
+ malformed = true;
927
+ }
928
+ }
929
+ return { records, exists: true, tornTail, malformed };
930
+ }
931
+ function assessSessionIntegrity(input) {
932
+ const anySessionFile = input.binding !== null || input.entries.exists || input.events.exists || input.capture !== null;
933
+ if (!anySessionFile) {
934
+ return { status: "unavailable", diagnostics: [] };
935
+ }
936
+ const diagnostics = [];
937
+ if (!input.binding || input.binding.schema !== SESSION_BINDING_SCHEMA) {
938
+ diagnostics.push("missing or invalid session binding");
939
+ }
940
+ if (!input.capture) {
941
+ diagnostics.push("missing session capture status");
942
+ return { status: "invalid", diagnostics };
943
+ }
944
+ try {
945
+ validateSessionCapture(input.capture);
946
+ }
947
+ catch (error) {
948
+ diagnostics.push(failureMessageForDiagnostic(error));
949
+ return { status: "invalid", diagnostics };
950
+ }
951
+ if (input.entries.malformed || input.events.malformed) {
952
+ diagnostics.push("malformed NDJSON line before the journal tail");
953
+ }
954
+ if (input.events.tornTail && input.capture.status !== "recording") {
955
+ diagnostics.push("terminal session event journal has a torn tail");
956
+ }
957
+ if (input.runTerminal && input.capture.status === "recording") {
958
+ diagnostics.push("terminal run still reports recording capture");
959
+ }
960
+ let expected = 1;
961
+ for (const event of input.events.records) {
962
+ try {
963
+ validateSessionEventRecord(event);
964
+ }
965
+ catch (error) {
966
+ diagnostics.push(failureMessageForDiagnostic(error));
967
+ break;
968
+ }
969
+ if (event.seq !== expected) {
970
+ diagnostics.push(`session event sequence gap at ${expected}`);
971
+ break;
972
+ }
973
+ expected += 1;
974
+ }
975
+ diagnostics.push(...sessionRelationshipDiagnostics(input.entries.records, input.events.records));
976
+ if (input.capture.status !== "recording") {
977
+ const lastEventSeq = input.events.records.at(-1)?.seq ?? 0;
978
+ if (input.capture.eventCount !== input.events.records.length ||
979
+ input.capture.entryCount !== input.entries.records.length ||
980
+ input.capture.lastEventSeq !== lastEventSeq) {
981
+ diagnostics.push("session capture counts do not match durable files");
982
+ }
983
+ }
984
+ if (diagnostics.length > 0) {
985
+ return { status: "invalid", diagnostics };
986
+ }
987
+ if (input.capture.status === "failed") {
988
+ return {
989
+ status: "failed",
990
+ diagnostics: [input.capture.failure?.message ?? "session capture failed"],
991
+ };
992
+ }
993
+ return { status: input.capture.status, diagnostics: [] };
994
+ }
995
+ function failureMessageForDiagnostic(error) {
996
+ return error instanceof Error ? error.message : String(error);
997
+ }
998
+ function createManifest(state, present) {
132
999
  return {
133
1000
  schema: RUN_BUNDLE_SCHEMA,
134
1001
  runId: state.runId,
@@ -143,6 +1010,11 @@ function createManifest(state) {
143
1010
  workflow: WORKFLOW_SNAPSHOT_PATH,
144
1011
  state: STATE_PATH,
145
1012
  trace: TRACE_PATH,
1013
+ ...(present.session ? { session: SESSION_DIR } : {}),
1014
+ // Declare this before any payload can externalize a string. Live
1015
+ // session-event patches may reference a newly written artifact before
1016
+ // the next workflow state projection refreshes the manifest.
1017
+ artifacts: "artifacts",
146
1018
  },
147
1019
  };
148
1020
  }
@@ -174,8 +1046,11 @@ function snapshotNode(node) {
174
1046
  }
175
1047
  async function writeJsonAtomic(filePath, value) {
176
1048
  const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
177
- await fs.mkdir(path.dirname(filePath), { recursive: true });
178
- await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
1049
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
1050
+ await fs.writeFile(tempPath, `${JSON.stringify(value, null, 2)}\n`, {
1051
+ encoding: "utf8",
1052
+ mode: 0o600,
1053
+ });
179
1054
  await fs.rename(tempPath, filePath);
180
1055
  }
181
1056
  //# sourceMappingURL=store.js.map