@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
@@ -1,11 +1,15 @@
1
+ import { managedInvocationContext, managedLifecycleCommand } from "./lifecycle-invocations.js";
2
+ import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
1
3
  import crypto from "node:crypto";
2
4
  import fs from "node:fs";
3
5
  import path from "node:path";
4
6
  import { AppError } from "../shared/errors.js";
7
+ import { runtimeBudgetForRun } from "./runtime-budget.js";
5
8
  import { flowCommand } from "./stage-pause.js";
6
- import { validateSchema } from "./schema-validation.js";
7
- import { adapterSessionId, runHarnessAdapter } from "./harness-adapter.js";
9
+ import { adapterSessionId, prepareHarnessFlowExecutable, runHarnessAdapter } from "./harness-adapter.js";
8
10
  import { harnessRuntimeArguments, resolveHarnessCommand } from "./harness-config.js";
11
+ import { assertRunMutationAllowed, recoveryGuard } from "./run-recovery.js";
12
+ import { loadAgentProfile, resolveExecutionPolicy, runtimeHarness } from "./execution-policy.js";
9
13
  /** A deterministic dispatcher; only the launched harness Session performs agent work. */
10
14
  export async function serveMergeRequests(context, input) {
11
15
  const running = context.db.get("SELECT server_id, pid FROM merge_servers WHERE status IN ('running','stopping') ORDER BY started_at LIMIT 1");
@@ -58,42 +62,82 @@ export async function serveMergeRequests(context, input) {
58
62
  export function mergeServerStatus(context) { return { ok: true, servers: context.db.all("SELECT server_id, profile_id, status, pid, started_at, heartbeat_at, stopped_at, journal_path FROM merge_servers ORDER BY started_at DESC") }; }
59
63
  export function stopMergeServer(context, input) { const changed = context.db.run("UPDATE merge_servers SET status = 'stopping', heartbeat_at = ? WHERE server_id = ? AND status = 'running'", [context.now(), input.serverId]); if (changed.changes !== 1)
60
64
  throw new AppError("not_found", "Running merge-server was not found", 1, { server_id: input.serverId }); return { ok: true, server_id: input.serverId, status: "stopping" }; }
65
+ /** Both dispatchers enter the same project FIFO before creating any provider Session. */
66
+ export function claimQueuedMergeRequest(context, input) {
67
+ return context.db.writeTransaction(() => {
68
+ const request = context.db.get("SELECT merge_request_id, project_id, run_id, executor_work_id, target_workspace, execution_route, status, created_at FROM merge_requests WHERE merge_request_id = ?", [input.requestId]);
69
+ if (!request)
70
+ throw new AppError("not_found", "MERGE request was not found", 1);
71
+ const generation = assertRunMutationAllowed(context, request.project_id, request.run_id, input.expectedGeneration);
72
+ const earlier = context.db.get("SELECT 1 FROM merge_requests WHERE project_id = ? AND status NOT IN ('completed','failed','cancelled','superseded') AND (created_at < ? OR (created_at = ? AND merge_request_id < ?)) LIMIT 1", [request.project_id, request.created_at, request.created_at, request.merge_request_id]);
73
+ if (request.status !== "queued" || request.execution_route !== "server" || earlier)
74
+ return null;
75
+ const token = crypto.randomUUID();
76
+ context.db.run("UPDATE merge_requests SET status = 'dispatching', dispatch_owner = ?, dispatch_lease_token = ?, dispatch_lease_expires_at = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'queued'", [input.ownerId, token, new Date(Date.now() + 120_000).toISOString(), context.now(), request.merge_request_id]);
77
+ return { request, token, generation };
78
+ });
79
+ }
61
80
  async function dispatch(context, input) {
62
- const token = crypto.randomUUID();
63
- const leaseUntil = new Date(Date.now() + 120_000).toISOString();
64
- const claimed = context.db.run("UPDATE merge_requests SET status = 'dispatching', dispatch_owner = ?, dispatch_lease_token = ?, dispatch_lease_expires_at = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'queued' AND execution_route = 'server'", [input.serverId, token, leaseUntil, context.now(), input.request.merge_request_id]);
65
- if (claimed.changes !== 1)
81
+ const run = context.db.get("SELECT index_json, project_root FROM runs WHERE project_id = ? AND id = ?", [input.request.project_id, input.request.run_id]);
82
+ if (!run)
83
+ throw new AppError("not_found", "MERGE RUN was not found", 1, { run_id: input.request.run_id });
84
+ const snapshot = JSON.parse(run.index_json).execution_profile;
85
+ if (snapshot?.settings?.execution) {
86
+ if (!snapshot.agent_profiles)
87
+ throw new AppError("execution_profile_not_frozen", "MERGE dispatch requires frozen RUN agent profiles", 1, { run_id: input.request.run_id });
88
+ const resolved = resolveExecutionPolicy({ ddFlowHome: context.ddFlowHome, policy: snapshot.settings.execution, profiles: snapshot.agent_profiles, stage: "merge" });
89
+ input = { ...input, profile: resolved.coordinator };
90
+ }
91
+ const claim = claimQueuedMergeRequest(context, { requestId: input.request.merge_request_id, ownerId: input.serverId });
92
+ if (!claim)
66
93
  return;
67
- const leaseHeartbeat = setInterval(() => { const now = context.now(); context.db.run("UPDATE merge_requests SET dispatch_lease_expires_at = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'dispatching' AND dispatch_owner = ? AND dispatch_lease_token = ?", [new Date(Date.now() + 120_000).toISOString(), now, input.request.merge_request_id, input.serverId, token]); }, 30_000);
68
- leaseHeartbeat.unref();
94
+ const { generation, token } = claim;
69
95
  const stateDir = path.join(input.root, input.request.merge_request_id);
70
96
  fs.mkdirSync(stateDir, { recursive: true });
71
97
  const promptFile = path.join(stateDir, "launch.md");
72
98
  const adapterJournal = path.join(stateDir, "adapter.events.jsonl");
73
- const stageCommand = `${flowCommand(context)} stage start ${input.request.run_id} --stage merge --project-root ${JSON.stringify(input.request.target_workspace)} --json --progress-jsonl`;
74
- fs.writeFileSync(promptFile, `Start the assigned MERGE stage now. Your first tool call must be this exact standalone command:\n\n${stageCommand}\n\nTrust and follow the complete stage packet it returns. Continue through merge apply and stage finish. Stop only when the stage reaches a terminal result or explicitly requests user/operator action.\n`);
99
+ const flowExecutable = prepareHarnessFlowExecutable(context, stateDir);
100
+ let runtimeContext = { ...context, env: { ...context.env, DD_FLOW_BIN: flowExecutable } };
101
+ const runtimeOwner = { schema_id: "dd-flow/runtime-owner@1", owner_id: `run:${input.request.run_id}:merge:${input.request.merge_request_id}`, role: "merge", project_id: input.request.project_id, run_id: input.request.run_id, work_id: input.request.executor_work_id, operation_id: `${input.request.merge_request_id}:${token}`, state_dir: stateDir, dd_flow_home: context.ddFlowHome, dd_flow_bin: flowExecutable, resource_home: context.env.DD_FLOW_RESOURCE_HOME ?? context.ddFlowHome, budget: runtimeBudgetForRun(context, input.request.project_id, input.request.run_id) };
75
102
  event(input.journal, { type: "launch_intent", server_id: input.serverId, request_id: input.request.merge_request_id, token, profile: input.profile, prompt_file: promptFile, at: context.now() });
76
103
  input.progress?.(`launching ${input.request.merge_request_id} with ${input.profile.id}`);
77
104
  const executable = resolveHarnessCommand(context.ddFlowHome, input.profile.harness, "adapter");
78
- const common = ["--state-dir", stateDir, "--journal", adapterJournal, "--cwd", input.request.target_workspace, "--provider", input.profile.provider, "--model", input.profile.model, "--reasoning", input.profile.reasoning, "--mode", input.profile.mode, "--permission", input.profile.permission, "--project-root", input.request.target_workspace, "--dd-flow-home", context.ddFlowHome, ...harnessRuntimeArguments(context.ddFlowHome, input.profile.harness), "--json"];
105
+ const common = ["--dd-flow-bin", flowExecutable, "--state-dir", stateDir, "--journal", adapterJournal, "--cwd", input.request.target_workspace, "--provider", input.profile.provider, "--model", input.profile.model, "--reasoning", input.profile.reasoning, "--mode", input.profile.mode, "--permission", input.profile.permission, "--project-root", run.project_root, "--dd-flow-home", context.ddFlowHome, ...harnessRuntimeArguments(context.ddFlowHome, input.profile.harness), "--json"];
106
+ const retained = { profile: input.profile, executable, owner: runtimeOwner, session_id: null, state_dir: stateDir, create_operation_id: `${input.request.merge_request_id}:${token}:session.create`, prompt_operation_id: `${input.request.merge_request_id}:${token}:session.prompt` };
107
+ const retain = () => { context.db.run("UPDATE merge_requests SET adapter_receipt_json = ?, updated_at = ? WHERE merge_request_id = ? AND dispatch_owner = ? AND dispatch_lease_token = ?", [JSON.stringify(retained), context.now(), input.request.merge_request_id, input.serverId, token]); };
108
+ retain();
109
+ const leaseHeartbeat = setInterval(() => { if (guarded(context, input.request) || (recoveryGuard(context, input.request.project_id, input.request.run_id)?.generation ?? 0) !== generation)
110
+ return; const now = context.now(); context.db.run("UPDATE merge_requests SET dispatch_lease_expires_at = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'dispatching' AND dispatch_owner = ? AND dispatch_lease_token = ?", [new Date(Date.now() + 120_000).toISOString(), now, input.request.merge_request_id, input.serverId, token]); }, 30_000);
111
+ leaseHeartbeat.unref();
79
112
  try {
80
- const adapterCall = (args, timeoutMs, progressMessage) => runHarnessAdapter({ executable, args, env: context.env, ...(timeoutMs ? { timeoutMs } : {}), ...(input.progress ? { progress: input.progress } : {}), ...(progressMessage ? { progressMessage } : {}), onEvidence: (value) => event(input.journal, { type: "adapter_call", ...value }) });
113
+ const adapterCall = (args, timeoutMs, progressMessage) => { assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation); return runHarnessAdapter({ executable, args, env: runtimeContext.env, runtimeOwner, operationId: `${input.request.merge_request_id}:${token}:${args[0]}.${args[1]}`, ...(timeoutMs ? { timeoutMs } : {}), ...(input.progress ? { progress: input.progress } : {}), ...(progressMessage ? { progressMessage } : {}), onEvidence: (value) => event(input.journal, { type: "adapter_call", ...value }) }); };
81
114
  await adapterCall(["daemon", "start", ...common]);
82
115
  const created = await adapterCall(["session", "create", ...common]);
83
116
  const sessionId = adapterSessionId(created);
84
117
  if (!sessionId)
85
118
  throw new AppError("merge_adapter_invalid", "Harness adapter did not return a Session id", 1, { harness: input.profile.harness, response: created });
119
+ Object.assign(retained, { session_id: sessionId, create: created });
120
+ retain();
121
+ runtimeContext = managedInvocationContext(runtimeContext, { harness: runtimeHarness(input.profile), stateDir, sessionId, projectRoot: run.project_root, runId: input.request.run_id, generation });
122
+ const stageCommand = managedLifecycleCommand(runtimeContext, `${flowCommand(runtimeContext)} stage start ${input.request.run_id} --stage merge --project-root ${JSON.stringify(run.project_root)} --json --progress-jsonl`);
123
+ fs.writeFileSync(promptFile, `Start the assigned MERGE stage now. Your first tool call must be this exact standalone command:\n\n${stageCommand}\n\nTrust and follow the complete stage packet it returns. Continue through merge apply and stage finish. Stop only when the stage reaches a terminal result or explicitly requests user/operator action.\n\n${stageLifecycleInstruction}\n`);
86
124
  const prompted = await adapterCall(["session", "prompt", "--session-id", sessionId, "--prompt-file", promptFile, ...common], 45 * 60 * 1000, `MERGE ${input.request.merge_request_id} Session ${sessionId} is still running`);
125
+ Object.assign(retained, { response: prompted });
126
+ retain();
127
+ assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation);
87
128
  const request = context.db.get("SELECT status FROM merge_requests WHERE merge_request_id = ?", [input.request.merge_request_id]);
88
- context.db.run("UPDATE merge_requests SET adapter_receipt_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ profile: input.profile, executable, session_id: sessionId, response: prompted }), context.now(), input.request.merge_request_id]);
89
129
  event(input.journal, { type: "adapter_settled", request_id: input.request.merge_request_id, session_id: sessionId, request_status: request?.status ?? null, at: context.now() });
90
130
  if (request?.status === "dispatching")
91
- context.db.run("UPDATE merge_requests SET status = 'queued', dispatch_owner = NULL, dispatch_lease_token = NULL, dispatch_lease_expires_at = NULL, last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "adapter_did_not_start_stage", response: prompted }), context.now(), input.request.merge_request_id]);
131
+ context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "adapter_did_not_start_stage", response: prompted }), context.now(), input.request.merge_request_id]);
92
132
  }
93
133
  catch (error) {
134
+ if (error instanceof AppError && ["run_recovery_guarded", "run_recovery_generation_stale"].includes(error.code)) {
135
+ event(input.journal, { type: "recovery_dispatch_blocked", request_id: input.request.merge_request_id, code: error.code, at: context.now() });
136
+ throw error;
137
+ }
94
138
  const request = context.db.get("SELECT status FROM merge_requests WHERE merge_request_id = ?", [input.request.merge_request_id]);
95
139
  if (request?.status === "dispatching")
96
- context.db.run("UPDATE merge_requests SET status = 'queued', dispatch_owner = NULL, dispatch_lease_token = NULL, dispatch_lease_expires_at = NULL, last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "adapter_launch_failed", error: String(error) }), context.now(), input.request.merge_request_id]);
140
+ context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "adapter_launch_failed", error: String(error) }), context.now(), input.request.merge_request_id]);
97
141
  else if (request?.status === "active")
98
142
  context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "adapter_lost_after_stage_start", error: String(error) }), context.now(), input.request.merge_request_id]);
99
143
  throw error;
@@ -102,23 +146,17 @@ async function dispatch(context, input) {
102
146
  clearInterval(leaseHeartbeat);
103
147
  }
104
148
  }
105
- function nextServerRequests(context, limit) { const selected = new Set(); return context.db.all("SELECT merge_request_id, project_id, run_id, executor_work_id, target_workspace, execution_route, status, created_at FROM merge_requests WHERE status = 'queued' AND execution_route = 'server' ORDER BY created_at, merge_request_id").filter((request) => { if (selected.has(request.project_id) || context.db.get("SELECT 1 FROM merge_requests WHERE project_id = ? AND status NOT IN ('completed','failed','cancelled') AND (created_at < ? OR (created_at = ? AND merge_request_id < ?)) LIMIT 1", [request.project_id, request.created_at, request.created_at, request.merge_request_id]))
149
+ function nextServerRequests(context, limit) { const selected = new Set(); return context.db.all("SELECT merge_request_id, project_id, run_id, executor_work_id, target_workspace, execution_route, status, created_at FROM merge_requests WHERE status = 'queued' AND execution_route = 'server' ORDER BY created_at, merge_request_id").filter((request) => { if (guarded(context, request) || selected.has(request.project_id) || context.db.get("SELECT 1 FROM merge_requests WHERE project_id = ? AND status NOT IN ('completed','failed','cancelled','superseded') AND (created_at < ? OR (created_at = ? AND merge_request_id < ?)) LIMIT 1", [request.project_id, request.created_at, request.created_at, request.merge_request_id]))
106
150
  return false; selected.add(request.project_id); return true; }).slice(0, limit); }
107
- function reconcileExpiredDispatches(context) { const expired = context.db.all("SELECT merge_request_id, executor_work_id FROM merge_requests WHERE status = 'dispatching' AND dispatch_lease_expires_at < ?", [context.now()]); for (const request of expired) {
151
+ function reconcileExpiredDispatches(context) { const expired = context.db.all("SELECT merge_request_id, executor_work_id, project_id, run_id FROM merge_requests WHERE status = 'dispatching' AND dispatch_lease_expires_at < ?", [context.now()]); for (const request of expired) {
152
+ if (guarded(context, request))
153
+ continue;
108
154
  const work = context.db.get("SELECT status FROM works WHERE work_id = ?", [request.executor_work_id]);
109
- if (work?.status === "created")
110
- context.db.run("UPDATE merge_requests SET status = 'queued', dispatch_owner = NULL, dispatch_lease_token = NULL, dispatch_lease_expires_at = NULL, last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "expired_dispatch_requeued" }), context.now(), request.merge_request_id]);
111
- else
112
- context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "expired_dispatch_with_started_work", work_status: work?.status ?? null }), context.now(), request.merge_request_id]);
155
+ context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "expired_dispatch_outcome_unknown", work_status: work?.status ?? null }), context.now(), request.merge_request_id]);
113
156
  } }
114
- function loadProfile(context, id) { const file = path.join(context.ddFlowHome, "agent-profiles", `${id}.json`); let value; try {
115
- value = JSON.parse(fs.readFileSync(file, "utf8"));
116
- }
117
- catch (error) {
118
- throw new AppError("agent_profile_missing", "Merge-server agent profile is unavailable", 1, { id, file, cause: String(error) });
119
- } validateSchema({ schemaName: "agent-profile", file }); if (value.id !== id)
120
- throw new AppError("agent_profile_invalid", "Agent profile id does not match its requested filename", 2, { file, expected: id, actual: value.id ?? null }); return value; }
157
+ function loadProfile(context, id) { return loadAgentProfile(context.ddFlowHome, id); }
121
158
  function event(file, value) { fs.appendFileSync(file, `${JSON.stringify(value)}\n`); }
159
+ function guarded(context, request) { const guard = recoveryGuard(context, request.project_id, request.run_id); return Boolean(guard && ["draining", "sealed", "resuming"].includes(guard.status)); }
122
160
  function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
123
161
  function processAlive(pid) { if (!pid)
124
162
  return false; try {
@@ -6,10 +6,12 @@ import { requireProjectByRoot } from "./projects.js";
6
6
  import { getProjectVersionStatus, resolveStatusProjectRoot } from "./version-status.js";
7
7
  import { resolveCanonRoot } from "./canon.js";
8
8
  import { getDatabase } from "../storage/database.js";
9
+ import { cleanupScopeWriters } from "./scope-writer-cleanup.js";
9
10
  import { resolveProjectRoot } from "../storage/paths.js";
10
11
  import { classifyCliOperation } from "./cli-operation-classifier.js";
11
12
  import { compatibilityContexts, selectEngine } from "./engines.js";
12
13
  import { getCliBuildInfo } from "./build-info.js";
14
+ import { prepareJsonFile } from "../cli/input-preparation.js";
13
15
  export function assessMigrationImpact(context, input) {
14
16
  const root = resolveStatusProjectRoot({ requestedRoot: input.projectRoot, cwd: process.cwd() });
15
17
  if (!root.root)
@@ -147,7 +149,7 @@ export function planMigration(context, input) {
147
149
  }
148
150
  };
149
151
  }
150
- export function applyMigration(context, input) {
152
+ export function prepareMigrationApply(context, input) {
151
153
  const classification = input.classification ?? classifyCliOperation(["migration", "apply"], context.env);
152
154
  if (classification.mode !== "mb_upgrade") {
153
155
  throw new AppError("upgrade_authorization_required", "Migration apply requires explicit mb-upgrade authorization", 1, {
@@ -197,7 +199,33 @@ export function applyMigration(context, input) {
197
199
  });
198
200
  }
199
201
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
202
+ const current = activeStateSummary(context, project.id);
203
+ if (activeStateBlockers(current).length)
204
+ throw new AppError("migration_active_state", "Migration apply requires a quiescent shared home", 1, { active_state: current });
205
+ return { project, sourceVersion, targetVersion, verifiedBackup, reportEngine, chain };
206
+ }
207
+ export function applyMigration(context, input, prepared = prepareMigrationApply(context, input)) {
200
208
  const writeDb = getDatabase(context.ddFlowHome, "migrate");
209
+ let result, primary, failed = false;
210
+ try {
211
+ result = applyPreparedMigration(context, prepared, writeDb);
212
+ }
213
+ catch (error) {
214
+ primary = error;
215
+ failed = true;
216
+ }
217
+ const cleanup = cleanupScopeWriters([{ name: writeDb.path, db: writeDb, rollback: false, close: "always" }]);
218
+ if (failed) {
219
+ if (primary instanceof AppError && cleanup.length)
220
+ primary.details.migration_cleanup_errors = cleanup;
221
+ throw primary;
222
+ }
223
+ if (cleanup.length)
224
+ throw new AppError("migration_cleanup_failed", "Migration receipt is available but its connection could not be closed", 1, { effect: result?.changed ? "committed" : "no_effect", migration_cleanup_errors: cleanup });
225
+ return result;
226
+ }
227
+ function applyPreparedMigration(context, prepared, writeDb) {
228
+ const { project, sourceVersion, targetVersion, verifiedBackup, reportEngine, chain } = prepared;
201
229
  const already = writeDb.get("SELECT value_json FROM runtime_config WHERE key = ?", [applyKey(project.id, sourceVersion, targetVersion)]);
202
230
  if (already) {
203
231
  return { ok: true, schema_id: "dd-flow/mb-upgrade-migration-apply@1", status: "verified_noop", changed: false, backup: verifiedBackup, recovery: JSON.parse(already.value_json) };
@@ -217,15 +245,14 @@ export function applyMigration(context, input) {
217
245
  chain: chain.steps.map((step) => ({ ...step, status: "applied" }))
218
246
  };
219
247
  try {
220
- writeDb.exec("BEGIN IMMEDIATE");
221
- writeDb.run(`INSERT INTO runtime_config (key, value_json, created_at, updated_at) VALUES (?, ?, ?, ?)`, [applyKey(project.id, sourceVersion, targetVersion), JSON.stringify(result), context.now(), context.now()]);
222
- writeDb.exec("COMMIT");
248
+ writeDb.writeTransaction(() => {
249
+ const current = activeStateSummary({ ...context, db: writeDb }, project.id);
250
+ if (activeStateBlockers(current).length)
251
+ throw new AppError("migration_active_state", "Migration apply requires a quiescent shared home", 1, { active_state: current });
252
+ writeDb.run(`INSERT INTO runtime_config (key, value_json, created_at, updated_at) VALUES (?, ?, ?, ?)`, [applyKey(project.id, sourceVersion, targetVersion), JSON.stringify(result), context.now(), context.now()]);
253
+ });
223
254
  }
224
255
  catch (error) {
225
- try {
226
- writeDb.exec("ROLLBACK");
227
- }
228
- catch { /* preserve the original failure */ }
229
256
  throw new AppError("migration_apply_failed", "Migration apply failed before upgrade RUN creation or canon sync", 1, {
230
257
  recovery: {
231
258
  status: "required",
@@ -235,7 +262,7 @@ export function applyMigration(context, input) {
235
262
  rollback_route: "restore the verified backup before retrying mb-upgrade apply",
236
263
  next_action: "inspect the failed apply and retry only with the same pinned target contract"
237
264
  },
238
- cause: String(error)
265
+ cause: error instanceof AppError ? { code: error.code, message: error.message, details: error.details } : String(error)
239
266
  });
240
267
  }
241
268
  return { ok: true, schema_id: "dd-flow/mb-upgrade-migration-apply@1", status: "applied", changed: true, backup: verifiedBackup, recovery: result };
@@ -513,13 +540,7 @@ function activeStateBlockers(active) {
513
540
  return blockers;
514
541
  }
515
542
  function readJsonObject(filePath) {
516
- let parsed;
517
- try {
518
- parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
519
- }
520
- catch (error) {
521
- throw new AppError("invalid_json", `Cannot read migration report: ${filePath}`, 2, { cause: String(error) });
522
- }
543
+ const { value: parsed } = prepareJsonFile(filePath, "Migration report");
523
544
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
524
545
  throw new AppError("validation", "Migration report must be a JSON object", 2, { file: filePath });
525
546
  }
@@ -0,0 +1,49 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { AppError } from "../shared/errors.js";
5
+ import { managedProcessBinding, managedProcessStatus, processTreeIsAlive, resourceHome } from "./managed-processes.js";
6
+ import { retainedDaemonOperations } from "./run-control.js";
7
+ import { managedProviderBelongsToDaemon } from "./managed-daemon-binding.js";
8
+ /** A replaced daemon is a settled resource, never another Session to resume. */
9
+ export function historicalDaemonSettlement(context, scopeId, record) {
10
+ const metadata = JSON.parse(record.metadata_json);
11
+ if (!record.kind.endsWith("-daemon") || !metadata.state_dir || !path.isAbsolute(metadata.state_dir))
12
+ throw new AppError("runtime_scope_owner_unknown", "Native history requires an absolute daemon directory", 1);
13
+ const current = JSON.parse(fs.readFileSync(path.join(metadata.state_dir, "daemon.json"), "utf8"));
14
+ if (current.resource_process?.id === record.id)
15
+ return null;
16
+ if (record.state !== "stopped" || record.termination_reason !== "daemon_stopped" || !record.pid || !record.pid_started_at || processTreeIsAlive(record))
17
+ throw new AppError("runtime_scope_owner_unknown", "Previous daemon has no physical completion proof", 1);
18
+ const directory = path.join(metadata.state_dir, "daemon-history");
19
+ const matches = fs.readdirSync(directory).filter(name => /^[a-zA-Z0-9-]+\.json$/.test(name)).map(name => {
20
+ const file = path.join(directory, name);
21
+ if (!fs.lstatSync(file).isFile())
22
+ throw new AppError("runtime_scope_owner_unknown", "Daemon history must contain regular receipts", 1);
23
+ const bytes = fs.readFileSync(file, "utf8");
24
+ return { file, bytes, state: JSON.parse(bytes) };
25
+ }).filter(candidate => candidate.state.resource_process?.id === record.id);
26
+ if (matches.length !== 1)
27
+ throw new AppError("runtime_scope_owner_unknown", "Previous daemon has no unique retained receipt", 1);
28
+ const { file, bytes, state } = matches[0], owner = state.config?.runtime_owner;
29
+ if (!state.daemon_id || path.basename(file) !== `${state.daemon_id}.json` || !owner || owner.budget?.scope_id !== scopeId || owner.owner_id !== record.owner_id || owner.role !== metadata.role || owner.state_dir !== metadata.state_dir || owner.adapter_executable !== metadata.adapter_executable || owner.dd_flow_home !== metadata.dd_flow_home || owner.resource_home !== resourceHome(context) || (owner.project_id ?? null) !== record.project_id || (owner.run_id ?? null) !== record.run_id || (owner.work_id ?? null) !== record.work_id || !record.operation_id?.startsWith(`${owner.operation_id}:`) || state.resource_process?.lease_token !== record.lease_token || state.pid !== record.pid)
30
+ throw new AppError("runtime_scope_owner_unknown", "Archived daemon does not match its registration", 1);
31
+ const closed = state.shutdown_state === "clean" && state.active_tree === false
32
+ ? retainedDaemonOperations(metadata.state_dir).find(operation => operation.daemon_id === state.daemon_id && operation.operation === "daemon.stop" && operation.state === "completed" && operation.result?.stopped === true && operation.result?.clean === true) : undefined;
33
+ const fresh = managedProcessStatus(context).find(item => item.id === record.id);
34
+ if (!closed || !fresh || fresh.lease_token !== record.lease_token || fresh.pid !== record.pid || fresh.pid_started_at !== record.pid_started_at || fresh.metadata_json !== record.metadata_json || fresh.state !== "stopped" || fresh.termination_reason !== "daemon_stopped" || processTreeIsAlive(fresh) || fs.readFileSync(file, "utf8") !== bytes)
35
+ throw new AppError("runtime_scope_outcome_unknown", "Previous daemon lacks stable clean shutdown evidence", 1);
36
+ const providers = managedProcessStatus(context).filter(item => managedProviderBelongsToDaemon(item, fresh, state));
37
+ if (state.provider_process && (providers.length !== 1 || providers[0].state !== "stopped" || providers[0].termination_reason !== "daemon_stopped" || !providers[0].operation_id?.startsWith(`${owner.operation_id}:`) || processTreeIsAlive(providers[0])))
38
+ throw new AppError("runtime_scope_outcome_unknown", "Archived provider lacks its exact physical completion proof", 1);
39
+ return { historical: true, process_id: record.id, role: metadata.role, state_dir: metadata.state_dir, daemon_id: state.daemon_id,
40
+ processes: providers.map(item => ({ process_id: item.id, native_settled: true, binding: managedProcessBinding(item, resourceHome(context)) })),
41
+ settled: true, native_settled: true, operation_id: String(closed.operation_id), owner_operation_id: owner.operation_id,
42
+ inventory_version: crypto.createHash("sha256").update(JSON.stringify([bytes, closed])).digest("hex") };
43
+ }
44
+ export function assertHistoricalDaemonSettlement(context, scopeId, proof) {
45
+ const record = managedProcessStatus(context).find(item => item.id === proof.process_id);
46
+ const fresh = record && historicalDaemonSettlement(context, scopeId, record);
47
+ if (!fresh || proof.historical !== true || proof.native_settled !== true || fresh.inventory_version !== proof.inventory_version)
48
+ throw new AppError("runtime_scope_inventory_changed", "Archived daemon settlement changed after observation", 1);
49
+ }
@@ -0,0 +1,39 @@
1
+ import { AppError } from "../shared/errors.js";
2
+ import { adapterSessionId, runHarnessAdapter } from "./harness-adapter.js";
3
+ export async function cancelControlledNativeSession(input) {
4
+ input.assertCurrent();
5
+ const reply = await runHarnessAdapter({ executable: input.executable,
6
+ args: input.observe ? ["daemon", "operation", "--operation-id", input.operationId, "--state-dir", input.stateDir, "--json"] : ["session", "cancel", "--session-id", input.sessionId, "--state-dir", input.stateDir, "--json"],
7
+ env: input.env, operationId: input.observe ? `${input.operationId}:observe` : input.operationId, timeoutMs: 30_000 });
8
+ if (input.observe && (reply.operation_id !== input.operationId || reply.operation !== "session.cancel" || reply.session_id !== input.sessionId))
9
+ throw new AppError("controller_operation_mismatch", "Cancellation observation belongs to another operation or Session", 1);
10
+ if (input.observe && reply.state === "failed") {
11
+ if (!reply.error || typeof reply.error !== "object" || Array.isArray(reply.error))
12
+ throw new AppError("controller_operation_mismatch", "Cancellation failure has no terminal error", 1);
13
+ input.assertCurrent();
14
+ return { status: "failed", receipt: reply };
15
+ }
16
+ const result = input.observe ? reply.state === "completed" ? reply.result : null : reply;
17
+ // A completed cancel command is an immutable ACK, not proof that the
18
+ // provider tree has stopped. Callers must use a separate fresh inspection.
19
+ if (!input.observe || reply.state === "completed")
20
+ assertNativeCancellationReceipt(result, input.sessionId);
21
+ input.assertCurrent();
22
+ return { status: result ? "completed" : "outcome_unknown", receipt: (result ?? reply) };
23
+ }
24
+ export function assertNativeCancellationReceipt(value, sessionId) {
25
+ const identity = adapterSessionId(value);
26
+ if (!value || typeof value !== "object" || Array.isArray(value) || identity && identity !== sessionId)
27
+ throw new AppError("controller_operation_mismatch", "Cancellation receipt has no valid result for its target Session", 1);
28
+ }
29
+ /** Native observation is shared by RUN and non-Work EVAL owners. */
30
+ export async function inspectControlledNativeSession(input) {
31
+ input.assertCurrent();
32
+ const receipt = await runHarnessAdapter({ executable: input.executable, args: ["session", "inspect", "--session-id", input.sessionId, "--state-dir", input.stateDir, ...(input.settlementObservation ? ["--no-flow"] : []), "--json"], env: input.env, operationId: input.operationId, timeoutMs: 30_000 });
33
+ if (adapterSessionId(receipt) !== input.sessionId)
34
+ throw new AppError("controller_operation_mismatch", "Session observation belongs to another target", 1);
35
+ if (input.harness && receipt.harness !== undefined && receipt.harness !== input.harness)
36
+ throw new AppError("controller_operation_mismatch", "Session observation belongs to another harness", 1);
37
+ input.assertCurrent();
38
+ return receipt;
39
+ }
@@ -6,18 +6,24 @@ import { parseJsonObject } from "../shared/json.js";
6
6
  import { refreshRunSessionProjection } from "./run-projection.js";
7
7
  export function readCanonicalPlan(planPath, protocolId) {
8
8
  if (!fs.existsSync(planPath) || !fs.statSync(planPath).isFile()) {
9
- throw new AppError("not_found", `Canonical protocol plan is missing: ${planPath}`, 1, { plan_path: planPath });
9
+ throw new AppError("runtime_artifact_missing", `Canonical protocol plan is missing: ${planPath}`, 1, { plan_path: planPath });
10
10
  }
11
11
  const raw = fs.readFileSync(planPath, "utf8");
12
- const value = parseJsonObject(raw, planPath);
13
- const plan = validatePlan(value, protocolId);
14
- const revisionValue = value.revision;
15
- const revision = typeof revisionValue === "number" && Number.isInteger(revisionValue) && revisionValue > 0 ? revisionValue : 1;
16
- return { plan, raw, sha256: crypto.createHash("sha256").update(raw).digest("hex"), revision };
12
+ try {
13
+ const value = parseJsonObject(raw, planPath);
14
+ const plan = validatePlan(value, protocolId);
15
+ const revisionValue = value.revision;
16
+ const revision = typeof revisionValue === "number" && Number.isInteger(revisionValue) && revisionValue > 0 ? revisionValue : 1;
17
+ return { plan, raw, sha256: crypto.createHash("sha256").update(raw).digest("hex"), revision };
18
+ }
19
+ catch (error) {
20
+ if (!(error instanceof AppError) || error.code !== "validation")
21
+ throw error;
22
+ throw new AppError("runtime_artifact_invalid", "Canonical protocol plan is invalid", 1, { plan_path: planPath, cause_code: error.code });
23
+ }
17
24
  }
18
- export function boundCanonicalPlan(context, input) {
19
- const canonical = readCanonicalPlan(input.planPath, input.protocolId);
20
- const binding = context.db.get("SELECT plan_revision, plan_sha256, plan_path FROM plan_bindings WHERE project_id = ? AND protocol_id = ?", [input.projectId, input.protocolId]);
25
+ export function prepareCanonicalPlan(context, input, canonical = readCanonicalPlan(input.planPath, input.protocolId)) {
26
+ const binding = context.db.get("SELECT plan_id, plan_revision, plan_sha256, plan_path FROM plan_bindings WHERE project_id = ? AND protocol_id = ?", [input.projectId, input.protocolId]);
21
27
  if (binding && (binding.plan_revision !== canonical.revision || binding.plan_sha256 !== canonical.sha256)) {
22
28
  throw new AppError("plan_stale", "Canonical plan changed after the runtime binding was created", 1, {
23
29
  protocol_id: input.protocolId,
@@ -28,10 +34,19 @@ export function boundCanonicalPlan(context, input) {
28
34
  plan_path: input.planPath
29
35
  });
30
36
  }
37
+ return canonical;
38
+ }
39
+ export function boundCanonicalPlan(context, input, prepared) {
40
+ const canonical = prepareCanonicalPlan(context, input, prepared);
41
+ const binding = context.db.get("SELECT plan_id, plan_revision, plan_sha256, plan_path FROM plan_bindings WHERE project_id = ? AND protocol_id = ?", [input.projectId, input.protocolId]);
31
42
  const now = context.now();
32
43
  if (!binding) {
33
- context.db.run(`INSERT INTO plan_bindings (project_id, protocol_id, plan_revision, plan_sha256, plan_path, bound_at, updated_at)
34
- VALUES (?, ?, ?, ?, ?, ?, ?)`, [input.projectId, input.protocolId, canonical.revision, canonical.sha256, input.planPath, now, now]);
44
+ context.db.run(`INSERT INTO plan_bindings (project_id, protocol_id, plan_id, plan_revision, plan_sha256, plan_path, bound_at, updated_at)
45
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [input.projectId, input.protocolId, canonical.plan.plan_id, canonical.revision, canonical.sha256, input.planPath, now, now]);
46
+ }
47
+ else if (binding.plan_id === null) {
48
+ // Older bindings are upgraded when their canonical source is validated.
49
+ context.db.run("UPDATE plan_bindings SET plan_id = ?, updated_at = ? WHERE project_id = ? AND protocol_id = ? AND plan_id IS NULL", [canonical.plan.plan_id, now, input.projectId, input.protocolId]);
35
50
  }
36
51
  for (const item of canonical.plan.items) {
37
52
  context.db.run(`INSERT INTO plan_progress
@@ -4,7 +4,7 @@ import { appendAudit } from "./audit.js";
4
4
  import { persistProtocolState, readProtocolRuntimeState, requireProtocol } from "./protocols.js";
5
5
  import { requireProjectByRoot } from "./projects.js";
6
6
  import { resolveProjectRoot } from "../storage/paths.js";
7
- import { planSummary, planWithProgress, updatePlanProgress } from "./plan-runtime.js";
7
+ import { planSummary, planWithProgress, prepareCanonicalPlan, updatePlanProgress } from "./plan-runtime.js";
8
8
  export function getPlanStatus(context, input) {
9
9
  const protocol = scopedProtocol(context, input.projectRoot, input.protocolId);
10
10
  const current = planWithProgress(context, { projectId: protocol.project_id, protocolId: protocol.id, planPath: protocol.plan_path }, { bind: false });
@@ -20,40 +20,43 @@ export function getPlanStatus(context, input) {
20
20
  };
21
21
  }
22
22
  export function startPlanItem(context, input) {
23
- return updatePlanItem(context, input.projectRoot, input.protocolId, input.itemId, (item, plan) => {
24
- assertDependenciesClosed(plan, item);
25
- return { ...item, status: "in_progress", summary: item.summary || "Started." };
26
- });
23
+ return updatePlanItem(context, { ...input, action: "start" });
27
24
  }
28
25
  export function completePlanItem(context, input) {
29
- return updatePlanItem(context, input.projectRoot, input.protocolId, input.itemId, (item, plan) => {
30
- assertDependenciesClosed(plan, item);
31
- return { ...item, status: "done", summary: input.summary, evidence: [...new Set([...item.evidence, ...input.evidence])] };
32
- });
26
+ return updatePlanItem(context, { ...input, action: "done" });
33
27
  }
34
28
  export function blockPlanItem(context, input) {
35
- return updatePlanItem(context, input.projectRoot, input.protocolId, input.itemId, (item) => ({
36
- ...item,
37
- status: "blocked",
38
- summary: input.reason,
39
- block_reason: input.reason,
40
- user_required: input.userRequired
41
- }));
29
+ return updatePlanItem(context, { ...input, action: "block" });
42
30
  }
43
31
  export function skipPlanItem(context, input) {
44
- return updatePlanItem(context, input.projectRoot, input.protocolId, input.itemId, (item) => ({
45
- ...item,
46
- status: "skipped",
47
- summary: input.reason
48
- }));
32
+ return updatePlanItem(context, { ...input, action: "skip" });
49
33
  }
50
- function updatePlanItem(context, projectRoot, protocolId, itemId, transform) {
34
+ export function preparePlanItemMutation(context, input) {
35
+ const { projectRoot, protocolId, itemId } = input;
36
+ const text = (value) => typeof value === "string" && value.trim().length > 0;
37
+ if (!text(itemId) || !["start", "done", "block", "skip"].includes(input.action) ||
38
+ (input.action === "done" && (!text(input.summary) || !Array.isArray(input.evidence) || !input.evidence.every(text))) ||
39
+ ((input.action === "block" || input.action === "skip") && !text(input.reason)) ||
40
+ (input.action === "block" && typeof input.userRequired !== "boolean")) {
41
+ throw new AppError("validation", "Plan item requires a valid action, item ID, nonempty summary/reason, text evidence and boolean userRequired", 2, { phase: "prepare", effect: "no_effect", recoverable: true });
42
+ }
51
43
  const protocol = scopedProtocol(context, projectRoot, protocolId);
52
- const current = planWithProgress(context, { projectId: protocol.project_id, protocolId: protocol.id, planPath: protocol.plan_path });
44
+ const scope = { projectId: protocol.project_id, protocolId: protocol.id, planPath: protocol.plan_path };
45
+ const current = planWithProgress(context, scope, { bind: false });
46
+ prepareCanonicalPlan(context, scope, current.canonical);
53
47
  const item = current.plan.items.find((candidate) => candidate.id === itemId);
54
48
  if (!item)
55
49
  throw new AppError("not_found", `Plan item is not found: ${itemId}`, 1);
56
- const nextItem = transform(item, current.plan);
50
+ if (input.action === "start" || input.action === "done")
51
+ assertDependenciesClosed(current.plan, item);
52
+ const nextItem = input.action === "start" ? { ...item, status: "in_progress", summary: item.summary || "Started." }
53
+ : input.action === "done" ? { ...item, status: "done", summary: input.summary, evidence: [...new Set([...item.evidence, ...input.evidence])] }
54
+ : input.action === "block" ? { ...item, status: "blocked", summary: input.reason, block_reason: input.reason, user_required: input.userRequired }
55
+ : { ...item, status: "skipped", summary: input.reason };
56
+ return { protocol, item, nextItem };
57
+ }
58
+ export function updatePlanItem(context, input) {
59
+ const { protocol, item, nextItem } = preparePlanItemMutation(context, input);
57
60
  updatePlanProgress(context, { projectId: protocol.project_id, protocolId: protocol.id, planPath: protocol.plan_path, item: nextItem });
58
61
  if (nextItem.status === "done") {
59
62
  context.db.run("UPDATE flow_jobs SET status = 'done', finished_at = COALESCE(finished_at, ?), updated_at = ? WHERE project_id = ? AND protocol_id = ? AND plan_item_id = ?", [context.now(), context.now(), protocol.project_id, protocol.id, nextItem.id]);
@@ -63,7 +66,7 @@ function updatePlanItem(context, projectRoot, protocolId, itemId, transform) {
63
66
  protocolId: protocol.id,
64
67
  projectId: protocol.project_id,
65
68
  eventType: "plan.progress.updated",
66
- payload: { protocol_id: protocol.id, item_id: itemId, from: item.status, to: nextItem.status }
69
+ payload: { protocol_id: protocol.id, item_id: input.itemId, from: item.status, to: nextItem.status }
67
70
  });
68
71
  return { ok: true, protocol_id: protocol.id, item: nextItem, plan: planSummary(context, { projectId: protocol.project_id, protocolId: protocol.id, planPath: protocol.plan_path }) };
69
72
  }
@@ -1,5 +1,6 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { foreignKeyTransaction } from "../storage/foreign-key-transaction.js";
3
4
  import { formatFullId, isFullEntityId, isShortEntityId, parseFullEntityId, slugFromRoot } from "../domain/entity-ids.js";
4
5
  import { AppError } from "../shared/errors.js";
5
6
  import { projectRuntimeRoot, resolveProjectRoot } from "../storage/paths.js";
@@ -37,8 +38,13 @@ export function registerProject(context, input) {
37
38
  }
38
39
  return { ok: true, project: { ...project, status: "active", updated_at: now }, db_path: context.db.path };
39
40
  }
40
- export function archiveProject(context, input) {
41
- const reason = input.reason.trim();
41
+ export function prepareProjectArchive(context, input) {
42
+ if (Boolean(input.idOrAlias) === Boolean(input.root))
43
+ throw new AppError("usage", "Project archive requires exactly one project ID/alias or --root", 2);
44
+ for (const value of [input.idOrAlias, input.root])
45
+ if (value !== undefined && (typeof value !== "string" || !value.trim()))
46
+ throw new AppError("validation", "Project archive target must be a non-empty string", 2);
47
+ const reason = typeof input.reason === "string" ? input.reason.trim() : "";
42
48
  if (!reason) {
43
49
  throw new AppError("validation", "project archive requires --reason", 2);
44
50
  }
@@ -50,6 +56,10 @@ export function archiveProject(context, input) {
50
56
  if (!project) {
51
57
  throw new AppError("not_found", "Project is not registered.", 1, { root: input.root, input: input.idOrAlias });
52
58
  }
59
+ return { project, reason };
60
+ }
61
+ export function archiveProject(context, input) {
62
+ const { project, reason } = prepareProjectArchive(context, input);
53
63
  const now = context.now();
54
64
  const result = context.db.run("UPDATE projects SET status = 'archived', updated_at = ? WHERE id = ? AND status <> 'archived'", [now, project.id]);
55
65
  if (result.changes === 1) {
@@ -139,9 +149,7 @@ export function migrateProjectIds(context, input) {
139
149
  if (conflictingProject) {
140
150
  throw new AppError("conflict", `Target project id already exists: ${target.id}`, 1, plan);
141
151
  }
142
- context.db.exec("PRAGMA foreign_keys = OFF");
143
- context.db.exec("BEGIN IMMEDIATE");
144
- try {
152
+ foreignKeyTransaction(context.db, () => {
145
153
  context.db.run("UPDATE projects SET id = ?, short_id = ?, slug = ?, state_root = ?, updated_at = ? WHERE id = ?", [target.id, target.short_id, target.slug, target.state_root, now, oldId]);
146
154
  for (const table of projectReferenceTables()) {
147
155
  context.db.run(`UPDATE ${table} SET project_id = ? WHERE project_id = ?`, [target.id, oldId]);
@@ -153,14 +161,7 @@ export function migrateProjectIds(context, input) {
153
161
  foreign_key_errors: foreignKeyErrors
154
162
  });
155
163
  }
156
- context.db.exec("COMMIT");
157
- context.db.exec("PRAGMA foreign_keys = ON");
158
- }
159
- catch (error) {
160
- context.db.exec("ROLLBACK");
161
- context.db.exec("PRAGMA foreign_keys = ON");
162
- throw error;
163
- }
164
+ });
164
165
  appendAudit(context, {
165
166
  projectId: target.id,
166
167
  eventType: "project.id_migrated",
@@ -232,9 +233,13 @@ export function findProjectByRoot(context, root) {
232
233
  return context.db.get("SELECT * FROM projects WHERE root = ?", [root]);
233
234
  }
234
235
  export function requireProjectByRoot(context, root) {
235
- const project = findProjectByRoot(context, root);
236
+ // Callers may receive a path through a native adapter or shell. Resolve
237
+ // aliases such as macOS `/var` -> `/private/var` before comparing with the
238
+ // canonical root persisted in the project registry.
239
+ const canonical = normalizeStoredRoot(root);
240
+ const project = findProjectByRoot(context, canonical);
236
241
  if (!project) {
237
- throw new AppError("not_found", `Project is not registered: ${root}`, 1);
242
+ throw new AppError("not_found", `Project is not registered: ${canonical}`, 1);
238
243
  }
239
244
  return project;
240
245
  }