@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.133
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.
- package/CHANGELOG.md +666 -0
- package/README.md +101 -1
- package/dist/build-info.json +10 -10
- package/dist/cli/argument-values.js +38 -0
- package/dist/cli/command-inputs.js +306 -0
- package/dist/cli/help.js +88 -12
- package/dist/cli/hook-ingress.js +78 -0
- package/dist/cli/input-preparation.js +116 -0
- package/dist/cli/native-hook-ingress.js +80 -0
- package/dist/cli/run-cli.js +1465 -450
- package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
- package/dist/cli/runtime-maintenance-ingress.js +52 -0
- package/dist/cli/runtime-process.js +153 -0
- package/dist/cli.js +17 -2
- package/dist/domain/stage-catalog.js +1 -1
- package/dist/harness-runtime/DD-ZCODE.md +99 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
- package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
- package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
- package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
- package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
- package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
- package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
- package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
- package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +1108 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
- package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
- package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
- package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
- package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
- package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
- package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
- package/dist/harness-runtime/lib/model-observations.mjs +101 -0
- package/dist/harness-runtime/lib/native-children.d.mts +13 -0
- package/dist/harness-runtime/lib/native-children.mjs +78 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
- package/dist/harness-runtime/lib/native-streams.mjs +45 -0
- package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
- package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
- package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
- package/dist/harness-runtime/lib/process-json.d.mts +5 -0
- package/dist/harness-runtime/lib/process-json.mjs +201 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
- package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
- package/dist/protocol/local-files.js +18 -9
- package/dist/runtime/context.js +8 -4
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-verification.schema.json +7 -5
- package/dist/schemas/code-work-batch.schema.json +2 -2
- package/dist/schemas/flow-run.schema.json +2 -0
- package/dist/schemas/plan-review-decision.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +118 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/branch-context.js +3 -3
- package/dist/services/canon.js +11 -8
- package/dist/services/check-runner-evidence.js +121 -0
- package/dist/services/cleanup.js +133 -40
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +851 -109
- package/dist/services/codex-capacity.js +367 -0
- package/dist/services/codex-hook-delivery.js +32 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/compatibility-preflight.js +13 -3
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-fanout.js +119 -0
- package/dist/services/dashboard.js +135 -56
- package/dist/services/engines.js +245 -119
- package/dist/services/eval-snapshots.js +1146 -105
- package/dist/services/execution-policy.js +181 -0
- package/dist/services/external-work-launch.js +230 -0
- package/dist/services/harness-adapter.js +329 -36
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +747 -325
- package/dist/services/lanes.js +78 -65
- package/dist/services/lifecycle-command.js +1 -288
- package/dist/services/lifecycle-contract.js +1 -0
- package/dist/services/lifecycle-invocations.js +1774 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-lease-monitor.js +133 -0
- package/dist/services/managed-processes.js +409 -51
- package/dist/services/merge-queue.js +228 -149
- package/dist/services/merge-server.js +163 -35
- package/dist/services/migrations.js +37 -16
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +26 -11
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +20 -15
- package/dist/services/prompts.js +28 -17
- package/dist/services/protocols.js +163 -87
- package/dist/services/recovery-observation-budget.js +121 -0
- package/dist/services/recovery-snapshot-database.js +145 -0
- package/dist/services/repair-intents.js +42 -0
- package/dist/services/review-copy.js +157 -0
- package/dist/services/review-deferral.js +23 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +411 -0
- package/dist/services/run-control.js +985 -0
- package/dist/services/run-controller-adapter.js +399 -0
- package/dist/services/run-controller-capture.js +179 -0
- package/dist/services/run-controller-process.js +187 -0
- package/dist/services/run-controller-recovery.js +289 -0
- package/dist/services/run-controller-state.js +97 -0
- package/dist/services/run-controller.js +1035 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +147 -0
- package/dist/services/run-observations.js +152 -0
- package/dist/services/run-projection.js +22 -64
- package/dist/services/run-recovery-guard.js +75 -0
- package/dist/services/run-recovery-runtime.js +112 -0
- package/dist/services/run-recovery.js +349 -0
- package/dist/services/runs.js +558 -217
- package/dist/services/runtime-budget.js +430 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +52 -0
- package/dist/services/runtime-scope-control.js +468 -0
- package/dist/services/runtime-scope-resume.js +599 -0
- package/dist/services/runtime-scope-stop.js +180 -0
- package/dist/services/runtime-scope-worker.js +287 -0
- package/dist/services/runtime-service.js +96 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/scope-writer-cleanup.js +27 -0
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +185 -19
- package/dist/services/stage-lifecycle.js +98 -107
- package/dist/services/stage-pause.js +89 -75
- package/dist/services/stage-report-renderer.js +158 -6
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/tooling.js +32 -23
- package/dist/services/usage.js +49 -101
- package/dist/services/verification-matrix.js +374 -0
- package/dist/services/vnext-code-review.js +222 -87
- package/dist/services/vnext-code.js +324 -251
- package/dist/services/vnext-contracts.js +10 -1
- package/dist/services/vnext-execution-profile.js +79 -4
- package/dist/services/vnext-fanout.js +177 -17
- package/dist/services/vnext-merge.js +335 -113
- package/dist/services/vnext-plan-review.js +276 -126
- package/dist/services/vnext-plan.js +227 -102
- package/dist/services/vnext-protocolize.js +335 -82
- package/dist/services/vnext-specify.js +119 -81
- package/dist/services/work-registry.js +1038 -192
- package/dist/services/workspace-bootstrap.js +87 -0
- package/dist/services/workspace-files.js +85 -0
- package/dist/services/worktrees.js +98 -44
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +17 -0
- package/dist/storage/agent-output.js +26 -0
- package/dist/storage/database.js +781 -37
- package/dist/storage/foreign-key-transaction.js +39 -0
- package/dist/storage/immutable-input.js +45 -0
- package/dist/storage/import-guard.js +102 -0
- package/dist/storage/native-cleanup.js +52 -0
- package/dist/storage/paths.js +17 -4
- package/dist/storage/projection-lock.js +73 -0
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +85 -0
- package/package.json +30 -13
- package/tools/repair-paused-run-status.mjs +84 -0
|
@@ -1,11 +1,18 @@
|
|
|
1
|
+
import { managedInvocationContext, managedLifecycleCommand } from "./lifecycle-invocations.js";
|
|
2
|
+
import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
|
|
3
|
+
import { continueCodexCapacity } from "./codex-capacity.js";
|
|
4
|
+
import { errorRecord } from "./run-controller-state.js";
|
|
1
5
|
import crypto from "node:crypto";
|
|
2
6
|
import fs from "node:fs";
|
|
3
7
|
import path from "node:path";
|
|
4
8
|
import { AppError } from "../shared/errors.js";
|
|
9
|
+
import { runtimeBudgetForRun } from "./runtime-budget.js";
|
|
10
|
+
import { managedLeaseMonitor } from "./managed-lease-monitor.js";
|
|
5
11
|
import { flowCommand } from "./stage-pause.js";
|
|
6
|
-
import {
|
|
7
|
-
import { adapterSessionId, runHarnessAdapter } from "./harness-adapter.js";
|
|
12
|
+
import { adapterSessionId, prepareHarnessFlowExecutable, runHarnessAdapter } from "./harness-adapter.js";
|
|
8
13
|
import { harnessRuntimeArguments, resolveHarnessCommand } from "./harness-config.js";
|
|
14
|
+
import { assertRunMutationAllowed, recoveryGuard } from "./run-recovery.js";
|
|
15
|
+
import { loadAgentProfile, resolveExecutionPolicy, runtimeHarness } from "./execution-policy.js";
|
|
9
16
|
/** A deterministic dispatcher; only the launched harness Session performs agent work. */
|
|
10
17
|
export async function serveMergeRequests(context, input) {
|
|
11
18
|
const running = context.db.get("SELECT server_id, pid FROM merge_servers WHERE status IN ('running','stopping') ORDER BY started_at LIMIT 1");
|
|
@@ -58,73 +65,194 @@ export async function serveMergeRequests(context, input) {
|
|
|
58
65
|
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
66
|
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
67
|
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" }; }
|
|
68
|
+
/** Both dispatchers enter the same project FIFO before creating any provider Session. */
|
|
69
|
+
export function claimQueuedMergeRequest(context, input) {
|
|
70
|
+
return context.db.writeTransaction(() => {
|
|
71
|
+
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]);
|
|
72
|
+
if (!request)
|
|
73
|
+
throw new AppError("not_found", "MERGE request was not found", 1);
|
|
74
|
+
const generation = assertRunMutationAllowed(context, request.project_id, request.run_id, input.expectedGeneration);
|
|
75
|
+
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]);
|
|
76
|
+
if (request.status !== "queued" || request.execution_route !== "server" || earlier)
|
|
77
|
+
return null;
|
|
78
|
+
const token = crypto.randomUUID();
|
|
79
|
+
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]);
|
|
80
|
+
return { request, token, generation };
|
|
81
|
+
});
|
|
82
|
+
}
|
|
61
83
|
async function dispatch(context, input) {
|
|
62
|
-
const
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
84
|
+
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]);
|
|
85
|
+
if (!run)
|
|
86
|
+
throw new AppError("not_found", "MERGE RUN was not found", 1, { run_id: input.request.run_id });
|
|
87
|
+
const snapshot = JSON.parse(run.index_json).execution_profile;
|
|
88
|
+
if (snapshot?.settings?.execution) {
|
|
89
|
+
if (!snapshot.agent_profiles)
|
|
90
|
+
throw new AppError("execution_profile_not_frozen", "MERGE dispatch requires frozen RUN agent profiles", 1, { run_id: input.request.run_id });
|
|
91
|
+
const resolved = resolveExecutionPolicy({ ddFlowHome: context.ddFlowHome, policy: snapshot.settings.execution, profiles: snapshot.agent_profiles, stage: "merge" });
|
|
92
|
+
input = { ...input, profile: resolved.coordinator };
|
|
93
|
+
}
|
|
94
|
+
const claim = claimQueuedMergeRequest(context, { requestId: input.request.merge_request_id, ownerId: input.serverId });
|
|
95
|
+
if (!claim)
|
|
66
96
|
return;
|
|
67
|
-
const
|
|
68
|
-
leaseHeartbeat.unref();
|
|
97
|
+
const { generation, token } = claim;
|
|
69
98
|
const stateDir = path.join(input.root, input.request.merge_request_id);
|
|
70
99
|
fs.mkdirSync(stateDir, { recursive: true });
|
|
71
100
|
const promptFile = path.join(stateDir, "launch.md");
|
|
72
101
|
const adapterJournal = path.join(stateDir, "adapter.events.jsonl");
|
|
73
|
-
const
|
|
74
|
-
|
|
102
|
+
const flowExecutable = prepareHarnessFlowExecutable(context, stateDir);
|
|
103
|
+
let runtimeContext = { ...context, env: { ...context.env, DD_FLOW_BIN: flowExecutable } };
|
|
104
|
+
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
105
|
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
106
|
input.progress?.(`launching ${input.request.merge_request_id} with ${input.profile.id}`);
|
|
77
107
|
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",
|
|
108
|
+
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"];
|
|
109
|
+
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` };
|
|
110
|
+
const retain = () => { const changed = 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]); if (changed.changes !== 1)
|
|
111
|
+
throw new AppError("capacity_continuation_blocked", "MERGE dispatch owner changed before durable receipt retention", 1); };
|
|
112
|
+
retain();
|
|
113
|
+
const lease = managedLeaseMonitor(attemptMs => {
|
|
114
|
+
const db = context.db.withDeadline(Date.now() + attemptMs);
|
|
115
|
+
return db.writeTransaction(() => {
|
|
116
|
+
assertRunMutationAllowed({ ...context, db }, input.request.project_id, input.request.run_id, generation);
|
|
117
|
+
const expiry = new Date(Date.now() + 120_000).toISOString();
|
|
118
|
+
const changed = db.run("UPDATE merge_requests SET dispatch_lease_expires_at = ?, updated_at = ? WHERE merge_request_id = ? AND status IN ('dispatching','active') AND dispatch_owner = ? AND dispatch_lease_token = ?", [expiry, context.now(), input.request.merge_request_id, input.serverId, token]);
|
|
119
|
+
return changed.changes === 1 ? { owned: true, lease_expires_at: expiry } : { owned: false };
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
const ownership = new AbortController();
|
|
123
|
+
const leaseHeartbeat = setInterval(() => {
|
|
124
|
+
lease.background(() => assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation), error => {
|
|
125
|
+
ownership.abort(error);
|
|
126
|
+
try {
|
|
127
|
+
event(input.journal, { type: "dispatch_lease_unconfirmed", request_id: input.request.merge_request_id, error: errorRecord(error), at: context.now() });
|
|
128
|
+
}
|
|
129
|
+
catch { /* No unhandled timer exception; the next boundary sees retained monitor failure. */ }
|
|
130
|
+
});
|
|
131
|
+
}, 30_000);
|
|
132
|
+
leaseHeartbeat.unref();
|
|
79
133
|
try {
|
|
80
|
-
const adapterCall = (args, timeoutMs, progressMessage
|
|
134
|
+
const adapterCall = async (args, timeoutMs, progressMessage, id = `${input.request.merge_request_id}:${token}:${args[0]}.${args[1]}`) => {
|
|
135
|
+
await lease.ensureConfirmed(() => assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation));
|
|
136
|
+
try {
|
|
137
|
+
return await runHarnessAdapter({ executable, args, harness: runtimeHarness(input.profile), env: runtimeContext.env, runtimeOwner, operationId: id, signal: ownership.signal, ...(timeoutMs !== undefined ? { timeoutMs } : {}), ...(input.progress ? { progress: input.progress } : {}), ...(progressMessage ? { progressMessage } : {}), onEvidence: (value) => event(input.journal, { type: "adapter_call", ...value }), onNativeOutcome: value => {
|
|
138
|
+
if (args[0] === "session" && args[1] === "create" && adapterSessionId(value)) {
|
|
139
|
+
Object.assign(retained, { session_id: adapterSessionId(value), create: value, settlement_pending: true });
|
|
140
|
+
retain();
|
|
141
|
+
}
|
|
142
|
+
} });
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (ownership.signal.aborted)
|
|
146
|
+
throw ownership.signal.reason;
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
81
150
|
await adapterCall(["daemon", "start", ...common]);
|
|
82
151
|
const created = await adapterCall(["session", "create", ...common]);
|
|
83
152
|
const sessionId = adapterSessionId(created);
|
|
84
153
|
if (!sessionId)
|
|
85
154
|
throw new AppError("merge_adapter_invalid", "Harness adapter did not return a Session id", 1, { harness: input.profile.harness, response: created });
|
|
86
|
-
|
|
155
|
+
Object.assign(retained, { session_id: sessionId, create: created, settlement_pending: false });
|
|
156
|
+
retain();
|
|
157
|
+
runtimeContext = managedInvocationContext(runtimeContext, { harness: runtimeHarness(input.profile), stateDir, sessionId, projectRoot: run.project_root, runId: input.request.run_id, generation });
|
|
158
|
+
const stageCommand = managedLifecycleCommand(runtimeContext, `${flowCommand(runtimeContext)} stage start ${input.request.run_id} --stage merge --project-root ${JSON.stringify(run.project_root)} --json --progress-jsonl`);
|
|
159
|
+
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`);
|
|
160
|
+
let prompted;
|
|
161
|
+
retained.progress_policy = "native-inactivity@1";
|
|
162
|
+
retain();
|
|
163
|
+
try {
|
|
164
|
+
prompted = await adapterCall(["session", "prompt", "--session-id", sessionId, "--prompt-file", promptFile, ...common], null, `MERGE ${input.request.merge_request_id} Session ${sessionId} is still running`);
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
if (runtimeHarness(input.profile) !== "codex-desktop")
|
|
168
|
+
throw error;
|
|
169
|
+
const capacityIntents = (retained.capacity_intents ?? []);
|
|
170
|
+
const capacityFailures = (retained.capacity_failures ?? []);
|
|
171
|
+
const resumed = await continueCodexCapacity({ error, sessionId, operationId: String(retained.prompt_operation_id), allowSettledDescendants: true,
|
|
172
|
+
signal: ownership.signal,
|
|
173
|
+
continuationText: `Continue only MERGE ${input.request.merge_request_id}, Work ${input.request.executor_work_id}, RUN ${input.request.run_id} in this same Session and target ${input.request.target_workspace}. First inspect current durable Stage/Work/MERGE receipts. Never repeat Stage start, accepted answer, completed apply or checks. Follow only the current exact issued successor and stop at the original boundary.`,
|
|
174
|
+
retainedIntents: () => capacityIntents,
|
|
175
|
+
retainedFailures: () => capacityFailures,
|
|
176
|
+
retainFailure: (_id, refusal) => { capacityFailures.push(refusal); retained.capacity_failures = capacityFailures; retain(); },
|
|
177
|
+
inspectOperation: id => adapterCall(["daemon", "operation", "--state-dir", stateDir, "--operation-id", id, "--json"], 30_000, undefined, `${id}:capacity-observe`),
|
|
178
|
+
inspectSession: turnId => adapterCall(["session", "inspect", "--session-id", sessionId, ...(turnId ? ["--turn-id", turnId] : []), ...common], 30_000, undefined, `${input.request.merge_request_id}:${token}:capacity-inspect`),
|
|
179
|
+
assertCurrent: () => {
|
|
180
|
+
assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation);
|
|
181
|
+
const current = context.db.get("SELECT status, dispatch_owner, dispatch_lease_token, dispatch_lease_expires_at, target_workspace FROM merge_requests WHERE merge_request_id = ?", [input.request.merge_request_id]);
|
|
182
|
+
if (current?.status === "completed" || current?.status === "action_required")
|
|
183
|
+
return;
|
|
184
|
+
if (!current || !["dispatching", "active"].includes(current.status) || current.dispatch_owner !== input.serverId || current.dispatch_lease_token !== token
|
|
185
|
+
|| current.dispatch_lease_expires_at <= context.now() || current.target_workspace !== input.request.target_workspace)
|
|
186
|
+
throw new AppError("capacity_continuation_blocked", "MERGE dispatch owner or target changed during capacity wait", 1, { request_id: input.request.merge_request_id });
|
|
187
|
+
if (!["created", "running", "paused", "completed"].includes(context.db.get("SELECT status FROM works WHERE work_id = ?", [input.request.executor_work_id])?.status ?? ""))
|
|
188
|
+
throw new AppError("capacity_continuation_blocked", "MERGE Work has failed or lost its binding", 1);
|
|
189
|
+
},
|
|
190
|
+
decision: () => {
|
|
191
|
+
const status = context.db.get("SELECT status FROM merge_requests WHERE merge_request_id = ?", [input.request.merge_request_id])?.status;
|
|
192
|
+
const workStatus = context.db.get("SELECT status FROM works WHERE work_id = ?", [input.request.executor_work_id])?.status;
|
|
193
|
+
return status === "completed" ? "completed" : status === "action_required" || workStatus === "paused" ? "paused" : "continue";
|
|
194
|
+
},
|
|
195
|
+
retainIntent: intent => { capacityIntents.push(intent); retained.capacity_intents = capacityIntents; retained.capacity_intent = intent; retain(); },
|
|
196
|
+
prompt: (id, text, ordinal) => {
|
|
197
|
+
const file = path.join(stateDir, `capacity-${ordinal}.md`);
|
|
198
|
+
if (fs.existsSync(file)) {
|
|
199
|
+
if (fs.readFileSync(file, "utf8") !== text)
|
|
200
|
+
throw new AppError("capacity_continuation_conflict", "Retained MERGE continuation prompt differs", 1);
|
|
201
|
+
}
|
|
202
|
+
else
|
|
203
|
+
fs.writeFileSync(file, text, { flag: "wx", mode: 0o600 });
|
|
204
|
+
return adapterCall(["session", "prompt", "--session-id", sessionId, "--prompt-file", file, ...common], null, `MERGE ${input.request.merge_request_id} Session ${sessionId} capacity continuation ${ordinal}`, id);
|
|
205
|
+
} });
|
|
206
|
+
if (!resumed)
|
|
207
|
+
throw error;
|
|
208
|
+
prompted = resumed;
|
|
209
|
+
}
|
|
210
|
+
Object.assign(retained, { response: prompted });
|
|
211
|
+
retain();
|
|
212
|
+
assertRunMutationAllowed(context, input.request.project_id, input.request.run_id, generation);
|
|
87
213
|
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
214
|
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
215
|
if (request?.status === "dispatching")
|
|
91
|
-
context.db.run("UPDATE merge_requests SET status = '
|
|
216
|
+
context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'dispatching' AND dispatch_owner = ? AND dispatch_lease_token = ? AND ? = COALESCE((SELECT MAX(generation) FROM run_recovery_guards WHERE project_id = merge_requests.project_id AND run_id = merge_requests.run_id), 0)", [JSON.stringify({ code: "adapter_did_not_start_stage", response: prompted }), context.now(), input.request.merge_request_id, input.serverId, token, generation]);
|
|
92
217
|
}
|
|
93
218
|
catch (error) {
|
|
219
|
+
if (error instanceof AppError && ["run_recovery_guarded", "run_recovery_generation_stale"].includes(error.code)) {
|
|
220
|
+
event(input.journal, { type: "recovery_dispatch_blocked", request_id: input.request.merge_request_id, code: error.code, at: context.now() });
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
94
223
|
const request = context.db.get("SELECT status FROM merge_requests WHERE merge_request_id = ?", [input.request.merge_request_id]);
|
|
95
|
-
if (request?.status === "dispatching")
|
|
96
|
-
context.db.run("UPDATE merge_requests SET status = '
|
|
97
|
-
else if (request?.status === "active")
|
|
98
|
-
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]);
|
|
224
|
+
if (request?.status === "dispatching" || request?.status === "active")
|
|
225
|
+
context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ? AND status = ? AND dispatch_owner = ? AND dispatch_lease_token = ? AND ? = COALESCE((SELECT MAX(generation) FROM run_recovery_guards WHERE project_id = merge_requests.project_id AND run_id = merge_requests.run_id), 0)", [JSON.stringify({ code: request.status === "dispatching" ? "adapter_launch_failed" : "adapter_lost_after_stage_start", error: errorRecord(error) }), context.now(), input.request.merge_request_id, request.status, input.serverId, token, generation]);
|
|
99
226
|
throw error;
|
|
100
227
|
}
|
|
101
228
|
finally {
|
|
229
|
+
lease.close();
|
|
102
230
|
clearInterval(leaseHeartbeat);
|
|
103
231
|
}
|
|
104
232
|
}
|
|
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','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]))
|
|
233
|
+
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
234
|
return false; selected.add(request.project_id); return true; }).slice(0, limit); }
|
|
107
|
-
function reconcileExpiredDispatches(context) {
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
context.db.
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
235
|
+
export function reconcileExpiredDispatches(context) {
|
|
236
|
+
context.db.writeTransaction(() => {
|
|
237
|
+
const now = context.now();
|
|
238
|
+
const expired = context.db.all("SELECT merge_request_id, executor_work_id, project_id, run_id, dispatch_owner, dispatch_lease_token, dispatch_lease_expires_at FROM merge_requests WHERE status = 'dispatching' AND dispatch_lease_expires_at < ?", [now]);
|
|
239
|
+
for (const request of expired) {
|
|
240
|
+
if (guarded(context, request))
|
|
241
|
+
continue;
|
|
242
|
+
const work = context.db.get("SELECT status FROM works WHERE work_id = ?", [request.executor_work_id]);
|
|
243
|
+
context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'dispatching' AND dispatch_owner IS ? AND dispatch_lease_token IS ? AND dispatch_lease_expires_at = ? AND dispatch_lease_expires_at < ?", [JSON.stringify({ code: "expired_dispatch_outcome_unknown", work_status: work?.status ?? null }), now, request.merge_request_id, request.dispatch_owner, request.dispatch_lease_token, request.dispatch_lease_expires_at, now]);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
116
246
|
}
|
|
117
|
-
|
|
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; }
|
|
247
|
+
function loadProfile(context, id) { return loadAgentProfile(context.ddFlowHome, id); }
|
|
121
248
|
function event(file, value) { fs.appendFileSync(file, `${JSON.stringify(value)}\n`); }
|
|
249
|
+
function guarded(context, request) { const guard = recoveryGuard(context, request.project_id, request.run_id); return Boolean(guard && ["draining", "sealed", "resuming"].includes(guard.status)); }
|
|
122
250
|
function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); }
|
|
123
251
|
function processAlive(pid) { if (!pid)
|
|
124
252
|
return false; try {
|
|
125
253
|
process.kill(pid, 0);
|
|
126
254
|
return true;
|
|
127
255
|
}
|
|
128
|
-
catch {
|
|
129
|
-
return
|
|
256
|
+
catch (error) {
|
|
257
|
+
return error.code !== "ESRCH";
|
|
130
258
|
} }
|
|
@@ -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
|
|
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.
|
|
221
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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("
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
|
19
|
-
const
|
|
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
|
package/dist/services/plans.js
CHANGED
|
@@ -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,
|
|
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,
|
|
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,
|
|
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,
|
|
45
|
-
...item,
|
|
46
|
-
status: "skipped",
|
|
47
|
-
summary: input.reason
|
|
48
|
-
}));
|
|
32
|
+
return updatePlanItem(context, { ...input, action: "skip" });
|
|
49
33
|
}
|
|
50
|
-
function
|
|
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
|
|
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
|
-
|
|
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
|
}
|