@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.134
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 +687 -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 +1128 -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 +14 -0
- package/dist/harness-runtime/lib/native-children.mjs +94 -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 +136 -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 +753 -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 +1828 -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 +182 -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 +1083 -194
- 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 +785 -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,22 +1,31 @@
|
|
|
1
|
+
import { managedLifecycleCommand } from "./lifecycle-invocations.js";
|
|
2
|
+
import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
|
|
1
3
|
import crypto from "node:crypto";
|
|
4
|
+
import { runWorkspaceBootstrap } from "./workspace-bootstrap.js";
|
|
2
5
|
import fs from "node:fs";
|
|
3
6
|
import path from "node:path";
|
|
4
7
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
5
8
|
import { vnextStageDirectory } from "../domain/stage-catalog.js";
|
|
6
9
|
import { AppError } from "../shared/errors.js";
|
|
10
|
+
import { assertSourceRepairEligible, checkRepairDisposition } from "./check-runner-evidence.js";
|
|
7
11
|
import { resolveProjectRoot } from "../storage/paths.js";
|
|
8
12
|
import { requireProjectByRoot } from "./projects.js";
|
|
9
13
|
import { nextMergeRequestId } from "./ids.js";
|
|
10
14
|
import { readProjectConfig } from "./config.js";
|
|
11
|
-
import { appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRun, completeFlowRunStage, gitFacts, prepareVnextMergeSourceRepairAttempt } from "./runs.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
+
import { appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRun, completeFlowRunStage, gitFacts, prepareFlowRunStageAttachment, prepareFlowRunStageCompletion, prepareVnextMergeSourceRepairAttempt, withStageSettlement } from "./runs.js";
|
|
16
|
+
import { stagePauseCommand, stagePauseCommandTemplate } from "./stage-pause.js";
|
|
17
|
+
import { runtimeCommand, checkRetryArgs, recoveryEvidenceInput } from "./runtime-command.js";
|
|
18
|
+
import { acceptStageReport, prepareStageReport, publishStageReport } from "./stage-report-renderer.js";
|
|
15
19
|
import { bindStageCoordinatorWork, createChildWork, failWork, finishFanInWork, finishWork, refreshRunWorkProjection, startStageCoordinatorWork } from "./work-registry.js";
|
|
16
20
|
import { addVnextCodeRepair } from "./vnext-code.js";
|
|
17
|
-
import { checkReceipts, effectiveCheckDeclarations, readCodeCheckProfile, runCodeChecks,
|
|
18
|
-
import { applyExternalStageContext } from "./stage-context.js";
|
|
19
|
-
import { ensureLaneWorkspace, heartbeatLaneLock, releaseLaneLock, waitAcquireLaneLock } from "./lanes.js";
|
|
21
|
+
import { checkReceiptEvidenceValid, checkReceipts, effectiveCheckDeclarations, mergeCheckProfileHash, readCodeCheckProfile, runCodeChecks, validateCheckDeclaration, validateFailedCheckRetry, workspaceChangedPaths, workspaceFingerprint } from "./code-checks.js";
|
|
22
|
+
import { currentStagePrompt, applyExternalStageContext, prepareExternalStageContext } from "./stage-context.js";
|
|
23
|
+
import { ensureLaneWorkspace, prepareLaneWorkspace, heartbeatLaneLock, releaseLaneLock, waitAcquireLaneLock } from "./lanes.js";
|
|
24
|
+
import { assertRunMutationAllowed } from "./run-recovery.js";
|
|
25
|
+
import { assertStageStartHookEvent } from "./hooks.js";
|
|
26
|
+
import { prepareJsonSchema, prepareOutputFile } from "../cli/input-preparation.js";
|
|
27
|
+
import { prepareRunVerificationMatrix, acceptVerificationMatrix, commitVerificationMatrixStart, resumeVerificationMatrix, verificationMatrixInstruction, latestRunVerificationMatrix, publishVerificationMatrix } from "./verification-matrix.js";
|
|
28
|
+
import { stageSuccessor } from "./vnext-contracts.js";
|
|
20
29
|
const stage = "merge";
|
|
21
30
|
const stageDir = vnextStageDirectory(stage);
|
|
22
31
|
export function isVnextMergeRun(context, input) {
|
|
@@ -25,16 +34,24 @@ export function isVnextMergeRun(context, input) {
|
|
|
25
34
|
}
|
|
26
35
|
/** Terminal CODE/CODE-REVIEW calls this once; it freezes source and creates the child MERGE Work. */
|
|
27
36
|
export function ensureVnextMergeRequest(context, input) {
|
|
37
|
+
return prepareVnextMergeRequest(context, input)();
|
|
38
|
+
}
|
|
39
|
+
/** Freeze filesystem evidence outside the stage writer lock; return only the SQL settlement. */
|
|
40
|
+
export function prepareVnextMergeRequest(context, input) {
|
|
28
41
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
29
42
|
const project = requireProjectByRoot(context, projectRoot);
|
|
30
43
|
const run = requireRun(context, project.id, input.runId);
|
|
44
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
31
45
|
const existing = context.db.get("SELECT * FROM merge_requests WHERE project_id = ? AND run_id = ? AND status NOT IN ('completed','failed','cancelled','superseded') ORDER BY created_at DESC LIMIT 1", [project.id, run.id]);
|
|
32
46
|
if (existing)
|
|
33
|
-
return requestView(context, existing);
|
|
47
|
+
return () => requestView(context, requireRequest(context, existing.merge_request_id));
|
|
34
48
|
const settings = executionSettings(run);
|
|
35
49
|
const route = settings.merge_mode ?? "same_session";
|
|
36
50
|
const home = requireHome(run);
|
|
37
51
|
const protocols = protocolIds(home);
|
|
52
|
+
if (route === "same_session" && path.resolve(run.workspace_root) !== path.resolve(projectRoot)) {
|
|
53
|
+
throw new AppError("merge_session_workspace_conflict", "The existing coordinator Session is bound to the feature workspace, but MERGE executes in the integration checkout", 2, { effect: "no_effect", recoverable: false, source_workspace: run.workspace_root, target_workspace: projectRoot });
|
|
54
|
+
}
|
|
38
55
|
const sourceBranch = gitValue(run.workspace_root, ["branch", "--show-current"]);
|
|
39
56
|
if (!sourceBranch)
|
|
40
57
|
throw new AppError("merge_source_invalid", "MERGE requires a named source branch", 1, { workspace_root: run.workspace_root });
|
|
@@ -47,7 +64,10 @@ export function ensureVnextMergeRequest(context, input) {
|
|
|
47
64
|
throw new AppError("merge_source_invalid", "MERGE could not determine the target branch", 1, { target_branch: targetBranch });
|
|
48
65
|
const semantic = planChecks(run.workspace_root, protocols);
|
|
49
66
|
validateMergeAcceptance(run.workspace_root, protocols, semantic);
|
|
67
|
+
const acceptanceRefs = mergeAcceptanceRefs(run.workspace_root, protocols);
|
|
50
68
|
const effective = effectiveCheckDeclarations(targetWorkspace, semantic, ["work", "code", "readiness", "merge"]);
|
|
69
|
+
for (const check of effective)
|
|
70
|
+
validateCheckDeclaration(run.workspace_root, check);
|
|
51
71
|
if (run.workspace_root !== targetWorkspace && effective.length === 0)
|
|
52
72
|
throw new AppError("merge_gate_missing", "A real source/target integration requires at least one semantic or policy merge check", 2, { run_id: run.id, protocol_ids: protocols });
|
|
53
73
|
const ignored = ignoredGitPaths(context, project.id);
|
|
@@ -56,18 +76,23 @@ export function ensureVnextMergeRequest(context, input) {
|
|
|
56
76
|
const freezeFile = path.join(freezeRoot, "source-freeze.json");
|
|
57
77
|
const gateFile = path.join(freezeRoot, "merge-gate.json");
|
|
58
78
|
fs.mkdirSync(freezeRoot, { recursive: true });
|
|
59
|
-
|
|
79
|
+
const profileHash = mergeCheckProfileHash(run.workspace_root, targetWorkspace, effective);
|
|
80
|
+
retainMergeProfile(freezeRoot, "baseline", targetWorkspace);
|
|
81
|
+
retainMergeProfile(freezeRoot, "source", run.workspace_root);
|
|
82
|
+
freezeMergeGate(gateFile, { runId: run.id, protocols, checks: effective, acceptanceRefs, profileHash, now: context.now() });
|
|
60
83
|
let sourceCommit;
|
|
61
84
|
let sourcePaths;
|
|
62
85
|
if (fs.existsSync(freezeFile)) {
|
|
63
86
|
const frozen = JSON.parse(fs.readFileSync(freezeFile, "utf8"));
|
|
64
87
|
sourceCommit = frozen.run_id === run.id && typeof frozen.source_commit === "string" ? frozen.source_commit : "";
|
|
65
88
|
sourcePaths = Array.isArray(frozen.paths) ? frozen.paths : [];
|
|
66
|
-
|
|
89
|
+
// A retry sees a clean tree: the original paths are already in sourceCommit.
|
|
90
|
+
// Reuse that receipt, but never accept new edits merely because names match.
|
|
91
|
+
if (!sourceCommit || frozen.source_workspace !== run.workspace_root || frozen.source_branch !== sourceBranch || gitValue(run.workspace_root, ["rev-parse", "HEAD"]) !== sourceCommit || meaningfulStatus(run.workspace_root, ignored).length)
|
|
67
92
|
throw new AppError("merge_source_freeze_conflict", "Existing MERGE source freeze does not match the accepted source", 2, { freeze_file: freezeFile });
|
|
68
93
|
}
|
|
69
94
|
else {
|
|
70
|
-
sourcePaths =
|
|
95
|
+
sourcePaths = meaningfulStatus(run.workspace_root, ignored);
|
|
71
96
|
if (accepted) {
|
|
72
97
|
const unexpected = sourcePaths.filter((item) => !accepted.includes(item));
|
|
73
98
|
const absent = accepted.filter((item) => !sourcePaths.includes(item));
|
|
@@ -83,58 +108,81 @@ export function ensureVnextMergeRequest(context, input) {
|
|
|
83
108
|
if (!sourceCommit)
|
|
84
109
|
throw new AppError("merge_source_invalid", "MERGE could not freeze source commit", 1, { source_commit: sourceCommit, target_branch: targetBranch });
|
|
85
110
|
const enqueueTarget = gitValue(targetWorkspace, ["rev-parse", targetBranch], true);
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
context.db.exec("BEGIN IMMEDIATE");
|
|
91
|
-
try {
|
|
111
|
+
return () => context.db.writeTransaction(() => {
|
|
112
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
113
|
+
const root = requireRootWork(context, project.id, run.id);
|
|
114
|
+
const now = context.now();
|
|
92
115
|
const raced = context.db.get("SELECT * FROM merge_requests WHERE project_id = ? AND run_id = ? AND status NOT IN ('completed','failed','cancelled','superseded') ORDER BY created_at DESC LIMIT 1", [project.id, run.id]);
|
|
93
|
-
if (raced)
|
|
94
|
-
context.db.exec("COMMIT");
|
|
116
|
+
if (raced)
|
|
95
117
|
return requestView(context, raced);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
requestId
|
|
99
|
-
context
|
|
100
|
-
context
|
|
101
|
-
}
|
|
102
|
-
catch (error) {
|
|
103
|
-
context.db.exec("ROLLBACK");
|
|
104
|
-
throw error;
|
|
105
|
-
}
|
|
106
|
-
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "merge_request_queued", merge_request_id: requestId, work_id: child.work_id, route, source_commit: sourceCommit, target_branch: targetBranch });
|
|
107
|
-
return requestView(context, requireRequest(context, requestId));
|
|
118
|
+
const child = createChildWork(context, { parentWorkId: root.work_id, stage: "merge", slug: "merge", task: `Integrate frozen source ${sourceCommit} into ${targetBranch}, resolve material conflicts, and preserve accepted behavior.`, launchPolicy: route === "server" ? "fresh_agent_required" : "reuse_allowed", resultSchema: "dd-flow/merge-result@1", payload: { kind: "merge", checks: semantic, protocol_ids: protocols } });
|
|
119
|
+
const requestId = nextMergeRequestId(context);
|
|
120
|
+
context.db.run("INSERT INTO merge_requests (merge_request_id, project_id, run_id, executor_work_id, protocol_ids_json, source_workspace, source_branch, source_commit, target_workspace, target_branch, enqueue_target_head, execution_target_head, integration_commit, execution_route, status, dispatch_owner, dispatch_lease_token, dispatch_lease_expires_at, lock_acquired_at, checkpoint, profile_hash, replacement_of_merge_request_id, adapter_receipt_json, result_json, last_error_json, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, 'queued', NULL, NULL, NULL, NULL, 'queued', ?, ?, NULL, NULL, NULL, ?, ?, NULL)", [requestId, project.id, run.id, child.work_id, JSON.stringify(protocols), run.workspace_root, sourceBranch, sourceCommit, targetWorkspace, targetBranch, enqueueTarget, route, profileHash, replacementOf(run), now, now]);
|
|
121
|
+
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "merge_request_queued", merge_request_id: requestId, work_id: child.work_id, route, source_commit: sourceCommit, target_branch: targetBranch });
|
|
122
|
+
return requestView(context, requireRequest(context, requestId));
|
|
123
|
+
});
|
|
108
124
|
}
|
|
109
|
-
export
|
|
125
|
+
export function prepareVnextMergeStart(context, input) {
|
|
110
126
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
111
127
|
const project = requireProjectByRoot(context, projectRoot);
|
|
112
128
|
const run = requireRun(context, project.id, input.runId);
|
|
113
129
|
const home = requireHome(run);
|
|
114
130
|
const request = requestForRun(context, project.id, run.id);
|
|
131
|
+
const generation = assertRunMutationAllowed(context, project.id, run.id);
|
|
132
|
+
const common = { projectRoot, project, run, request, generation };
|
|
115
133
|
if (request.status === "completed")
|
|
134
|
+
return { ...common, terminal: true };
|
|
135
|
+
if (!["queued", "dispatching", "active", "action_required"].includes(request.status))
|
|
136
|
+
throw new AppError("merge_request_state_invalid", "MERGE request cannot be started in its current state", 1, { status: request.status, merge_request_id: request.merge_request_id });
|
|
137
|
+
const root = path.join(home, stageDir), workRoot = path.join(root, "works", request.executor_work_id);
|
|
138
|
+
const resultPath = path.join(workRoot, "result.json"), promptPath = path.join(workRoot, "prompt.md");
|
|
139
|
+
const work = context.db.get("SELECT status, project_id, run_id FROM works WHERE work_id = ?", [request.executor_work_id]);
|
|
140
|
+
if (!work || work.project_id !== project.id || work.run_id !== run.id || !["created", "running"].includes(work.status))
|
|
141
|
+
throw new AppError("runtime_artifact_invalid", "MERGE executor Work is missing or not startable", 1, { work_id: request.executor_work_id });
|
|
142
|
+
const index = JSON.parse(run.index_json);
|
|
143
|
+
const attachment = ["active", "action_required"].includes(request.status) && index.stage_runs?.some(entry => entry.stage === stage) ? null : prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@2" });
|
|
144
|
+
prepareLaneWorkspace(context, { projectRoot, lane: "merge", workspacePath: request.target_workspace, branch: request.target_branch });
|
|
145
|
+
const checks = effectiveMergeChecks(run, request), settings = executionSettings(run);
|
|
146
|
+
const existingPrompt = ["active", "action_required"].includes(request.status) && fs.existsSync(promptPath) ? fs.readFileSync(promptPath, "utf8") : null;
|
|
147
|
+
if (existingPrompt === null || input.externalContext)
|
|
148
|
+
prepareOutputFile(promptPath);
|
|
149
|
+
if (input.externalContext)
|
|
150
|
+
prepareExternalStageContext({ stageRoot: root, loaded: input.externalContext });
|
|
151
|
+
const matrix = existingPrompt !== null ? latestRunVerificationMatrix(context, project.id, run.id, stage, "input") : prepareRunVerificationMatrix(context, { projectId: project.id, runId: run.id, stage, role: "input", ...(attachment ? { stageAttempt: attachment.attempt } : {}) });
|
|
152
|
+
return { ...common, terminal: false, root, workRoot, resultPath, promptPath, checks, settings, existingPrompt, matrix };
|
|
153
|
+
}
|
|
154
|
+
export async function startVnextMerge(context, input, prepared = prepareVnextMergeStart(context, input)) {
|
|
155
|
+
const { projectRoot, project, run, request, generation } = prepared;
|
|
156
|
+
if (prepared.terminal)
|
|
116
157
|
return requestView(context, request);
|
|
117
|
-
const root
|
|
118
|
-
|
|
158
|
+
const { root, workRoot, resultPath, promptPath, checks, settings, existingPrompt } = prepared;
|
|
159
|
+
if (existingPrompt !== null)
|
|
160
|
+
resumeVerificationMatrix(context, project.id, run.id, stage);
|
|
161
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
162
|
+
assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
163
|
+
const alreadyAttached = ["active", "action_required"].includes(request.status) && (JSON.parse(requireRun(context, project.id, run.id).index_json).stage_runs ?? []).some((item) => item.stage === stage);
|
|
164
|
+
if (!alreadyAttached)
|
|
165
|
+
prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@2" }, true);
|
|
119
166
|
fs.mkdirSync(workRoot, { recursive: true });
|
|
120
|
-
const resultPath = path.join(workRoot, "result.json");
|
|
121
|
-
const promptPath = path.join(workRoot, "prompt.md");
|
|
122
167
|
ensureLaneWorkspace(context, { projectRoot, lane: "merge", workspacePath: request.target_workspace, branch: request.target_branch });
|
|
123
168
|
const lane = await waitAcquireLaneLock(context, { projectRoot, lane: "merge", workerId: request.executor_work_id, workspacePath: request.target_workspace, timeoutSeconds: 3600, pollIntervalSeconds: 15, ttlSeconds: 7200, reason: `MERGE ${request.merge_request_id}`, ...(input.progress ? { progress: input.progress } : {}) });
|
|
124
169
|
if (!lane.acquired)
|
|
125
170
|
throw new AppError("merge_lane_wait_failed", "MERGE could not acquire the project integration lane", 1, { merge_request_id: request.merge_request_id, status: lane.status ?? "unknown" });
|
|
126
171
|
try {
|
|
172
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
127
173
|
if (["active", "action_required"].includes(request.status)) {
|
|
128
174
|
const pendingWork = context.db.get("SELECT status FROM works WHERE work_id = ?", [request.executor_work_id]);
|
|
129
175
|
const binding = pendingWork?.status === "created"
|
|
130
176
|
? startStageCoordinatorWork(context, { workId: request.executor_work_id, hookEventId: input.hookEventId, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) })
|
|
131
177
|
: bindStageCoordinatorWork(context, { workId: request.executor_work_id, hookEventId: input.hookEventId, stage, promptPath, resultPath, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
132
|
-
const prompt =
|
|
133
|
-
if (
|
|
178
|
+
const prompt = existingPrompt ?? `${mergePrompt(context, { run, request, resultPath, projectRoot }, checks, settings)}\n${stageLifecycleInstruction}\n${verificationMatrixInstruction(prepared.matrix?.metadata ?? null, run.run_root, "MERGE source/target verification and residual-risk assessment")}\n`;
|
|
179
|
+
if (existingPrompt === null)
|
|
134
180
|
fs.writeFileSync(promptPath, prompt);
|
|
135
|
-
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
136
|
-
|
|
137
|
-
|
|
181
|
+
const externalContext = applyExternalStageContext({ context, stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
182
|
+
const attachmentInput = { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@2" };
|
|
183
|
+
const attachment = alreadyAttached ? null : prepareFlowRunStageAttachment(context, attachmentInput);
|
|
184
|
+
commitVerificationMatrixStart(context, prepared.matrix, () => attachment ? attachFlowRunStage(context, attachmentInput, attachment) : undefined);
|
|
185
|
+
return startPacket(context, run, request, binding, promptPath, resultPath, projectRoot, checks, externalContext);
|
|
138
186
|
}
|
|
139
187
|
const current = requireRequest(context, request.merge_request_id);
|
|
140
188
|
const targetHead = gitValue(current.target_workspace, ["rev-parse", current.target_branch], true);
|
|
@@ -148,31 +196,42 @@ export async function startVnextMerge(context, input) {
|
|
|
148
196
|
if (claimed.changes !== 1 && requireRequest(context, current.merge_request_id).status !== "active")
|
|
149
197
|
throw new AppError("merge_claim_conflict", "MERGE request could not acquire the integration lane", 1, { merge_request_id: current.merge_request_id });
|
|
150
198
|
const started = startStageCoordinatorWork(context, { workId: current.executor_work_id, hookEventId: input.hookEventId, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
151
|
-
const prompt = mergePrompt(context, { run, request: requireRequest(context, current.merge_request_id), resultPath, projectRoot })
|
|
199
|
+
const prompt = `${mergePrompt(context, { run, request: requireRequest(context, current.merge_request_id), resultPath, projectRoot }, checks, settings)}\n${stageLifecycleInstruction}\n${verificationMatrixInstruction(prepared.matrix?.metadata ?? null, run.run_root, "MERGE source/target verification and residual-risk assessment")}\n`;
|
|
152
200
|
fs.writeFileSync(promptPath, prompt);
|
|
153
|
-
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
201
|
+
const externalContext = applyExternalStageContext({ context, stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
154
202
|
context.db.run("UPDATE work_sessions SET prompt_path = ?, result_path = ?, updated_at = ? WHERE work_id = ? AND status = 'running'", [promptPath, resultPath, context.now(), current.executor_work_id]);
|
|
155
|
-
|
|
203
|
+
const attachmentInput = { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@2" };
|
|
204
|
+
const attachment = alreadyAttached ? null : prepareFlowRunStageAttachment(context, attachmentInput);
|
|
205
|
+
commitVerificationMatrixStart(context, prepared.matrix, () => attachment ? attachFlowRunStage(context, attachmentInput, attachment) : undefined);
|
|
156
206
|
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "merge_started", merge_request_id: current.merge_request_id, work_id: current.executor_work_id, target_head: targetHead });
|
|
157
|
-
return startPacket(context, run, current, started, promptPath, resultPath,
|
|
207
|
+
return startPacket(context, run, current, started, promptPath, resultPath, projectRoot, checks, externalContext);
|
|
158
208
|
}
|
|
159
209
|
catch (error) {
|
|
160
210
|
const latest = requireRequest(context, request.merge_request_id);
|
|
211
|
+
if (error instanceof AppError && ["run_recovery_guarded", "run_recovery_generation_stale"].includes(error.code)) {
|
|
212
|
+
releaseMergeLane(context, projectRoot, latest, `MERGE ${latest.merge_request_id} interrupted`);
|
|
213
|
+
throw error;
|
|
214
|
+
}
|
|
161
215
|
if (["active", "dispatching"].includes(latest.status))
|
|
162
216
|
context.db.run("UPDATE merge_requests SET status = 'action_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "merge_start_failed", error: error instanceof Error ? error.message : String(error) }), context.now(), latest.merge_request_id]);
|
|
163
217
|
releaseMergeLane(context, projectRoot, latest, `MERGE ${latest.merge_request_id} start failed`);
|
|
164
218
|
throw error;
|
|
165
219
|
}
|
|
166
220
|
}
|
|
167
|
-
function startPacket(context, run, request, binding, promptPath, resultPath,
|
|
168
|
-
return { ok: true, run_id: run.id, stage, merge_request_id: request.merge_request_id, work_id: request.executor_work_id, session_binding: binding.session_binding ?? binding,
|
|
221
|
+
function startPacket(context, run, request, binding, promptPath, resultPath, projectRoot, checks, externalContext) {
|
|
222
|
+
return { ok: true, run_id: run.id, stage, merge_request_id: request.merge_request_id, work_id: request.executor_work_id, session_binding: binding.session_binding ?? binding, result_path: resultPath, ...currentStagePrompt(context, promptPath), ...(externalContext ? { external_context: externalContext } : {}), queue: queueStatus(context, request), effective_checks: checks, next: { apply_command: applyCommand(context, request, projectRoot), finish_command: finishCommand(context, run.id, request, projectRoot) } };
|
|
169
223
|
}
|
|
170
224
|
export function applyVnextMerge(context, input) {
|
|
171
225
|
const existing = requireRequest(context, input.requestId);
|
|
172
226
|
const receiptFile = applyReceiptPath(context, existing);
|
|
173
|
-
if (existing.executor_work_id === input.workId && ["apply_recorded", "integration_committed", "bootstrap_ready", "checks_passed", "delivered", "finalized"].includes(existing.checkpoint) && fs.existsSync(receiptFile))
|
|
174
|
-
return JSON.parse(fs.readFileSync(receiptFile, "utf8"));
|
|
175
227
|
const request = requireOwnedActiveRequest(context, input);
|
|
228
|
+
assertRunMutationAllowed(context, request.project_id, request.run_id);
|
|
229
|
+
if (["apply_recorded", "integration_committed", "bootstrap_ready", "checks_passed", "delivered", "finalized"].includes(request.checkpoint) && fs.existsSync(receiptFile)) {
|
|
230
|
+
const receipt = JSON.parse(fs.readFileSync(receiptFile, "utf8"));
|
|
231
|
+
if (receipt.merge_request_id !== request.merge_request_id || receipt.work_id !== request.executor_work_id || receipt.source_commit !== request.source_commit)
|
|
232
|
+
throw new AppError("merge_apply_receipt_invalid", "Existing merge apply receipt does not match the active request", 1, { receipt_path: receiptFile });
|
|
233
|
+
return receipt;
|
|
234
|
+
}
|
|
176
235
|
heartbeatLaneLock(context, { projectRoot: input.projectRoot, lane: "merge", workerId: request.executor_work_id, workspacePath: request.target_workspace, ttlSeconds: 7200 });
|
|
177
236
|
assertExecutionBaseline(request);
|
|
178
237
|
input.progress?.(`applying ${request.source_commit} to ${request.target_branch}`);
|
|
@@ -194,54 +253,81 @@ export function applyVnextMerge(context, input) {
|
|
|
194
253
|
context.db.run("UPDATE merge_requests SET checkpoint = 'apply_recorded', result_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ apply_receipt: receiptFile }), context.now(), request.merge_request_id]);
|
|
195
254
|
return { ok: true, ...receipt };
|
|
196
255
|
}
|
|
197
|
-
export
|
|
256
|
+
export function prepareVnextMergeFinish(context, input) {
|
|
198
257
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
199
258
|
const project = requireProjectByRoot(context, projectRoot);
|
|
200
259
|
const run = requireRun(context, project.id, input.runId);
|
|
201
260
|
const existing = requireRequest(context, input.requestId);
|
|
261
|
+
const generation = assertRunMutationAllowed(context, project.id, run.id);
|
|
202
262
|
if (existing.project_id !== project.id || existing.run_id !== run.id || existing.executor_work_id !== input.workId)
|
|
203
263
|
throw new AppError("merge_request_mismatch", "MRG/Work/RUN/project identity does not match", 2);
|
|
204
|
-
if (existing.status === "completed")
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
}
|
|
208
|
-
let request = requireOwnedActiveRequest(context, input);
|
|
209
|
-
heartbeatLaneLock(context, { projectRoot, lane: "merge", workerId: request.executor_work_id, workspacePath: request.target_workspace, ttlSeconds: 7200 });
|
|
264
|
+
if (existing.status === "completed")
|
|
265
|
+
return { projectRoot, project, run, existing, generation, terminal: true };
|
|
266
|
+
const request = requireOwnedActiveRequest(context, input);
|
|
210
267
|
if (request.run_id !== run.id)
|
|
211
268
|
throw new AppError("merge_request_mismatch", "MRG does not belong to RUN", 2);
|
|
212
269
|
if (request.checkpoint === "baseline_locked" || !fs.existsSync(applyReceiptPath(context, request)))
|
|
213
270
|
throw new AppError("merge_apply_required", "Run the exact merge apply command before MERGE finish", 2, { merge_request_id: request.merge_request_id, checkpoint: request.checkpoint });
|
|
214
|
-
|
|
215
|
-
|
|
271
|
+
const conflicts = unmerged(request.target_workspace);
|
|
272
|
+
if (conflicts.length)
|
|
273
|
+
throw new AppError("merge_conflicts_unresolved", "Resolve every unmerged path before finishing MERGE", 2, { paths: conflicts });
|
|
216
274
|
const resultPath = path.join(requireHome(run), stageDir, "works", request.executor_work_id, "result.json");
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
if (semantic.outcome !== "completed")
|
|
275
|
+
const result = prepareJsonSchema(resultPath, "MERGE result", { schemaName: "merge-result", projectRoot: request.target_workspace, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireHome(run) });
|
|
276
|
+
if (result.value.outcome !== "completed")
|
|
220
277
|
throw new AppError("merge_semantic_blocked", "A blocked semantic result cannot complete MERGE", 2, { result_path: resultPath });
|
|
278
|
+
const gate = readFrozenMergeGate(path.join(requireHome(run), stageDir, "merge-gate.json"), request.merge_request_id);
|
|
279
|
+
if (input.retryCheckId)
|
|
280
|
+
validateFailedCheckRetry(context, { projectId: project.id, runId: run.id, receiptId: input.retryCheckId, declarations: gate.checks, reason: input.retryReason });
|
|
281
|
+
return { projectRoot, project, run, existing, generation, terminal: false, request, resultPath, result, gate };
|
|
282
|
+
}
|
|
283
|
+
export async function finishVnextMerge(context, input, prepared = prepareVnextMergeFinish(context, input)) {
|
|
284
|
+
const { projectRoot, project, run, existing, generation } = prepared;
|
|
285
|
+
if (prepared.terminal) {
|
|
286
|
+
recoverCompletedMergeRun(context, run, projectRoot, existing);
|
|
287
|
+
releaseMergeLane(context, projectRoot, existing, `MERGE ${existing.merge_request_id} completion recovered`);
|
|
288
|
+
return { ok: true, resumed: true, run_id: run.id, stage, outcome: "completed", merge_request_id: existing.merge_request_id, work_id: existing.executor_work_id, integration_commit: existing.integration_commit, report_path: path.join(requireHome(run), stageDir, "stage-report.json"), next_action: "merge_completed" };
|
|
289
|
+
}
|
|
290
|
+
let request = prepared.request;
|
|
291
|
+
heartbeatLaneLock(context, { projectRoot, lane: "merge", workerId: request.executor_work_id, workspacePath: request.target_workspace, ttlSeconds: 7200 });
|
|
292
|
+
const semantic = prepared.result.value;
|
|
221
293
|
if (request.checkpoint === "apply_recorded") {
|
|
222
294
|
input.progress?.("bootstrapping integrated target");
|
|
223
|
-
runBootstrap(run, request.target_workspace);
|
|
295
|
+
await runBootstrap(context, run, request.target_workspace, request.merge_request_id, input.progress);
|
|
296
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
224
297
|
context.db.run("UPDATE merge_requests SET checkpoint = 'bootstrap_ready', updated_at = ? WHERE merge_request_id = ?", [context.now(), request.merge_request_id]);
|
|
225
298
|
request = requireRequest(context, request.merge_request_id);
|
|
226
299
|
}
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
300
|
+
const gate = prepared.gate, checks = gate.checks;
|
|
301
|
+
if (input.retryCheckId)
|
|
302
|
+
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "check_retry_requested", check_receipt_id: input.retryCheckId, stage, reason: input.retryReason ?? "operator retry" });
|
|
303
|
+
for (const check of checks)
|
|
304
|
+
validateCheckDeclaration(request.target_workspace, check);
|
|
305
|
+
retainMergeProfile(path.join(requireHome(run), stageDir), "target", request.target_workspace);
|
|
306
|
+
const acceptancePath = path.join(requireHome(run), stageDir, "merge-gate-acceptance.json");
|
|
307
|
+
const recovered = readMergeGateAcceptance(context, acceptancePath, request, gate);
|
|
308
|
+
const resumingGate = ["checks_passed", "integration_committed", "delivered"].includes(request.checkpoint);
|
|
309
|
+
if (resumingGate && !recovered.valid)
|
|
310
|
+
return recovery(context, request, "merge_evidence_missing", { checkpoint: request.checkpoint });
|
|
311
|
+
if (request.checkpoint === "checks_passed" && request.accepted_tree && gitValue(request.target_workspace, ["write-tree"]) !== request.accepted_tree)
|
|
312
|
+
return recovery(context, request, "merge_workspace_drift_after_checks", { accepted_tree: request.accepted_tree });
|
|
313
|
+
const receipts = resumingGate ? recovered.receipts : await runCodeChecks(context, { projectId: project.id, runId: run.id, runHome: requireHome(run), workspaceRoot: request.target_workspace, workId: request.executor_work_id, artifactDir: path.join(stageDir, "works", request.executor_work_id), scope: "aggregate", checks, expectedProfileHash: gate.profileHash, ...(input.retryCheckId ? { retryReceiptId: input.retryCheckId, retryReason: input.retryReason } : {}), ...(input.progress ? { progress: input.progress } : {}) });
|
|
314
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
232
315
|
const failed = receipts.filter((receipt) => receipt.status !== "passed");
|
|
233
316
|
if (failed.length) {
|
|
234
317
|
context.db.run("UPDATE merge_requests SET status = 'action_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "merge_gate_failed", failures: failed }), context.now(), request.merge_request_id]);
|
|
235
|
-
|
|
318
|
+
const sourceRepair = failed.every(receipt => checkRepairDisposition(receipt) === "source_repair");
|
|
319
|
+
throw new AppError("merge_gate_failed", "Integrated target checks failed. Only assertion-backed failures permit source repair; tooling or unknown evidence requires diagnosis/settlement first.", 2, { failures: failed, ...(sourceRepair ? { repair_command: repairCommand(context, request, projectRoot) } : { outcome: "blocked", recoverable: false }), continuation: { ...recoveryEvidenceInput(run.run_root, failed[0].id), command_after_input: finishCommand(context, run.id, request, projectRoot, failed[0].id) } });
|
|
236
320
|
}
|
|
237
|
-
const requiredRefs = mergeAcceptanceRefs(run.workspace_root, JSON.parse(request.protocol_ids_json));
|
|
238
321
|
const passedRefs = new Set(receipts.flatMap((receipt) => receipt.check_refs));
|
|
239
|
-
const missingRefs =
|
|
322
|
+
const missingRefs = frozenGateRefs(gate).filter((ref) => !passedRefs.has(ref));
|
|
240
323
|
if (missingRefs.length)
|
|
241
|
-
throw new AppError("merge_acceptance_unproven", "Current MERGE receipts do not cover every merge
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
324
|
+
throw new AppError("merge_acceptance_unproven", "Current MERGE receipts do not cover every frozen merge-gate reference", 2, { missing_check_refs: missingRefs });
|
|
325
|
+
if (!request.integration_commit) {
|
|
326
|
+
const acceptedTree = gitValue(request.target_workspace, ["write-tree"]);
|
|
327
|
+
writeMergeGateAcceptance(context, acceptancePath, request, gate, acceptedTree, receipts);
|
|
328
|
+
context.db.run("UPDATE merge_requests SET checkpoint = 'checks_passed', accepted_tree = ?, status = 'active', updated_at = ? WHERE merge_request_id = ?", [acceptedTree, context.now(), request.merge_request_id]);
|
|
329
|
+
request = requireRequest(context, request.merge_request_id);
|
|
330
|
+
}
|
|
245
331
|
if (!request.integration_commit) {
|
|
246
332
|
commitIntegration(request.target_workspace, run.id, ignoredGitPaths(context, project.id));
|
|
247
333
|
const commit = gitValue(request.target_workspace, ["rev-parse", "HEAD"]);
|
|
@@ -252,17 +338,35 @@ export async function finishVnextMerge(context, input) {
|
|
|
252
338
|
context.db.run("UPDATE merge_requests SET integration_commit = ?, checkpoint = 'integration_committed', updated_at = ? WHERE merge_request_id = ?", [commit, context.now(), request.merge_request_id]);
|
|
253
339
|
request = requireRequest(context, request.merge_request_id);
|
|
254
340
|
}
|
|
341
|
+
if (request.integration_commit && request.accepted_tree && gitValue(request.target_workspace, ["rev-parse", `${request.integration_commit}^{tree}`]) !== request.accepted_tree)
|
|
342
|
+
return recovery(context, request, "merge_committed_tree_drift", { accepted_tree: request.accepted_tree, integration_commit: request.integration_commit });
|
|
255
343
|
verifyLocalDelivery(request);
|
|
256
344
|
context.db.run("UPDATE merge_requests SET checkpoint = 'delivered', updated_at = ? WHERE merge_request_id = ?", [context.now(), request.merge_request_id]);
|
|
257
345
|
request = requireRequest(context, request.merge_request_id);
|
|
346
|
+
const matrix = prepareRunVerificationMatrix(context, { projectId: project.id, runId: run.id, stage, role: "output", receipts, semanticFile: prepared.resultPath });
|
|
347
|
+
// Retain exact bounded sources before deleting the feature checkout. A
|
|
348
|
+
// crash here recovers presentation from packets, never repeats the checks.
|
|
349
|
+
context.db.writeTransaction(() => acceptVerificationMatrix(context, matrix));
|
|
350
|
+
publishVerificationMatrix(context, matrix);
|
|
258
351
|
performConfiguredCleanup(run, request);
|
|
259
|
-
|
|
352
|
+
const acceptedResult = prepared.result.text;
|
|
353
|
+
const executor = context.db.get("SELECT status, result FROM works WHERE work_id = ?", [request.executor_work_id]);
|
|
354
|
+
if (!executor)
|
|
355
|
+
return recovery(context, request, "merge_executor_missing", { work_id: request.executor_work_id });
|
|
356
|
+
if (executor.status === "running")
|
|
357
|
+
await finishWork(context, request.executor_work_id, acceptedResult);
|
|
358
|
+
else if (executor.status !== "completed" || executor.result !== acceptedResult)
|
|
359
|
+
return recovery(context, request, "merge_executor_settlement_mismatch", { work_id: request.executor_work_id, status: executor.status });
|
|
360
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
260
361
|
const now = context.now();
|
|
261
362
|
context.db.run("UPDATE merge_requests SET status = 'completed', checkpoint = 'finalized', result_json = ?, completed_at = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify(semantic), now, now, request.merge_request_id]);
|
|
262
|
-
const report = mergeReport(context, run, requireRequest(context, request.merge_request_id), semantic, receipts);
|
|
263
363
|
const root = path.join(requireHome(run), stageDir);
|
|
264
|
-
|
|
265
|
-
|
|
364
|
+
const retainedReport = completedMergeReport(context, run, root);
|
|
365
|
+
const report = retainedReport ?? mergeReport(context, run, requireRequest(context, request.merge_request_id), semantic, receipts);
|
|
366
|
+
if (matrix)
|
|
367
|
+
Object.assign(report.semantic, { verification_matrix: matrix.metadata });
|
|
368
|
+
if (!retainedReport)
|
|
369
|
+
commitMergeStageReport(context, run, projectRoot, root, report);
|
|
266
370
|
const rootWork = requireRootWork(context, project.id, run.id);
|
|
267
371
|
finishFanInWork(context, rootWork.work_id, JSON.stringify(report));
|
|
268
372
|
completeFlowRun(context, { projectRoot, runId: run.id, status: "done", verdict: "merge_completed", nextAction: undefined });
|
|
@@ -281,37 +385,100 @@ function ensureMergeStageAttached(context, run, projectRoot) {
|
|
|
281
385
|
function recoverCompletedMergeRun(context, run, projectRoot, request) {
|
|
282
386
|
const root = path.join(requireHome(run), stageDir);
|
|
283
387
|
const reportPath = path.join(root, "stage-report.json");
|
|
284
|
-
|
|
285
|
-
|
|
388
|
+
const retainedReport = completedMergeReport(context, run, root);
|
|
389
|
+
let report;
|
|
390
|
+
if (retainedReport)
|
|
391
|
+
report = retainedReport;
|
|
392
|
+
else if (!fs.existsSync(reportPath)) {
|
|
393
|
+
const semantic = request.result_json ? JSON.parse(request.result_json) : null;
|
|
394
|
+
const gate = readFrozenMergeGate(path.join(root, "merge-gate.json"), request.merge_request_id);
|
|
395
|
+
const accepted = readMergeGateAcceptance(context, path.join(root, "merge-gate-acceptance.json"), request, gate);
|
|
396
|
+
if (!semantic || typeof semantic.summary !== "string" || typeof semantic.verification_summary !== "string" || !Array.isArray(semantic.residual_risks) || !semantic.residual_risks.every(item => typeof item === "string") || !accepted.valid)
|
|
397
|
+
throw new AppError("merge_report_missing", "Completed MERGE has insufficient authoritative evidence to rebuild its report", 1, { merge_request_id: request.merge_request_id, report_path: reportPath });
|
|
398
|
+
verifyLocalDelivery(request);
|
|
399
|
+
performConfiguredCleanup(run, request);
|
|
400
|
+
report = mergeReport(context, run, request, semantic, accepted.receipts);
|
|
401
|
+
}
|
|
402
|
+
else
|
|
403
|
+
report = JSON.parse(fs.readFileSync(reportPath, "utf8"));
|
|
286
404
|
ensureMergeStageAttached(context, run, projectRoot);
|
|
287
|
-
|
|
405
|
+
if (!retainedReport)
|
|
406
|
+
commitMergeStageReport(context, run, projectRoot, root, report);
|
|
288
407
|
const rootWork = findRootWork(context, run.project_id, run.id);
|
|
289
408
|
const rootStatus = rootWork.status;
|
|
290
409
|
if (rootStatus === "running")
|
|
291
410
|
finishFanInWork(context, rootWork.work_id, fs.readFileSync(reportPath, "utf8"));
|
|
411
|
+
else if (rootStatus !== "completed")
|
|
412
|
+
throw new AppError("merge_root_settlement_mismatch", "Completed MERGE cannot recover a non-completed root Work", 1, { merge_request_id: request.merge_request_id, work_id: rootWork.work_id, status: rootStatus });
|
|
292
413
|
const runStatus = context.db.get("SELECT status FROM runs WHERE project_id = ? AND id = ?", [run.project_id, run.id])?.status;
|
|
293
414
|
if (runStatus !== "done")
|
|
294
415
|
completeFlowRun(context, { projectRoot, runId: run.id, status: "done", verdict: "merge_completed", nextAction: undefined });
|
|
295
416
|
refreshRunWorkProjection(context, run.project_id, run.id);
|
|
296
417
|
}
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
418
|
+
function completedMergeReport(context, run, root) {
|
|
419
|
+
const current = requireRun(context, run.project_id, run.id);
|
|
420
|
+
const index = JSON.parse(current.index_json);
|
|
421
|
+
const entry = index.stage_runs?.find(item => item.stage === stage);
|
|
422
|
+
if (entry?.status !== "done")
|
|
423
|
+
return null;
|
|
424
|
+
const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_report' ORDER BY id DESC", [run.project_id]);
|
|
425
|
+
const receipt = rows.map(row => JSON.parse(row.payload_json))
|
|
426
|
+
.find(item => item.run_id === run.id && item.stage === stage && item.attempt === entry.attempt && item.root === root);
|
|
427
|
+
if (receipt) {
|
|
428
|
+
if (crypto.createHash("sha256").update(receipt.bytes.json).digest("hex") !== receipt.sha256)
|
|
429
|
+
throw new AppError("stage_report_invalid", "Accepted MERGE report receipt has invalid bytes", 1, { run_id: run.id });
|
|
430
|
+
publishStageReport(context, run.project_id, run.id, stage, root);
|
|
431
|
+
return JSON.parse(receipt.bytes.json);
|
|
432
|
+
}
|
|
433
|
+
const file = path.join(root, "stage-report.json");
|
|
434
|
+
if (!fs.existsSync(file))
|
|
435
|
+
throw new AppError("merge_report_missing", "Completed MERGE has no accepted report receipt or published report", 1, { run_id: run.id, report_path: file });
|
|
436
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
437
|
+
}
|
|
438
|
+
function commitMergeStageReport(context, run, projectRoot, root, report) {
|
|
439
|
+
const matrix = latestRunVerificationMatrix(context, run.project_id, run.id, stage, "output");
|
|
440
|
+
if (matrix)
|
|
441
|
+
Object.assign(report.semantic, { verification_matrix: matrix.metadata });
|
|
442
|
+
if (JSON.parse(run.index_json).verification_matrix_contract && !matrix)
|
|
443
|
+
throw new AppError("verification_matrix_packet_missing", "Completed marked MERGE lacks its retained final matrix", 1, { run_id: run.id });
|
|
444
|
+
const preparedReport = prepareStageReport(report);
|
|
445
|
+
const completion = { projectRoot, runId: run.id, stage, status: "done", data: "stage-report.json", dataSchemaId: "dd-flow/stage-report@2", report: "stage-report.md", stageReport: "stage-report.html", dataSha256: preparedReport.sha256 };
|
|
446
|
+
const preparedCompletion = prepareFlowRunStageCompletion(context, completion);
|
|
447
|
+
withStageSettlement(context, () => {
|
|
448
|
+
acceptVerificationMatrix(context, matrix);
|
|
449
|
+
acceptStageReport(context, { projectId: run.project_id, runId: run.id, stage, root, prepared: preparedReport });
|
|
450
|
+
completeFlowRunStage(context, completion, preparedCompletion);
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
export function routeVnextMergeRequest(context, input) {
|
|
454
|
+
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
455
|
+
const request = context.db.writeTransaction(() => {
|
|
456
|
+
const request = requireRequest(context, input.requestId);
|
|
457
|
+
if (request.project_id !== project.id || request.status !== "queued")
|
|
458
|
+
throw new AppError("invalid_merge_state", "Only a queued request without an active dispatch may change route", 2, { status: request.status });
|
|
459
|
+
assertRunMutationAllowed(context, request.project_id, request.run_id);
|
|
460
|
+
context.db.run("UPDATE merge_requests SET execution_route = ?, last_error_json = ?, updated_at = ? WHERE merge_request_id = ? AND status = 'queued'", [input.mode, JSON.stringify({ route_reason: input.reason }), context.now(), request.merge_request_id]);
|
|
461
|
+
context.db.run("UPDATE works SET launch_policy = ?, updated_at = ? WHERE work_id = ? AND status = 'created'", [input.mode === "server" ? "fresh_agent_required" : "reuse_allowed", context.now(), request.executor_work_id]);
|
|
462
|
+
return request;
|
|
463
|
+
});
|
|
464
|
+
refreshRunWorkProjection(context, request.project_id, request.run_id);
|
|
465
|
+
return requestView(context, requireRequest(context, request.merge_request_id));
|
|
302
466
|
}
|
|
303
|
-
catch (error) {
|
|
304
|
-
context.db.exec("ROLLBACK");
|
|
305
|
-
throw error;
|
|
306
|
-
} refreshRunWorkProjection(context, request.project_id, request.run_id); return requestView(context, requireRequest(context, request.merge_request_id)); }
|
|
307
467
|
/** Move a failed integration gate back to the source CODE/CODE-REVIEW loop. */
|
|
308
468
|
export async function repairVnextMerge(context, input) {
|
|
309
469
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
310
470
|
const project = requireProjectByRoot(context, projectRoot);
|
|
311
471
|
const request = requireRequest(context, input.requestId);
|
|
472
|
+
const generation = assertRunMutationAllowed(context, project.id, request.run_id);
|
|
473
|
+
if (request.project_id === project.id && request.status === "superseded" && errorCode(request) === "merge_source_repair") {
|
|
474
|
+
const saved = JSON.parse(request.last_error_json);
|
|
475
|
+
releaseMergeLane(context, projectRoot, request, `MERGE ${request.merge_request_id} moved to source repair`);
|
|
476
|
+
return { ok: true, run_id: request.run_id, merge_request_id: request.merge_request_id, status: "superseded", source_repair: { repair_work_id: saved.repair_work_id }, next: stageSuccessor(context, { projectRoot, runId: request.run_id, stage: "code", command: runtimeCommand(context, ["stage", "start", request.run_id, "--stage", "code", "--project-root", projectRoot, "--json", "--progress-jsonl"]) }) };
|
|
477
|
+
}
|
|
312
478
|
if (request.project_id !== project.id || request.status !== "action_required" || errorCode(request) !== "merge_gate_failed") {
|
|
313
479
|
throw new AppError("invalid_merge_repair_state", "MERGE source repair requires an action-required failed integration gate", 2, { merge_request_id: input.requestId, status: request.status, code: errorCode(request) });
|
|
314
480
|
}
|
|
481
|
+
assertSourceRepairEligible(checkReceipts(context, { projectId: project.id, runId: request.run_id }).filter(receipt => failedReceiptIds(request).includes(receipt.id)));
|
|
315
482
|
abortIntegration(request);
|
|
316
483
|
const originWorkIds = sourceCodeWorkIds(context, request.project_id, request.run_id);
|
|
317
484
|
if (!originWorkIds.length)
|
|
@@ -321,37 +488,77 @@ export async function repairVnextMerge(context, input) {
|
|
|
321
488
|
throw new AppError("runtime_missing", "MERGE failure has no durable failed receipt", 1, { merge_request_id: request.merge_request_id });
|
|
322
489
|
// Settle the child while its canonical result path still exists; the next
|
|
323
490
|
// step archives the entire MERGE attempt as immutable evidence.
|
|
324
|
-
|
|
491
|
+
const executor = context.db.get("SELECT status FROM works WHERE work_id = ?", [request.executor_work_id]);
|
|
492
|
+
if (executor?.status !== "failed")
|
|
493
|
+
await failWork(context, request.executor_work_id, `Superseded by source repair after failed integration gate ${failed[0]}.`);
|
|
494
|
+
assertRunMutationAllowed(context, project.id, request.run_id, generation);
|
|
325
495
|
const prepared = prepareVnextMergeSourceRepairAttempt(context, { projectRoot, runId: request.run_id, mergeRequestId: request.merge_request_id });
|
|
326
|
-
const repair = addVnextCodeRepair(context, { projectRoot, runId: request.run_id, checkReceiptId: failed[0], originWorkIds, objective: `Repair source behavior evidenced by failed integration check ${failed[0]}.` });
|
|
496
|
+
const repair = addVnextCodeRepair(context, { projectRoot, runId: request.run_id, stage: "code", checkReceiptId: failed[0], originWorkIds, reviewCycle: `MRR-${request.merge_request_id}`, objective: `Repair source behavior evidenced by failed integration check ${failed[0]}.` });
|
|
327
497
|
const now = context.now();
|
|
328
498
|
context.db.run("UPDATE merge_requests SET status = 'superseded', checkpoint = 'source_repair_required', last_error_json = ?, completed_at = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code: "merge_source_repair", replacement_pending: true, failed_receipt_ids: failed, repair_work_id: repair.repair_work_id }), now, now, request.merge_request_id]);
|
|
329
499
|
releaseMergeLane(context, projectRoot, request, `MERGE ${request.merge_request_id} moved to source repair`);
|
|
330
500
|
appendFlowRunTimelineEvent(context, project.id, request.run_id, { type: "merge_source_repair_created", merge_request_id: request.merge_request_id, repair_work_id: repair.repair_work_id, cycle: prepared.cycle, failed_receipt_ids: failed });
|
|
331
|
-
return { ok: true, run_id: request.run_id, merge_request_id: request.merge_request_id, status: "superseded", source_repair: repair, next: {
|
|
501
|
+
return { ok: true, run_id: request.run_id, merge_request_id: request.merge_request_id, status: "superseded", source_repair: repair, next: stageSuccessor(context, { projectRoot, runId: request.run_id, stage: "code", command: runtimeCommand(context, ["stage", "start", request.run_id, "--stage", "code", "--project-root", projectRoot, "--json", "--progress-jsonl"]) }) };
|
|
502
|
+
}
|
|
503
|
+
function mergePrompt(context, input, checks, settings) { const pause = stagePauseCommand(context, { runId: input.run.id, stage: "merge", workId: input.request.executor_work_id, projectRoot: input.projectRoot }); const repair = repairCommand(context, input.request, input.projectRoot); return ["<stage_identity>", `- RUN: ${input.run.id}`, `- MERGE request: ${input.request.merge_request_id}`, `- Work: ${input.request.executor_work_id}`, "- stage: merge", "</stage_identity>", "", "<trusted_runtime_context>", `- integration workspace: ${input.request.target_workspace}`, `- source workspace: ${input.request.source_workspace}`, `- frozen source commit: ${input.request.source_commit}`, `- target branch: ${input.request.target_branch}`, `- execution target baseline: ${input.request.execution_target_head}`, `- queue route: ${input.request.execution_route}`, `- delivery: ${JSON.stringify(settings.merge_delivery)}`, `- cleanup: ${JSON.stringify(settings.merge_cleanup)}`, "These facts and the acquired project integration lane were established by dd-flow. Do not repeat discovery and do not run git merge/rebase/squash yourself.", "</trusted_runtime_context>", "", "<effective_merge_gate>", ...checks.map((check) => `- ${check.canonical_ref ?? check.id}: ${check.command} — ${check.purpose}`), "</effective_merge_gate>", "", "<execution_contract>", `1. Run this exact standalone command first: ${applyCommand(context, input.request, input.projectRoot)}`, "2. If it reports conflicts, resolve only the actual unmerged paths in the integration workspace. Do not repeat merge apply and do not edit product code, tests, documentation or configuration merely to make a gate pass.", `3. Write the compact semantic result to ${input.resultPath}:`, "```json", JSON.stringify({ schema_id: "dd-flow/merge-result@1", outcome: "completed", summary: "What was integrated.", conflict_resolution: "How material conflicts were resolved, or empty when none.", verification_summary: "Why the integrated result is ready for deterministic checks.", residual_risks: [] }, null, 2), "```", `4. Finish with this exact standalone command and wait for all progress: ${finishCommand(context, input.run.id, input.request, input.projectRoot)}`, `If a gate fails, read its receipt and logs and determine the cause. For a product defect use ${repair}; it restores the target baseline and opens CODE → independent CODE-REVIEW → replacement MRG. For an environment failure restore the declared environment in this MERGE and write the returned recovery JSON file and use continuation.command_after_input. The CLI reruns the real gate and retains the old receipt. Never edit product code in the integration target to make a gate pass.`, "If a material conflict has no reasonable answer in accepted evidence, pause this same Work by writing the question file and then running the separate standalone command below, ask the returned user_message, then use the exact resume command returned by CLI:", "```sh", stagePauseCommandTemplate(pause), "```", "</execution_contract>", ""].join("\n"); }
|
|
504
|
+
function mergeReport(context, run, request, semantic, receipts) {
|
|
505
|
+
const now = context.now();
|
|
506
|
+
const startedAt = request.lock_acquired_at ?? request.created_at;
|
|
507
|
+
const cleanup = cleanupReceiptPath(run);
|
|
508
|
+
return { schema_id: "dd-flow/stage-report@2", run_id: run.id, stage, generated_at: now, verdict: "done", summary: semantic.summary,
|
|
509
|
+
semantic: { result: semantic.summary, acceptance: ["source_commit_frozen", "integration_commit_created", "merge_gate_passed", "delivery_confirmed"], changed_files: [], checks: receipts.map((item) => item.command), evidence: [applyReceiptPath(context, request), ...receipts.map((item) => item.receipt_path), ...(fs.existsSync(cleanup) ? [cleanup] : [])], next_action: "merge_completed", merge: { merge_request_id: request.merge_request_id, work_id: request.executor_work_id, protocols: JSON.parse(request.protocol_ids_json), source_commit: request.source_commit, execution_target_head: request.execution_target_head, accepted_tree: request.accepted_tree, integration_commit: request.integration_commit, route: request.execution_route, delivery: executionSettings(run).merge_delivery, cleanup: executionSettings(run).merge_cleanup, verification_summary: semantic.verification_summary, residual_risks: semantic.residual_risks } },
|
|
510
|
+
mechanical: { started_at: startedAt, finished_at: now, wall_clock_ms: Math.max(0, Date.parse(now) - Date.parse(startedAt)), git: gitFacts(request.target_workspace), queue: queueStatus(context, request) },
|
|
511
|
+
artifacts: { json: "stage-report.json", markdown: "stage-report.md", html: "stage-report.html" }, validation: { status: "passed" } };
|
|
332
512
|
}
|
|
333
|
-
function mergePrompt(context, input) { const pause = `${flowCommand(context)} stage pause ${input.run.id} --stage merge --work ${input.request.executor_work_id} --project-root ${JSON.stringify(input.projectRoot)} --question-stdin --json`; const repair = `${flowCommand(context)} merge repair ${input.request.merge_request_id} --project-root ${JSON.stringify(input.projectRoot)} --json`; return ["<stage_identity>", `- RUN: ${input.run.id}`, `- MERGE request: ${input.request.merge_request_id}`, `- Work: ${input.request.executor_work_id}`, "- stage: merge", "</stage_identity>", "", "<trusted_runtime_context>", `- integration workspace: ${input.request.target_workspace}`, `- source workspace: ${input.request.source_workspace}`, `- frozen source commit: ${input.request.source_commit}`, `- target branch: ${input.request.target_branch}`, `- execution target baseline: ${input.request.execution_target_head}`, `- queue route: ${input.request.execution_route}`, `- delivery: ${JSON.stringify(executionSettings(input.run).merge_delivery)}`, `- cleanup: ${JSON.stringify(executionSettings(input.run).merge_cleanup)}`, "These facts and the acquired project integration lane were established by dd-flow. Do not repeat discovery and do not run git merge/rebase/squash yourself.", "</trusted_runtime_context>", "", "<effective_merge_gate>", ...effectiveMergeChecks(input.run, input.request).map((check) => `- ${check.canonical_ref ?? check.id}: ${check.command} — ${check.purpose}`), "</effective_merge_gate>", "", "<execution_contract>", `1. Run this exact standalone command first: ${applyCommand(context, input.request, input.projectRoot)}`, "2. If it reports conflicts, resolve only the actual unmerged paths in the integration workspace. Do not repeat merge apply and do not edit product code, tests, documentation or configuration merely to make a gate pass.", `3. Write the compact semantic result to ${input.resultPath}:`, "```json", JSON.stringify({ schema_id: "dd-flow/merge-result@1", outcome: "completed", summary: "What was integrated.", conflict_resolution: "How material conflicts were resolved, or empty when none.", verification_summary: "Why the integrated result is ready for deterministic checks.", residual_risks: [] }, null, 2), "```", `4. Finish with this exact standalone command and wait for all progress: ${finishCommand(context, input.run.id, input.request, input.projectRoot)}`, `If a gate fails, inspect only the returned receipt/logs, then run this exact source-repair command: ${repair}. It restores the integration target to baseline and creates a CODE → independent CODE-REVIEW → replacement MRG cycle. Do not repair the integration target and do not retry this MRG.`, "If a material conflict has no reasonable answer in accepted evidence, pause this same Work with the exact heredoc below, ask the returned user_message, then use the exact resume command returned by CLI:", "```sh", stagePauseCommandTemplate(pause), "```", "</execution_contract>", ""].join("\n"); }
|
|
334
|
-
function mergeReport(context, run, request, semantic, receipts) { const now = context.now(); const cleanup = cleanupReceiptPath(run); return { schema_id: "dd-flow/stage-report@2", run_id: run.id, stage, generated_at: now, verdict: "done", summary: semantic.summary, semantic: { result: semantic.summary, acceptance: ["source_commit_frozen", "integration_commit_created", "merge_gate_passed", "delivery_confirmed"], changed_files: [], checks: receipts.map((item) => item.command), evidence: [applyReceiptPath(context, request), ...receipts.map((item) => item.receipt_path), ...(fs.existsSync(cleanup) ? [cleanup] : [])], next_action: "merge_completed", merge: { merge_request_id: request.merge_request_id, work_id: request.executor_work_id, protocols: JSON.parse(request.protocol_ids_json), source_commit: request.source_commit, execution_target_head: request.execution_target_head, accepted_tree: request.accepted_tree, integration_commit: request.integration_commit, route: request.execution_route, delivery: executionSettings(run).merge_delivery, cleanup: executionSettings(run).merge_cleanup, verification_summary: semantic.verification_summary, residual_risks: semantic.residual_risks } }, mechanical: { started_at: request.lock_acquired_at, finished_at: now, git: gitFacts(request.target_workspace), queue: queueStatus(context, request) }, artifacts: { json: "stage-report.json", markdown: "stage-report.md", html: "stage-report.html" }, validation: { status: "passed" } }; }
|
|
335
513
|
function effectiveMergeChecks(run, request) { return readFrozenMergeGate(path.join(requireHome(run), stageDir, "merge-gate.json"), request.merge_request_id).checks; }
|
|
336
514
|
function planChecks(workspace, protocols) { return protocols.flatMap((protocol) => { const file = path.join(workspace, ".memory-bank", "protocol", protocol, "plan.json"); if (!fs.existsSync(file))
|
|
337
|
-
|
|
515
|
+
throw new AppError("merge_plan_missing", "MERGE requires every accepted PLAN", 2, { protocol_id: protocol }); const plan = JSON.parse(fs.readFileSync(file, "utf8")); return (plan.checks ?? []).map((check) => ({ ...check, canonical_ref: `${protocol}/${check.id}` })); }); }
|
|
338
516
|
function validateMergeAcceptance(workspace, protocols, checks) { const known = new Set(checks.map((check) => check.canonical_ref)); const missing = mergeAcceptanceRefs(workspace, protocols).filter((ref) => !known.has(ref)); if (missing.length)
|
|
339
517
|
throw new AppError("merge_acceptance_invalid", "A merge acceptance criterion references a missing check", 2, { check_refs: missing }); }
|
|
340
|
-
function freezeMergeGate(file, input) { const canonical = JSON.stringify(input.checks); const hash = cryptoHash(canonical); if (fs.existsSync(file)) {
|
|
518
|
+
function freezeMergeGate(file, input) { const canonical = JSON.stringify({ checks: input.checks, acceptance_refs: [...input.acceptanceRefs].sort() }); const hash = cryptoHash(canonical); if (fs.existsSync(file)) {
|
|
341
519
|
const existing = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
342
|
-
if (existing.run_id !== input.runId || existing.
|
|
520
|
+
if (existing.run_id !== input.runId || existing.gate_hash !== hash)
|
|
343
521
|
throw new AppError("merge_gate_freeze_conflict", "MERGE gate is already frozen with different checks", 2, { file });
|
|
344
522
|
return;
|
|
345
|
-
} fs.writeFileSync(file, `${JSON.stringify({ schema_id: "dd-flow/merge-gate@
|
|
523
|
+
} fs.writeFileSync(file, `${JSON.stringify({ schema_id: "dd-flow/merge-gate@2", run_id: input.runId, protocols: input.protocols, checks: input.checks, acceptance_refs: [...input.acceptanceRefs].sort(), gate_hash: hash, profile_hash: input.profileHash, frozen_at: input.now }, null, 2)}\n`); }
|
|
346
524
|
function readFrozenMergeGate(file, requestId) { try {
|
|
347
525
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
348
|
-
if (value.schema_id !== "dd-flow/merge-gate@
|
|
526
|
+
if (value.schema_id !== "dd-flow/merge-gate@2" || !Array.isArray(value.checks) || !Array.isArray(value.acceptance_refs) || !value.acceptance_refs.every(ref => typeof ref === "string") || typeof value.gate_hash !== "string" || value.gate_hash !== cryptoHash(JSON.stringify({ checks: value.checks, acceptance_refs: [...value.acceptance_refs].sort() })))
|
|
349
527
|
throw new Error("invalid gate");
|
|
350
|
-
return { checks: value.checks };
|
|
528
|
+
return { checks: value.checks, acceptanceRefs: [...value.acceptance_refs].sort(), profileHash: value.profile_hash ?? null, gateHash: value.gate_hash };
|
|
351
529
|
}
|
|
352
530
|
catch (cause) {
|
|
353
531
|
throw new AppError("merge_gate_missing", "MERGE gate is missing or invalid", 1, { merge_request_id: requestId, file, cause: String(cause) });
|
|
354
532
|
} }
|
|
533
|
+
function retainMergeProfile(root, role, workspace) {
|
|
534
|
+
const { profile, hash, file: profileFile } = readCodeCheckProfile(workspace);
|
|
535
|
+
const file = path.join(root, `check-profile-${role}.json`);
|
|
536
|
+
const bytes = `${JSON.stringify({ schema_id: "dd-flow/retained-check-profile@1", profile, profile_sha256: hash, profile_bytes: profile ? fs.readFileSync(profileFile, "utf8") : null }, null, 2)}\n`;
|
|
537
|
+
if (fs.existsSync(file)) {
|
|
538
|
+
if (fs.readFileSync(file, "utf8") !== bytes)
|
|
539
|
+
throw new AppError("check_profile_drift", "Retained MERGE profile changed", 2, { role, file });
|
|
540
|
+
}
|
|
541
|
+
else
|
|
542
|
+
fs.writeFileSync(file, bytes, { flag: "wx" });
|
|
543
|
+
}
|
|
544
|
+
function frozenGateRefs(gate) { return [...new Set([...gate.checks.map(check => check.canonical_ref ?? check.id), ...gate.acceptanceRefs])].sort(); }
|
|
545
|
+
function writeMergeGateAcceptance(context, file, request, gate, acceptedTree, receipts) { const persisted = new Map(checkReceipts(context, { projectId: request.project_id, runId: request.run_id }).map(receipt => [receipt.id, receipt])); const value = { schema_id: "dd-flow/merge-gate-acceptance@2", merge_request_id: request.merge_request_id, run_id: request.run_id, work_id: request.executor_work_id, gate_hash: gate.gateHash, profile_hash: gate.profileHash, accepted_tree: acceptedTree, receipts: receipts.map(receipt => ({ id: receipt.id, execution_refs: [...(persisted.get(receipt.id)?.check_refs ?? receipt.check_refs)].sort(), binding_refs: [...receipt.check_refs].sort(), input_hash: receipt.input_hash })) }; const temporary = `${file}.tmp-${process.pid}-${crypto.randomUUID()}`; fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`); fs.renameSync(temporary, file); }
|
|
546
|
+
function readMergeGateAcceptance(context, file, request, gate) { try {
|
|
547
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
548
|
+
if (value.schema_id !== "dd-flow/merge-gate-acceptance@2" || value.merge_request_id !== request.merge_request_id || value.run_id !== request.run_id || value.work_id !== request.executor_work_id || value.gate_hash !== gate.gateHash || value.profile_hash !== gate.profileHash || value.accepted_tree !== request.accepted_tree || !Array.isArray(value.receipts) || !value.receipts.every(receipt => receipt && typeof receipt.id === "string" && typeof receipt.input_hash === "string" && Array.isArray(receipt.execution_refs) && receipt.execution_refs.every(ref => typeof ref === "string") && Array.isArray(receipt.binding_refs) && receipt.binding_refs.every(ref => typeof ref === "string")))
|
|
549
|
+
return { valid: false, receipts: [] };
|
|
550
|
+
const all = checkReceipts(context, { projectId: request.project_id, runId: request.run_id });
|
|
551
|
+
const receipts = value.receipts.map(saved => all.find(receipt => receipt.id === saved.id && receipt.input_hash === saved.input_hash && JSON.stringify([...receipt.check_refs].sort()) === JSON.stringify(saved.execution_refs))).filter((receipt) => Boolean(receipt));
|
|
552
|
+
const bindingRefs = value.receipts.flatMap(receipt => receipt.binding_refs);
|
|
553
|
+
const bindings = new Set(bindingRefs);
|
|
554
|
+
const expected = frozenGateRefs(gate);
|
|
555
|
+
if (receipts.length !== value.receipts.length || bindingRefs.length !== bindings.size || !receipts.every(checkReceiptEvidenceValid) || JSON.stringify([...bindings].sort()) !== JSON.stringify(expected) || gitValue(request.target_workspace, ["write-tree"]) !== value.accepted_tree)
|
|
556
|
+
return { valid: false, receipts: [] };
|
|
557
|
+
return { valid: true, receipts: receipts.map((receipt, index) => ({ ...receipt, check_refs: value.receipts[index].binding_refs })) };
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
return { valid: false, receipts: [] };
|
|
561
|
+
} }
|
|
355
562
|
function cryptoHash(value) { return crypto.createHash("sha256").update(value).digest("hex"); }
|
|
356
563
|
function mergeAcceptanceRefs(workspace, protocols) { return protocols.flatMap((protocol) => { const file = path.join(workspace, ".memory-bank", "protocol", protocol, "plan.json"); if (!fs.existsSync(file))
|
|
357
564
|
return []; const plan = JSON.parse(fs.readFileSync(file, "utf8")); return (plan.acceptance ?? []).filter((entry) => entry.gate === "merge").flatMap((entry) => (entry.check_refs ?? []).map((ref) => `${protocol}/${ref}`)); }); }
|
|
@@ -360,9 +567,14 @@ function protocolIds(home) { const root = path.join(home, "03-plan"); if (!fs.ex
|
|
|
360
567
|
function workspaceRoute(home) { const file = path.join(home, "02-protocolize", "workspace-route.json"); const value = JSON.parse(fs.readFileSync(file, "utf8")); if (!value.policy?.integration_branch)
|
|
361
568
|
throw new AppError("workspace_route_missing", "MERGE requires the frozen integration branch", 1, { file }); return { integration_branch: value.policy.integration_branch }; }
|
|
362
569
|
function executionSettings(run) { return JSON.parse(run.index_json).execution_profile?.settings ?? {}; }
|
|
363
|
-
function runBootstrap(run, cwd
|
|
364
|
-
|
|
365
|
-
|
|
570
|
+
async function runBootstrap(context, run, cwd, mergeId, progress) {
|
|
571
|
+
const command = executionSettings(run).code_bootstrap?.command;
|
|
572
|
+
if (!command)
|
|
573
|
+
throw new AppError("execution_profile_invalid", "MERGE requires a frozen workspace bootstrap command", 2);
|
|
574
|
+
const result = await runWorkspaceBootstrap(context, { projectId: run.project_id, runId: run.id, runHome: requireHome(run), workspaceRoot: cwd, command, artifactDir: `${stageDir}/${mergeId}/readiness`, progress });
|
|
575
|
+
if (result.exit_code !== 0 || result.error)
|
|
576
|
+
throw new AppError("merge_bootstrap_failed", "Integrated target bootstrap failed; inspect its retained logs", 2, { command, ...result });
|
|
577
|
+
}
|
|
366
578
|
function verifyLocalDelivery(request) { const head = gitValue(request.target_workspace, ["rev-parse", request.target_branch]); if (!request.integration_commit || head !== request.integration_commit)
|
|
367
579
|
throw new AppError("merge_delivery_unproven", "Local integration branch does not resolve to the accepted integration commit", 1, { target_branch: request.target_branch, expected: request.integration_commit, actual: head }); }
|
|
368
580
|
function cleanupReceiptPath(run) { return path.join(requireHome(run), stageDir, "cleanup-receipt.json"); }
|
|
@@ -390,7 +602,12 @@ function releaseMergeLane(context, projectRoot, request, reason) {
|
|
|
390
602
|
try {
|
|
391
603
|
releaseLaneLock(context, { projectRoot, lane: "merge", workerId: request.executor_work_id, workspacePath: request.target_workspace, reason });
|
|
392
604
|
}
|
|
393
|
-
catch {
|
|
605
|
+
catch (error) {
|
|
606
|
+
// An absent/replaced lease is already no longer ours. Storage and other
|
|
607
|
+
// failures must remain visible so a repeated operation can release it.
|
|
608
|
+
if (!(error instanceof AppError) || !["lane_lock_not_active", "lane_lock_owned_by_other_worker"].includes(error.code))
|
|
609
|
+
throw error;
|
|
610
|
+
}
|
|
394
611
|
}
|
|
395
612
|
function queueAhead(context, request) { return context.db.get("SELECT COUNT(*) AS count FROM merge_requests WHERE project_id = ? AND status NOT IN ('completed','failed','cancelled','superseded') AND (created_at < ? OR (created_at = ? AND merge_request_id < ?))", [request.project_id, request.created_at, request.created_at, request.merge_request_id])?.count ?? 0; }
|
|
396
613
|
function queueStatus(context, request) { return { position: queueAhead(context, request) + 1, requests_ahead: queueAhead(context, request), status: request.status, route: request.execution_route }; }
|
|
@@ -399,15 +616,17 @@ function requireOwnedActiveRequest(context, input) { const project = requireProj
|
|
|
399
616
|
function assertExecutionBaseline(request) { const head = gitValue(request.target_workspace, ["rev-parse", "HEAD"], true); if (request.checkpoint === "baseline_locked" && head !== request.execution_target_head)
|
|
400
617
|
throw new AppError("merge_target_changed", "Integration target changed after the lane baseline was locked", 1, { expected: request.execution_target_head, actual: head }); }
|
|
401
618
|
function recovery(context, request, code, detail) { context.db.run("UPDATE merge_requests SET status = 'recovery_required', last_error_json = ?, updated_at = ? WHERE merge_request_id = ?", [JSON.stringify({ code, detail }), context.now(), request.merge_request_id]); throw new AppError("merge_recovery_required", "MERGE mutation could not be reconciled automatically", 1, { merge_request_id: request.merge_request_id, code, detail }); }
|
|
402
|
-
function commitPendingSource(cwd, runId, ignored) { const paths = meaningfulStatus(cwd, ignored)
|
|
619
|
+
function commitPendingSource(cwd, runId, ignored) { const paths = meaningfulStatus(cwd, ignored); if (!paths.length)
|
|
403
620
|
return; git(cwd, ["add", "-A", "--", ...paths]); git(cwd, ["commit", "-m", `chore(${runId.toLowerCase()}): freeze accepted source`]); }
|
|
404
|
-
function commitIntegration(cwd, runId, ignored) { const mergeHead = fs.existsSync(path.join(gitDirectory(cwd), "MERGE_HEAD")); const paths = meaningfulStatus(cwd, ignored)
|
|
621
|
+
function commitIntegration(cwd, runId, ignored) { const mergeHead = fs.existsSync(path.join(gitDirectory(cwd), "MERGE_HEAD")); const paths = meaningfulStatus(cwd, ignored); if (!mergeHead && !paths.length)
|
|
405
622
|
return; if (paths.length)
|
|
406
623
|
git(cwd, ["add", "-A", "--", ...paths]); git(cwd, ["commit", "-m", `merge(${runId.toLowerCase()}): integrate accepted source`]); }
|
|
407
|
-
function ignoredGitPaths(context, projectId) {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
624
|
+
function ignoredGitPaths(context, projectId) {
|
|
625
|
+
// Shared workspace classification omits only the exact untracked qualified
|
|
626
|
+
// hook. Tracked or mixed user hooks remain ordinary product changes.
|
|
627
|
+
return [readProjectConfig(context, projectId).dashboard.markdown_path.replaceAll("\\", "/")];
|
|
628
|
+
}
|
|
629
|
+
function meaningfulStatus(cwd, ignored) { return workspaceChangedPaths(cwd).filter((item) => !ignored.includes(item)); }
|
|
411
630
|
function unmerged(cwd) { const value = gitValue(cwd, ["diff", "--name-only", "--diff-filter=U"], true); return value.split(/\r?\n/).filter(Boolean); }
|
|
412
631
|
function gitDirectory(cwd) { const value = gitValue(cwd, ["rev-parse", "--git-dir"]); return path.resolve(cwd, value); }
|
|
413
632
|
function git(cwd, args) { try {
|
|
@@ -463,5 +682,8 @@ function findRootWork(context, projectId, runId) { const work = context.db.get("
|
|
|
463
682
|
throw new AppError("runtime_missing", "vNext RUN has no root Work", 1); return work; }
|
|
464
683
|
function requireRootWork(context, projectId, runId) { const work = findRootWork(context, projectId, runId); if (work.status !== "running")
|
|
465
684
|
throw new AppError("runtime_missing", "vNext RUN has no running root Work", 1); return work; }
|
|
466
|
-
function applyCommand(context, request, projectRoot) { return
|
|
467
|
-
function
|
|
685
|
+
function applyCommand(context, request, projectRoot) { return managedLifecycleCommand(context, runtimeCommand(context, ["merge", "apply", request.merge_request_id, "--work", request.executor_work_id, "--project-root", projectRoot, "--json", "--progress-jsonl"])); }
|
|
686
|
+
function repairCommand(context, request, projectRoot) { return managedLifecycleCommand(context, runtimeCommand(context, ["merge", "repair", request.merge_request_id, "--project-root", projectRoot, "--json"])); }
|
|
687
|
+
export function finishCommand(context, runId, request, projectRoot, retryCheckId) {
|
|
688
|
+
return managedLifecycleCommand(context, runtimeCommand(context, ["stage", "finish", runId, "--stage", "merge", "--request", request.merge_request_id, "--work", request.executor_work_id, "--project-root", projectRoot, "--json", "--progress-jsonl", ...checkRetryArgs(context, projectRoot, runId, retryCheckId)]));
|
|
689
|
+
}
|