@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.134

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 (204) hide show
  1. package/CHANGELOG.md +687 -0
  2. package/README.md +101 -1
  3. package/dist/build-info.json +10 -10
  4. package/dist/cli/argument-values.js +38 -0
  5. package/dist/cli/command-inputs.js +306 -0
  6. package/dist/cli/help.js +88 -12
  7. package/dist/cli/hook-ingress.js +78 -0
  8. package/dist/cli/input-preparation.js +116 -0
  9. package/dist/cli/native-hook-ingress.js +80 -0
  10. package/dist/cli/run-cli.js +1465 -450
  11. package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
  12. package/dist/cli/runtime-maintenance-ingress.js +52 -0
  13. package/dist/cli/runtime-process.js +153 -0
  14. package/dist/cli.js +17 -2
  15. package/dist/domain/stage-catalog.js +1 -1
  16. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  17. package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
  18. package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
  19. package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
  20. package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
  21. package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
  22. package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
  23. package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
  24. package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
  25. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  26. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  27. package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
  28. package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
  29. package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
  30. package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
  31. package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
  32. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  33. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
  34. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  35. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  36. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
  37. package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
  38. package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
  39. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
  40. package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
  41. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
  42. package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
  43. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
  44. package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
  45. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
  46. package/dist/harness-runtime/lib/dd-zcode.mjs +1128 -0
  47. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  48. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  49. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  50. package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
  51. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  52. package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
  53. package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
  54. package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
  55. package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
  56. package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
  57. package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
  58. package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
  59. package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
  60. package/dist/harness-runtime/lib/model-observations.mjs +101 -0
  61. package/dist/harness-runtime/lib/native-children.d.mts +14 -0
  62. package/dist/harness-runtime/lib/native-children.mjs +94 -0
  63. package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
  64. package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
  65. package/dist/harness-runtime/lib/native-streams.mjs +45 -0
  66. package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
  67. package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
  68. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  69. package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
  70. package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
  71. package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
  72. package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
  73. package/dist/harness-runtime/lib/process-json.d.mts +5 -0
  74. package/dist/harness-runtime/lib/process-json.mjs +201 -0
  75. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  76. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  77. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  78. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  79. package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
  80. package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
  81. package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
  82. package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
  83. package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
  84. package/dist/protocol/local-files.js +18 -9
  85. package/dist/runtime/context.js +8 -4
  86. package/dist/schemas/agent-profile.schema.json +1 -1
  87. package/dist/schemas/code-review-result.schema.json +1 -1
  88. package/dist/schemas/code-verification.schema.json +7 -5
  89. package/dist/schemas/code-work-batch.schema.json +2 -2
  90. package/dist/schemas/flow-run.schema.json +2 -0
  91. package/dist/schemas/plan-review-decision.schema.json +3 -3
  92. package/dist/schemas/plan-review-result.schema.json +2 -2
  93. package/dist/schemas/run-control-receipt.schema.json +118 -0
  94. package/dist/schemas/run-control-request.schema.json +36 -0
  95. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  96. package/dist/services/branch-context.js +3 -3
  97. package/dist/services/canon.js +11 -8
  98. package/dist/services/check-runner-evidence.js +121 -0
  99. package/dist/services/cleanup.js +133 -40
  100. package/dist/services/cli-operation-classifier.js +22 -24
  101. package/dist/services/code-checks.js +851 -109
  102. package/dist/services/codex-capacity.js +367 -0
  103. package/dist/services/codex-hook-delivery.js +32 -0
  104. package/dist/services/command-context.js +80 -0
  105. package/dist/services/compatibility-preflight.js +13 -3
  106. package/dist/services/config.js +11 -8
  107. package/dist/services/continuation-outcome.js +20 -0
  108. package/dist/services/controller-fanout.js +136 -0
  109. package/dist/services/dashboard.js +135 -56
  110. package/dist/services/engines.js +245 -119
  111. package/dist/services/eval-snapshots.js +1146 -105
  112. package/dist/services/execution-policy.js +181 -0
  113. package/dist/services/external-work-launch.js +230 -0
  114. package/dist/services/harness-adapter.js +329 -36
  115. package/dist/services/harness-config.js +2 -0
  116. package/dist/services/hooks.js +753 -325
  117. package/dist/services/lanes.js +78 -65
  118. package/dist/services/lifecycle-command.js +1 -288
  119. package/dist/services/lifecycle-contract.js +1 -0
  120. package/dist/services/lifecycle-invocations.js +1828 -0
  121. package/dist/services/managed-daemon-binding.js +38 -0
  122. package/dist/services/managed-lease-monitor.js +133 -0
  123. package/dist/services/managed-processes.js +409 -51
  124. package/dist/services/merge-queue.js +228 -149
  125. package/dist/services/merge-server.js +163 -35
  126. package/dist/services/migrations.js +37 -16
  127. package/dist/services/native-daemon-history.js +49 -0
  128. package/dist/services/native-session-control.js +39 -0
  129. package/dist/services/plan-runtime.js +26 -11
  130. package/dist/services/plans.js +28 -25
  131. package/dist/services/projects.js +20 -15
  132. package/dist/services/prompts.js +28 -17
  133. package/dist/services/protocols.js +163 -87
  134. package/dist/services/recovery-observation-budget.js +121 -0
  135. package/dist/services/recovery-snapshot-database.js +145 -0
  136. package/dist/services/repair-intents.js +42 -0
  137. package/dist/services/review-copy.js +157 -0
  138. package/dist/services/review-deferral.js +23 -0
  139. package/dist/services/run-control-receipt.js +56 -0
  140. package/dist/services/run-control-worker.js +411 -0
  141. package/dist/services/run-control.js +985 -0
  142. package/dist/services/run-controller-adapter.js +399 -0
  143. package/dist/services/run-controller-capture.js +179 -0
  144. package/dist/services/run-controller-process.js +187 -0
  145. package/dist/services/run-controller-recovery.js +289 -0
  146. package/dist/services/run-controller-state.js +97 -0
  147. package/dist/services/run-controller.js +1035 -0
  148. package/dist/services/run-engine-bindings.js +1 -1
  149. package/dist/services/run-fork.js +147 -0
  150. package/dist/services/run-observations.js +152 -0
  151. package/dist/services/run-projection.js +22 -64
  152. package/dist/services/run-recovery-guard.js +75 -0
  153. package/dist/services/run-recovery-runtime.js +112 -0
  154. package/dist/services/run-recovery.js +349 -0
  155. package/dist/services/runs.js +558 -217
  156. package/dist/services/runtime-budget.js +430 -0
  157. package/dist/services/runtime-command.js +43 -0
  158. package/dist/services/runtime-scope-capture.js +52 -0
  159. package/dist/services/runtime-scope-control.js +468 -0
  160. package/dist/services/runtime-scope-resume.js +599 -0
  161. package/dist/services/runtime-scope-stop.js +180 -0
  162. package/dist/services/runtime-scope-worker.js +287 -0
  163. package/dist/services/runtime-service.js +96 -0
  164. package/dist/services/schema-validation.js +10 -8
  165. package/dist/services/scope-writer-cleanup.js +27 -0
  166. package/dist/services/sessions.js +35 -69
  167. package/dist/services/stage-blocker.js +17 -7
  168. package/dist/services/stage-context.js +185 -19
  169. package/dist/services/stage-lifecycle.js +98 -107
  170. package/dist/services/stage-pause.js +89 -75
  171. package/dist/services/stage-report-renderer.js +158 -6
  172. package/dist/services/stage-work-graph.js +35 -0
  173. package/dist/services/tooling.js +32 -23
  174. package/dist/services/usage.js +49 -101
  175. package/dist/services/verification-matrix.js +374 -0
  176. package/dist/services/vnext-code-review.js +222 -87
  177. package/dist/services/vnext-code.js +324 -251
  178. package/dist/services/vnext-contracts.js +10 -1
  179. package/dist/services/vnext-execution-profile.js +79 -4
  180. package/dist/services/vnext-fanout.js +182 -17
  181. package/dist/services/vnext-merge.js +335 -113
  182. package/dist/services/vnext-plan-review.js +276 -126
  183. package/dist/services/vnext-plan.js +227 -102
  184. package/dist/services/vnext-protocolize.js +335 -82
  185. package/dist/services/vnext-specify.js +119 -81
  186. package/dist/services/work-registry.js +1083 -194
  187. package/dist/services/workspace-bootstrap.js +87 -0
  188. package/dist/services/workspace-files.js +85 -0
  189. package/dist/services/worktrees.js +98 -44
  190. package/dist/shared/entity-references.js +8 -0
  191. package/dist/shared/errors.js +17 -0
  192. package/dist/storage/agent-output.js +26 -0
  193. package/dist/storage/database.js +785 -37
  194. package/dist/storage/foreign-key-transaction.js +39 -0
  195. package/dist/storage/immutable-input.js +45 -0
  196. package/dist/storage/import-guard.js +102 -0
  197. package/dist/storage/native-cleanup.js +52 -0
  198. package/dist/storage/paths.js +17 -4
  199. package/dist/storage/projection-lock.js +73 -0
  200. package/dist/storage/work-references.js +23 -0
  201. package/dist/storage/writer-contract.js +77 -0
  202. package/dist/storage/writer-migration.js +85 -0
  203. package/package.json +30 -13
  204. package/tools/repair-paused-run-status.mjs +84 -0
@@ -0,0 +1,200 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { withRunnerLock as withLock } from "./runner-lock.mjs";
5
+ import { isObservationLoss, errorRecord } from "./operation-errors.mjs";
6
+ import { operationContext } from "./operation-context.mjs";
7
+
8
+ const appendQueues = new Map();
9
+
10
+ export function canonicalJson(value) {
11
+ const normalize = (item) => {
12
+ if (Array.isArray(item)) return item.map(normalize);
13
+ if (item && typeof item === "object") return Object.fromEntries(Object.keys(item).sort().map((key) => [key, normalize(item[key])]));
14
+ return item;
15
+ };
16
+ return `${JSON.stringify(normalize(value))}\n`;
17
+ }
18
+
19
+ export function sha256(value) {
20
+ return createHash("sha256").update(value).digest("hex");
21
+ }
22
+
23
+ export function hashJson(value) { return sha256(canonicalJson(value)); }
24
+
25
+ export async function writeJsonAtomic(file, value) {
26
+ await mkdir(path.dirname(file), { recursive: true });
27
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
28
+ try {
29
+ const payload = await open(temporary, "wx", 0o600);
30
+ try { await payload.writeFile(`${JSON.stringify(value, null, 2)}\n`); await payload.sync(); }
31
+ finally { await payload.close(); }
32
+ await rename(temporary, file);
33
+ const directory = await open(path.dirname(file), "r");
34
+ try { await directory.sync(); }
35
+ finally { await directory.close(); }
36
+ } finally { await unlink(temporary).catch(error => { if (error.code !== "ENOENT") throw error; }); }
37
+ }
38
+
39
+ export async function readJsonLines(file, label = "JSONL") {
40
+ try {
41
+ const source = await readFile(file, "utf8");
42
+ return source.split("\n").filter(Boolean).map((line, index) => {
43
+ try { return JSON.parse(line); }
44
+ catch { throw new Error(`invalid ${label} record at ${file}:${index + 1}`); }
45
+ });
46
+ } catch (error) {
47
+ if (error?.code === "ENOENT") return [];
48
+ throw error;
49
+ }
50
+ }
51
+
52
+ export async function readEvents(file) {
53
+ const records = await readJsonLines(file, "runner event");
54
+ return records.map((record, index) => {
55
+ try { return validateRunnerEvent(record); }
56
+ catch { throw new Error(`invalid runner event at ${file}:${index + 1}`); }
57
+ });
58
+ }
59
+
60
+ export function validateRunnerEvent(value) {
61
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.specversion !== "1.0" || typeof value.id !== "string" || typeof value.source !== "string" || typeof value.type !== "string" || typeof value.time !== "string" || !value.data || typeof value.data !== "object" || !Number.isInteger(value.data.sequence) || value.data.sequence < 1) {
62
+ throw new Error("invalid normalized runner event");
63
+ }
64
+ return value;
65
+ }
66
+
67
+ export async function appendEvent(file, input) {
68
+ const prior = appendQueues.get(file) ?? Promise.resolve();
69
+ const current = prior.then(() => withLock(file, async () => {
70
+ const events = await readEvents(file);
71
+ // Internal callers can validate a dispatch or bind its generation under
72
+ // the same cross-process lock that orders cancellation and completion.
73
+ if (input.deduplicate && input.id) { const existing = events.find(event => event.id === input.id); if (existing) return existing; }
74
+ if (input.beforeAppend?.(events) === false) return null;
75
+ const sequence = events.length + 1;
76
+ const event = {
77
+ specversion: "1.0",
78
+ id: input.id ?? `EVT-${randomUUID()}`,
79
+ source: input.source,
80
+ type: input.type,
81
+ time: input.time ?? new Date().toISOString(),
82
+ subject: input.subject ?? "runner",
83
+ datacontenttype: "application/json",
84
+ runid: input.runId,
85
+ executionid: input.executionId,
86
+ traceid: input.traceId,
87
+ spanid: input.spanId ?? randomUUID(),
88
+ ...(input.parentSpanId ? { parentspanid: input.parentSpanId } : {}),
89
+ data: { sequence, ...input.data }
90
+ };
91
+ const context = operationContext.getStore();
92
+ if (context?.eventsFile === file && context.executionId === input.executionId && context.operationId && input.executionId) {
93
+ event.data.execution_operation_id ??= context.operationId;
94
+ }
95
+ validateRunnerEvent(event);
96
+ await mkdir(path.dirname(file), { recursive: true });
97
+ const handle = await open(file, "a");
98
+ try { await handle.write(`${JSON.stringify(event)}\n`); await handle.sync(); }
99
+ finally { await handle.close(); }
100
+ return event;
101
+ }));
102
+ const tail = current.catch(() => {}); appendQueues.set(file, tail);
103
+ try { return await current; }
104
+ finally { if (appendQueues.get(file) === tail) appendQueues.delete(file); }
105
+ }
106
+
107
+ export function reduceEvents(events) {
108
+ const operations = new Map();
109
+ let state = "planned";
110
+ for (const event of events) {
111
+ const data = event?.data ?? {};
112
+ if (["dev.dd.eval.planned", "dev.dd.eval.completed"].includes(event.type) && typeof data.state === "string") state = data.state;
113
+ if (typeof data.operation_id !== "string") continue;
114
+ const prior = operations.get(data.operation_id) ?? { id: data.operation_id, requested: false, started: false, terminal: null };
115
+ if (event.type.endsWith(".requested")) prior.requested = true;
116
+ if (event.type.endsWith(".started")) prior.started = true;
117
+ if (event.type.endsWith(".observation_lost")) prior.observation_lost = data.error ?? { code: "observation_lost" };
118
+ if (event.type.endsWith(".completed") || event.type.endsWith(".failed") || event.type.endsWith(".cancelled")) {
119
+ const terminal = event.type.split(".").at(-1);
120
+ const result = terminal === "completed" ? data.result : { error: data.error ?? null };
121
+ const resultHash = hashJson({ terminal, result });
122
+ if (prior.terminal && (prior.terminal !== terminal || prior.result_hash !== resultHash)) {
123
+ throw Object.assign(new Error(`runner operation ${data.operation_id} has conflicting terminal events`), { code: "journal_conflict", operation_id: data.operation_id });
124
+ }
125
+ prior.terminal = terminal;
126
+ prior.result = result;
127
+ prior.result_hash = resultHash;
128
+ }
129
+ operations.set(data.operation_id, prior);
130
+ }
131
+ return { state, operations: Object.fromEntries([...operations].map(([id, value]) => [id, value])) };
132
+ }
133
+
134
+ export async function recordOperation({ eventsFile, source, runId, executionId, traceId, operationId, operation, subject = "runner", action }) {
135
+ const existing = await withLock(`${eventsFile}.${operationId.replace(/[^a-zA-Z0-9._-]/g, "_")}`, async () => {
136
+ const current = reduceEvents(await readEvents(eventsFile)).operations[operationId];
137
+ if (current?.terminal === "completed") return current;
138
+ if (current?.terminal) throw Object.assign(new Error(`operation ${operationId} is already ${current.terminal}; use explicit recovery instead of replaying it`), { code: "operation_terminal", operation_id: operationId, terminal: current.terminal });
139
+ if (current?.started && !current.terminal) {
140
+ const error = new Error(current.observation_lost
141
+ ? `operation ${operationId} has no confirmed outcome; reconcile its provider state before retrying`
142
+ : `operation ${operationId} is already in progress; reconcile before retrying`);
143
+ error.code = current.observation_lost ? "operation_observation_lost" : "operation_in_progress";
144
+ error.operation_id = operationId;
145
+ throw error;
146
+ }
147
+ await appendEvent(eventsFile, { source, runId, executionId, traceId, subject, type: "dev.dd.eval.operation.requested", data: { operation_id: operationId, operation, status: "requested" } });
148
+ await appendEvent(eventsFile, { source, runId, executionId, traceId, subject, type: "dev.dd.eval.operation.started", data: { operation_id: operationId, operation, status: "started" } });
149
+ return null;
150
+ });
151
+ if (existing) return { reused: true, operation_id: operationId, result: existing.result };
152
+ try {
153
+ const result = await operationContext.run({ operationId, eventsFile, runId, executionId }, action);
154
+ await completeOperation({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, result });
155
+ return { reused: false, operation_id: operationId, result };
156
+ } catch (error) {
157
+ if (isObservationLoss(error)) await observationLost({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, error });
158
+ else await failOperation({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, error });
159
+ throw error;
160
+ }
161
+ }
162
+
163
+ export async function completeOperation({ eventsFile, source, runId, executionId, traceId, subject = "runner", operationId, operation, result }) {
164
+ return await settleOperation({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, terminal: "completed", result });
165
+ }
166
+
167
+ export async function failOperation({ eventsFile, source, runId, executionId, traceId, subject = "runner", operationId, operation, error }) {
168
+ return await settleOperation({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, terminal: "failed", result: { error: errorRecord(error) } });
169
+ }
170
+
171
+ /** A lost observer response is deliberately non-terminal: replay could duplicate a provider Turn. */
172
+ export async function observationLost({ eventsFile, source, runId, executionId, traceId, subject = "runner", operationId, operation, error }) {
173
+ return await withLock(`${eventsFile}.${operationId.replace(/[^a-zA-Z0-9._-]/g, "_")}`, async () => {
174
+ const existing = reduceEvents(await readEvents(eventsFile)).operations[operationId];
175
+ if (existing?.terminal) return { reused: true, operation_id: operationId, result: existing.result };
176
+ if (!existing?.started) throw Object.assign(new Error(`operation ${operationId} has no started receipt`), { code: "operation_not_started" });
177
+ if (existing.observation_lost) return { reused: true, operation_id: operationId, observation_lost: existing.observation_lost };
178
+ const recorded = errorRecord(error);
179
+ await appendEvent(eventsFile, { source, runId, executionId, traceId, subject, type: "dev.dd.eval.operation.observation_lost", data: { operation_id: operationId, operation, status: "observation_lost", error: recorded } });
180
+ return { reused: false, operation_id: operationId, observation_lost: recorded };
181
+ });
182
+ }
183
+
184
+ async function settleOperation({ eventsFile, source, runId, executionId, traceId, subject, operationId, operation, terminal, result }) {
185
+ return await withLock(`${eventsFile}.${operationId.replace(/[^a-zA-Z0-9._-]/g, "_")}`, async () => {
186
+ const existing = reduceEvents(await readEvents(eventsFile)).operations[operationId];
187
+ const expectedHash = hashJson({ terminal, result });
188
+ if (existing?.terminal) {
189
+ if (existing.terminal === terminal && existing.result_hash === expectedHash) return { reused: true, operation_id: operationId, result: existing.result };
190
+ throw Object.assign(new Error(`runner operation ${operationId} has conflicting terminal result`), { code: "journal_conflict", operation_id: operationId });
191
+ }
192
+ if (!existing?.started) throw Object.assign(new Error(`operation ${operationId} has no started receipt`), { code: "operation_not_started" });
193
+ const type = terminal === "completed" ? "dev.dd.eval.operation.completed" : "dev.dd.eval.operation.failed";
194
+ const data = terminal === "completed"
195
+ ? { operation_id: operationId, operation, status: terminal, result }
196
+ : { operation_id: operationId, operation, status: terminal, error: result.error };
197
+ await appendEvent(eventsFile, { source, runId, executionId, traceId, subject, type, data });
198
+ return { reused: false, operation_id: operationId, result };
199
+ });
200
+ }
@@ -0,0 +1,42 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync, readdirSync, readFileSync, writeFileSync, unlinkSync, rmdirSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ function release(lock, owner) {
6
+ try { unlinkSync(path.join(lock, owner)); } catch (error) { if (error.code === "ENOENT") return; throw error; }
7
+ // Never recursively remove a directory: another owner may already have acquired it.
8
+ try { rmdirSync(lock); } catch (error) { if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code)) throw error; }
9
+ }
10
+
11
+ function reclaimDeadOwner(lock) {
12
+ let entries;
13
+ try { entries = readdirSync(lock); } catch (error) { if (error.code === "ENOENT") return; throw error; }
14
+ if (entries.length !== 1 || !/^owner-.*\.json$/.test(entries[0])) return;
15
+ let owner;
16
+ try { owner = JSON.parse(readFileSync(path.join(lock, entries[0]), "utf8")); } catch { return; }
17
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0) return;
18
+ try { process.kill(owner.pid, 0); }
19
+ catch (error) { if (error.code === "ESRCH") release(lock, entries[0]); }
20
+ // A live/reused PID or unknown owner is conservative: age never proves death.
21
+ }
22
+
23
+ export async function withRunnerLock(file, action, { timeoutMs = 30_000 } = {}) {
24
+ const lock = `${file}.lock`;
25
+ const owner = `owner-${process.pid}-${randomUUID()}.json`;
26
+ const deadline = performance.now() + timeoutMs;
27
+ for (;;) {
28
+ let acquired = false;
29
+ try { mkdirSync(lock); acquired = true; }
30
+ catch (error) { if (error.code !== "EEXIST") throw error; }
31
+ if (acquired) {
32
+ // No await between acquisition and identifying the owner.
33
+ try { writeFileSync(path.join(lock, owner), JSON.stringify({ pid: process.pid }), { flag: "wx" }); }
34
+ catch (error) { release(lock, owner); throw error; }
35
+ try { return await action(); }
36
+ finally { release(lock, owner); }
37
+ }
38
+ reclaimDeadOwner(lock);
39
+ if (performance.now() >= deadline) throw Object.assign(new Error(`runner lock has a live or unconfirmed owner: ${lock}; inspect its owner before recovery`), { code: "runner_lock_timeout" });
40
+ await new Promise((resolve) => setTimeout(resolve, 10));
41
+ }
42
+ }
@@ -0,0 +1,30 @@
1
+ import { errorRecord } from "./operation-errors.mjs";
2
+
3
+ /** Diagnostic failure never prevents cancellation of already owned Sessions.
4
+ * Only a fresh successful observation can establish settlement. */
5
+ export async function waitForSettlement({ observe, cancel, knownSessions = () => [], timeoutMs = 5_000 }) {
6
+ const deadline = performance.now() + timeoutMs;
7
+ const cancelled = new Set(), errors = [];
8
+ if (cancel) for (const id of knownSessions()) {
9
+ cancelled.add(id);
10
+ try { await cancel(id); } catch (error) { errors.push({ phase: "cancel", session_id: id, ...errorRecord(error) }); }
11
+ }
12
+ for (;;) {
13
+ let state;
14
+ try { state = await observe(); }
15
+ catch (error) {
16
+ if (!cancel) throw error;
17
+ errors.push({ phase: "observe", ...errorRecord(error) });
18
+ state = { sessions: knownSessions(), active: true, observation_error: errorRecord(error) };
19
+ }
20
+ if (!state.active && state.sessions.length === 0) return { ...state, cleanup_errors: errors };
21
+ // The observation budget must not skip a newly discovered owned target.
22
+ // Attempt its cancellation once, then leave physical settlement pending.
23
+ for (const id of state.sessions) if (cancel && !cancelled.has(id)) {
24
+ cancelled.add(id);
25
+ try { await cancel(id); } catch (error) { errors.push({ phase: "cancel", session_id: id, ...errorRecord(error) }); }
26
+ }
27
+ if (!cancel || performance.now() >= deadline) throw Object.assign(new Error("daemon still owns an unsettled Session tree"), { code: "tree_not_settled", details: { ...state, cleanup_errors: errors } });
28
+ await new Promise(resolve => setTimeout(resolve, 50));
29
+ }
30
+ }
@@ -0,0 +1,9 @@
1
+ export const SETUP_STARTUP_MS: number;
2
+ export const SETUP_QUIET_MS: number;
3
+ export const setupPhases: Set<string>;
4
+ export function setupReporter(operationId?: string): (phase: string, step?: string | number | null) => void;
5
+ export const publishSetup: ReturnType<typeof setupReporter>;
6
+ export function isSetupPhase(value: unknown): boolean;
7
+ export function startupObserver(stateDir: string, daemonId: string): () => Promise<number>;
8
+ export function setupObserver(operationId: string): (value: unknown) => boolean;
9
+ export function observationDetails(clock: import('./observation-clock.mjs').ObservationClock, phase: string | null, pid: number | undefined): Record<string, unknown>;
@@ -0,0 +1,51 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ export const SETUP_STARTUP_MS = 120_000;
4
+ export const SETUP_QUIET_MS = 30_000;
5
+ export const setupPhases = new Set(['ingress_entered', 'imports_ready', 'probe_started', 'probe_completed', 'dependency_check_completed', 'transfer_progress', 'identity_digest_progress', 'identity_digest_completed', 'native_initialized', 'ready']);
6
+ export function setupReporter(operationId = process.env.DD_EVAL_OPERATION_ID) {
7
+ if (!operationId) return () => {};
8
+ let sequence = 0;
9
+ return (phase, step = null) => {
10
+ if (!setupPhases.has(phase)) throw new Error('Invalid setup phase');
11
+ process.stderr.write(JSON.stringify({ kind: 'setup_phase', operation_id: operationId, phase, step, sequence: ++sequence, observed_at: new Date().toISOString() }) + '\n');
12
+ };
13
+ }
14
+ export const publishSetup = setupReporter();
15
+ export function isSetupPhase(value) {
16
+ return value?.kind === 'setup_phase' && typeof value.operation_id === 'string' && value.operation_id.length > 0 && setupPhases.has(value.phase)
17
+ && Number.isSafeInteger(value.sequence) && value.sequence > 0 && value.sequence <= 1_000_000
18
+ && (value.step === null || typeof value.step === 'string' && value.step.length <= 4096 || Number.isSafeInteger(value.step) && value.step >= 0)
19
+ && typeof value.observed_at === 'string' && Number.isFinite(Date.parse(value.observed_at))
20
+ && !Object.hasOwn(value, 'error') && !Object.hasOwn(value, 'code');
21
+ }
22
+ export function startupObserver(stateDir, daemonId) {
23
+ const seen = new Set(); let sequence = 0, binding;
24
+ return async () => {
25
+ let state;
26
+ try { state = JSON.parse(await readFile(path.join(stateDir, 'daemon.json'), 'utf8')); }
27
+ catch (error) { if (error.code === 'ENOENT') return sequence; throw error; }
28
+ if (state.daemon_id !== daemonId) throw Object.assign(new Error('Startup daemon identity changed'), { code: 'operation_binding_conflict' });
29
+ const owner = state.config?.runtime_owner;
30
+ const identity = JSON.stringify([state.started_at ?? null, owner?.owner_id ?? null, owner?.operation_id ?? null, state.generation ?? null]);
31
+ binding ??= identity;
32
+ if (identity !== binding) throw Object.assign(new Error('Startup ownership binding changed'), { code: 'operation_binding_conflict' });
33
+ const marker = JSON.stringify([state.pid ?? null, state.provider_pid ?? null, state.shutdown_state ?? null, state.startup_phase ?? null]);
34
+ if (!seen.has(marker)) { seen.add(marker); sequence++; publishSetup(state.shutdown_state === 'running' ? 'native_initialized' : 'probe_started', `${daemonId}:${sequence}`); }
35
+ return sequence;
36
+ };
37
+ }
38
+ export function setupObserver(operationId) {
39
+ const startedAt = Date.now(); let sequence = 0; const markers = new Set();
40
+ return value => {
41
+ if (typeof operationId !== 'string' || markers.size >= 4096 || !isSetupPhase(value) || value.operation_id !== operationId
42
+ || value.sequence <= sequence || Date.parse(value.observed_at) < startedAt || Date.parse(value.observed_at) > Date.now()) return false;
43
+ const marker = JSON.stringify([value.phase, value.step]);
44
+ if (markers.has(marker)) return false;
45
+ markers.add(marker); sequence = value.sequence; return true;
46
+ };
47
+ }
48
+ export function observationDetails(clock, phase, pid) {
49
+ return { reason: clock.observationLost ? 'observation_gap' : 'inactivity', phase, pid,
50
+ timeout_ms: clock.timeoutMs, observation_lost: clock.observationLost, observation_clock: clock.state(), ...(clock.setupProgress ? { last_setup: clock.setupProgress } : {}), effect: 'unknown' };
51
+ }
@@ -0,0 +1,21 @@
1
+ export interface ToolEvent {
2
+ session?: { harness_id: string; session_id: string };
3
+ call_id?: string;
4
+ status?: string;
5
+ name?: string;
6
+ reason?: string;
7
+ [key: string]: unknown;
8
+ }
9
+ export function classifyCodexItem(type: unknown): "tool" | "non_tool" | "unknown";
10
+ export class ToolObservations {
11
+ calls: Map<string, ToolEvent>;
12
+ turns: Map<string, { session: { harness_id: string; session_id: string }; turn_id: string; started: boolean; completed: boolean }>;
13
+ gaps: Set<string>;
14
+ sources: Map<string, ToolEvent>;
15
+ add(event: ToolEvent | null): void;
16
+ observeTurn(event: { session: { harness_id: string; session_id: string }; turn_id: string; started?: boolean; completed?: boolean }): void;
17
+ summary(sessionId?: string, cursor?: Set<string>): { total: number; failures: number; pending: number; by_tool: Record<string, number>; completeness: string; outcome_completeness: string; sessions: Array<{ session: { harness_id: string; session_id: string }; total: number; failures: number; pending: number; by_tool: Record<string, number> }>; reasons: string[] };
18
+ cursor(): Set<string>;
19
+ }
20
+ export function codexToolObservation(record: Record<string, unknown>, sessionId: string): ToolEvent | null;
21
+ export function replayToolJournal(file: string, options: { harness: string; rootSessionId: string; adapterSessionId?: string; text?: string; expectedSessionIds?: string[] }, reducer?: ToolObservations): ToolObservations;
@@ -0,0 +1,228 @@
1
+ import fs from "node:fs";
2
+
3
+ /** Canonical physical-session tool accounting. Native decoding lives below;
4
+ * consumers never have to inspect provider envelopes or aggregate tokens. */
5
+ export class ToolObservations {
6
+ constructor() { this.calls = new Map(); this.turns = new Map(); this.gaps = new Set(); this.transcriptSessions = new Set(); this.sources = new Map(); }
7
+ observeTurn(event) {
8
+ if (!event?.session?.harness_id || !event.session.session_id || !event.turn_id) { this.gaps.add("turn_identity_missing"); return; }
9
+ const key = JSON.stringify([event.session, event.turn_id]);
10
+ const old = this.turns.get(key);
11
+ this.turns.set(key, { ...old, ...event, started: old?.started || event.started || false,
12
+ completed: old?.completed || event.completed || false });
13
+ }
14
+ add(event) {
15
+ if (!event) return;
16
+ if (event.reason) this.gaps.add(event.reason);
17
+ if (event.source_observed && event.session?.harness_id && event.session?.session_id) { this.sources.set(JSON.stringify(event.session), event); return; }
18
+ if (event.reason && !event.call_id) return;
19
+ const { harness_id, session_id } = event.session ?? {};
20
+ if (!harness_id || !session_id || !event.call_id) { this.gaps.add("tool_identity_missing"); return; }
21
+ const key = JSON.stringify([harness_id, session_id, event.epoch ?? "", event.call_id]);
22
+ const physical = JSON.stringify([harness_id, session_id]);
23
+ if (event.source?.channel === "agy.native_transcript") {
24
+ this.transcriptSessions.add(physical);
25
+ for (const [oldKey, call] of this.calls) if (JSON.stringify([call.session.harness_id, call.session.session_id]) === physical && call.source?.channel !== "agy.native_transcript") {
26
+ this.calls.delete(oldKey); this.gaps.add("agy_live_transcript_correlation_unproven");
27
+ }
28
+ } else if (this.transcriptSessions.has(physical)) { this.gaps.add("agy_live_transcript_correlation_unproven"); return; }
29
+ const old = this.calls.get(key);
30
+ // Replay and late starts cannot undo a terminal outcome. Conflicting
31
+ // terminal facts remain visible rather than silently choosing success.
32
+ const proven = value => ["completed", "failed"].includes(value);
33
+ if (old && proven(old.status) && proven(event.status) && old.status !== event.status) this.gaps.add("conflicting_tool_outcomes");
34
+ this.calls.set(key, { ...old, ...event, name: event.name ?? old?.name ?? "unknown",
35
+ status: old?.status === "failed" || event.status === "failed" ? "failed"
36
+ : old?.status === "completed" || event.status === "completed" ? "completed"
37
+ : old?.status === "unknown" || event.status === "unknown" ? "unknown" : "running" });
38
+ }
39
+ summary(sessionId, cursor) {
40
+ const by_tool = Object.create(null), sessions = new Map(), reasons = new Set(this.gaps); let total = 0, failures = 0, pending = 0;
41
+ for (const [key, value] of this.calls) {
42
+ if (sessionId !== undefined && value.session.session_id !== sessionId || cursor?.has(key)) continue;
43
+ const id = JSON.stringify(value.session);
44
+ if (value.name === "unknown") reasons.add("tool_start_missing");
45
+ const session = sessions.get(id) ?? { session: value.session, parent_session: value.parent_session ?? null, total: 0, failures: 0, pending: 0, by_tool: Object.create(null) };
46
+ total++; session.total++; by_tool[value.name] = (by_tool[value.name] ?? 0) + 1; session.by_tool[value.name] = (session.by_tool[value.name] ?? 0) + 1;
47
+ if (value.status === "failed") { failures++; session.failures++; }
48
+ if (!["completed", "failed"].includes(value.status)) { pending++; session.pending++; }
49
+ sessions.set(id, session);
50
+ }
51
+ if (!cursor) for (const turn of this.turns.values()) {
52
+ if (sessionId !== undefined && turn.session.session_id !== sessionId) continue;
53
+ const id = JSON.stringify(turn.session);
54
+ sessions.set(id, sessions.get(id) ?? { session: turn.session, parent_session: null, total: 0, failures: 0, pending: 0, by_tool: {} });
55
+ if (!turn.started || !turn.completed) reasons.add("turn_lifecycle_incomplete");
56
+ }
57
+ if (!cursor) for (const [id, event] of this.sources) {
58
+ if (sessionId !== undefined && event.session.session_id !== sessionId) continue;
59
+ sessions.set(id, sessions.get(id) ?? { session: event.session, parent_session: event.parent_session ?? null, total: 0, failures: 0, pending: 0, by_tool: {} });
60
+ }
61
+ return { schema_id: "dd-flow/tool-summary@1", scope: "physical_sessions", measurement: "observed_invocations", origin: "native_tool_events", aggregation: cursor ? "delta" : "cumulative", total, failures, pending, by_tool,
62
+ sessions: [...sessions.values()], completeness: reasons.size ? "partial" : "complete", outcome_completeness: pending ? "partial" : "complete", reasons: [...reasons] };
63
+ }
64
+ cursor() { return new Set(this.calls.keys()); }
65
+ }
66
+
67
+ /** For adapters whose raw transcript is not portable, retain only normalized
68
+ * tool facts in the existing owned journal. Repeated snapshots are idempotent. */
69
+ export function journalToolObservations(file, events, previous) {
70
+ const batch = new ToolObservations();
71
+ for (const event of events) batch.add(event);
72
+ const records = [...batch.calls.values(), ...batch.sources.values(), ...[...batch.gaps].map(reason => ({ reason }))];
73
+ for (const event of records) {
74
+ const key = JSON.stringify([event.session, event.epoch, event.call_id, event.reason]);
75
+ const encoded = JSON.stringify(event);
76
+ if (previous.get(key) === encoded) continue;
77
+ fs.appendFileSync(file, `${JSON.stringify({ kind: "tool_observation", schema_id: "dd-flow/tool-observation@1", observed_at: new Date().toISOString(), event })}\n`, { mode: 0o600 });
78
+ previous.set(key, encoded);
79
+ }
80
+ }
81
+
82
+ const identity = (harness_id, session_id) => ({ harness_id, session_id });
83
+ const status = value => ["error", "failed", "ERROR"].includes(value) ? "failed" : ["completed", "success", "DONE"].includes(value) ? "completed"
84
+ : value === undefined || value === null || ["running", "pending", "in_progress", "inProgress", "RUNNING", "PENDING", "IN_PROGRESS"].includes(value) ? "running" : "unknown";
85
+ const nativeStatus = value => ({ status: status(value), ...(status(value) === "unknown" ? { reason: "tool_status_unsupported" } : {}) });
86
+ export function zcodePhysicalSession(update, rootSessionId) {
87
+ const native = update?._meta?.zcodeRuntime ?? {};
88
+ if (native.source === "subagent" && !native.childSessionId) return null;
89
+ return native.childSessionId ?? rootSessionId;
90
+ }
91
+
92
+ export function acpToolObservation(message, { harness = "zcode-acp", rootSessionId, adapterSessionId } = {}) {
93
+ if (!["session/update", "_x.ai/session_notification"].includes(message?.method)) return null;
94
+ const update = message.params?.update;
95
+ if (!["tool_call", "tool_call_update"].includes(update?.sessionUpdate)) return null;
96
+ const transport = message.params?.sessionId;
97
+ if (adapterSessionId && transport !== adapterSessionId) return null;
98
+ const root = rootSessionId ?? transport;
99
+ const session = harness === "zcode-acp" ? zcodePhysicalSession(update, root) : harness === "grok-acp" ? transport : root;
100
+ if (!session || !update.toolCallId) return { reason: "tool_identity_missing" };
101
+ return { session: identity(harness, session), parent_session: session !== root ? identity(harness, root) : null,
102
+ transport_session_id: transport, call_id: update.toolCallId, name: update._meta?.["x.ai/tool"]?.name ?? update._meta?.claudeCode?.toolName ?? update.title?.split(":", 1)[0], ...nativeStatus(update.status) };
103
+ }
104
+
105
+ export function droidToolObservations(record, sessionId) {
106
+ return (Array.isArray(record.message?.content) ? record.message.content : []).flatMap(block => {
107
+ if (block.type === "tool_use") return [{ session: identity("droid-cli", sessionId), call_id: block.id, name: block.name, status: "running" }];
108
+ if (block.type === "tool_result") return [{ session: identity("droid-cli", sessionId), call_id: block.tool_use_id, status: block.is_error ? "failed" : "completed" }];
109
+ return [];
110
+ });
111
+ }
112
+
113
+ export function codexToolObservation(record, sessionId) {
114
+ if (record.type !== "response_item") return null;
115
+ const p = record.payload ?? {};
116
+ if (["function_call", "custom_tool_call"].includes(p.type)) return { session: identity("codex-desktop", sessionId), call_id: p.call_id, name: p.name, status: "running" };
117
+ if (["function_call_output", "custom_tool_call_output"].includes(p.type)) {
118
+ return { session: identity("codex-desktop", sessionId), call_id: p.call_id, status: structuredFailure(p.output) ? "failed" : "unknown" };
119
+ }
120
+ return null;
121
+ }
122
+
123
+ function structuredFailure(value) {
124
+ if (!value || typeof value !== "object") return false;
125
+ return value.ok === false || value.is_error === true || value.isError === true || value.error === true
126
+ || typeof value.exit_code === "number" && value.exit_code !== 0;
127
+ }
128
+
129
+ const codexTools = new Set(["commandExecution", "fileChange", "mcpToolCall", "dynamicToolCall", "collabAgentToolCall", "webSearch", "imageView", "imageGeneration", "sleep"]);
130
+ const codexNonTools = new Set(["userMessage", "hookPrompt", "agentMessage", "functionCallOutput", "plan", "reasoning", "subAgentActivity", "enteredReviewMode", "exitedReviewMode", "contextCompaction"]);
131
+ export function classifyCodexItem(type) {
132
+ return codexTools.has(type) ? "tool" : codexNonTools.has(type) ? "non_tool" : "unknown";
133
+ }
134
+ export function codexAppServerObservation(message) {
135
+ if (!["item/started", "item/completed"].includes(message?.method)) return null;
136
+ const { threadId, turnId, item } = message.params ?? {};
137
+ if (!item || classifyCodexItem(item.type) === "non_tool") return null;
138
+ if (classifyCodexItem(item.type) === "unknown") return { reason: "codex_item_type_unsupported" };
139
+ if (!threadId || !item.id) return { reason: "tool_identity_missing" };
140
+ const native = item.status;
141
+ const failed = ["failed", "declined", "interrupted"].includes(native) || item.type === "commandExecution" && typeof item.exitCode === "number" && item.exitCode !== 0;
142
+ const completed = message.method === "item/completed" && (native === undefined || native === "completed");
143
+ const known = native === undefined || ["inProgress", "completed", "failed", "declined", "interrupted"].includes(native);
144
+ return { session: identity("codex-desktop", threadId), epoch: turnId ?? "", call_id: item.id, name: item.type,
145
+ status: !known ? "unknown" : failed ? "failed" : completed ? "completed" : "running", ...(!known ? { reason: "codex_item_status_unsupported" } : {}) };
146
+ }
147
+
148
+ export function openCodeToolObservation(part, sessionId, messageId) {
149
+ if (part.type !== "tool") return null;
150
+ return { session: identity("opencode-server", part.sessionID ?? sessionId), call_id: part.callID ?? part.id,
151
+ epoch: messageId, name: part.tool, ...nativeStatus(part.state?.status) };
152
+ }
153
+
154
+ export function agyToolObservation(step, rootSessionId) {
155
+ if (step.step_type !== "tool" && !(step.step_type === "subagent" && step.tool_name === "invoke_subagent")) return null;
156
+ const sessionId = step.conversation_id ?? rootSessionId;
157
+ return { session: identity("antigravity-cli", sessionId), parent_session: sessionId !== rootSessionId ? identity("antigravity-cli", rootSessionId) : null,
158
+ call_id: step.step_id ?? step.stepId ?? step.id ?? step.tool_call_id ?? step.toolCallId ?? (Number.isInteger(step.step_index) ? String(step.step_index) : null),
159
+ name: step.tool_name ?? step.tool_info?.name, ...(step.tool_info?.error ? { status: "failed" } : nativeStatus(step.state)) };
160
+ }
161
+
162
+ /** Native AGY JSONL records have planner tool invocations, not matching live
163
+ * step IDs. GENERIC result text is deliberately not guessed into success. */
164
+ export function agyTranscriptObservations(text, sessionId, parentSessionId, source = {}) {
165
+ const events = [], lines = text.split("\n"); let recognized = false;
166
+ const session = identity("antigravity-cli", sessionId);
167
+ for (const [line, bytes] of lines.entries()) {
168
+ if (!bytes.trim()) continue;
169
+ let record; try { record = JSON.parse(bytes); } catch { events.push({ session, reason: line === lines.length - 1 ? "agy_transcript_partial_tail" : "agy_transcript_invalid_record" }); continue; }
170
+ if (!record || typeof record !== "object" || Array.isArray(record)) { events.push({ session, reason: "agy_transcript_shape_unsupported" }); continue; }
171
+ if (record.conversation_id && record.conversation_id !== sessionId) { events.push({ session, reason: "agy_transcript_session_mismatch" }); continue; }
172
+ if (!["SYSTEM_MESSAGE", "USER_INPUT", "PLANNER_RESPONSE", "GENERIC", "TOOL_RESPONSE", "CHECKPOINT"].includes(record.type)) { events.push({ session, reason: "agy_transcript_shape_unsupported" }); continue; }
173
+ recognized = true;
174
+ if (record.tool_calls !== undefined && !Array.isArray(record.tool_calls)) events.push({ session, reason: "agy_transcript_shape_unsupported" });
175
+ if (record.truncated || record.truncation || typeof record.content === "string" && /\[.*truncat|<.*truncat/i.test(record.content)) events.push({ session, reason: "agy_transcript_truncated" });
176
+ for (const [index, call] of (Array.isArray(record.tool_calls) ? record.tool_calls : []).entries()) {
177
+ if (!Number.isInteger(record.step_index) || !call || typeof call.name !== "string" || !call.name) { events.push({ session, reason: "agy_transcript_tool_identity_missing" }); continue; }
178
+ const id = call.id ?? call.tool_call_id;
179
+ events.push({ session, parent_session: identity("antigravity-cli", parentSessionId), epoch: "native_transcript", call_id: id ?? `${record.step_index}:${index}`, name: call.name,
180
+ status: "unknown", reason: "agy_transcript_tool_outcome_unproven", source: { ...source, channel: "agy.native_transcript", line: line + 1, step_index: record.step_index } });
181
+ }
182
+ }
183
+ if (!recognized) events.push({ session, reason: "agy_transcript_shape_unsupported" });
184
+ else events.push({ session, parent_session: identity("antigravity-cli", parentSessionId), source_observed: true, source: { ...source, channel: "agy.native_transcript" } });
185
+ return events;
186
+ }
187
+
188
+ /** Read-only replay, shared by accounting and offline diagnosis. A journal
189
+ * carries physical identities; an ACP connection identity never crosses out. */
190
+ export function replayToolJournal(file, options, reducer = new ToolObservations()) {
191
+ let bytes;
192
+ try { bytes = options.text ?? fs.readFileSync(file, "utf8"); } catch (error) { reducer.gaps.add(error.code === "ENOENT" ? "journal_missing" : "journal_unreadable"); return reducer; }
193
+ const lines = bytes.split("\n"); let session = options.rootSessionId, transport = options.adapterSessionId;
194
+ for (const [index, line] of lines.entries()) {
195
+ if (!line.trim()) continue;
196
+ let e; try { e = JSON.parse(line); } catch { reducer.gaps.add(index === lines.length - 1 ? "journal_partial_tail" : "journal_invalid_record"); continue; }
197
+ const add = event => { if (event) reducer.add({ ...event, source: { ...event.source, journal: file, journal_line: index + 1 }, observed_at: e.observed_at ?? e.timestamp ?? e.at ?? e.ts ?? null }); };
198
+ if (e.kind === "tool_observation" && e.schema_id === "dd-flow/tool-observation@1") { add(e.event); continue; }
199
+ if (e.kind === "notification_failure") reducer.gaps.add("notification_failure");
200
+ const m = e.payload ?? e;
201
+ if (options.harness === "zcode-acp" || options.harness === "grok-acp") {
202
+ if (m.method === "zcode/session/allocated" && m.params?.provider_session_id === session) transport = m.params.adapter_session_id;
203
+ if (e.kind === "inbound" || m.method) add(acpToolObservation(m, { ...options, rootSessionId: session, adapterSessionId: transport }));
204
+ } else if (options.harness === "codex-desktop") {
205
+ if (e.type === "session_meta" && e.payload?.id !== session) { reducer.gaps.add("session_identity_mismatch"); break; }
206
+ if (m.params?.threadId && options.expectedSessionIds && !options.expectedSessionIds.includes(m.params.threadId)) continue;
207
+ if (["turn/started", "turn/completed"].includes(m.method)) {
208
+ const params = m.params ?? {};
209
+ if (params.threadId && params.turn?.id) reducer.observeTurn({ session: identity("codex-desktop", params.threadId), turn_id: params.turn.id,
210
+ started: m.method === "turn/started", completed: m.method === "turn/completed" && params.turn.status === "completed" });
211
+ else reducer.gaps.add("turn_identity_missing");
212
+ }
213
+ add(codexAppServerObservation(m) ?? codexToolObservation(e, session));
214
+ } else if (options.harness === "droid-cli") {
215
+ if (e.type === "session_start" && e.id !== session) { reducer.gaps.add("session_identity_mismatch"); break; }
216
+ for (const event of droidToolObservations(e, session)) add(event);
217
+ } else if (options.harness === "antigravity-cli") {
218
+ const native = m.event ?? e;
219
+ if (native.event === "step_update") add(agyToolObservation(native.step_update ?? {}, session));
220
+ } else if (options.harness === "opencode-server") {
221
+ // Native SSE message.part.updated, retained in the adapter journal.
222
+ const event = m.event ?? m;
223
+ const part = event.properties?.part;
224
+ if (part) add(openCodeToolObservation(part, session, part.messageID));
225
+ } else reducer.gaps.add("tool_observation_unsupported");
226
+ }
227
+ return reducer;
228
+ }