@deksden-com/dd-flow-cli 0.9.0-beta.11 → 0.9.0-beta.111

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 (162) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/README.md +68 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +305 -0
  5. package/dist/cli/help.js +89 -13
  6. package/dist/cli/hook-ingress.js +77 -0
  7. package/dist/cli/input-preparation.js +116 -0
  8. package/dist/cli/native-hook-ingress.js +48 -0
  9. package/dist/cli/run-cli.js +1465 -384
  10. package/dist/cli.js +8 -2
  11. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  12. package/dist/harness-runtime/bin/dd-agy.mjs +52 -0
  13. package/dist/harness-runtime/bin/dd-codex.mjs +26 -0
  14. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  15. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  16. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  17. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  18. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  19. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  20. package/dist/harness-runtime/lib/daemon-operations.mjs +226 -0
  21. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  22. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +500 -0
  23. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  24. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  25. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +149 -0
  26. package/dist/harness-runtime/lib/dd-codex.mjs +563 -0
  27. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  28. package/dist/harness-runtime/lib/dd-droid.mjs +475 -0
  29. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +394 -0
  30. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  31. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +219 -0
  32. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  33. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +645 -0
  34. package/dist/harness-runtime/lib/dd-zcode.mjs +982 -0
  35. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  36. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  37. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  38. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  39. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  40. package/dist/harness-runtime/lib/managed-daemon.mjs +327 -0
  41. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  42. package/dist/harness-runtime/lib/native-hook-command.d.mts +3 -0
  43. package/dist/harness-runtime/lib/native-hook-command.mjs +108 -0
  44. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  45. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  46. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  47. package/dist/harness-runtime/lib/process-json.mjs +71 -0
  48. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  49. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  50. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  51. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  52. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  53. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  54. package/dist/harness-runtime/lib/zcode-usage.mjs +54 -0
  55. package/dist/protocol/local-files.js +18 -9
  56. package/dist/runtime/context.js +2 -2
  57. package/dist/schemas/agent-profile.schema.json +1 -1
  58. package/dist/schemas/code-review-result.schema.json +1 -1
  59. package/dist/schemas/code-work-batch.schema.json +3 -3
  60. package/dist/schemas/code-work-result.schema.json +3 -3
  61. package/dist/schemas/plan-review-result.schema.json +2 -2
  62. package/dist/schemas/run-control-receipt.schema.json +99 -0
  63. package/dist/schemas/run-control-request.schema.json +36 -0
  64. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  65. package/dist/services/canon.js +11 -8
  66. package/dist/services/cleanup.js +132 -39
  67. package/dist/services/cli-operation-classifier.js +22 -24
  68. package/dist/services/code-checks.js +589 -106
  69. package/dist/services/codex-hook-delivery.js +28 -0
  70. package/dist/services/command-context.js +80 -0
  71. package/dist/services/config.js +11 -8
  72. package/dist/services/continuation-outcome.js +20 -0
  73. package/dist/services/controller-fanout.js +173 -0
  74. package/dist/services/dashboard.js +103 -31
  75. package/dist/services/engines.js +121 -76
  76. package/dist/services/eval-snapshots.js +994 -97
  77. package/dist/services/execution-policy.js +181 -0
  78. package/dist/services/external-work-launch.js +166 -0
  79. package/dist/services/harness-adapter.js +147 -24
  80. package/dist/services/harness-config.js +2 -0
  81. package/dist/services/hooks.js +702 -327
  82. package/dist/services/lanes.js +78 -65
  83. package/dist/services/lifecycle-command.js +113 -18
  84. package/dist/services/lifecycle-contract.js +30 -0
  85. package/dist/services/lifecycle-invocations.js +1379 -0
  86. package/dist/services/managed-daemon-binding.js +38 -0
  87. package/dist/services/managed-processes.js +302 -34
  88. package/dist/services/merge-queue.js +228 -149
  89. package/dist/services/merge-server.js +66 -28
  90. package/dist/services/migrations.js +37 -16
  91. package/dist/services/native-daemon-history.js +49 -0
  92. package/dist/services/native-session-control.js +39 -0
  93. package/dist/services/plan-runtime.js +26 -11
  94. package/dist/services/plans.js +28 -25
  95. package/dist/services/projects.js +20 -15
  96. package/dist/services/prompts.js +25 -16
  97. package/dist/services/protocols.js +160 -86
  98. package/dist/services/recovery-observation-budget.js +61 -0
  99. package/dist/services/recovery-snapshot-database.js +142 -0
  100. package/dist/services/repair-intents.js +40 -0
  101. package/dist/services/review-copy.js +136 -0
  102. package/dist/services/run-control-receipt.js +56 -0
  103. package/dist/services/run-control-worker.js +351 -0
  104. package/dist/services/run-control.js +888 -0
  105. package/dist/services/run-controller-adapter.js +231 -0
  106. package/dist/services/run-controller-capture.js +167 -0
  107. package/dist/services/run-controller-process.js +180 -0
  108. package/dist/services/run-controller-recovery.js +221 -0
  109. package/dist/services/run-controller-state.js +36 -0
  110. package/dist/services/run-controller.js +798 -0
  111. package/dist/services/run-engine-bindings.js +1 -1
  112. package/dist/services/run-fork.js +142 -0
  113. package/dist/services/run-observations.js +112 -0
  114. package/dist/services/run-projection.js +22 -64
  115. package/dist/services/run-recovery-runtime.js +80 -0
  116. package/dist/services/run-recovery.js +345 -0
  117. package/dist/services/runs.js +536 -181
  118. package/dist/services/runtime-budget.js +413 -0
  119. package/dist/services/runtime-command.js +43 -0
  120. package/dist/services/runtime-scope-capture.js +52 -0
  121. package/dist/services/runtime-scope-control.js +460 -0
  122. package/dist/services/runtime-scope-resume.js +577 -0
  123. package/dist/services/runtime-scope-stop.js +159 -0
  124. package/dist/services/runtime-scope-worker.js +242 -0
  125. package/dist/services/runtime-service.js +97 -0
  126. package/dist/services/schema-validation.js +10 -8
  127. package/dist/services/scope-writer-cleanup.js +26 -0
  128. package/dist/services/sessions.js +35 -69
  129. package/dist/services/stage-blocker.js +17 -7
  130. package/dist/services/stage-context.js +50 -19
  131. package/dist/services/stage-lifecycle.js +100 -103
  132. package/dist/services/stage-pause.js +88 -75
  133. package/dist/services/stage-report-renderer.js +116 -6
  134. package/dist/services/stage-work-graph.js +35 -0
  135. package/dist/services/usage.js +35 -98
  136. package/dist/services/vnext-code-review.js +197 -84
  137. package/dist/services/vnext-code.js +278 -251
  138. package/dist/services/vnext-execution-profile.js +5 -3
  139. package/dist/services/vnext-fanout.js +172 -17
  140. package/dist/services/vnext-merge.js +345 -111
  141. package/dist/services/vnext-plan-review.js +171 -111
  142. package/dist/services/vnext-plan.js +180 -87
  143. package/dist/services/vnext-protocolize.js +320 -74
  144. package/dist/services/vnext-specify.js +115 -77
  145. package/dist/services/work-registry.js +1001 -187
  146. package/dist/services/workspace-bootstrap.js +76 -0
  147. package/dist/services/workspace-files.js +83 -0
  148. package/dist/services/worktrees.js +88 -36
  149. package/dist/shared/entity-references.js +8 -0
  150. package/dist/shared/errors.js +12 -0
  151. package/dist/storage/database.js +692 -35
  152. package/dist/storage/foreign-key-transaction.js +39 -0
  153. package/dist/storage/immutable-input.js +45 -0
  154. package/dist/storage/import-guard.js +102 -0
  155. package/dist/storage/native-cleanup.js +52 -0
  156. package/dist/storage/paths.js +17 -4
  157. package/dist/storage/projection-lock.js +73 -0
  158. package/dist/storage/work-references.js +23 -0
  159. package/dist/storage/writer-contract.js +77 -0
  160. package/dist/storage/writer-migration.js +85 -0
  161. package/package.json +24 -13
  162. package/tools/repair-paused-run-status.mjs +84 -0
@@ -0,0 +1,226 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, readdir, link, unlink, open } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import path from "node:path";
5
+ import { hashJson, writeJsonAtomic } from "./runner-events.mjs";
6
+ import { errorRecord, isObservationLoss, reportedError } from "./operation-errors.mjs";
7
+ import { assertDaemonOwnership, budgetObservationScope, releaseBudgetObservation, completeBudgetOperation } from "./managed-daemon.mjs";
8
+ import { readModelObservations, modelAttribution } from "./model-observations.mjs";
9
+
10
+ const productive = new Set(["session.create", "session.prompt", "session.start", "session.fork", "session.resume"]);
11
+ const controls = new Map();
12
+ const dispatchGenerations = new Map();
13
+
14
+ async function controlDispatch(root, request, action) {
15
+ const key = request.operation === "daemon.stop" ? `stop:${request.params?.cancelTree === true}` : `cancel:${request.params?.sessionId ?? ""}`;
16
+ let pending = controls.get(root);
17
+ if (!pending) { pending = new Map(); controls.set(root, pending); }
18
+ if (pending.has(key)) return await pending.get(key);
19
+ // Preserve the adapter's identity check for every distinct cancel target.
20
+ // A stop arriving after cancel waits for its attempts before verification.
21
+ const predecessors = key.startsWith("stop:") ? [...pending.values()] : [];
22
+ const promise = (async () => { await Promise.allSettled(predecessors); return await action(); })();
23
+ pending.set(key, promise);
24
+ try { return await promise; }
25
+ finally { pending.delete(key); if (!pending.size) controls.delete(root); }
26
+ }
27
+ function location(root, id) {
28
+ if (typeof id !== "string" || !id) throw Object.assign(new Error("operation id is required"), { code: "operation_id_required" });
29
+ return path.join(root, "operations", createHash("sha256").update(id).digest("hex"));
30
+ }
31
+ async function read(file) { try { return JSON.parse(await readFile(file, "utf8")); } catch (error) { if (error.code === "ENOENT") return null; throw error; } }
32
+
33
+ export async function inspectDaemonOperation(root, id) {
34
+ if (typeof root !== "string" || !path.isAbsolute(root)) throw Object.assign(new Error("operation observation requires an absolute state directory"), { code: "invalid_path" });
35
+ const directory = location(root, id);
36
+ const requested = await read(path.join(directory, "requested.json"));
37
+ if (!requested) throw Object.assign(new Error("daemon operation is not recorded"), { code: "operation_not_found", details: { operation_id: id } });
38
+ const settlement = await read(path.join(directory, "settlement.json"));
39
+ const hookFailures = [];
40
+ for (const name of await readdir(path.join(directory, "hooks")).catch(error => { if (error.code === "ENOENT") return []; throw error; })) {
41
+ if (!/^[A-Za-z0-9-]{1,128}\.json$/.test(name)) continue;
42
+ const binding = await read(path.join(directory, "hooks", name));
43
+ if (binding?.schema_id !== "dd-flow/hook-request@1" || binding.request_id !== name.slice(0, -5) || binding.operation_id !== id || binding.daemon_id !== requested.daemon_id) continue;
44
+ const failure = await read(path.join(root, "hook-failures", name));
45
+ if (failure?.request_id !== binding.request_id || typeof failure.code !== "string" || typeof failure.message !== "string") continue;
46
+ hookFailures.push({ code: failure.code, message: failure.message, observed_at: failure.observed_at ?? null, details: { ...failure.details, ...binding, effect: "unknown" } });
47
+ }
48
+ hookFailures.sort((a, b) => String(a.observed_at ?? "").localeCompare(String(b.observed_at ?? "")));
49
+ // Admission failure is causal evidence, not proof that the native tree stopped.
50
+ return { ...requested, ...(await read(path.join(directory, "result.json")) ?? await read(path.join(directory, "interrupted.json")) ?? await read(path.join(directory, "observation-lost.json")) ?? { state: "running" }), ...(settlement ? { settlement } : {}), ...(hookFailures[0] ? { primary_error: hookFailures[0] } : {}) };
51
+ }
52
+
53
+ /** Retry only the bookkeeping that follows a durable productive receipt.
54
+ * This is intentionally separate from dispatch: it never invokes a native
55
+ * prompt/create/fork operation, so recovery cannot duplicate agent work. */
56
+ export async function settleDaemonOperation(root, id) {
57
+ const current = await inspectDaemonOperation(root, id);
58
+ if (current.state !== "completed") return current;
59
+ if (current.settlement?.state === "settled") return current;
60
+ let settlement;
61
+ try {
62
+ settlement = await completeBudgetOperation(root, {
63
+ id: current.operation_id,
64
+ operation: current.operation,
65
+ params: { sessionId: current.session_id ?? undefined }
66
+ }, current.result);
67
+ } catch (error) {
68
+ settlement = { state: "pending", reason: "settlement_error", observed_at: new Date().toISOString(), error: errorRecord(error) };
69
+ }
70
+ try { await writeSettlement(root, id, settlement); }
71
+ catch (error) {
72
+ settlement = { state: "blocked", reason: "settlement_storage_error", observed_at: new Date().toISOString(), error: errorRecord(error) };
73
+ }
74
+ return { ...current, settlement };
75
+ }
76
+
77
+ /** A sealed whole-tree stop is the only authority that may turn an unknown
78
+ * productive request into a terminal interruption. This is deliberately a
79
+ * journal operation: a closed daemon cannot be asked to manufacture a reply. */
80
+ export async function interruptDaemonOperation(root, id, barrier) {
81
+ if (!barrier || typeof barrier !== "object" || typeof barrier.control_id !== "string" || !barrier.control_id) throw Object.assign(new Error("interruption requires a sealed control identity"), { code: "stop_barrier_invalid" });
82
+ const current = await inspectDaemonOperation(root, id);
83
+ if (["completed", "failed", "interrupted"].includes(current.state)) return current;
84
+ if (!(["running", "awaiting_provider"].includes(current.state)) || !productive.has(current.operation)) throw Object.assign(new Error("only an observed productive operation may be interrupted"), { code: "operation_not_interruptible" });
85
+ // A lazy session/create is allowed to have no ACP/native session id yet.
86
+ // The owned daemon identity plus the sealed stop operation is the authority
87
+ // in that case; never manufacture a session id merely to satisfy the check.
88
+ const barrierSession = barrier.session_id ?? null;
89
+ const currentSession = current.session_id ?? null;
90
+ if (barrier.daemon_id !== current.daemon_id || barrierSession !== currentSession) throw Object.assign(new Error("interruption barrier belongs to another daemon operation"), { code: "stop_barrier_mismatch" });
91
+ const value = { state: "interrupted", outcome: "interrupted", observed_at: new Date().toISOString(), interrupted_by: { control_id: barrier.control_id, stop_operation_id: barrier.stop_operation_id, evidence: barrier.evidence ?? null }, error: { code: "operation_interrupted", message: "Operation was interrupted after the owned native tree was stopped", cause: current.error ?? null } };
92
+ const saved = await writeTerminal(root, id, value);
93
+ if (saved.state !== "interrupted" || saved.interrupted_by?.control_id !== barrier.control_id) throw Object.assign(new Error("operation already has a conflicting terminal outcome"), { code: "operation_terminal_conflict" });
94
+ return await inspectDaemonOperation(root, id);
95
+ }
96
+
97
+ /** At-most-once dispatch and a durable terminal reply, including when the socket
98
+ * observer disconnects. Recovery reads this receipt; it never resends a prompt. */
99
+ export async function durableDaemonDispatch(root, request, action, observe) {
100
+ if (request.operation === "operation.inspect") return await inspectDaemonOperation(root, request.params?.operationId);
101
+ if (request.operation === "daemon.status") {
102
+ const result = await action();
103
+ if (!result?.config?.journal) return result;
104
+ try { return { ...result, model_attribution: modelAttribution(await readModelObservations(result.config.journal)) }; }
105
+ catch (error) { return { ...result, model_observation_error: errorRecord(error) }; }
106
+ }
107
+ if (request.operation === "session.inspect") {
108
+ const scope = await budgetObservationScope(root, request.params?.sessionId);
109
+ const result = await action();
110
+ let settlement;
111
+ if (!scope?.operationIds.length) settlement = { state: "not_required" };
112
+ else if (result?.settled !== true) settlement = { state: "pending", reason: "tree_unsettled" };
113
+ else try {
114
+ await releaseBudgetObservation(scope, result);
115
+ settlement = { state: "settled", operation_ids: scope.operationIds, source: "inspection" };
116
+ } catch (error) {
117
+ settlement = { state: "pending", reason: "settlement_error", observed_at: new Date().toISOString(), error: errorRecord(error) };
118
+ }
119
+ return settlement.state === "not_required" || !result || typeof result !== "object" || Array.isArray(result) ? result : { ...result, settlement };
120
+ }
121
+ const control = ["daemon.stop", "session.cancel"].includes(request.operation);
122
+ if (!productive.has(request.operation) && !control) return await action();
123
+ const generation = dispatchGenerations.get(root) ?? 0;
124
+ if (control) dispatchGenerations.set(root, generation + 1);
125
+ const assertCurrent = () => { if (generation !== (dispatchGenerations.get(root) ?? 0)) throw Object.assign(new Error("control cancelled a queued productive dispatch"), { code: "operation_cancelled" }); };
126
+ const result = await journalDispatch(root, request, async () => {
127
+ // Persist before admission so a racing fence can observe the writer.
128
+ if (!control) await assertDaemonOwnership(root, { "operation-id": request.id, operation: request.operation, "native-session-id": request.params?.sessionId, "prompt-sha256": typeof request.params?.prompt === "string" ? createHash("sha256").update(request.params.prompt).digest("hex") : undefined }, assertCurrent);
129
+ if (!control) assertCurrent();
130
+ return control ? await controlDispatch(root, request, action) : await action();
131
+ });
132
+ if (control) return result;
133
+ let settlement;
134
+ try {
135
+ settlement = await completeBudgetOperation(root, request, result, observe);
136
+ } catch (error) {
137
+ settlement = { state: "pending", reason: "settlement_error", observed_at: new Date().toISOString(), error: errorRecord(error) };
138
+ }
139
+ try { await writeSettlement(root, request.id, settlement); }
140
+ catch (error) {
141
+ settlement = { state: "blocked", reason: "settlement_storage_error", observed_at: new Date().toISOString(), error: errorRecord(error) };
142
+ }
143
+ return settlement?.state === "not_required" || !result || typeof result !== "object" || Array.isArray(result)
144
+ ? result
145
+ : { ...result, settlement };
146
+ }
147
+
148
+ async function writeSettlement(root, id, value) {
149
+ const directory = location(root, id);
150
+ await writeJsonAtomic(path.join(directory, "settlement.json"), value);
151
+ }
152
+
153
+ /** Startup has no registered daemon yet. Its existing native implementation
154
+ * owns registration/admission; only the CLI entrypoint uses this journal path. */
155
+ export async function durableDaemonStart(options, action) {
156
+ const root = options.stateDir;
157
+ if (typeof root !== "string" || !path.isAbsolute(root)) throw Object.assign(new Error("daemon startup requires an absolute state directory"), { code: "invalid_path" });
158
+ // Keep only configuration locations, never inherited credentials. The owned
159
+ // scope can reuse this exact adapter launch after retiring the old daemon.
160
+ const launch = { schema_id: "dd-flow/native-launch@1", executable: options.entryPath ?? null, args: process.argv.slice(2), cwd: process.cwd(), runtime_owner: process.env.DD_FLOW_RUNTIME_OWNER ?? null,
161
+ env: Object.fromEntries(["CODEX_HOME", "DD_FLOW_CONFIG_HOME", "DD_FLOW_HOME", "DD_FLOW_BIN", "DD_FLOW_RESOURCE_HOME"].map(key => [key, process.env[key] ?? null])) };
162
+ const request = { id: process.env.DD_EVAL_OPERATION_ID ?? randomUUID(), operation: "daemon.start", params: { ...options, runtimeOwner: process.env.DD_FLOW_RUNTIME_OWNER ?? null, resourceHome: process.env.DD_FLOW_RESOURCE_HOME ?? null, launch } };
163
+ return await journalDispatch(root, request, () => action(options));
164
+ }
165
+
166
+ async function journalDispatch(root, request, action) {
167
+ const directory = location(root, request.id), fingerprint = hashJson({ operation: request.operation, params: request.params ?? {} });
168
+ await mkdir(directory, { recursive: true, mode: 0o700 });
169
+ // Publish a complete request atomically and exclusively. Writing directly with
170
+ // wx exposes a partially written JSON document to a concurrent observer.
171
+ const temporary = path.join(directory, `requested-${randomUUID()}.json`);
172
+ const daemon = await read(path.join(root, "daemon.json"));
173
+ const startup = request.operation === "daemon.start";
174
+ const daemonId = daemon?.daemon_id ?? daemon?.config?.daemonId ?? null;
175
+ await writeJsonAtomic(temporary, { schema_id: "dd-flow/daemon-operation@1", operation_id: request.id, operation: request.operation, session_id: request.params?.sessionId ?? null, daemon_id: startup ? null : daemonId, ...(startup ? { predecessor_daemon_id: daemonId, launch: request.params?.launch } : {}), params_sha256: fingerprint, requested_at: new Date().toISOString() });
176
+ try {
177
+ await link(temporary, path.join(directory, "requested.json"));
178
+ } catch (error) {
179
+ if (error.code !== "EEXIST") throw error;
180
+ const saved = await inspectDaemonOperation(root, request.id);
181
+ if (saved.params_sha256 !== fingerprint) throw Object.assign(new Error("operation id was reused with different parameters"), { code: "operation_conflict", details: { operation_id: request.id } });
182
+ if (saved.state === "completed") return saved.result;
183
+ if (["failed", "interrupted"].includes(saved.state)) throw reportedError(saved.error, "provider operation failed");
184
+ throw Object.assign(new Error("provider operation has no confirmed terminal result; inspect the existing operation instead of resending it"), { code: "operation_observation_lost", details: { operation_id: request.id, receipt_directory: directory } });
185
+ } finally { await unlink(temporary); }
186
+ let result;
187
+ try {
188
+ result = await action();
189
+ }
190
+ catch (error) {
191
+ const unknown = isObservationLoss(error);
192
+ if (unknown) await writeJsonAtomic(path.join(directory, "observation-lost.json"), { state: "awaiting_provider", observed_at: new Date().toISOString(), error: errorRecord(error) });
193
+ else {
194
+ const terminal = await writeTerminal(root, request.id, { state: "failed", observed_at: new Date().toISOString(), error: errorRecord(error) });
195
+ if (terminal.state !== "failed") throw reportedError(terminal.error, "provider operation did not retain this failure");
196
+ }
197
+ throw error;
198
+ }
199
+ try {
200
+ const terminal = await writeTerminal(root, request.id, { state: "completed", ...(startup ? { started_daemon_id: result?.daemon_id ?? null } : {}), finished_at: new Date().toISOString(), result });
201
+ if (terminal.state !== "completed") throw reportedError(terminal.error, "provider operation was terminalized before its late reply arrived");
202
+ } catch (cause) {
203
+ if (cause?.code === "operation_interrupted" || cause?.code === "operation_terminal_conflict") throw cause;
204
+ throw Object.assign(new Error("provider returned but the durable reply could not be saved; do not resend the operation"), { code: "operation_observation_lost", cause, details: { operation_id: request.id, receipt_directory: directory } });
205
+ }
206
+ return result;
207
+ }
208
+
209
+ /** `result.json` is the one exclusive terminal slot. Old interrupted.json
210
+ * files remain readable for compatibility, but new writes never race them. */
211
+ async function writeTerminal(root, id, value) {
212
+ const file = path.join(location(root, id), "result.json");
213
+ const temporary = `${file}.${randomUUID()}.tmp`;
214
+ const handle = await open(temporary, "wx", 0o600);
215
+ try { await handle.writeFile(`${JSON.stringify(value, null, 2)}\n`); await handle.sync(); }
216
+ finally { await handle.close(); }
217
+ try {
218
+ await link(temporary, file);
219
+ return value;
220
+ } catch (error) {
221
+ if (error.code !== "EEXIST") throw error;
222
+ const saved = await read(file);
223
+ if (!saved || !["completed", "failed", "interrupted"].includes(saved.state)) throw Object.assign(new Error("operation terminal record is invalid"), { code: "operation_terminal_conflict" });
224
+ return saved;
225
+ } finally { await unlink(temporary); }
226
+ }
@@ -0,0 +1,6 @@
1
+ export declare function qualifyAgyHooks(projectRoot: string, options?: { stateDir?: string | null; install?: boolean }): Promise<{
2
+ hooksSha256: string;
3
+ workspaceHooksPath: string;
4
+ workspaceHooksSha256: string;
5
+ workspaceHooksInstalled: string;
6
+ }>;