@deksden-com/dd-flow-cli 0.9.0-beta.11 → 0.9.0-beta.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +526 -0
- package/README.md +68 -0
- package/dist/build-info.json +8 -8
- package/dist/cli/command-inputs.js +305 -0
- package/dist/cli/help.js +89 -13
- package/dist/cli/hook-ingress.js +77 -0
- package/dist/cli/input-preparation.js +116 -0
- package/dist/cli/native-hook-ingress.js +48 -0
- package/dist/cli/run-cli.js +1465 -384
- package/dist/cli.js +8 -2
- package/dist/harness-runtime/DD-ZCODE.md +99 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +52 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +26 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +83 -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/daemon-operations.mjs +226 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +500 -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 +149 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +563 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +475 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +394 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +219 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +645 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +982 -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 +129 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +327 -0
- package/dist/harness-runtime/lib/model-observations.mjs +77 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +3 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +108 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
- package/dist/harness-runtime/lib/process-json.mjs +71 -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/tool-observations.d.mts +17 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +54 -0
- package/dist/protocol/local-files.js +18 -9
- package/dist/runtime/context.js +2 -2
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-work-batch.schema.json +3 -3
- package/dist/schemas/code-work-result.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/run-control-receipt.schema.json +99 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/canon.js +11 -8
- package/dist/services/cleanup.js +132 -39
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +589 -106
- package/dist/services/codex-hook-delivery.js +28 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-fanout.js +173 -0
- package/dist/services/dashboard.js +103 -31
- package/dist/services/engines.js +121 -76
- package/dist/services/eval-snapshots.js +994 -97
- package/dist/services/execution-policy.js +181 -0
- package/dist/services/external-work-launch.js +166 -0
- package/dist/services/harness-adapter.js +147 -24
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +702 -327
- package/dist/services/lanes.js +78 -65
- package/dist/services/lifecycle-command.js +113 -18
- package/dist/services/lifecycle-contract.js +30 -0
- package/dist/services/lifecycle-invocations.js +1379 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-processes.js +302 -34
- package/dist/services/merge-queue.js +228 -149
- package/dist/services/merge-server.js +66 -28
- 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 +25 -16
- package/dist/services/protocols.js +160 -86
- package/dist/services/recovery-observation-budget.js +61 -0
- package/dist/services/recovery-snapshot-database.js +142 -0
- package/dist/services/repair-intents.js +40 -0
- package/dist/services/review-copy.js +136 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +351 -0
- package/dist/services/run-control.js +888 -0
- package/dist/services/run-controller-adapter.js +231 -0
- package/dist/services/run-controller-capture.js +167 -0
- package/dist/services/run-controller-process.js +180 -0
- package/dist/services/run-controller-recovery.js +221 -0
- package/dist/services/run-controller-state.js +36 -0
- package/dist/services/run-controller.js +798 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +142 -0
- package/dist/services/run-observations.js +112 -0
- package/dist/services/run-projection.js +22 -64
- package/dist/services/run-recovery-runtime.js +80 -0
- package/dist/services/run-recovery.js +345 -0
- package/dist/services/runs.js +536 -181
- package/dist/services/runtime-budget.js +413 -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 +460 -0
- package/dist/services/runtime-scope-resume.js +577 -0
- package/dist/services/runtime-scope-stop.js +159 -0
- package/dist/services/runtime-scope-worker.js +242 -0
- package/dist/services/runtime-service.js +97 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/scope-writer-cleanup.js +26 -0
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +50 -19
- package/dist/services/stage-lifecycle.js +100 -103
- package/dist/services/stage-pause.js +88 -75
- package/dist/services/stage-report-renderer.js +116 -6
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/usage.js +35 -98
- package/dist/services/vnext-code-review.js +197 -84
- package/dist/services/vnext-code.js +278 -251
- package/dist/services/vnext-execution-profile.js +5 -3
- package/dist/services/vnext-fanout.js +172 -17
- package/dist/services/vnext-merge.js +345 -111
- package/dist/services/vnext-plan-review.js +171 -111
- package/dist/services/vnext-plan.js +180 -87
- package/dist/services/vnext-protocolize.js +320 -74
- package/dist/services/vnext-specify.js +115 -77
- package/dist/services/work-registry.js +1001 -187
- package/dist/services/workspace-bootstrap.js +76 -0
- package/dist/services/workspace-files.js +83 -0
- package/dist/services/worktrees.js +88 -36
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +12 -0
- package/dist/storage/database.js +692 -35
- 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 +24 -13
- package/tools/repair-paused-run-status.mjs +84 -0
|
@@ -1,24 +1,29 @@
|
|
|
1
|
+
import { managedLifecycleCommand } from "./lifecycle-invocations.js";
|
|
2
|
+
import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
|
|
1
3
|
import crypto from "node:crypto";
|
|
2
4
|
import fs from "node:fs";
|
|
3
5
|
import path from "node:path";
|
|
4
|
-
import { execFileSync } from "node:child_process";
|
|
5
6
|
import { AppError } from "../shared/errors.js";
|
|
6
7
|
import { resolveProjectRoot } from "../storage/paths.js";
|
|
7
8
|
import { requireProjectByRoot } from "./projects.js";
|
|
8
|
-
import { advanceFlowRun, appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRun, completeFlowRunStage, freezeFlowRunReviewMode, gitFacts } from "./runs.js";
|
|
9
|
+
import { advanceFlowRun, appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRun, completeFlowRunStage, prepareFlowRunStageCompletion, freezeFlowRunReviewMode, gitFacts } from "./runs.js";
|
|
9
10
|
import { validateSchema } from "./schema-validation.js";
|
|
10
|
-
import {
|
|
11
|
+
import { runtimeCommand, checkRetryArgs } from "./runtime-command.js";
|
|
11
12
|
import { assertStageStartHookEvent } from "./hooks.js";
|
|
12
13
|
import { requireVnextWorkspaceRoute } from "./vnext-workspace-policy.js";
|
|
13
|
-
import { addVnextCodeRepair } from "./vnext-code.js";
|
|
14
|
-
import { finalCodeCheckDeclarations, runCodeChecks,
|
|
15
|
-
import { addWorkBatch, bindStageCoordinatorWork,
|
|
14
|
+
import { addVnextCodeRepair, prepareVnextCodeRepair, registerAggregateCodeRepair, resumeAcceptedCodeStage } from "./vnext-code.js";
|
|
15
|
+
import { finalCodeCheckDeclarations, runCodeChecks, validateFailedCheckRetry, workspaceChangedPaths } from "./code-checks.js";
|
|
16
|
+
import { addWorkBatch, prepareWorkBatch, bindStageCoordinatorWork, finishStageCoordinatorWork, refreshRunWorkProjection } from "./work-registry.js";
|
|
17
|
+
import { withStageSettlement, prepareFlowRunStageAttachment } from "./runs.js";
|
|
16
18
|
import { vnextStageDirectory } from "../domain/stage-catalog.js";
|
|
17
|
-
import {
|
|
18
|
-
import { applyExternalStageContext } from "./stage-context.js";
|
|
19
|
+
import { acceptStageReport, prepareStageReport } from "./stage-report-renderer.js";
|
|
20
|
+
import { applyExternalStageContext, prepareExternalStageContext } from "./stage-context.js";
|
|
19
21
|
import { readFanoutDescriptor, writeFanoutDescriptor } from "./vnext-fanout.js";
|
|
20
|
-
import {
|
|
22
|
+
import { stageGraphScope } from "./stage-work-graph.js";
|
|
23
|
+
import { prepareVnextMergeRequest } from "./vnext-merge.js";
|
|
21
24
|
import { validateVnextCodeHandoff } from "./vnext-plan.js";
|
|
25
|
+
import { assertRunMutationAllowed } from "./run-recovery.js";
|
|
26
|
+
import { prepareJsonFile, prepareOutputFile } from "../cli/input-preparation.js";
|
|
22
27
|
const stage = "code-review";
|
|
23
28
|
const stageDir = vnextStageDirectory(stage);
|
|
24
29
|
const baselineAspects = ["goal_traceability", "coding_standards_design_review", "verification_evidence_review"];
|
|
@@ -26,60 +31,89 @@ export function isVnextCodeReviewRun(context, input) {
|
|
|
26
31
|
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
27
32
|
return Boolean(context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ? AND flow_kind = 'vnext_protocolize'", [project.id, input.runId]));
|
|
28
33
|
}
|
|
29
|
-
export function
|
|
34
|
+
export function prepareVnextCodeReviewStart(context, input) {
|
|
30
35
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
31
36
|
const project = requireProjectByRoot(context, projectRoot);
|
|
32
37
|
const run = requireRun(context, project.id, input.runId);
|
|
33
38
|
const home = requireHome(run);
|
|
34
|
-
|
|
39
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
35
40
|
requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage });
|
|
36
41
|
if (!fs.existsSync(path.join(home, "05-code", "stage-report.json")))
|
|
37
|
-
throw new AppError("
|
|
42
|
+
throw new AppError("runtime_artifact_missing", "CODE-REVIEW requires an accepted CODE report", 1);
|
|
38
43
|
const root = path.join(home, stageDir);
|
|
39
|
-
fs.mkdirSync(root, { recursive: true });
|
|
40
44
|
const rootWork = requireRootWork(context, project.id, run.id);
|
|
41
45
|
const prior = stageStatus(run, stage);
|
|
42
46
|
const existingPrompt = path.join(root, "stage-prompt.md");
|
|
43
|
-
if (
|
|
47
|
+
if (input.externalContext)
|
|
48
|
+
prepareExternalStageContext({ stageRoot: root, loaded: input.externalContext });
|
|
49
|
+
prepareOutputFile(existingPrompt);
|
|
50
|
+
const common = { projectRoot, project, run, home, root, rootWork, existingPrompt };
|
|
51
|
+
if (prior && fs.existsSync(existingPrompt))
|
|
52
|
+
return { ...common, resumed: true, prior, prompt: fs.readFileSync(existingPrompt, "utf8"), orchestration: readFanoutDescriptor(root) };
|
|
53
|
+
prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@1" });
|
|
54
|
+
const mode = effectiveMode(home, run);
|
|
55
|
+
const cycle = reviewCycle(run);
|
|
56
|
+
const codeReportSha256 = sha256File(path.join(home, "05-code", "stage-report.json"));
|
|
57
|
+
const groups = mode.mode === "off" ? [] : reviewGroups(home);
|
|
58
|
+
const batch = { works: groups.map((group, index) => ({ key: `code-review-${index + 1}`, task: reviewerTask(home, group), launch_policy: "fresh_agent_required", result_schema: "dd-flow/code-review-result@1", payload: { kind: "code-review", review_cycle: cycle, group, read_only: true } })) };
|
|
59
|
+
const items = mode.mode === "off" ? [] : prepareWorkBatch(context, { parentWorkId: rootWork.work_id, value: batch });
|
|
60
|
+
const template = mode.mode === "off" ? "" : read(path.join(run.workspace_root, ".memory-bank", "dd-flow", "vnext", "code-review.md"));
|
|
61
|
+
const checks = mode.mode === "off" ? [] : acceptedCodeChecks(context, project.id, run.id).map(({ id, purpose }) => ({ id, purpose }));
|
|
62
|
+
for (const name of ["review-context.json", ...(mode.mode === "off" ? ["decision.json"] : ["review-work-batch.json", "fanout.json"])])
|
|
63
|
+
prepareOutputFile(path.join(root, name));
|
|
64
|
+
return { ...common, resumed: false, mode, cycle, codeReportSha256, groups, batch, items, template, checks };
|
|
65
|
+
}
|
|
66
|
+
export function startVnextCodeReview(context, input, prepared = prepareVnextCodeReviewStart(context, input)) {
|
|
67
|
+
const { projectRoot, project, run, root, rootWork, existingPrompt } = prepared;
|
|
68
|
+
assertRunMutationAllowed(context, project.id, run.id);
|
|
69
|
+
assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
70
|
+
fs.mkdirSync(root, { recursive: true });
|
|
71
|
+
if (prepared.resumed) {
|
|
44
72
|
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath: existingPrompt, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
45
73
|
const binding = bindStageCoordinatorWork(context, { workId: rootWork.work_id, hookEventId: input.hookEventId, stage, promptPath: existingPrompt, resultPath: path.join(root, "stage-report.json"), ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
46
74
|
const prompt = fs.readFileSync(existingPrompt, "utf8");
|
|
47
|
-
const orchestration =
|
|
48
|
-
return { ok: true, resumed: true, run_id: run.id, stage, stage_status: prior, id: binding.work_session_id, prompt_path: existingPrompt, worker_prompt_markdown: prompt, ...(externalContext ? { external_context: externalContext } : {}), ...(orchestration ? { orchestration } : {}), next: { finish_command: finishCommand(context, run.id, projectRoot, path.join(root, "decision.json")) } };
|
|
75
|
+
const orchestration = prepared.orchestration;
|
|
76
|
+
return { ok: true, resumed: true, run_id: run.id, stage, stage_status: prepared.prior, id: binding.work_session_id, prompt_path: existingPrompt, worker_prompt_markdown: prompt, ...(externalContext ? { external_context: externalContext } : {}), ...(orchestration ? { orchestration } : {}), next: { finish_command: finishCommand(context, run.id, projectRoot, path.join(root, "decision.json")) } };
|
|
49
77
|
}
|
|
50
|
-
const mode
|
|
78
|
+
const { mode, cycle, groups, batch, items, template, checks, codeReportSha256 } = prepared;
|
|
79
|
+
const aspectMapChecksums = mode.mode === "off" ? [] : fs.readdirSync(path.join(run.run_root, "03-plan"), { withFileTypes: true })
|
|
80
|
+
.filter(entry => entry.isDirectory() && fs.existsSync(path.join(run.run_root, "03-plan", entry.name, "aspect-map.json")))
|
|
81
|
+
.map(entry => ({ path: `03-plan/${entry.name}/aspect-map.json`, sha256: sha256File(path.join(run.run_root, "03-plan", entry.name, "aspect-map.json")) }))
|
|
82
|
+
.sort((a, b) => a.path.localeCompare(b.path));
|
|
51
83
|
freezeFlowRunReviewMode(context, { projectRoot, runId: run.id, review: "code", mode: mode.mode, source: mode.source, reason: mode.reason });
|
|
52
84
|
const promptPath = path.join(root, "stage-prompt.md");
|
|
53
85
|
const reviewContextPath = path.join(root, "review-context.json");
|
|
54
|
-
fs.writeFileSync(reviewContextPath, `${JSON.stringify({ schema_id: "dd-flow/code-review-context@1", mode: mode.mode, mode_source: mode.source, mode_reason: mode.reason,
|
|
86
|
+
fs.writeFileSync(reviewContextPath, `${JSON.stringify({ schema_id: "dd-flow/code-review-context@1", cycle, mode: mode.mode, mode_source: mode.source, mode_reason: mode.reason, ...(mode.mode !== "off" ? { read_only_input: { parent_work_id: rootWork.work_id, version: 3 } } : {}), code_report_sha256: codeReportSha256, review_batch_sha256: sha256Value(`${JSON.stringify(batch, null, 2)}\n`), aspect_map_checksums: aspectMapChecksums }, null, 2)}\n`);
|
|
55
87
|
if (mode.mode === "off") {
|
|
56
|
-
|
|
88
|
+
fs.writeFileSync(path.join(root, "decision.json"), `${JSON.stringify(disabledReviewDecision(), null, 2)}\n`);
|
|
89
|
+
const prompt = `<stage_identity>\n- RUN: ${run.id}\n- stage: code-review\n- mode: off\n</stage_identity>\n\nCODE-REVIEW is disabled by the frozen RUN configuration. Finish with: ${finishCommand(context, run.id, projectRoot, path.join(root, "decision.json"))}\n${stageLifecycleInstruction}\n`;
|
|
57
90
|
fs.writeFileSync(promptPath, prompt);
|
|
58
91
|
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
59
92
|
const binding = bindStageCoordinatorWork(context, { workId: rootWork.work_id, hookEventId: input.hookEventId, stage, promptPath, resultPath: path.join(root, "stage-report.json"), ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
60
93
|
attachFlowRunStage(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@1" });
|
|
61
94
|
return { ok: true, run_id: run.id, stage, mode: mode.mode, mode_source: mode.source, id: binding.work_session_id, prompt_path: promptPath, worker_prompt_markdown: fs.readFileSync(promptPath, "utf8"), ...(externalContext ? { external_context: externalContext } : {}), next: { finish_command: finishCommand(context, run.id, projectRoot, path.join(root, "decision.json")) } };
|
|
62
95
|
}
|
|
63
|
-
const groups = reviewGroups(home);
|
|
64
|
-
const batch = { works: groups.map((group, index) => ({ key: `code-review-${index + 1}`, task: reviewerTask(home, group), launch_policy: "fresh_agent_required", result_schema: "dd-flow/code-review-result@1", payload: { kind: "code-review", group, read_only: true } })) };
|
|
65
96
|
const batchFile = path.join(root, "review-work-batch.json");
|
|
66
97
|
fs.writeFileSync(batchFile, `${JSON.stringify(batch, null, 2)}\n`);
|
|
67
|
-
const prompt = orchestratorPrompt(context, { projectRoot, run, root, rootWork, mode: mode.mode, groups })
|
|
98
|
+
const prompt = `${orchestratorPrompt(context, { projectRoot, run, root, rootWork, mode: mode.mode, groups, template, checks })}\n${stageLifecycleInstruction}\n`;
|
|
68
99
|
fs.writeFileSync(promptPath, prompt);
|
|
69
100
|
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
70
101
|
const binding = bindStageCoordinatorWork(context, { workId: rootWork.work_id, hookEventId: input.hookEventId, stage, promptPath, resultPath: path.join(root, "stage-report.json"), ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
71
|
-
const registered = addWorkBatch(context, { parentWorkId: rootWork.work_id,
|
|
72
|
-
const orchestration = writeFanoutDescriptor(root, { stage, parent_work_id: rootWork.work_id, dispatch: "none", capacity_required: true });
|
|
73
|
-
attachFlowRunStage(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@1" });
|
|
102
|
+
const registered = addWorkBatch(context, { parentWorkId: rootWork.work_id, value: batch, prepared: items, stage, cycle });
|
|
103
|
+
const orchestration = writeFanoutDescriptor(root, { stage, parent_work_id: rootWork.work_id, dispatch: "none", capacity_required: true, scope: stageGraphScope(context, project.id, run.id, stage) });
|
|
104
|
+
attachFlowRunStage(context, { projectRoot, runId: run.id, stage, dir: stageDir, status: "running", dataSchemaId: "dd-flow/stage-report@1", inputSha256: sha256Value(JSON.stringify({ batch: sha256File(batchFile), aspect_maps: aspectMapChecksums })) });
|
|
74
105
|
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "code_review_started", work_id: rootWork.work_id, mode: mode.mode, mode_source: mode.source, groups, registered });
|
|
75
106
|
return { ok: true, run_id: run.id, stage, mode: mode.mode, mode_source: mode.source, id: binding.work_session_id, prompt_path: promptPath, worker_prompt_markdown: fs.readFileSync(promptPath, "utf8"), ...(externalContext ? { external_context: externalContext } : {}), orchestration, review: { groups, works: registered }, next: { finish_command: finishCommand(context, run.id, projectRoot, path.join(root, "decision.json")) } };
|
|
76
107
|
}
|
|
77
|
-
|
|
78
|
-
|
|
108
|
+
export function prepareVnextCodeReviewRepair(context, input) {
|
|
109
|
+
if (!Array.isArray(input.findingIds) || !input.findingIds.length || input.findingIds.some(id => typeof id !== "string" || !id.trim()))
|
|
110
|
+
throw new AppError("validation", "Repair requires nonempty finding IDs", 2);
|
|
111
|
+
if (!input.checkRefsByFinding || typeof input.checkRefsByFinding !== "object" || Array.isArray(input.checkRefsByFinding) || Object.entries(input.checkRefsByFinding).some(([id, refs]) => !input.findingIds.includes(id) || !Array.isArray(refs) || refs.some(ref => typeof ref !== "string" || !ref.trim())))
|
|
112
|
+
throw new AppError("validation", "Repair check references must map selected findings to check IDs", 2);
|
|
79
113
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
80
114
|
const project = requireProjectByRoot(context, projectRoot);
|
|
81
115
|
const run = requireRun(context, project.id, input.runId);
|
|
82
|
-
const reviewers = reviewerWorks(context, project.id, run.id);
|
|
116
|
+
const reviewers = reviewerWorks(context, project.id, run.id, reviewCycle(run));
|
|
83
117
|
const findings = canonicalCodeFindings(reviewers);
|
|
84
118
|
const selected = findings.filter((finding) => input.findingIds.includes(finding.finding_ref));
|
|
85
119
|
if (selected.length !== new Set(input.findingIds).size)
|
|
@@ -99,17 +133,20 @@ export function addVnextCodeReviewRepair(context, input) {
|
|
|
99
133
|
const unknown = requestedCheckRefs.filter((ref) => !checks.has(ref));
|
|
100
134
|
if (unknown.length)
|
|
101
135
|
throw new AppError("review_check_reference_unknown", "CODE-REVIEW finding cites a check absent from the accepted CODE handoff", 2, { check_refs: unknown });
|
|
102
|
-
const reviewChecks = requestedCheckRefs.map((ref) => checks.get(ref))
|
|
103
|
-
|
|
104
|
-
throw new AppError("review_repair_executable_check_required", "CODE-REVIEW repair requires at least one executable causal check; external-only evidence cannot validate a repair Work", 2, { finding_ids: input.findingIds, check_refs: requestedCheckRefs });
|
|
105
|
-
return addVnextCodeRepair(context, {
|
|
136
|
+
const reviewChecks = requestedCheckRefs.map((ref) => checks.get(ref));
|
|
137
|
+
const repairInput = {
|
|
106
138
|
projectRoot,
|
|
107
139
|
runId: run.id,
|
|
108
140
|
reviewFindings: selected.map(({ finding_ref, finding }) => ({ finding_ref, priority: finding.priority, problem: finding.problem, impact: finding.impact, required_outcome: finding.required_outcome, evidence_refs: finding.evidence_refs, obligation_refs: finding.obligation_refs, decision_reason: input.decisionReasonsByFinding?.[finding_ref] ?? input.objective, check_refs: input.checkRefsByFinding[finding_ref] ?? [] })),
|
|
109
141
|
reviewChecks,
|
|
110
142
|
originWorkIds: origins,
|
|
111
|
-
objective: input.objective
|
|
112
|
-
|
|
143
|
+
objective: input.objective,
|
|
144
|
+
reviewCycle: reviewCycle(run)
|
|
145
|
+
};
|
|
146
|
+
return { input: repairInput, value: prepareVnextCodeRepair(context, repairInput) };
|
|
147
|
+
}
|
|
148
|
+
export function addVnextCodeReviewRepair(context, input, prepared = prepareVnextCodeReviewRepair(context, input)) {
|
|
149
|
+
return addVnextCodeRepair(context, prepared.input, prepared.value);
|
|
113
150
|
}
|
|
114
151
|
export async function finishVnextCodeReview(context, input) {
|
|
115
152
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
@@ -117,6 +154,14 @@ export async function finishVnextCodeReview(context, input) {
|
|
|
117
154
|
const run = requireRun(context, project.id, input.runId);
|
|
118
155
|
const home = requireHome(run);
|
|
119
156
|
const root = path.join(home, stageDir);
|
|
157
|
+
const generation = assertRunMutationAllowed(context, project.id, run.id);
|
|
158
|
+
const reportPath = path.join(root, "stage-report.json");
|
|
159
|
+
if (stageStatus(run, stage) === "done" && fs.existsSync(reportPath)) {
|
|
160
|
+
const report = readJson(reportPath);
|
|
161
|
+
const next = report.semantic?.next_action ?? "code_review_completed";
|
|
162
|
+
resumeAcceptedCodeStage(context, run, projectRoot, stage, report, next);
|
|
163
|
+
return { ok: true, resumed: true, run_id: run.id, stage, outcome: "accepted", report_path: reportPath, next_action: next };
|
|
164
|
+
}
|
|
120
165
|
const reviewContext = readJson(path.join(root, "review-context.json"));
|
|
121
166
|
const mode = reviewContext.mode;
|
|
122
167
|
if (!mode)
|
|
@@ -126,22 +171,23 @@ export async function finishVnextCodeReview(context, input) {
|
|
|
126
171
|
const handoffFailures = validateVnextCodeHandoff(context, { projectRoot, workspaceRoot: run.workspace_root, runId: run.id, home });
|
|
127
172
|
if (handoffFailures.length)
|
|
128
173
|
throw new AppError("validation", "CODE-REVIEW handoff no longer matches the accepted PLAN", 2, { errors: handoffFailures });
|
|
129
|
-
const reportPath = path.join(root, "stage-report.json");
|
|
130
|
-
if (stageStatus(run, stage) === "done" && fs.existsSync(reportPath)) {
|
|
131
|
-
const report = readJson(reportPath);
|
|
132
|
-
return { ok: true, resumed: true, run_id: run.id, stage, outcome: "accepted", report_path: reportPath, next_action: report.semantic?.next_action ?? "code_review_completed" };
|
|
133
|
-
}
|
|
134
174
|
const rootWork = requireRootWork(context, project.id, run.id);
|
|
135
175
|
const coordinator = context.db.get("SELECT session_id, result_path FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [rootWork.work_id]);
|
|
136
176
|
if (!coordinator || path.resolve(coordinator.result_path ?? "") !== path.resolve(reportPath))
|
|
137
177
|
throw new AppError("code_review_session_binding_conflict", "CODE-REVIEW can finish only after its successful stage start bound the coordinator Session and report path", 1, { run_id: run.id, expected_result_path: reportPath, actual_result_path: coordinator?.result_path ?? null });
|
|
138
|
-
const decisionFile = input.decisionFile ?? path.join(root, "decision.json");
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
const
|
|
178
|
+
const decisionFile = path.resolve(input.decisionFile ?? path.join(root, "decision.json"));
|
|
179
|
+
const disabledDecision = disabledReviewDecision();
|
|
180
|
+
// The implicit review-off decision is the one deliberate no-file path. An
|
|
181
|
+
// explicitly supplied --decision-file is still caller input and must be
|
|
182
|
+
// readable before any lifecycle work can proceed.
|
|
183
|
+
const decision = mode === "off" && !input.decision && !input.decisionFile && !fs.existsSync(decisionFile)
|
|
184
|
+
? disabledDecision
|
|
185
|
+
: readCodeReviewDecision(decisionFile, reviewContext.accepted_decision, Boolean(input.decisionFile), input.decision);
|
|
186
|
+
validateSchema({ schemaName: "code-review-decision", file: decisionFile, data: decision, projectRoot: run.workspace_root, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: home });
|
|
187
|
+
const cycle = reviewContext.cycle ?? "initial";
|
|
188
|
+
const reviewers = reviewerWorks(context, project.id, run.id, cycle);
|
|
144
189
|
if (mode !== "off") {
|
|
190
|
+
assertCodeReviewCoverage(reviewGroups(home), reviewers);
|
|
145
191
|
const incomplete = reviewers.filter((work) => work.status !== "completed");
|
|
146
192
|
if (incomplete.length)
|
|
147
193
|
throw new AppError("reviewer_jobs_incomplete", "CODE-REVIEW cannot finish while reviewer Work is unsettled", 2, { works: incomplete.map((work) => ({ work_id: work.work_id, status: work.status })) });
|
|
@@ -149,30 +195,35 @@ export async function finishVnextCodeReview(context, input) {
|
|
|
149
195
|
validateReviewerResult(context, work, run);
|
|
150
196
|
const canonical = reviewDecisionForRepair(decision, reviewers);
|
|
151
197
|
const checkRefsByFinding = validateRepairChecks(context, { projectId: project.id, runId: run.id, decision: canonical.decision });
|
|
152
|
-
let repairs = reviewRepairWorks(context, project.id, run.id, root);
|
|
153
|
-
const decisionSha = sha256File(decisionFile);
|
|
198
|
+
let repairs = reviewRepairWorks(context, project.id, run.id, root, cycle);
|
|
154
199
|
const frozenShaFile = path.join(root, ".decision-sha256");
|
|
155
|
-
|
|
200
|
+
const decisionHash = sha256Value(input.decisionText ?? JSON.stringify(decision));
|
|
201
|
+
if (!reviewContext.accepted_decision && fs.existsSync(frozenShaFile) && fs.readFileSync(frozenShaFile, "utf8").trim() !== decisionHash)
|
|
156
202
|
throw new AppError("review_decision_changed", "The accepted CODE-REVIEW decision cannot change during repair", 2, { decision_file: decisionFile });
|
|
157
203
|
const fixIds = canonical.fix_ids;
|
|
158
204
|
if (fixIds.length && repairs.length === 0) {
|
|
205
|
+
// Accept the value once. Repairs consume this decision, not a mutable
|
|
206
|
+
// operator file. Reuse the existing context artifact and review cycle.
|
|
207
|
+
const contextFile = path.join(root, "review-context.json"), temporary = `${contextFile}.tmp-${crypto.randomUUID()}`;
|
|
208
|
+
fs.writeFileSync(temporary, `${JSON.stringify({ ...reviewContext, accepted_decision: decision }, null, 2)}\n`);
|
|
209
|
+
fs.renameSync(temporary, contextFile);
|
|
159
210
|
const repair = addVnextCodeReviewRepair(context, { projectRoot, runId: run.id, findingIds: fixIds, checkRefsByFinding, decisionReasonsByFinding: Object.fromEntries(canonical.decision.findings.map((item) => [item.finding_ref, item.reason])), objective: `Resolve accepted CODE-REVIEW findings: ${fixIds.join(", ")}` });
|
|
160
|
-
|
|
161
|
-
return { ok: true, run_id: run.id, stage, outcome: "repair_required", decision_sha256: decisionSha, repair, instruction: "Run the returned repair Work in one fresh child session. When it completes, invoke the same stage finish command again with the unchanged decision file.", next: { finish_command: finishCommand(context, run.id, projectRoot, decisionFile) } };
|
|
211
|
+
return { ok: true, run_id: run.id, stage, outcome: "repair_required", repair, instruction: "The repair Work is already registered: do not invoke its start_command in this coordinator Session. End this Turn so the controller can launch it in a fresh child Session. When it completes, invoke next.finish_command; this review cycle uses the decision already accepted by the runtime.", next: { finish_command: finishCommand(context, run.id, projectRoot, decisionFile) } };
|
|
162
212
|
}
|
|
163
|
-
repairs = reviewRepairWorks(context, project.id, run.id, root);
|
|
213
|
+
repairs = reviewRepairWorks(context, project.id, run.id, root, cycle);
|
|
164
214
|
const incompleteRepairs = repairs.filter((work) => work.status !== "completed");
|
|
165
215
|
if (incompleteRepairs.length)
|
|
166
216
|
throw new AppError("review_repair_incomplete", "CODE-REVIEW cannot finish while a repair Work is unsettled", 2, { works: incompleteRepairs.map((work) => ({ work_id: work.work_id, status: work.status })) });
|
|
167
217
|
validateDecision(context, { decision: canonical.decision, reviewers: canonical.reviewers, repairs, workspaceRoot: run.workspace_root });
|
|
168
218
|
}
|
|
169
219
|
const outcome = decision.findings.some((item) => item.disposition === "defer") ? "accepted_with_DEF" : "accepted";
|
|
170
|
-
const repairs = reviewRepairWorks(context, project.id, run.id, root);
|
|
220
|
+
const repairs = reviewRepairWorks(context, project.id, run.id, root, cycle);
|
|
171
221
|
const finalChecks = finalCodeCheckDeclarations(run.workspace_root, codeWorks(context, project.id, run.id).flatMap((work) => { const payload = readJsonString(work.payload_json); return Array.isArray(payload.checks) ? payload.checks : []; }));
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
222
|
+
if (input.retryCheckId) {
|
|
223
|
+
validateFailedCheckRetry(context, { projectId: project.id, runId: run.id, receiptId: input.retryCheckId, declarations: finalChecks, reason: input.retryReason });
|
|
224
|
+
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "check_retry_requested", check_receipt_id: input.retryCheckId, stage, reason: input.retryReason ?? "operator retry" });
|
|
225
|
+
}
|
|
226
|
+
const receipts = await runCodeChecks(context, { projectId: project.id, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, artifactDir: stageDir, scope: "aggregate", checks: finalChecks, ...(input.retryCheckId ? { retryReceiptId: input.retryCheckId, retryReason: input.retryReason } : {}), ...(input.progress ? { progress: input.progress } : {}) });
|
|
176
227
|
const failed = receipts.filter((receipt) => receipt.status !== "passed");
|
|
177
228
|
if (failed.length)
|
|
178
229
|
throw new AppError("code_review_gate_failed", "CODE-REVIEW repair changed the project but the aggregate gate failed", 2, {
|
|
@@ -180,30 +231,68 @@ export async function finishVnextCodeReview(context, input) {
|
|
|
180
231
|
outcome: "repair_required",
|
|
181
232
|
retry_after_workspace_change: true,
|
|
182
233
|
workspace_fingerprint: failed[0].workspace_fingerprint,
|
|
183
|
-
|
|
234
|
+
continuation: registerAggregateCodeRepair(context, { projectRoot, runId: run.id, stage, failures: failed, checks: finalChecks, generation }),
|
|
235
|
+
instruction: "Repair Work is already registered. End this Turn so the controller can launch a fresh child; after it finishes, repeat finish with the already accepted review decision. Do not redo review."
|
|
184
236
|
});
|
|
185
237
|
const stopTarget = executionStopTarget(run);
|
|
186
238
|
const nextAction = stopTarget === "merge_completed" ? "start_merge" : "code_review_completed";
|
|
187
239
|
const now = context.now();
|
|
188
240
|
const startedAt = stageStartedAt(run, now);
|
|
189
|
-
const report = { schema_id: "dd-flow/stage-report@1", run_id: run.id, stage, generated_at: now, verdict: "done", semantic: { result: `Independent CODE review completed: ${reviewers.length} reviewer Work(s), ${repairs.length} repair Work(s).`, acceptance: ["all_selected_review_groups_completed", "all_material_findings_classified", ...(repairs.length ? ["all_accepted_repairs_completed"] : []), "current_final_gate_passed"], run_changed_files: changedPaths(run.workspace_root), checks: receipts.map((receipt) => receipt.command), evidence: [...reviewers.flatMap((work) => readJsonString(work.result).findings.flatMap((finding) => finding.evidence_refs)), ...receipts.map((receipt) => runRef(run.id, home, receipt.receipt_path))], next_action: nextAction, code_review: { mode, reviewer_work_ids: reviewers.map((work) => work.work_id), repair_work_ids: repairs.map((work) => work.work_id), decision } }, mechanical: { started_at: startedAt, finished_at: now, wall_clock_ms: Math.max(0, Date.parse(now) - Date.parse(startedAt)), git: gitFacts(run.workspace_root), session_stats_command:
|
|
241
|
+
const report = { schema_id: "dd-flow/stage-report@1", run_id: run.id, stage, generated_at: now, verdict: "done", semantic: { result: `Independent CODE review completed: ${reviewers.length} reviewer Work(s), ${repairs.length} repair Work(s).`, acceptance: ["all_selected_review_groups_completed", "all_material_findings_classified", ...(repairs.length ? ["all_accepted_repairs_completed"] : []), "current_final_gate_passed"], run_changed_files: changedPaths(run.workspace_root), checks: receipts.map((receipt) => receipt.command), evidence: [...reviewers.flatMap((work) => readJsonString(work.result).findings.flatMap((finding) => finding.evidence_refs)), ...receipts.map((receipt) => runRef(run.id, home, receipt.receipt_path))], next_action: nextAction, code_review: { mode, reviewer_work_ids: reviewers.map((work) => work.work_id), repair_work_ids: repairs.map((work) => work.work_id), decision } }, mechanical: { started_at: startedAt, finished_at: now, wall_clock_ms: Math.max(0, Date.parse(now) - Date.parse(startedAt)), git: gitFacts(run.workspace_root), session_stats_command: runtimeCommand(context, ["stat", "run", "sessions", "ls", "--run", run.id, "--project-root", projectRoot, "--json"]), usage_stats_command: runtimeCommand(context, ["stat", "usage", "--run", run.id, "--project-root", projectRoot, "--json"]) }, artifacts: { json: "stage-report.json", markdown: "stage-report.md", html: "stage-report.html" }, validation: { status: "passed" } };
|
|
190
242
|
// The request must exist before CODE-REVIEW becomes terminal. Otherwise a
|
|
191
243
|
// merge-gate error creates an irrecoverable `done` report with no MRG-*.
|
|
192
244
|
const acceptedPaths = changedPaths(run.workspace_root);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
245
|
+
let mergeRequest = null;
|
|
246
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
247
|
+
const prepareMerge = nextAction === "start_merge" ? prepareVnextMergeRequest(context, { projectRoot, runId: run.id, acceptedPaths }) : null;
|
|
248
|
+
const preparedReport = prepareStageReport(report);
|
|
249
|
+
const completionInput = { projectRoot, runId: run.id, stage, status: "done", data: "stage-report.json", dataSchemaId: "dd-flow/stage-report@1", report: "stage-report.md", stageReport: "stage-report.html", dataSha256: preparedReport.sha256, git: report.mechanical.git };
|
|
250
|
+
withStageSettlement(context, () => {
|
|
251
|
+
assertRunMutationAllowed(context, project.id, run.id, generation);
|
|
252
|
+
const currentReviewers = reviewerWorks(context, project.id, run.id, cycle);
|
|
253
|
+
const currentRepairs = reviewRepairWorks(context, project.id, run.id, root, cycle);
|
|
254
|
+
if (currentReviewers.length !== reviewers.length || currentRepairs.length !== repairs.length || [...currentReviewers, ...currentRepairs].some(work => work.status !== "completed" || ![...reviewers, ...repairs].some(accepted => accepted.work_id === work.work_id && accepted.result === work.result))) {
|
|
255
|
+
throw new AppError("reviewer_jobs_incomplete", "Review or repair results changed while the final checks were running", 2);
|
|
256
|
+
}
|
|
257
|
+
mergeRequest = prepareMerge?.() ?? null;
|
|
258
|
+
const preparedCompletion = prepareFlowRunStageCompletion(context, completionInput);
|
|
259
|
+
acceptStageReport(context, { projectId: project.id, runId: run.id, stage, root, prepared: preparedReport });
|
|
260
|
+
completeFlowRunStage(context, completionInput, preparedCompletion);
|
|
261
|
+
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "code_review_completed", work_id: rootWork.work_id, outcome });
|
|
262
|
+
if (nextAction === "start_merge")
|
|
263
|
+
advanceFlowRun(context, { settlementStage: "code-review", projectRoot, runId: run.id, status: "running", verdict: "code_review_completed", nextAction });
|
|
264
|
+
else {
|
|
265
|
+
finishStageCoordinatorWork(context, rootWork.work_id, JSON.stringify(report, null, 2));
|
|
266
|
+
completeFlowRun(context, { projectRoot, runId: run.id, status: "done", verdict: "code_review_completed", nextAction: undefined });
|
|
267
|
+
}
|
|
268
|
+
refreshRunWorkProjection(context, project.id, run.id);
|
|
269
|
+
});
|
|
270
|
+
return { ok: true, run_id: run.id, stage, outcome, report_path: path.join(root, "stage-report.json"), next_action: nextAction, ...(mergeRequest ? { merge_request: mergeRequest, next: { kind: "start_stage", stage: "merge", command: managedLifecycleCommand(context, runtimeCommand(context, ["stage", "start", run.id, "--stage", "merge", "--project-root", projectRoot, "--json", "--progress-jsonl"])) } } : {}) };
|
|
271
|
+
}
|
|
272
|
+
export function readCodeReviewDecision(file, accepted, explicit = false, prepared) {
|
|
273
|
+
if (!accepted)
|
|
274
|
+
return prepared ?? prepareJsonFile(file, "CODE-REVIEW decision").value;
|
|
275
|
+
if ((prepared !== undefined || (explicit && fs.existsSync(file))) && JSON.stringify(prepared ?? prepareJsonFile(file, "CODE-REVIEW decision").value) !== JSON.stringify(accepted)) {
|
|
276
|
+
throw new AppError("review_decision_changed", "This review cycle already accepted a different decision", 2, { decision_file: file });
|
|
202
277
|
}
|
|
203
|
-
|
|
204
|
-
|
|
278
|
+
return accepted;
|
|
279
|
+
}
|
|
280
|
+
function disabledReviewDecision() {
|
|
281
|
+
return { schema_id: "dd-flow/code-review-decision@3", summary: "CODE-REVIEW is disabled by RUN configuration.", findings: [] };
|
|
205
282
|
}
|
|
206
|
-
|
|
283
|
+
/** Retained decisions remain authoritative after their caller file is gone. */
|
|
284
|
+
export function prepareCodeReviewDecision(runRoot, file) {
|
|
285
|
+
const root = path.join(runRoot, "06-code-review");
|
|
286
|
+
const context = readJson(path.join(root, "review-context.json"));
|
|
287
|
+
const source = path.resolve(file ?? path.join(root, "decision.json"));
|
|
288
|
+
if (context.accepted_decision && !fs.existsSync(source))
|
|
289
|
+
return { value: context.accepted_decision };
|
|
290
|
+
if (context.mode === "off" && !file && !fs.existsSync(source))
|
|
291
|
+
return { value: disabledReviewDecision() };
|
|
292
|
+
const prepared = prepareJsonFile(source, "CODE-REVIEW decision");
|
|
293
|
+
return { value: readCodeReviewDecision(source, context.accepted_decision, Boolean(file), prepared.value), text: prepared.text };
|
|
294
|
+
}
|
|
295
|
+
export function reviewGroups(home) {
|
|
207
296
|
const expected = new Set(baselineAspects);
|
|
208
297
|
const declared = [];
|
|
209
298
|
for (const file of findFiles(path.join(home, "03-plan"), "aspect-map.json")) {
|
|
@@ -218,17 +307,35 @@ function reviewGroups(home) {
|
|
|
218
307
|
if (!declared.length)
|
|
219
308
|
return [{ key: "baseline", aspect_ids: [...expected].sort() }];
|
|
220
309
|
const assigned = new Set();
|
|
310
|
+
const scoped = new Set();
|
|
221
311
|
for (const group of declared)
|
|
222
312
|
for (const aspectId of group.aspect_ids) {
|
|
223
|
-
|
|
224
|
-
|
|
313
|
+
const assignment = `${group.key.slice(0, group.key.lastIndexOf("/"))}/${aspectId}`;
|
|
314
|
+
if (scoped.has(assignment))
|
|
315
|
+
throw new AppError("code_review_groups_invalid", "A CODE-REVIEW aspect appears in more than one group of the same protocol", 2, { aspect_id: aspectId });
|
|
316
|
+
scoped.add(assignment);
|
|
225
317
|
assigned.add(aspectId);
|
|
226
318
|
}
|
|
227
319
|
const missing = [...expected].filter((aspectId) => !assigned.has(aspectId)).sort();
|
|
228
320
|
return [...declared, ...(missing.length ? [{ key: "baseline", aspect_ids: missing }] : [])];
|
|
229
321
|
}
|
|
322
|
+
export function assertCodeReviewCoverage(groups, reviewers) {
|
|
323
|
+
const expected = new Map(groups.map(group => [group.key, [...group.aspect_ids].sort()]));
|
|
324
|
+
if (!expected.size || expected.size !== groups.length)
|
|
325
|
+
throw new AppError("reviewer_coverage_invalid", "CODE-REVIEW expected group identities must be nonempty and unique", 2);
|
|
326
|
+
const seen = new Set();
|
|
327
|
+
for (const work of reviewers) {
|
|
328
|
+
const group = readJsonString(work.payload_json).group;
|
|
329
|
+
if (!group?.key || seen.has(group.key) || !expected.has(group.key) || !Array.isArray(group.aspect_ids) || JSON.stringify([...group.aspect_ids].sort()) !== JSON.stringify(expected.get(group.key)))
|
|
330
|
+
throw new AppError("reviewer_coverage_invalid", "CODE-REVIEW Work does not match its expected group", 2, { work_id: work.work_id });
|
|
331
|
+
seen.add(group.key);
|
|
332
|
+
}
|
|
333
|
+
const missing = [...expected.keys()].filter(key => !seen.has(key));
|
|
334
|
+
if (missing.length || !expected.size)
|
|
335
|
+
throw new AppError("reviewer_coverage_invalid", "CODE-REVIEW requires every expected reviewer group", 2, { missing_groups: missing });
|
|
336
|
+
}
|
|
230
337
|
export function reviewerTask(home, group) { return `Read-only independent CODE review for ${group.key}. Assess every assigned aspect exactly once: ${group.aspect_ids.join(", ")}. Read the accepted PLAN, ${path.join(home, "05-code", "stage-report.json")}, and any files needed under the bounded CODE evidence root ${path.join(home, "05-code")}. Verify that universal and exclusive constraints (only, any, all, never, whole) and stated exceptions were not narrowed. For every changed mutation guarded by membership, ownership, authorization or parent lifecycle state, trace the decision to the write boundary: the predicate must remain in the write statement or the guard and write must share one explicit transaction with the needed lock. A separate earlier read is not proof of current authority or lifecycle state; report a material finding when this invariant is broken. Evidence closes a claim only when it exercises the named failure mechanism; a sequential negative test does not prove a concurrency race, and proof limits cannot waive an accepted obligation. Report only material, evidenced defects: a violated obligation or rule, direct evidence, impact, and minimum required outcome. Do not report taste, cosmetics, or untargeted refactoring. Use local finding ids FIND-001, FIND-002, and so on; dd-flow adds the Work-qualified canonical reference. Return dd-flow/code-review-result@1.`; }
|
|
231
|
-
function orchestratorPrompt(context, input) { const template
|
|
338
|
+
function orchestratorPrompt(context, input) { const { template, checks } = input; const decision = path.join(input.root, "decision.json"); return ["<stage_identity>", `- RUN: ${input.run.id}`, `- root Work: ${input.rootWork.work_id}`, `- stage: ${stage}`, `- mode: ${input.mode}`, "</stage_identity>", "", "<trusted_runtime_context>", `- project root: ${input.projectRoot}`, `- immutable write workspace: ${input.run.workspace_root}`, `- stage workspace: ${input.root}`, `- bounded CODE evidence root: ${path.join(input.run.run_root, "05-code")}`, "CODE is already semantically verified and all declared checks passed. Do not redo CODE verification; conduct independent quality review.", "</trusted_runtime_context>", "", "<review_groups>", ...input.groups.map((group) => `- ${group.key}: ${group.aspect_ids.join(", ")}`), "</review_groups>", "", "<execution_commands>", "Do not choose a provider delegation tool from this stage prompt. At the Work-graph boundary, return immediately; the shared controller supplies the selected adapter's native tool, exact parameters, child task, and wait contract. Each reviewer Work must run in one fresh child session. The coordinator must never invoke a Work start_command itself: a child runs its exact start_command after native delegation. Reviewers are read-only and must not create subagents. Do not interrupt a quiet worker.", "Ready reviewer Works: " + runtimeCommand(context, ["work", "ls", "--run", input.run.id, "--ready", "--project-root", input.projectRoot, "--json"]), `Write the decision to this exact absolute path, not a relative look-alike: ${decision}`, `Finish only after every reviewer Work settles and that exact file exists: ${finishCommand(context, input.run.id, input.projectRoot, decision)}`, "Reviewer results use local FIND-NNN ids. Classify them by the canonical WRK-.../FIND-NNN finding_ref returned by dd-flow. Fix P0/P1. Fix bounded safe P2 by default; defer only a legitimate P2 with a named DEF. P3 is an observation or a reasoned rejection, not automatic repair/DEF. For every disposition fix, check_refs is mandatory: choose the one or more causal checks from the accepted list below that the repair must rerun. Do not guess a CHK id or copy every check. The first successful Finish freezes this decision and creates one repair Work when needed. Do not invoke that Work's start_command from the coordinator Session: end this Turn so the controller can launch a fresh child, then call the returned next.finish_command after it completes. Internal invocation IDs are runtime-owned and must not be copied or reused. Review is not repeated.", "If the aggregate gate fails with repair_required, its repair Work is already registered with all causal checks. End this Turn so the controller launches a fresh child. Do not copy receipt IDs, create another repair, invoke its start_command in the coordinator, or edit invisibly in the root orchestrator.", `Accepted repair checks: ${JSON.stringify(checks)}`, "```json", JSON.stringify({ schema_id: "dd-flow/code-review-decision@3", summary: "Evidence-backed conclusion.", findings: [{ finding_ref: "WRK-001-review/FIND-001", disposition: "fix | defer | reject | duplicate", reason: "Why this classification is correct.", check_refs: ["CHK-CAUSAL-CHECK only when disposition is fix"], def_id: "DEF-0001 only for an allowed P2 deferral", duplicate_of: "canonical finding_ref only for duplicate" }] }, null, 2), "```", "</execution_commands>", "", "<stage_instructions>", template, "</stage_instructions>", ""].join("\n"); }
|
|
232
339
|
function canonicalReviewEvidence(decision, reviewers) {
|
|
233
340
|
const known = new Set(canonicalCodeFindings(reviewers).map((item) => item.finding_ref));
|
|
234
341
|
const items = new Map(decision.findings.map((item) => [item.finding_ref, item]));
|
|
@@ -320,7 +427,7 @@ function validateReviewerResult(_context, work, _run) {
|
|
|
320
427
|
if (result.aspects.some((aspect) => aspect.verdict === "blocked"))
|
|
321
428
|
throw new AppError("review_blocked", "A blocked review aspect must be resolved before CODE-REVIEW can finish", 2, { work_id: work.work_id });
|
|
322
429
|
}
|
|
323
|
-
function reviewerWorks(context, projectId, runId) { return context.db.all("SELECT * FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id", [projectId, runId]).filter((work) => { const
|
|
430
|
+
function reviewerWorks(context, projectId, runId, cycle) { return context.db.all("SELECT * FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id", [projectId, runId]).filter((work) => { const payload = readJsonString(work.payload_json); return Boolean(payload.kind === "code-review" && (typeof payload.review_cycle === "string" ? payload.review_cycle : "initial") === cycle); }); }
|
|
324
431
|
function codeWorks(context, projectId, runId) { return context.db.all("SELECT * FROM works WHERE project_id = ? AND run_id = ? AND status = 'completed' ORDER BY created_at, work_id", [projectId, runId]).filter((work) => readJsonString(work.payload_json).schema_id === "dd-flow/code-work-packet@5" && !reviewFindingIds(work).length); }
|
|
325
432
|
function acceptedCodeChecks(context, projectId, runId) { return codeWorks(context, projectId, runId).flatMap((work) => { const payload = readJsonString(work.payload_json); return Array.isArray(payload.checks) ? payload.checks : []; }); }
|
|
326
433
|
function validateRepairChecks(context, input) { const known = new Set(acceptedCodeChecks(context, input.projectId, input.runId).map((check) => check.id)); const selected = {}; for (const item of input.decision.findings.filter((item) => item.disposition === "fix")) {
|
|
@@ -332,7 +439,7 @@ function validateRepairChecks(context, input) { const known = new Set(acceptedCo
|
|
|
332
439
|
throw new AppError("review_check_reference_unknown", "CODE-REVIEW repair selects a check absent from the accepted CODE handoff", 2, { finding_ref: item.finding_ref, check_refs: unknown });
|
|
333
440
|
selected[item.finding_ref] = refs;
|
|
334
441
|
} return selected; }
|
|
335
|
-
function reviewRepairWorks(context, projectId, runId, root) { return context.db.all("SELECT * FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id", [projectId, runId]).filter((work) => isCodeReviewStageRepair(work, root)); }
|
|
442
|
+
function reviewRepairWorks(context, projectId, runId, root, cycle) { return context.db.all("SELECT * FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id", [projectId, runId]).filter((work) => { const payload = readJsonString(work.payload_json); return isCodeReviewStageRepair(work, root) && (typeof payload.review_cycle === "string" ? payload.review_cycle : "initial") === cycle; }); }
|
|
336
443
|
export function isCodeReviewStageRepair(work, root) {
|
|
337
444
|
if (reviewFindingIds(work).length)
|
|
338
445
|
return true;
|
|
@@ -350,22 +457,27 @@ function reviewFindingIds(work) { const repair = readJsonString(work.payload_jso
|
|
|
350
457
|
function reviewCheckRefs(work) { const repair = readJsonString(work.payload_json).repair; if (!repair || typeof repair !== "object" || Array.isArray(repair))
|
|
351
458
|
return []; const findings = repair.review_findings; return Array.isArray(findings) ? [...new Set(findings.flatMap((value) => typeof value === "object" && value !== null && Array.isArray(value.check_refs) ? value.check_refs.filter((ref) => typeof ref === "string") : []))] : []; }
|
|
352
459
|
function canonicalCodeFindings(works) { return works.flatMap((work) => readJsonString(work.result).findings.map((finding) => ({ finding_ref: `${work.work_id}/${finding.finding_id}`, finding }))); }
|
|
353
|
-
function effectiveMode(home, run) { const index = JSON.parse(run.index_json);
|
|
460
|
+
function effectiveMode(home, run) { const index = JSON.parse(run.index_json); if (index.variables?.["merge.source_repair"])
|
|
461
|
+
return { mode: "standard", source: "project_policy", reason: "A failed integration gate requires independent review of its source repair." }; const configured = index.settings?.code_review; const requested = configured?.mode ?? "auto"; if (requested !== "auto")
|
|
354
462
|
return { mode: requested, source: configured?.source === "user_instruction" ? "user_instruction" : "project_policy", reason: configured?.reason ?? "Frozen RUN configuration." }; const assessments = findFiles(path.join(home, "03-plan"), "plan.json").map((file) => readJson(file)); const deep = assessments.some((plan) => plan.assessment?.failure_impact?.level === "high" || plan.assessment?.solution_uncertainty?.level === "high"); return { mode: deep ? "deep" : "standard", source: "plan_assessment", reason: deep ? "Accepted PLAN assessment records high impact or uncertainty." : "Accepted PLAN assessment requires the standard independent review." }; }
|
|
355
463
|
function executionStopTarget(run) { return JSON.parse(run.index_json).execution_profile?.settings?.stop_target ?? "code_review_completed"; }
|
|
356
|
-
function changedPaths(workspaceRoot) {
|
|
357
|
-
return execFileSync("git", ["status", "--porcelain=v1", "--untracked-files=all"], { cwd: workspaceRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split(/\r?\n/).filter(Boolean).map((line) => line.slice(3).replace(/^.* -> /, ""));
|
|
358
|
-
}
|
|
359
|
-
catch {
|
|
360
|
-
return [];
|
|
361
|
-
} }
|
|
464
|
+
function changedPaths(workspaceRoot) { return workspaceChangedPaths(workspaceRoot); }
|
|
362
465
|
function sha256File(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
|
|
466
|
+
function sha256Value(value) { return crypto.createHash("sha256").update(value).digest("hex"); }
|
|
363
467
|
function stageStatus(run, name) { try {
|
|
364
468
|
return JSON.parse(run.index_json).stage_runs?.find((item) => item.stage === name)?.status ?? null;
|
|
365
469
|
}
|
|
366
470
|
catch {
|
|
367
471
|
return null;
|
|
368
472
|
} }
|
|
473
|
+
function reviewCycle(run) { try {
|
|
474
|
+
const value = JSON.parse(run.index_json);
|
|
475
|
+
const repair = value.variables?.["merge.source_repair"];
|
|
476
|
+
return repair && typeof repair === "object" && !Array.isArray(repair) && typeof repair.cycle === "string" ? String(repair.cycle) : "initial";
|
|
477
|
+
}
|
|
478
|
+
catch {
|
|
479
|
+
return "initial";
|
|
480
|
+
} }
|
|
369
481
|
function stageStartedAt(run, fallback) { try {
|
|
370
482
|
return JSON.parse(run.index_json).stage_runs?.find((item) => item.stage === stage)?.started_at ?? fallback;
|
|
371
483
|
}
|
|
@@ -379,7 +491,9 @@ function requireRun(context, projectId, runId) { const run = context.db.get("SEL
|
|
|
379
491
|
throw new AppError("not_found", "RUN is not registered", 1); return run; }
|
|
380
492
|
function requireHome(run) { if (!run.run_root)
|
|
381
493
|
throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1); return run.run_root; }
|
|
382
|
-
function finishCommand(context, runId, projectRoot, decision
|
|
494
|
+
export function finishCommand(context, runId, projectRoot, decision, retryCheckId) {
|
|
495
|
+
return managedLifecycleCommand(context, runtimeCommand(context, ["stage", "finish", runId, "--stage", "code-review", "--decision-file", decision, "--project-root", projectRoot, "--json", "--progress-jsonl", ...checkRetryArgs(context, projectRoot, runId, retryCheckId)]));
|
|
496
|
+
}
|
|
383
497
|
function findFiles(root, name) { if (!fs.existsSync(root))
|
|
384
498
|
return []; const out = []; for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
385
499
|
const file = path.join(root, entry.name);
|
|
@@ -397,4 +511,3 @@ function readJsonString(value) { try {
|
|
|
397
511
|
catch {
|
|
398
512
|
return {};
|
|
399
513
|
} }
|
|
400
|
-
function writeReport(root, report) { writeStageReport(root, report); }
|