@deksden-com/dd-flow-cli 0.9.0-beta.7 → 0.9.0-beta.74

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 (121) hide show
  1. package/CHANGELOG.md +396 -0
  2. package/README.md +65 -0
  3. package/dist/build-info.json +10 -10
  4. package/dist/cli/help.js +81 -9
  5. package/dist/cli/run-cli.js +442 -46
  6. package/dist/harness-runtime/bin/dd-agy.mjs +37 -0
  7. package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
  8. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  9. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  10. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  11. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  12. package/dist/harness-runtime/lib/daemon-operations.mjs +215 -0
  13. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +423 -0
  14. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  15. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +141 -0
  16. package/dist/harness-runtime/lib/dd-codex.mjs +438 -0
  17. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  18. package/dist/harness-runtime/lib/dd-droid.mjs +470 -0
  19. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +274 -0
  20. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  21. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +198 -0
  22. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  23. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +644 -0
  24. package/dist/harness-runtime/lib/dd-zcode.mjs +910 -0
  25. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  26. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  27. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  28. package/dist/harness-runtime/lib/managed-daemon.mjs +260 -0
  29. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  30. package/dist/harness-runtime/lib/native-hook-command.mjs +34 -0
  31. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  32. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  33. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  34. package/dist/harness-runtime/lib/process-json.mjs +70 -0
  35. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  36. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  37. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  38. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  39. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  40. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  41. package/dist/runtime/context.js +3 -1
  42. package/dist/schemas/agent-profile.schema.json +1 -1
  43. package/dist/schemas/code-review-result.schema.json +2 -2
  44. package/dist/schemas/code-work-batch.schema.json +4 -3
  45. package/dist/schemas/code-work-result.schema.json +4 -4
  46. package/dist/schemas/harness-config.schema.json +23 -0
  47. package/dist/schemas/plan-review-result.schema.json +2 -2
  48. package/dist/schemas/run-control-receipt.schema.json +99 -0
  49. package/dist/schemas/run-control-request.schema.json +36 -0
  50. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  51. package/dist/services/cleanup.js +8 -5
  52. package/dist/services/cli-operation-classifier.js +11 -1
  53. package/dist/services/code-checks.js +543 -96
  54. package/dist/services/controller-fanout.js +120 -0
  55. package/dist/services/dashboard.js +9 -0
  56. package/dist/services/engines.js +50 -19
  57. package/dist/services/eval-snapshots.js +639 -60
  58. package/dist/services/execution-policy.js +177 -0
  59. package/dist/services/external-work-launch.js +110 -0
  60. package/dist/services/harness-adapter.js +147 -24
  61. package/dist/services/harness-config.js +68 -0
  62. package/dist/services/hooks.js +413 -168
  63. package/dist/services/lanes.js +1 -1
  64. package/dist/services/lifecycle-command.js +74 -6
  65. package/dist/services/lifecycle-invocations.js +637 -0
  66. package/dist/services/managed-daemon-binding.js +38 -0
  67. package/dist/services/managed-processes.js +138 -22
  68. package/dist/services/merge-queue.js +6 -6
  69. package/dist/services/merge-server.js +75 -29
  70. package/dist/services/migrations.js +1 -1
  71. package/dist/services/native-daemon-history.js +49 -0
  72. package/dist/services/native-session-control.js +39 -0
  73. package/dist/services/projects.js +7 -3
  74. package/dist/services/prompts.js +4 -2
  75. package/dist/services/protocols.js +11 -2
  76. package/dist/services/recovery-observation-budget.js +61 -0
  77. package/dist/services/recovery-snapshot-database.js +107 -0
  78. package/dist/services/run-control-receipt.js +56 -0
  79. package/dist/services/run-control-worker.js +363 -0
  80. package/dist/services/run-control.js +876 -0
  81. package/dist/services/run-controller-adapter.js +211 -0
  82. package/dist/services/run-controller-capture.js +134 -0
  83. package/dist/services/run-controller-process.js +189 -0
  84. package/dist/services/run-controller-recovery.js +222 -0
  85. package/dist/services/run-controller-state.js +31 -0
  86. package/dist/services/run-controller.js +733 -0
  87. package/dist/services/run-engine-bindings.js +20 -62
  88. package/dist/services/run-fork.js +124 -0
  89. package/dist/services/run-observations.js +112 -0
  90. package/dist/services/run-recovery-runtime.js +69 -0
  91. package/dist/services/run-recovery.js +327 -0
  92. package/dist/services/runs.js +280 -40
  93. package/dist/services/runtime-budget.js +362 -0
  94. package/dist/services/runtime-scope-capture.js +50 -0
  95. package/dist/services/runtime-scope-control.js +450 -0
  96. package/dist/services/runtime-scope-resume.js +543 -0
  97. package/dist/services/runtime-scope-stop.js +99 -0
  98. package/dist/services/runtime-scope-worker.js +210 -0
  99. package/dist/services/runtime-service.js +96 -0
  100. package/dist/services/schema-validation.js +12 -12
  101. package/dist/services/stage-context.js +2 -2
  102. package/dist/services/stage-lifecycle.js +32 -10
  103. package/dist/services/stage-pause.js +25 -13
  104. package/dist/services/usage.js +37 -93
  105. package/dist/services/vnext-code-review.js +149 -89
  106. package/dist/services/vnext-code.js +223 -215
  107. package/dist/services/vnext-execution-profile.js +5 -3
  108. package/dist/services/vnext-fanout.js +135 -21
  109. package/dist/services/vnext-merge.js +258 -89
  110. package/dist/services/vnext-plan-review.js +75 -64
  111. package/dist/services/vnext-plan.js +77 -29
  112. package/dist/services/vnext-protocolize.js +21 -14
  113. package/dist/services/vnext-specify.js +26 -16
  114. package/dist/services/work-registry.js +592 -154
  115. package/dist/services/workspace-bootstrap.js +76 -0
  116. package/dist/shared/errors.js +12 -0
  117. package/dist/storage/database.js +341 -31
  118. package/dist/storage/writer-contract.js +77 -0
  119. package/dist/storage/writer-migration.js +102 -0
  120. package/package.json +20 -13
  121. package/tools/repair-paused-run-status.mjs +59 -0
@@ -0,0 +1,14 @@
1
+ const generations = new WeakMap();
2
+
3
+ // A cancellation invalidates preparation already in flight, while a later
4
+ // explicit prompt captures a fresh generation and can resume normally.
5
+ export function captureDispatchGuard(owner) {
6
+ const generation = generations.get(owner) ?? 0;
7
+ return () => {
8
+ if (generation !== (generations.get(owner) ?? 0)) throw Object.assign(new Error("Prompt cancelled before native dispatch"), { code: "operation_cancelled" });
9
+ };
10
+ }
11
+
12
+ export function cancelPendingDispatch(owner) {
13
+ generations.set(owner, (generations.get(owner) ?? 0) + 1);
14
+ }
@@ -0,0 +1,129 @@
1
+ import { processSnapshot } from "./process-snapshot.mjs";
2
+ import { readdir, readFile, mkdir, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { inspectDaemonOperation } from "./daemon-operations.mjs";
5
+ import { writeJsonAtomic } from "./runner-events.mjs";
6
+ import { reportedError } from "./operation-errors.mjs";
7
+ import { ObservationClock } from "./observation-clock.mjs";
8
+ import { runtimeProcess } from "./managed-daemon.mjs";
9
+
10
+ /** Explicit same-Session restart retains native stores and the old daemon
11
+ * receipt; it does not turn a terminal directory into a new execution. */
12
+ export async function authorizeRetainedDaemonResume(root, previous, sessionId, config) {
13
+ const sessions = [...(previous.sessions ?? []), ...(previous.root_session_id ? [previous.root_session_id] : [])];
14
+ if (previous.shutdown_state !== "clean" || previous.active_tree === true || typeof sessionId !== "string" || !sessions.some(session => (typeof session === "string" ? session : session.provider_session_id) === sessionId)) throw Object.assign(new Error("terminal daemon restart requires a retained, settled Session identity"), { code: "daemon_state_terminal" });
15
+ for (const key of ["cwd", "projectRoot", "ddFlowHome", "ddFlowBin", "provider", "model", "reasoning", "mode", "variant", "agent", "bin", "noFlow"]) {
16
+ if ((previous.config?.[key] ?? null) !== (config[key] ?? null)) throw Object.assign(new Error(`retained daemon configuration changed: ${key}`), { code: "daemon_config_mismatch" });
17
+ }
18
+ await assertDaemonReplaceable(root);
19
+ await reconcileDriverReplies(root);
20
+ if (!/^[a-zA-Z0-9-]+$/.test(previous.daemon_id ?? "")) throw Object.assign(new Error("original daemon identity is invalid"), { code: "daemon_state_terminal" });
21
+ const directory = path.join(root, "daemon-history"); await mkdir(directory, { recursive: true, mode: 0o700 });
22
+ const file = path.join(directory, `${previous.daemon_id}.json`), bytes = `${JSON.stringify(previous, null, 2)}\n`;
23
+ try { await writeFile(file, bytes, { flag: "wx", mode: 0o600 }); }
24
+ catch (error) { if (error.code !== "EEXIST" || await readFile(file, "utf8") !== bytes) throw error; }
25
+ }
26
+
27
+ /** A dead bridge alone does not prove its provider tree was stopped. Require
28
+ * the adapter's durable clean-shutdown receipt as well, for every bridge. */
29
+ export async function recoverySettlement(driversRoot) {
30
+ const daemons = [];
31
+ const registries = new Map();
32
+ async function visit(directory) {
33
+ const entries = await readdir(directory, { withFileTypes: true });
34
+ const daemonRoot = entries.some(entry => entry.name === "daemon.json" && entry.isFile());
35
+ for (const entry of entries) {
36
+ const file = path.join(directory, entry.name);
37
+ if (entry.isSymbolicLink()) throw Object.assign(new Error("driver evidence contains a symbolic link"), { code: "recovery_settlement_unconfirmed" });
38
+ // Native stores contain package/auth symlinks, not adapter daemon
39
+ // receipts. Do not traverse their contents as a daemon inventory.
40
+ if (entry.isDirectory()) {
41
+ if (daemonRoot && ["gemini", "grok-home", "home", "xdg-data", "xdg-cache", "xdg-config"].includes(entry.name)) continue;
42
+ await visit(file);
43
+ }
44
+ else if (entry.name === "daemon.json") {
45
+ const state = JSON.parse(await readFile(file, "utf8"));
46
+ if (state.shutdown_state !== "clean" || state.active_tree === true) throw Object.assign(new Error("provider tree has no clean shutdown receipt"), { code: "recovery_settlement_unconfirmed" });
47
+ await assertDaemonReplaceable(directory);
48
+ await reconcileDriverReplies(directory);
49
+ if (state.config?.resourceHome && state.resource_process?.id) {
50
+ const key = state.config.resourceHome;
51
+ if (!registries.has(key)) registries.set(key, await runtimeProcess(state.config, "status"));
52
+ const processes = registries.get(key)?.processes;
53
+ if (!Array.isArray(processes) || !processes.some(record => record.id === state.resource_process.id)) throw Object.assign(new Error("managed daemon registration is missing"), { code: "recovery_settlement_unconfirmed" });
54
+ const attemptRoot = path.dirname(path.resolve(driversRoot));
55
+ for (const record of processes.filter(record => record.id === state.resource_process.id || [record.stdout_path, record.stderr_path].some(file => typeof file === "string" && path.resolve(file).startsWith(`${attemptRoot}${path.sep}`)))) {
56
+ if (!["stopped", "failed"].includes(record.state)) throw Object.assign(new Error("a retained managed process has not settled"), { code: "recovery_settlement_unconfirmed", details: { process_id: record.id, state: record.state } });
57
+ if (Number.isInteger(record.pid) && record.pid > 0) {
58
+ try { process.kill(record.pid, 0); }
59
+ catch (error) { if (error.code === "ESRCH") continue; }
60
+ if (typeof record.pid_started_at === "string" && record.pid_started_at.trim()) {
61
+ const observed = (await processSnapshot()).find(item => item.pid === record.pid);
62
+ if (!observed || record.pid_started_at.trim().replace(/\s+/g, " ") !== observed.started) continue;
63
+ }
64
+ throw Object.assign(new Error("a retained managed process is still live or unconfirmed"), { code: "recovery_settlement_unconfirmed", details: { process_id: record.id } });
65
+ }
66
+ }
67
+ }
68
+ daemons.push({ state_file: file, daemon_id: state.daemon_id, shutdown_state: state.shutdown_state, pid: state.pid });
69
+ }
70
+ }
71
+ }
72
+ await visit(driversRoot);
73
+ if (!daemons.length) throw Object.assign(new Error("no provider shutdown evidence found"), { code: "recovery_settlement_unconfirmed" });
74
+ return { settled: true, reason: "observed_clean_adapter_shutdown", observed_at: new Date().toISOString(), daemons };
75
+ }
76
+
77
+ export async function assertDaemonReplaceable(root) {
78
+ let state;
79
+ try { state = JSON.parse(await readFile(path.join(root, "daemon.json"), "utf8")); }
80
+ catch (error) { if (error.code === "ENOENT") return; throw error; }
81
+ if (!Number.isInteger(state.pid) || state.pid <= 0) throw Object.assign(new Error("original daemon ownership is unknown"), { code: "operation_observation_lost", details: { state_dir: root } });
82
+ const pids = new Set([state.pid, state.provider_pid, ...(state.owned_processes ?? []).map(process => process.pid)].filter(pid => Number.isInteger(pid) && pid > 0));
83
+ for (const pid of pids) {
84
+ try { process.kill(pid, 0); }
85
+ catch (error) { if (error.code === "ESRCH") continue; }
86
+ const retained = state.owned_processes?.filter(record => record.pid === pid && typeof record.started === "string" && record.started.trim());
87
+ if (retained?.length) {
88
+ const observed = (await processSnapshot()).find(record => record.pid === pid);
89
+ if (!observed || retained.every(record => record.started !== observed.started)) continue;
90
+ }
91
+ throw Object.assign(new Error("original daemon/provider is live or its ownership is unconfirmed; do not create a competing bridge"), { code: "operation_observation_lost", details: { state_dir: root, pid } });
92
+ }
93
+ }
94
+
95
+ /** Observe the original operation; never re-send its parameters. */
96
+ export async function recoverDriverReply(root, id, { timeoutMs = 30_000, pollMs = 250 } = {}) {
97
+ const clock = new ObservationClock({ timeoutMs });
98
+ do {
99
+ let receipt;
100
+ try { receipt = await inspectDaemonOperation(root, id); }
101
+ catch (error) { if (error.code !== "operation_not_found") throw error; }
102
+ if (receipt?.state === "completed") return receipt.result;
103
+ if (receipt?.state === "failed") throw reportedError(receipt.error, "provider operation failed");
104
+ if (clock.sample()) break;
105
+ await new Promise(resolve => setTimeout(resolve, pollMs));
106
+ } while (true);
107
+ throw Object.assign(new Error("original provider operation has no confirmed reply; reconcile it before starting another Turn"), {
108
+ code: "operation_observation_lost", details: { operation_id: id, state_dir: root }
109
+ });
110
+ }
111
+
112
+ /** Crash recovery barrier. Import late replies into the client ledger before
113
+ * any subsequent productive call, even when a new runner process is used. */
114
+ export async function reconcileDriverReplies(root) {
115
+ const directory = path.join(root, "client-operations");
116
+ let entries;
117
+ try { entries = await readdir(directory); } catch (error) { if (error.code === "ENOENT") return; throw error; }
118
+ for (const entry of entries.filter(name => name.endsWith(".json"))) {
119
+ const file = path.join(directory, entry), record = JSON.parse(await readFile(file, "utf8"));
120
+ if (["completed", "failed", "interrupted"].includes(record.state)) continue;
121
+ let receipt;
122
+ try { receipt = await inspectDaemonOperation(root, record.operation_id); }
123
+ catch (error) { if (error.code !== "operation_not_found") throw error; }
124
+ if (!["completed", "failed", "interrupted"].includes(receipt?.state)) throw Object.assign(new Error("a previous driver request has an unknown outcome; no new productive request was sent"), {
125
+ code: "operation_observation_lost", details: { operation_id: record.operation_id, state_dir: root }
126
+ });
127
+ await writeJsonAtomic(file, { ...record, state: receipt.state, result: receipt.result, error: receipt.error, reconciled_at: new Date().toISOString() });
128
+ }
129
+ }
@@ -0,0 +1,66 @@
1
+ import { createHash } from "node:crypto";
2
+ import { open, readFile, readdir, stat } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ /** Cache native filenames, then read only a bounded header and small settings.
6
+ * New child discovery may walk the directory once; heartbeats never replay it. */
7
+ export class DroidMetadataReader {
8
+ constructor(factory) { this.factory = factory; this.files = new Map(); this.cache = new Map(); }
9
+ async locate(id) {
10
+ if (this.files.has(id)) return this.files.get(id);
11
+ const visit = async directory => {
12
+ for (const entry of await readdir(directory, { withFileTypes: true }).catch(error => { if (error.code === "ENOENT") return []; throw error; })) {
13
+ const file = path.join(directory, entry.name);
14
+ if (entry.isDirectory()) await visit(file);
15
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) this.files.set(entry.name.slice(0, -6), file);
16
+ }
17
+ };
18
+ await visit(path.join(this.factory, "sessions"));
19
+ return this.files.get(id) ?? null;
20
+ }
21
+ async read(id) {
22
+ const file = await this.locate(id); if (!file) return null;
23
+ const settingsFile = file.replace(/\.jsonl$/, ".settings.json");
24
+ const info = await stat(settingsFile).catch(error => { if (error.code === "ENOENT") return null; throw error; });
25
+ if (!info || info.size > 1_048_576) return null;
26
+ const identity = `${info.ino}:${info.mtimeMs}:${info.size}`;
27
+ if (this.cache.get(id)?.identity === identity) return this.cache.get(id).value;
28
+ const handle = await open(file, "r"); const buffer = Buffer.alloc(65_536);
29
+ let header;
30
+ try { const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0); header = JSON.parse(buffer.subarray(0, bytesRead).toString("utf8").split("\n")[0]); }
31
+ finally { await handle.close(); }
32
+ if (header.type !== "session_start" || header.id !== id) throw Object.assign(new Error("native metadata Session identity differs"), { code: "session_identity_mismatch" });
33
+ let bytes, settings;
34
+ try { bytes = await readFile(settingsFile, "utf8"); settings = JSON.parse(bytes); }
35
+ catch (error) { if (error instanceof SyntaxError || error.code === "ENOENT") return null; throw error; }
36
+ const value = { header, settings, transcript_path: file, source: { path: settingsFile, sha256: createHash("sha256").update(bytes).digest("hex") } };
37
+ this.cache.set(id, { identity, value }); return value;
38
+ }
39
+ }
40
+
41
+ export function parseDroidRoutingLine(line) {
42
+ if (!line.includes("[Model-Router] Model transition | Context: ")) return null;
43
+ let context; try { context = JSON.parse(line.split(" | Context: ").slice(1).join(" | Context: ")); } catch { return null; }
44
+ if (context.slot !== "main" || typeof context.sessionId !== "string" || typeof context.modelId !== "string") return null;
45
+ return { session_id: context.sessionId, model: context.modelId, previous_model: context.previousModelId ?? null,
46
+ reason: typeof context.reason === "string" ? context.reason : null, native_timestamp: /^\[([^\]]+)\]/.exec(line)?.[1] ?? null,
47
+ event_sha256: createHash("sha256").update(line).digest("hex") };
48
+ }
49
+
50
+ /** Keep the cursor in daemon state. Bound every read, tolerate incomplete lines
51
+ * and restart from zero after truncation/rotation of this execution's own log. */
52
+ export async function readDroidRoutingLog(file, cursor = {}) {
53
+ let handle;
54
+ try { handle = await open(file, "r"); } catch (error) { if (error.code === "ENOENT") return { cursor, events: [] }; throw error; }
55
+ try {
56
+ const info = await handle.stat();
57
+ const offset = info.ino === cursor.ino && info.size >= (cursor.offset ?? 0) ? cursor.offset ?? 0 : 0;
58
+ const buffer = Buffer.alloc(Math.min(1_048_576, Math.max(0, info.size - offset)));
59
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
60
+ const end = buffer.subarray(0, bytesRead).lastIndexOf(10) + 1;
61
+ const lines = buffer.subarray(0, end).toString("utf8").split("\n");
62
+ // Persist offsets only, never a partial native line that may contain secrets.
63
+ return { cursor: { ino: info.ino, offset: offset + (end || (bytesRead === buffer.length && bytesRead === 1_048_576 ? bytesRead : 0)) }, events: lines.map(parseDroidRoutingLine).filter(Boolean) };
64
+
65
+ } finally { await handle.close(); }
66
+ }
@@ -0,0 +1,260 @@
1
+ import { lstat, readFile, readdir, mkdir } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import path from "node:path";
4
+ import { commandJson } from "./process-json.mjs";
5
+ import { errorRecord } from "./operation-errors.mjs";
6
+ import { writeJsonAtomic } from "./runner-events.mjs";
7
+
8
+ const leases = new Map();
9
+
10
+ /** Freeze resource ownership independently of whether Subject hooks are enabled. */
11
+ export function bindRuntimeOwner(config, env = process.env) {
12
+ const raw = Object.hasOwn(config, "runtime_owner") ? config.runtime_owner === null ? undefined : JSON.stringify(config.runtime_owner) : env.DD_FLOW_RUNTIME_OWNER;
13
+ if (raw === undefined) return config.runtime_owner = null;
14
+ let owner;
15
+ try { if (raw.length > 16_384) throw new Error(); owner = JSON.parse(raw); }
16
+ catch { throw Object.assign(new Error("runtime ownership descriptor is invalid"), { code: "runtime_owner_invalid" }); }
17
+ const fields = ["schema_id", "owner_id", "role", "project_id", "run_id", "work_id", "operation_id", "state_dir", "dd_flow_home", "dd_flow_bin", "resource_home", "adapter_executable", "budget"];
18
+ const text = value => typeof value === "string" && value.trim().length > 0;
19
+ if (!owner || typeof owner !== "object" || Array.isArray(owner) || Object.keys(owner).some(key => !fields.includes(key))
20
+ || owner.schema_id !== "dd-flow/runtime-owner@1" || !text(owner.owner_id) || !text(owner.operation_id)
21
+ || !["subject", "worker", "merge", "judge", "probe"].includes(owner.role)
22
+ || ["state_dir", "dd_flow_home", "dd_flow_bin", "resource_home"].some(key => !text(owner[key]) || !path.isAbsolute(owner[key]))
23
+ || (owner.adapter_executable !== undefined && (!text(owner.adapter_executable) || !path.isAbsolute(owner.adapter_executable)))
24
+ || ["project_id", "run_id", "work_id"].some(key => owner[key] !== undefined && !text(owner[key]))
25
+ || (["subject", "worker", "merge"].includes(owner.role) && (!text(owner.project_id) || !text(owner.run_id)))
26
+ || (["worker", "merge"].includes(owner.role) && !text(owner.work_id))
27
+ || (["judge", "probe"].includes(owner.role) && owner.work_id !== undefined)) {
28
+ throw Object.assign(new Error("runtime ownership descriptor does not match its role and scope"), { code: "runtime_owner_invalid" });
29
+ }
30
+ if (owner.budget !== undefined) {
31
+ const budget = owner.budget, names = ["codex-desktop", "zcode-acp", "grok-acp", "antigravity-cli", "opencode-server", "droid-cli"];
32
+ if (!budget || typeof budget !== "object" || Array.isArray(budget) || Object.keys(budget).some(key => !["schema_id", "scope_id", "per_harness"].includes(key)) || budget.schema_id !== "dd-flow/runtime-budget@1" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(budget.scope_id ?? "") || !budget.per_harness || typeof budget.per_harness !== "object" || Array.isArray(budget.per_harness) || Object.entries(budget.per_harness).some(([name, limit]) => !names.includes(name) || !Number.isSafeInteger(limit) || limit < 1 || limit > 1024)) throw Object.assign(new Error("runtime owner budget is invalid"), { code: "runtime_budget_invalid" });
33
+ }
34
+ config.runtime_owner = Object.fromEntries(fields.filter(key => owner[key] !== undefined).map(key => [key, owner[key]]));
35
+ return config.runtime_owner;
36
+ }
37
+
38
+ /** Reject rebinding before provider setup, including the already-running path. */
39
+ export async function prepareRuntimeOwner(config, stateDir, env = process.env) {
40
+ const owner = bindRuntimeOwner(config, env);
41
+ if (owner && path.resolve(owner.state_dir) !== path.resolve(stateDir)) {
42
+ throw Object.assign(new Error("runtime owner belongs to another state directory"), { code: "runtime_owner_mismatch" });
43
+ }
44
+ let previous;
45
+ try { previous = JSON.parse(await readFile(path.join(stateDir, "daemon.json"), "utf8")); }
46
+ catch (error) { if (error.code === "ENOENT") return owner; throw error; }
47
+ const retained = bindRuntimeOwner({ runtime_owner: previous?.config?.runtime_owner ?? null }, {});
48
+ if (JSON.stringify(retained) !== JSON.stringify(owner)) {
49
+ throw Object.assign(new Error("retained daemon ownership differs; use explicit recovery instead of rebinding its sessions"), { code: "runtime_owner_mismatch" });
50
+ }
51
+ return owner;
52
+ }
53
+
54
+ export async function assertDaemonOwnership(stateDir, dispatch = {}, assertCurrent = () => {}) {
55
+ for (const lease of leases.values()) if (lease.error) throw lease.error;
56
+ const state = JSON.parse(await readFile(path.join(stateDir, "daemon.json"), "utf8"));
57
+ const owner = bindRuntimeOwner({ runtime_owner: state.config?.runtime_owner ?? null }, {});
58
+ if (!owner) return;
59
+ const record = state.resource_process;
60
+ if (owner.state_dir !== stateDir || !record?.id || !record.lease_token) throw Object.assign(new Error("owned daemon has no confirmed resource binding"), { code: "process_ownership_unknown" });
61
+ for (;;) {
62
+ assertCurrent();
63
+ const result = await runtimeProcess(state.config, "admission", { id: record.id, "lease-token": record.lease_token, owner: owner.owner_id, "state-dir": stateDir, "daemon-id": state.daemon_id ?? state.config?.daemonId, ...dispatch });
64
+ assertCurrent();
65
+ if (result?.ok === true && result.admitted === true && result.process_id === record.id) return;
66
+ if (result?.ok !== true || result.reason !== "provider_capacity" || result.process_id !== record.id) throw Object.assign(new Error("productive runtime admission was not confirmed"), { code: "process_ownership_unknown" });
67
+ // The daemon, not its disposable socket client, owns this queue. Recheck
68
+ // the RUN fence and process lease on every admission attempt.
69
+ await new Promise(resolve => setTimeout(resolve, 250));
70
+ }
71
+ }
72
+
73
+ /** Snapshot terminal operations BEFORE observing native idle. A later Turn
74
+ * cannot be released by an older observation of the same Session. */
75
+ export async function budgetObservationScope(stateDir, sessionId) {
76
+ const state = await budgetState(stateDir);
77
+ if (!state?.config?.runtime_owner?.budget || !sessionId) return null;
78
+ const daemonId = state.daemon_id ?? state.config?.daemonId, operationIds = [];
79
+ for (const name of await readdir(path.join(stateDir, "operations")).catch(error => { if (error.code === "ENOENT") return []; throw error; })) {
80
+ const directory = path.join(stateDir, "operations", name);
81
+ try {
82
+ const requested = JSON.parse(await readFile(path.join(directory, "requested.json"), "utf8"));
83
+ const result = JSON.parse(await readFile(path.join(directory, "result.json"), "utf8"));
84
+ if (requested.daemon_id === daemonId && requested.session_id === sessionId && ["completed", "failed", "interrupted"].includes(result.state) && ["session.prompt", "session.start", "session.resume"].includes(requested.operation)) operationIds.push(requested.operation_id);
85
+ } catch (error) { if (error.code !== "ENOENT") throw error; }
86
+ }
87
+ return { stateDir, state, daemonId, sessionId, operationIds };
88
+ }
89
+
90
+ export async function releaseBudgetObservation(scope, observation) {
91
+ if (!scope || !scope.operationIds.length || observation?.settled !== true) return;
92
+ const id = observation.provider_session_id ?? observation.session_id ?? observation.adapter_session_id;
93
+ if (id !== scope.sessionId) throw Object.assign(new Error("budget observation belongs to another Session"), { code: "session_identity_mismatch" });
94
+ const directory = path.join(scope.stateDir, "budget-observations");
95
+ await mkdir(directory, { recursive: true, mode: 0o700 });
96
+ const file = path.join(directory, `${randomUUID()}.json`);
97
+ await writeJsonAtomic(file, { daemon_id: scope.daemonId, session_id: scope.sessionId, settled: true, operation_ids: scope.operationIds, observed_at: new Date().toISOString() });
98
+ await releaseBudget(scope.state, { "observation-file": file });
99
+ }
100
+
101
+ export async function completeBudgetOperation(stateDir, request, result, observe) {
102
+ const state = await budgetState(stateDir);
103
+ if (!state?.config?.runtime_owner?.budget) return { state: "not_required" };
104
+ if (["session.create", "session.fork"].includes(request.operation)) {
105
+ await releaseBudget(state, { "operation-id": request.id });
106
+ return { state: "settled", operation_ids: [request.id], source: "creation_receipt" };
107
+ }
108
+ const sessionId = request.params?.sessionId;
109
+ // A productive daemon receipt is bound to this exact dispatch. Reuse its
110
+ // complete tree proof instead of immediately asking the provider again.
111
+ if (["session.prompt", "session.start", "session.resume"].includes(request.operation)
112
+ && result?.settled === true
113
+ && typeof sessionId === "string"
114
+ && (result.provider_session_id ?? result.session_id ?? result.adapter_session_id) === sessionId) {
115
+ const scope = { stateDir, state, daemonId: state.daemon_id ?? state.config?.daemonId, sessionId, operationIds: [request.id] };
116
+ await releaseBudgetObservation(scope, result);
117
+ return { state: "settled", operation_ids: [request.id], source: "operation_receipt" };
118
+ }
119
+ // A known live tree is not a reason to poll it again. Preserve capacity and
120
+ // let the next explicit reconciliation obtain fresh proof.
121
+ if (result?.settled === false) return { state: "pending", reason: "tree_unsettled" };
122
+ const scope = await budgetObservationScope(stateDir, request.params?.sessionId);
123
+ if (!scope?.operationIds.length) return { state: "not_required" };
124
+ // Reconciliation requires a fresh, explicit proof. Treating an arbitrary
125
+ // productive reply as proof would silently release a live turn.
126
+ if (!observe) return { state: "pending", reason: "settlement_evidence_required" };
127
+ const observation = await observe();
128
+ if (observation?.settled !== true) return { state: "pending", reason: "tree_unsettled" };
129
+ await releaseBudgetObservation(scope, observation);
130
+ return { state: "settled", operation_ids: scope.operationIds, source: "reconciliation_observation" };
131
+ }
132
+
133
+ async function budgetState(stateDir) {
134
+ try { return JSON.parse(await readFile(path.join(stateDir, "daemon.json"), "utf8")); }
135
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
136
+ }
137
+
138
+ async function releaseBudget(state, options) {
139
+ const record = state.resource_process, owner = state.config.runtime_owner;
140
+ const receipt = await runtimeProcess(state.config, "release-turn", { id: record.id, "lease-token": record.lease_token, owner: owner.owner_id, "daemon-id": state.daemon_id ?? state.config?.daemonId, ...options });
141
+ if (receipt?.ok !== true) throw Object.assign(new Error("runtime budget release was not confirmed"), { code: "runtime_budget_release_unconfirmed" });
142
+ }
143
+
144
+ export async function runtimeProcess(config, action, options = {}) {
145
+ const owner = config.runtime_owner;
146
+ const resourceHome = owner?.resource_home ?? config.resourceHome;
147
+ const ddFlowHome = owner?.dd_flow_home ?? config.ddFlowHome;
148
+ const ddFlowBin = owner?.dd_flow_bin ?? config.ddFlowBin;
149
+ if (!resourceHome || !ddFlowHome || !ddFlowBin) return null;
150
+ const args = ["runtime", "process", action];
151
+ for (const [key, value] of Object.entries(options)) if (value !== null && value !== undefined) args.push(`--${key}`, String(value));
152
+ return await commandJson(ddFlowBin, args, {
153
+ cwd: config.cwd,
154
+ env: { ...(config.env ?? {}), DD_FLOW_HOME: ddFlowHome, DD_FLOW_RESOURCE_HOME: resourceHome }
155
+ });
156
+ }
157
+
158
+ export async function registerDaemonProcess(config, input) {
159
+ const owner = bindRuntimeOwner(config);
160
+ const harness = ({ "codex-daemon": "codex-desktop", "zcode-daemon": "zcode-acp", "grok-daemon": "grok-acp", "agy-daemon": "antigravity-cli", "opencode-daemon": "opencode-server", "droid-daemon": "droid-cli" })[input.kind];
161
+ const scope = owner ? { owner: owner.owner_id, "project-id": owner.project_id, run: owner.run_id, work: owner.work_id, role: owner.role, "state-dir": owner.state_dir, "adapter-executable": owner.adapter_executable, ...(owner.budget ? { "budget-json": JSON.stringify(owner.budget), harness } : {}), ...(owner.project_id && owner.run_id || owner.budget ? { "dispatch-barrier": "run-generation@1" } : {}), operation: `${owner.operation_id}:${input.operation ?? input.kind}` } : {};
162
+ const result = await runtimeProcess(config, "register", { ...input, ...scope, "owner-pid": process.pid, "lease-ms": 300_000 });
163
+ return result?.process ? { id: result.process.id, lease_token: result.process.lease_token, kind: input.kind } : null;
164
+ }
165
+
166
+ export async function confirmDaemonProcess(config, record, child) {
167
+ if (!record) return;
168
+ if (!child?.pid) {
169
+ await finishDaemonProcess(config, record, "failed", "daemon_spawn_missing_pid");
170
+ return;
171
+ }
172
+ await runtimeProcess(config, "confirm", { id: record.id, "lease-token": record.lease_token, pid: child.pid, "process-group-id": child.pid, "owner-pid": record.kind?.endsWith("-daemon") ? child.pid : process.pid, "lease-ms": 300_000 });
173
+ }
174
+
175
+ export async function heartbeatDaemonProcess(config, record) {
176
+ if (!record?.id || !record.lease_token) return;
177
+ let lease = leases.get(record.id);
178
+ if (!lease) {
179
+ lease = { pending: null, error: null, timer: null, lost: false };
180
+ leases.set(record.id, lease);
181
+ lease.timer = setInterval(() => { void heartbeatDaemonProcess(config, record).catch(() => {}); }, 60_000);
182
+ lease.timer.unref();
183
+ }
184
+ if (lease.lost) throw lease.error;
185
+ if (lease.pending) return await lease.pending;
186
+ lease.pending = (async () => {
187
+ try {
188
+ const result = await runtimeProcess(config, "heartbeat", { id: record.id, "lease-token": record.lease_token, "lease-ms": 300_000 });
189
+ if (result?.ok !== true) {
190
+ lease.lost = true; clearInterval(lease.timer);
191
+ throw Object.assign(new Error("managed process lease is no longer owned; new productive operations are blocked"), { code: "process_lease_lost", details: { process_id: record.id } });
192
+ }
193
+ lease.error = null;
194
+ } catch (cause) {
195
+ lease.error = cause.code === "process_lease_lost" ? cause : Object.assign(new Error("cannot confirm managed process ownership"), { code: "process_ownership_unknown", cause, details: { process_id: record.id } });
196
+ throw lease.error;
197
+ }
198
+ })();
199
+ try { await lease.pending; } finally { lease.pending = null; }
200
+ }
201
+
202
+ export async function finishDaemonProcess(config, process, state = "stopped", reason = "daemon_stopped") {
203
+ if (process?.id && process.lease_token) {
204
+ const lease = leases.get(process.id); if (lease) clearInterval(lease.timer);
205
+ const result = await runtimeProcess(config, "finish", { id: process.id, "lease-token": process.lease_token, state, reason });
206
+ if (result?.ok !== true) throw Object.assign(new Error("managed process finish was not accepted"), { code: "process_lease_lost", details: { process_id: process.id } });
207
+ leases.delete(process.id);
208
+ }
209
+ }
210
+
211
+ /** Preserve the startup error and retain the lease/resources if cleanup cannot
212
+ * prove termination. A failed cleanup is not a terminal managed process. */
213
+ export async function cleanupFailedStart(config, record, child, original) {
214
+ try {
215
+ await stopProcessGroup(child);
216
+ await finishDaemonProcess(config, record, "failed", original.code ?? "startup_failed");
217
+ } catch (cleanup) {
218
+ original.details = { ...original.details, cleanup_failed: errorRecord(cleanup), process_id: record?.id ?? null, pid: child?.pid ?? null };
219
+ }
220
+ }
221
+
222
+ export async function stopProcessGroup(child, graceMs = 1_000) {
223
+ if (!child?.pid) return;
224
+ // Harness bridges are detached on Unix, so their own process group is the
225
+ // smallest reliable unit of cleanup. Windows has no equivalent negative-PID
226
+ // signal operation; there the direct child is the safe best effort.
227
+ const target = process.platform === "win32" ? child.pid : -child.pid;
228
+ const alive = () => { try { process.kill(target, 0); return true; } catch (error) { if (error.code === "ESRCH") return false; if (error.code === "EPERM") return true; throw error; } };
229
+ if (!alive()) return;
230
+ if ((child.exitCode !== undefined && child.exitCode !== null) || (child.signalCode !== undefined && child.signalCode !== null)) {
231
+ // The leader can exit a few ticks before its helpers. Observe their normal
232
+ // shutdown before failing ownership; never signal a leaderless group.
233
+ const deadline = Date.now() + Math.max(1_000, graceMs);
234
+ while (alive() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 25));
235
+ if (!alive()) return;
236
+ throw Object.assign(new Error("process group remains after its leader exited; ownership cannot be proven from this child handle"), { code: "process_group_ownership_unknown", details: { pid: child.pid } });
237
+ }
238
+ process.kill(target, "SIGTERM");
239
+ await new Promise((resolve) => setTimeout(resolve, graceMs));
240
+ if (!alive()) return;
241
+ if (child.exitCode != null || child.signalCode != null) return stopProcessGroup(child, graceMs);
242
+ process.kill(target, "SIGKILL");
243
+ // Grace controls escalation, not the OS acknowledgement budget. A caller
244
+ // testing immediate escalation must still allow the kernel to reap children.
245
+ const deadline = Date.now() + Math.max(1_000, graceMs);
246
+ while (alive() && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 25));
247
+ if (alive()) throw Object.assign(new Error(`process group ${child.pid} did not stop`), { code: "process_group_stop_incomplete" });
248
+ }
249
+
250
+ /** A daemon acknowledgement is not a completed stop until its endpoint closes. */
251
+ export async function confirmDaemonStopped(request, socket, timeoutMs = 30_000) {
252
+ const result = await request();
253
+ const deadline = Date.now() + timeoutMs;
254
+ while (Date.now() < deadline) {
255
+ try { await lstat(socket); }
256
+ catch (error) { if (error.code === "ENOENT") return result; throw error; }
257
+ await new Promise((resolve) => setTimeout(resolve, 25));
258
+ }
259
+ throw Object.assign(new Error("daemon acknowledged stop but its socket remained live"), { code: "daemon_stop_incomplete", details: { socket } });
260
+ }
@@ -0,0 +1,77 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, open, readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { withRunnerLock } from "./runner-lock.mjs";
5
+
6
+ const text = value => typeof value === "string" && value.trim() ? value.trim() : null;
7
+ const fields = ["provider", "model", "reasoning", "mode", "permission_mode"];
8
+ export const observedFields = value => Object.fromEntries(fields.map(key => [key, text(value?.[key])]));
9
+ export const modelObservationFile = journal => path.join(path.dirname(journal), "model-observations.jsonl");
10
+
11
+ /** Routing is allowed. Permission/autonomy changes remain integrity failures.
12
+ * Missing native fields are unknown, never proof that the request was applied. */
13
+ export function checkObservedProfile(requested, observed, { strict = false, required = [] } = {}) {
14
+ const unknown = fields.filter(key => requested?.[key] && !observed?.[key]);
15
+ const changes = fields.filter(key => requested?.[key] && observed?.[key] && requested[key] !== observed[key]);
16
+ const violations = changes.filter(key => strict || ["mode", "permission_mode"].includes(key));
17
+ const missing = required.filter(key => !observed?.[key]);
18
+ if (violations.length || missing.length) throw Object.assign(new Error("native execution profile integrity is not confirmed"), {
19
+ code: "profile_integrity_violation", details: { requested: observedFields(requested), observed: observedFields(observed), violations, missing }
20
+ });
21
+ return { requested: observedFields(requested), observed: observedFields(observed), status: unknown.length ? "incomplete" : changes.length ? "mixed" : "matched", matched: !unknown.length && !changes.length, unknown, changes };
22
+ }
23
+
24
+ export async function readModelObservations(journal) {
25
+ try { const text = await readFile(modelObservationFile(journal), "utf8"); return text.slice(0, text.lastIndexOf("\n") + 1).split("\n").filter(Boolean).map(JSON.parse); }
26
+ catch (error) { if (error.code === "ENOENT") return []; throw error; }
27
+ }
28
+
29
+ /** Only adapter-verified native facts enter this file. It records changes,
30
+ * not every tool or token; reading it never requires replaying native history. */
31
+ export async function observeModel({ journal, harness, sessionId, parentSessionId = null, requested = {}, observed = {}, source, evidence = "configured", reason = null, nativeTimestamp = null, previousModel = null }) {
32
+ if (!journal || !sessionId) return null;
33
+ if (!source || !["configured", "request", "response", "unavailable"].includes(evidence)) throw new Error("model observation requires a native source and evidence level");
34
+ const file = modelObservationFile(journal), profile = observedFields(observed);
35
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
36
+ return withRunnerLock(file, async () => {
37
+ const events = await readModelObservations(journal);
38
+ const replay = source?.event_sha256 ? events.find(item => item.session_id === sessionId && item.source?.event_sha256 === source.event_sha256) : null;
39
+ if (replay) return replay;
40
+ const channel = source?.channel ?? evidence;
41
+ const previous = events.findLast(item => item.harness === harness && item.session_id === sessionId && (item.source?.channel ?? item.evidence) === channel);
42
+ const normalizedReason = text(reason)?.slice(0, 200) ?? null;
43
+ if (previous && JSON.stringify(previous.observed) === JSON.stringify(profile) && previous.reason === normalizedReason && previous.evidence === evidence) return previous;
44
+ const previousKnown = events.findLast(item => item.harness === harness && item.session_id === sessionId && item.evidence === evidence && item.observed?.model);
45
+ const fromModel = text(previousModel) ?? previousKnown?.observed.model ?? null;
46
+ const changed = Boolean(profile.model && fromModel && profile.model !== fromModel);
47
+ const value = { schema_id: "dd-flow/model-observation@1", sequence: events.length + 1,
48
+ harness, session_id: sessionId, parent_session_id: parentSessionId,
49
+ kind: changed ? "model_changed" : !profile.model ? "model_observation_unavailable" : "model_observed",
50
+ previous_model: fromModel, requested: observedFields(requested), observed: profile,
51
+ source, evidence, reason: normalizedReason, native_timestamp: text(nativeTimestamp), observed_at: new Date().toISOString() };
52
+ value.id = createHash("sha256").update(JSON.stringify(value)).digest("hex");
53
+ const handle = await open(file, "a", 0o600);
54
+ try {
55
+ const bytes = await readFile(file); const committed = bytes.lastIndexOf(10) + 1;
56
+ if (committed < bytes.length) await handle.truncate(committed);
57
+ await handle.write(`${JSON.stringify(value)}\n`); await handle.sync();
58
+ } finally { await handle.close(); }
59
+ const directory = await open(path.dirname(file), "r");
60
+ try { await directory.sync(); } finally { await directory.close(); }
61
+ return value;
62
+ });
63
+ }
64
+
65
+ export function modelAttribution(events) {
66
+ const sessions = new Map();
67
+ for (const event of events) {
68
+ const key = `${event.harness}:${event.session_id}`;
69
+ const session = sessions.get(key) ?? { harness: event.harness, session_id: event.session_id, parent_session_id: event.parent_session_id, requested: event.requested, observations: [] };
70
+ session.observations.push(event); sessions.set(key, session);
71
+ }
72
+ const models = [...new Set(events.map(event => event.observed?.model).filter(Boolean))];
73
+ const incomplete = !events.length || [...sessions.values()].some(session => session.observations.some(event => event.evidence === "unavailable" || !event.observed?.model));
74
+ return { models, mixed: models.length > 1 || events.some(event => event.observed?.model && event.requested?.model && event.observed.model !== event.requested.model),
75
+ observation_completeness: incomplete ? "incomplete" : "available_native_sources", transitions: events.filter(event => event.kind === "model_changed"),
76
+ sessions: [...sessions.values()], usage_attribution: "session_totals_unattributed_to_model", note: "Native settings/events do not prove undisclosed server routing or per-model token costs." };
77
+ }
@@ -0,0 +1,34 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ /** Preserve the native hook protocol across the CLI process boundary. */
4
+ export async function invokeNativeHook({ bin, args, payload, home, timeoutMs = 15_000 }) {
5
+ const script = /\.[cm]?js$/.test(bin);
6
+ const output = await new Promise((resolve, reject) => {
7
+ const child = spawn(script ? process.execPath : bin, [...(script ? [bin] : []), ...args], {
8
+ env: { ...process.env, DD_FLOW_HOME: home }, stdio: ["pipe", "pipe", "pipe"]
9
+ });
10
+ let stdout = "", stderr = "", failure;
11
+ const stop = error => { failure ??= error; child.kill("SIGKILL"); };
12
+ const timer = setTimeout(() => stop(Object.assign(new Error("Native hook admission timed out"), { code: "native_hook_timeout" })), timeoutMs);
13
+ child.stdout.setEncoding("utf8").on("data", chunk => { stdout += chunk; if (stdout.length > 1_048_576) stop(new Error("Native hook response exceeds protocol limit")); });
14
+ child.stderr.setEncoding("utf8").on("data", chunk => { stderr = (stderr + chunk).slice(-65_536); });
15
+ child.stdin.on("error", error => { failure ??= error; });
16
+ child.on("error", error => { clearTimeout(timer); reject(error); });
17
+ child.on("close", code => {
18
+ clearTimeout(timer);
19
+ if (failure) return reject(failure);
20
+ if (code !== 0) {
21
+ let record;
22
+ try { record = JSON.parse(stderr.trim()).error; } catch { /* Non-JSON stderr remains diagnostic evidence. */ }
23
+ return reject(Object.assign(new Error(record?.message ?? (stderr.trim() || "Native hook admission failed")), { code: record?.code ?? "native_hook_failed", details: record?.details }));
24
+ }
25
+ resolve(stdout);
26
+ });
27
+ child.stdin.end(`${JSON.stringify(payload)}\n`);
28
+ });
29
+ let result;
30
+ try { result = JSON.parse(output); } catch { throw Object.assign(new Error("Invalid native hook JSON response"), { code: "native_hook_response_invalid" }); }
31
+ if (result?.ok === false && typeof result.error?.code === "string") throw Object.assign(new Error(result.error.message ?? "Native hook failed"), { code: result.error.code, details: result.error.details });
32
+ if (!result || typeof result !== "object" || Array.isArray(result) || result.ok === false) throw Object.assign(new Error("Native hook did not return a successful protocol object"), { code: "native_hook_response_invalid" });
33
+ return result;
34
+ }
@@ -0,0 +1,36 @@
1
+ /** Only observed time counts toward inactivity. A scheduling/clock gap is not
2
+ * evidence of OS sleep, nor of provider progress. Call sample regularly. */
3
+ export class ObservationClock {
4
+ constructor({ timeoutMs, gapMs = 60_000, wall = Date.now, monotonic = () => performance.now(), onGap = () => {} }) {
5
+ if (!(timeoutMs > 0) || !(gapMs > 0)) throw new RangeError("positive observation timeout and gap required");
6
+ Object.assign(this, { timeoutMs, gapMs, wall, monotonic, onGap });
7
+ this.lastWall = wall(); this.lastMono = monotonic(); this.elapsed = 0;
8
+ this.progress = undefined;
9
+ }
10
+ sample(progress, progressAt) {
11
+ const wall = this.wall(), mono = this.monotonic();
12
+ const delta = mono - this.lastMono, wallDelta = wall - this.lastWall;
13
+ const gap = delta > this.gapMs || wallDelta > this.gapMs || delta < 0 || wallDelta < 0;
14
+ if (gap) {
15
+ this.onGap({ source: "observer_clock", classification: "observation_gap", confirmed_sleep: false,
16
+ started_at: new Date(this.lastWall).toISOString(), observed_at: new Date(wall).toISOString(),
17
+ wall_delta_ms: wallDelta, monotonic_delta_ms: delta });
18
+ this.elapsed = 0;
19
+ } else this.elapsed += delta;
20
+ this.lastWall = wall; this.lastMono = mono;
21
+ if (progress !== undefined && progress !== this.progress) {
22
+ this.progress = progress;
23
+ this.elapsed = !gap && Number.isFinite(progressAt) ? Math.max(0, Math.min(this.timeoutMs, wall - progressAt)) : 0;
24
+ }
25
+ return this.elapsed >= this.timeoutMs;
26
+ }
27
+ }
28
+
29
+ /** Node timeout handle: callers can keep their existing clearTimeout cleanup. */
30
+ export function observedTimeout(callback, timeoutMs, options = {}) {
31
+ const clock = new ObservationClock({ timeoutMs, ...options });
32
+ const timer = setInterval(() => {
33
+ if (clock.sample(options.progress?.())) { clearInterval(timer); callback(); }
34
+ }, Math.max(1, Math.min(1_000, timeoutMs / 4)));
35
+ return timer;
36
+ }
@@ -0,0 +1,5 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ // The existing runner operation owns its child driver requests, including calls
4
+ // nested in Judge/HITL/fanout. Async context keeps parallel executions separate.
5
+ export const operationContext = new AsyncLocalStorage();