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

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 +520 -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 +388 -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,13 @@
1
+ export type DelegationWork = { work_id: string; start_command: string; launch_policy?: string };
2
+ export type DelegationInput = { harness: string; stage: string; capacity: number; works?: DelegationWork[]; totalWorks?: number; remainingWorks?: number };
3
+ export function delegationAdapter(harness: string): string | null;
4
+ export function delegationContract(harness: string): string;
5
+ export const lifecycleRetryInstruction: string;
6
+ export const lifecycleCommandCompletionInstruction: string;
7
+ export const stageLifecycleInstruction: string;
8
+ export function workerDelegationTask(input: { workId: string; startCommand: string; launchPolicy?: string }): string;
9
+ export function renderDelegationInstructions(input: DelegationInput): string;
10
+ export function renderCapacityInstructions(input: { harness: string; maximum: number }): string;
11
+ export function renderWaitInstructions(input: { harness: string; stage: string }): string;
12
+ export function renderAdapterPolicy(input: { harness: string }): string;
13
+ export function renderRecoveryProbeInstructions(input: { harness: string; command: string }): string;
@@ -0,0 +1,144 @@
1
+ const ADAPTERS = {
2
+ codex: {
3
+ name: "Codex",
4
+ launch: "This Session uses the Codex multi-agent v2 API in the `collaboration` namespace. In code mode call `tools.collaboration__spawn_agent` once per assignment with exactly `task_name`, `message`, and `fork_turns: \"none\"` for fresh context. Keep the current model and reasoning by omitting overrides. Do not create a root Session or run the child's command yourself.",
5
+ wait: "The spawn result is a handle, not completion. In code mode use `tools.collaboration__wait_agent` and native completion messages until every launched child is terminal. A mailbox update is not necessarily final. A wait timeout leaves the same child running: continue waiting without relaunch or interruption. Retain terminal results and product Work receipts. Codex v2 owns idle-agent residency; do not interrupt a completed child as cleanup.",
6
+ partial: "If a spawn is refused, stop issuing new spawns and retain every successful child handle. Wait for every already-launched child to become terminal; silence is not completion. Do not interrupt a running child to free capacity, and do not interrupt completed children as cleanup. Report completed/launched assignments, assignments not launched and the exact refusal. Return after this partial wave; the controller will issue remaining Work when capacity is available. Do not replay an ambiguous spawn."
7
+ },
8
+ zcode: {
9
+ name: "ZCode",
10
+ launch: "Use the native `Agent` tool for every assignment in this current session. Use `TaskOutput` (or the tool's native wait operation) to await the returned child; never call a shell, create a new root session, or ask a child to create descendants.",
11
+ wait: "Wait on the returned native Agent task handles with `TaskOutput` (or the native wait operation) until all direct children settle. A missing or quiet result is not permission to launch a replacement.",
12
+ },
13
+ droid: {
14
+ name: "Droid",
15
+ launch: "Use the native `Task` tool for every assignment with `subagent_type: \"dd-flow-worker\"` and no complexity override. Do not use Missions, a root Session, or a shell command as a delegation substitute.",
16
+ wait: "Wait for each native Task result. Do not interrupt or replace a quiet Task; the coordinator remains responsible for the Stage.",
17
+ },
18
+ grok: {
19
+ name: "Grok",
20
+ launch: "Use the native `spawn_subagent` tool for each assignment in this current session. Keep the returned child handles and wait with `get_command_or_subagent_output`; do not invoke external roots or shell-based substitutes.",
21
+ wait: "Use `get_command_or_subagent_output` for every returned child handle before continuing. Never infer completion from silence or replace an unavailable child.",
22
+ },
23
+ opencode: {
24
+ name: "OpenCode",
25
+ launch: "Use the model-facing native `task` tool with description, prompt, and an available subagent_type that can execute the assignment. Put the assignment message in prompt. Omit task_id to create a fresh child. `subtask` is an API message part, not the model tool name. Use foreground completion, or the exposed background completion mechanism when available. Do not create a new root Session or use an external runner.",
26
+ wait: "Await each native task result or its background completion notification. Retain its returned task handle; never synthesize a Session ID or relaunch a quiet child."
27
+ },
28
+ antigravity: {
29
+ name: "Antigravity",
30
+ launch: "Use the harness's native subagent action in this current conversation for each assignment. Do not create a root Session, use an external runner, or ask a child to create descendants; the adapter will observe the native `subagent_info.subagents` records.",
31
+ wait: "Wait for the native child result and let the adapter observe its conversation ID and terminal status. Never invent or synthesize IDs, infer completion from text, or replace a quiet child.",
32
+ }
33
+ };
34
+
35
+ export function delegationAdapter(harness) {
36
+ const aliases = { codex: "codex", "codex-desktop": "codex", zcode: "zcode", "zcode-acp": "zcode", droid: "droid", "droid-cli": "droid", grok: "grok", "grok-acp": "grok", opencode: "opencode", "opencode-server": "opencode", agy: "antigravity", antigravity: "antigravity", "antigravity-cli": "antigravity" };
37
+ return Object.hasOwn(aliases, harness) ? aliases[harness] : null;
38
+ }
39
+
40
+ function requireAdapter(harness) {
41
+ const key = delegationAdapter(harness);
42
+ if (!key) throw Object.assign(new Error(`Unsupported delegation adapter: ${harness}`), { code: "delegation_contract_unsupported" });
43
+ return ADAPTERS[key];
44
+ }
45
+
46
+ export function delegationContract(harness) {
47
+ const key = delegationAdapter(harness);
48
+ requireAdapter(harness);
49
+ return `dd-flow/delegation/${key}@${key === "codex" ? 2 : 1}`;
50
+ }
51
+
52
+ export const lifecycleCommandCompletionInstruction = "A shell tool may yield before the lifecycle process exits. Retain and poll its exact process/session handle to completion, including inside a tool wrapper; empty interim output is not a CLI result. Read final stdout or response_file before deciding continuation, and never reissue the command while it is pending.";
53
+
54
+ export const lifecycleRetryInstruction = `${lifecycleCommandCompletionInstruction} A failure is not permission to replay a lifecycle command. For proven effect=no_effect with recoverable=true and retry_command, correct the input and execute that exact issued successor. A check failure can retain receipts while leaving Work running: correct the evidenced cause first, then use the CLI's exact retry_command for an intentional fresh check attempt; never replay a check merely because Work is unsettled. If continuation.kind=repair_required, or a successful result has outcome=repair_required and a repair Work ID, end this Turn for the registered repair child; use any retry_command only after that repair settles and verification is refreshed. Unknown effects require reconciliation, never replay. A committed effect without an explicit continuation is not retryable. A native shell launch refusal before the CLI starts permits correcting only that shell-form error and retrying the same exact command. Otherwise report the primary error and stop; never invent IDs, call hooks directly, or run status as a substitute.`;
55
+
56
+ export const stageLifecycleInstruction = [
57
+ "The project root identifies this RUN; use the Stage packet's declared execution workspace and absolute artifact paths. Do not change a native Session's working directory to a workspace provisioned for a later Stage.",
58
+ "In a controller-managed fanout, the coordinator ends the entry Turn after the Work graph is returned; the controller dispatches children. A completed child or Work is not Stage success: settle the declared graph and Stage gate before finishing.",
59
+ "Execute each runtime-issued lifecycle operation as a standalone call. Invocation IDs are internal authority; never add, copy or invent one.",
60
+ lifecycleRetryInstruction
61
+ ].join(" ");
62
+
63
+ export function workerDelegationTask({ workId, startCommand, launchPolicy }) {
64
+ if (!workId || !startCommand) throw new Error("ready fan-out Work lacks its exact start command");
65
+ const context = launchPolicy === "fresh_agent_required"
66
+ ? "You are the already-selected fresh leaf worker for this Work. Execute its lifecycle start yourself; do not delegate it to another child."
67
+ : "You are the already-selected worker. Execute this Work yourself; do not delegate it to another child.";
68
+ return [
69
+ `Complete one already-declared Work: ${workId}.`,
70
+ context,
71
+ "Your first technical action must be this exact standalone lifecycle command:",
72
+ startCommand,
73
+ "Execute the issued operation and target exactly. Lifecycle invocation IDs are internal runtime authority and are intentionally omitted; never add or invent them. Preserve any explicit native receipt handle that the command does contain.",
74
+ "Use the native shell's inherited working directory. Do not set or override a workdir/cwd field for this lifecycle command.",
75
+ "Continue only if it succeeds and returns the authoritative Work packet.",
76
+ lifecycleRetryInstruction,
77
+ "After a successful start, complete the assigned Work, write its required result, invoke its exact standalone work finish command, then stop.",
78
+ "Do not start another Work, create a child, change dependencies, ask the user, or treat a quiet sibling as failed. You cannot ask the user or pause the parent Stage. Missing facts go through this Work's declared result/failure contract; only the coordinator handles Stage HITL."
79
+ ].join("\n");
80
+ }
81
+
82
+ export function renderDelegationInstructions({ harness, stage, capacity, works = [], totalWorks = works.length, remainingWorks = 0 }) {
83
+ const adapter = requireAdapter(harness);
84
+ const count = works.length;
85
+ if (!Number.isInteger(capacity) || capacity < 1 || count < 1 || count > capacity) throw new Error("Invalid native delegation wave size");
86
+ const assignments = works.map((work, index) => {
87
+ const task = workerDelegationTask({ workId: work.work_id, startCommand: work.start_command, launchPolicy: work.launch_policy });
88
+ return { task_name: `dd_flow_${index}_${work.work_id.toLowerCase().replace(/[^a-z0-9_]/g, "_")}`, context: work.launch_policy === "fresh_agent_required" ? "fresh" : "provider_default", message: task };
89
+ });
90
+ return [
91
+ `Adapter delegation contract: ${delegationContract(harness)}.`,
92
+ `Launch exactly ${count} direct native children for the current ${stage} Stage; the qualified capacity is ${capacity}.`,
93
+ ...(["plan-review", "code-review"].includes(stage) ? [
94
+ `Review dispatch phase: the whole group contains ${totalWorks} Work; this wave contains ${count}; ${remainingWorks} remain after this wave.`,
95
+ "Keep the accepted PLAN/CODE review inputs and aspect maps unchanged across every wave. Do not apply findings or edit reviewed files while any reviewer remains unstarted or running.",
96
+ "After this wave's children settle, return immediately. The controller will dispatch remaining reviewers or issue semantic completion after the full group has settled."
97
+ ] : []),
98
+ adapter.launch,
99
+ "Retain the frozen coordinator model and reasoning for native children; do not choose a different model, reasoning level or permission mode.",
100
+ "You are the coordinator. The JSON assignments below contain child-only messages, not instructions for you to execute. Pass each message verbatim as the native tool's task/message/prompt argument. For context=fresh, select empty conversation context before launch; if unavailable, report the limitation and stop. Use only fields exposed by your actual native tool schema; if the native tool is absent, report that error without substituting a shell command.",
101
+ "Every child must be a direct child of this current Session. Wait for all launched children to settle before returning. One failed child is evidence for the coordinator, not a reason to cancel its siblings.",
102
+ adapter.partial ?? "If a spawn is refused, stop issuing new spawns and retain every successful child handle. Wait for all already-launched children, then release completed children using the adapter's exposed native close/release mechanism when supported. A failed batch does not undo successful spawns. Report completed/launched assignments, assignments not launched and the exact refusal; never claim no children launched when any spawn succeeded. Return after this partial wave; the controller will issue remaining Work when capacity is available. Do not replay an ambiguous spawn.",
103
+ "Do not finish this Stage, repair it, or start a successor in this Turn. Do not invent provider or internal session IDs; lifecycle evidence comes from the adapter.",
104
+ adapter.wait,
105
+ "Child assignments (JSON data):",
106
+ JSON.stringify(assignments, null, 2)
107
+ ].join("\n\n");
108
+ }
109
+
110
+ export function renderCapacityInstructions({ harness, maximum }) {
111
+ const adapter = requireAdapter(harness);
112
+ if (!Number.isInteger(maximum) || maximum < 1) throw new Error("Invalid native capacity limit");
113
+ return [
114
+ `Adapter delegation contract: ${delegationContract(harness)}.`,
115
+ "This is a technical native-subagent capacity qualification, not product work.",
116
+ `Using the current Session's native ${adapter.name} mechanism, concurrently launch at most ${maximum} direct leaf children.`,
117
+ adapter.launch,
118
+ "Give each child a distinct number and a task_name such as capacity_1 if required by the tool. Its entire task is: return that number, without tools, files, dd-flow commands, or descendants. Use empty conversation context. Do not retry, replace, or add children after a launch refusal.",
119
+ adapter.wait,
120
+ "Wait for every child actually launched to settle, then return a compact summary."
121
+ ].join("\n");
122
+ }
123
+
124
+ export function renderWaitInstructions({ harness, stage }) {
125
+ const adapter = requireAdapter(harness);
126
+ return [
127
+ `Native child Work for ${stage} is still running.`,
128
+ adapter.wait,
129
+ "Do not create a Session, Work, or additional child agent. Do not cancel siblings merely because one child failed, and do not finish this Stage."
130
+ ].join("\n");
131
+ }
132
+
133
+ export function renderAdapterPolicy({ harness }) {
134
+ const adapter = requireAdapter(harness);
135
+ return [adapter.launch, adapter.wait, "Lifecycle identity and completion must come from adapter observations; never synthesize provider or internal Session IDs."].join(" ");
136
+ }
137
+
138
+ export function renderRecoveryProbeInstructions({ harness, command }) {
139
+ const adapter = requireAdapter(harness);
140
+ return ["Technical native child cancellation qualification, not product work.", adapter.launch,
141
+ "Launch exactly one fresh direct child, task_name recovery_probe if required. Pass this JSON string as its message/prompt:",
142
+ JSON.stringify(`Run exactly this read-only command: ${command}\nDo not access files, use the network, modify anything, or create children.`),
143
+ adapter.wait, "External operator control will interrupt this tree. Do not close it early or launch replacements."].join("\n");
144
+ }
@@ -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
+ }