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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/README.md +68 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +305 -0
  5. package/dist/cli/help.js +89 -13
  6. package/dist/cli/hook-ingress.js +77 -0
  7. package/dist/cli/input-preparation.js +116 -0
  8. package/dist/cli/native-hook-ingress.js +48 -0
  9. package/dist/cli/run-cli.js +1465 -384
  10. package/dist/cli.js +8 -2
  11. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  12. package/dist/harness-runtime/bin/dd-agy.mjs +52 -0
  13. package/dist/harness-runtime/bin/dd-codex.mjs +26 -0
  14. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  15. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  16. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  17. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  18. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  19. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  20. package/dist/harness-runtime/lib/daemon-operations.mjs +226 -0
  21. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  22. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +500 -0
  23. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  24. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  25. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +149 -0
  26. package/dist/harness-runtime/lib/dd-codex.mjs +563 -0
  27. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  28. package/dist/harness-runtime/lib/dd-droid.mjs +475 -0
  29. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +394 -0
  30. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  31. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +219 -0
  32. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  33. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +645 -0
  34. package/dist/harness-runtime/lib/dd-zcode.mjs +982 -0
  35. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  36. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  37. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  38. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  39. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  40. package/dist/harness-runtime/lib/managed-daemon.mjs +327 -0
  41. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  42. package/dist/harness-runtime/lib/native-hook-command.d.mts +3 -0
  43. package/dist/harness-runtime/lib/native-hook-command.mjs +108 -0
  44. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  45. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  46. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  47. package/dist/harness-runtime/lib/process-json.mjs +71 -0
  48. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  49. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  50. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  51. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  52. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  53. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  54. package/dist/harness-runtime/lib/zcode-usage.mjs +54 -0
  55. package/dist/protocol/local-files.js +18 -9
  56. package/dist/runtime/context.js +2 -2
  57. package/dist/schemas/agent-profile.schema.json +1 -1
  58. package/dist/schemas/code-review-result.schema.json +1 -1
  59. package/dist/schemas/code-work-batch.schema.json +3 -3
  60. package/dist/schemas/code-work-result.schema.json +3 -3
  61. package/dist/schemas/plan-review-result.schema.json +2 -2
  62. package/dist/schemas/run-control-receipt.schema.json +99 -0
  63. package/dist/schemas/run-control-request.schema.json +36 -0
  64. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  65. package/dist/services/canon.js +11 -8
  66. package/dist/services/cleanup.js +132 -39
  67. package/dist/services/cli-operation-classifier.js +22 -24
  68. package/dist/services/code-checks.js +589 -106
  69. package/dist/services/codex-hook-delivery.js +28 -0
  70. package/dist/services/command-context.js +80 -0
  71. package/dist/services/config.js +11 -8
  72. package/dist/services/continuation-outcome.js +20 -0
  73. package/dist/services/controller-fanout.js +173 -0
  74. package/dist/services/dashboard.js +103 -31
  75. package/dist/services/engines.js +121 -76
  76. package/dist/services/eval-snapshots.js +994 -97
  77. package/dist/services/execution-policy.js +181 -0
  78. package/dist/services/external-work-launch.js +166 -0
  79. package/dist/services/harness-adapter.js +147 -24
  80. package/dist/services/harness-config.js +2 -0
  81. package/dist/services/hooks.js +702 -327
  82. package/dist/services/lanes.js +78 -65
  83. package/dist/services/lifecycle-command.js +113 -18
  84. package/dist/services/lifecycle-contract.js +30 -0
  85. package/dist/services/lifecycle-invocations.js +1379 -0
  86. package/dist/services/managed-daemon-binding.js +38 -0
  87. package/dist/services/managed-processes.js +302 -34
  88. package/dist/services/merge-queue.js +228 -149
  89. package/dist/services/merge-server.js +66 -28
  90. package/dist/services/migrations.js +37 -16
  91. package/dist/services/native-daemon-history.js +49 -0
  92. package/dist/services/native-session-control.js +39 -0
  93. package/dist/services/plan-runtime.js +26 -11
  94. package/dist/services/plans.js +28 -25
  95. package/dist/services/projects.js +20 -15
  96. package/dist/services/prompts.js +25 -16
  97. package/dist/services/protocols.js +160 -86
  98. package/dist/services/recovery-observation-budget.js +61 -0
  99. package/dist/services/recovery-snapshot-database.js +142 -0
  100. package/dist/services/repair-intents.js +40 -0
  101. package/dist/services/review-copy.js +136 -0
  102. package/dist/services/run-control-receipt.js +56 -0
  103. package/dist/services/run-control-worker.js +351 -0
  104. package/dist/services/run-control.js +888 -0
  105. package/dist/services/run-controller-adapter.js +231 -0
  106. package/dist/services/run-controller-capture.js +167 -0
  107. package/dist/services/run-controller-process.js +180 -0
  108. package/dist/services/run-controller-recovery.js +221 -0
  109. package/dist/services/run-controller-state.js +36 -0
  110. package/dist/services/run-controller.js +798 -0
  111. package/dist/services/run-engine-bindings.js +1 -1
  112. package/dist/services/run-fork.js +142 -0
  113. package/dist/services/run-observations.js +112 -0
  114. package/dist/services/run-projection.js +22 -64
  115. package/dist/services/run-recovery-runtime.js +80 -0
  116. package/dist/services/run-recovery.js +345 -0
  117. package/dist/services/runs.js +536 -181
  118. package/dist/services/runtime-budget.js +413 -0
  119. package/dist/services/runtime-command.js +43 -0
  120. package/dist/services/runtime-scope-capture.js +52 -0
  121. package/dist/services/runtime-scope-control.js +460 -0
  122. package/dist/services/runtime-scope-resume.js +577 -0
  123. package/dist/services/runtime-scope-stop.js +159 -0
  124. package/dist/services/runtime-scope-worker.js +242 -0
  125. package/dist/services/runtime-service.js +97 -0
  126. package/dist/services/schema-validation.js +10 -8
  127. package/dist/services/scope-writer-cleanup.js +26 -0
  128. package/dist/services/sessions.js +35 -69
  129. package/dist/services/stage-blocker.js +17 -7
  130. package/dist/services/stage-context.js +50 -19
  131. package/dist/services/stage-lifecycle.js +100 -103
  132. package/dist/services/stage-pause.js +88 -75
  133. package/dist/services/stage-report-renderer.js +116 -6
  134. package/dist/services/stage-work-graph.js +35 -0
  135. package/dist/services/usage.js +35 -98
  136. package/dist/services/vnext-code-review.js +197 -84
  137. package/dist/services/vnext-code.js +278 -251
  138. package/dist/services/vnext-execution-profile.js +5 -3
  139. package/dist/services/vnext-fanout.js +172 -17
  140. package/dist/services/vnext-merge.js +345 -111
  141. package/dist/services/vnext-plan-review.js +171 -111
  142. package/dist/services/vnext-plan.js +180 -87
  143. package/dist/services/vnext-protocolize.js +320 -74
  144. package/dist/services/vnext-specify.js +115 -77
  145. package/dist/services/work-registry.js +1001 -187
  146. package/dist/services/workspace-bootstrap.js +76 -0
  147. package/dist/services/workspace-files.js +83 -0
  148. package/dist/services/worktrees.js +88 -36
  149. package/dist/shared/entity-references.js +8 -0
  150. package/dist/shared/errors.js +12 -0
  151. package/dist/storage/database.js +692 -35
  152. package/dist/storage/foreign-key-transaction.js +39 -0
  153. package/dist/storage/immutable-input.js +45 -0
  154. package/dist/storage/import-guard.js +102 -0
  155. package/dist/storage/native-cleanup.js +52 -0
  156. package/dist/storage/paths.js +17 -4
  157. package/dist/storage/projection-lock.js +73 -0
  158. package/dist/storage/work-references.js +23 -0
  159. package/dist/storage/writer-contract.js +77 -0
  160. package/dist/storage/writer-migration.js +85 -0
  161. package/package.json +24 -13
  162. package/tools/repair-paused-run-status.mjs +84 -0
@@ -1,100 +1,117 @@
1
+ import { managedLifecycleCommand } from "./lifecycle-invocations.js";
2
+ import { prepareJsonSchema, prepareOutputFile } from "../cli/input-preparation.js";
1
3
  import crypto from "node:crypto";
4
+ import { withStageSettlement, prepareFlowRunStageAttachment, prepareFlowRunStageCompletion } from "./runs.js";
2
5
  import fs from "node:fs";
3
6
  import path from "node:path";
4
7
  import { AppError } from "../shared/errors.js";
5
8
  import { effectiveCheckDeclarations, readCodeCheckProfile, validateCheckDeclaration, validateCheckPlacement, validateCodeCheckCommands } from "./code-checks.js";
6
9
  import { requireProjectByRoot } from "./projects.js";
7
- import { resolveProjectRoot } from "../storage/paths.js";
10
+ import { canonicalPath, resolveProjectRoot } from "../storage/paths.js";
8
11
  import { advanceFlowRun, appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRunStage, getFlowRunVariables, gitFacts } from "./runs.js";
9
12
  import { validateSchema } from "./schema-validation.js";
10
- import { bindRunningWorkSession, bindStageCoordinatorWork, ensureWorkRegistry, refreshRunWorkProjection, validateWorkBatchFile } from "./work-registry.js";
13
+ import { bindRunningWorkSession, bindStageCoordinatorWork, ensureWorkRegistry, refreshRunWorkProjection, validateWorkBatch } from "./work-registry.js";
11
14
  import { flowCommand, stagePauseCommand, stagePauseCommandTemplate } from "./stage-pause.js";
12
15
  import { assertStageStartHookEvent } from "./hooks.js";
13
16
  import { requireVnextWorkspaceRoute } from "./vnext-workspace-policy.js";
14
17
  import { readVnextSpecifyResult } from "./vnext-specify.js";
15
18
  import { nextWorkId } from "./ids.js";
16
19
  import { vnextStageDirectory } from "../domain/stage-catalog.js";
17
- import { writeStageReport } from "./stage-report-renderer.js";
18
- import { applyExternalStageContext } from "./stage-context.js";
20
+ import { acceptStageReport, prepareStageReport } from "./stage-report-renderer.js";
21
+ import { applyExternalStageContext, prepareExternalStageContext } from "./stage-context.js";
19
22
  import { subagentCapacityKey } from "./vnext-fanout.js";
23
+ import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
20
24
  export function isVnextPlanRun(context, input) {
21
25
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
22
26
  return Boolean(context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ? AND flow_kind = 'vnext_protocolize'", [project.id, input.runId]));
23
27
  }
24
- export function startVnextPlan(context, input) {
25
- ensureWorkRegistry(context);
28
+ export function prepareVnextPlanStart(context, input) {
26
29
  const projectRoot = resolveProjectRoot(input.projectRoot);
27
30
  const project = requireProjectByRoot(context, projectRoot);
28
31
  const run = requireRun(context, projectRoot, input.runId);
29
32
  const home = requireHome(run);
30
- assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage: "plan", projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
31
33
  const workspaceRoute = requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
32
34
  const protocols = protocolIds(home);
33
35
  if (!protocols.length)
34
- throw new AppError("not_found", "PLAN requires accepted PROTOCOLIZE protocols", 1);
36
+ throw new AppError("runtime_artifact_missing", "PLAN requires accepted PROTOCOLIZE protocols", 1);
35
37
  // Static inputs are checked before PLAN creates a Work or materializes a
36
- // draft. A rejected start is therefore side-effect free and safe to retry.
38
+ // draft. Retained corruption is still an infrastructure failure, not a typo.
37
39
  const template = read(path.join(projectRoot, ".memory-bank", "dd-flow", "vnext", "plan.md"));
38
40
  assertProtocolWorkspace(run.workspace_root, protocols);
39
41
  const { profile: codeCheckProfile } = readCodeCheckProfile(run.workspace_root);
40
42
  if (context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND task = ? AND status = 'running'", [project.id, run.id, planTask]))
41
43
  throw new AppError("invalid_work_state", "PLAN already has a running Work", 1, { run_id: run.id });
44
+ prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage: "plan", dir: "03-plan", status: "running", dataSchemaId: "dd-flow/protocol-plan@6" });
42
45
  const root = path.join(home, vnextStageDirectory("plan"));
43
- fs.mkdirSync(root, { recursive: true });
44
- const now = context.now();
46
+ if (input.externalContext)
47
+ prepareExternalStageContext({ stageRoot: root, loaded: input.externalContext });
45
48
  const rootWork = context.db.get("SELECT work_id FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id IS NULL ORDER BY created_at LIMIT 1", [project.id, run.id]);
46
49
  if (!rootWork)
47
50
  throw new AppError("runtime_missing", "vNext RUN has no root Work", 1);
51
+ const planPaths = protocols.map(id => path.join(run.workspace_root, ".memory-bank", "protocol", id, "plan.json"));
52
+ const mapPaths = protocols.map(id => path.join(root, id, "aspect-map.json"));
53
+ const owned = protocolOwnership(home, protocols);
54
+ const identities = protocols.map(protocolId => planIdentity(home, run.id, protocolId, owned.get(protocolId) ?? []));
55
+ const aspects = aspectCatalog(run.workspace_root);
56
+ const runVariables = getFlowRunVariables(context, { projectRoot, runId: run.id });
57
+ const mergeRequired = runEndsAtMerge(context, projectRoot, run.id);
58
+ const git = gitFacts(run.workspace_root);
59
+ for (const file of [...planPaths, ...mapPaths, ...["stage-prompt.md", "work-context.json", "fixture-root.prompt.md"].map(name => path.join(root, name))])
60
+ prepareOutputFile(file);
61
+ return { projectRoot, project, run, home, root, rootWork, workspaceRoute, protocols, template, codeCheckProfile, planPaths, mapPaths, owned, identities, aspects, runVariables, mergeRequired, git };
62
+ }
63
+ export function startVnextPlan(context, input, prepared = prepareVnextPlanStart(context, input)) {
64
+ const { projectRoot, project, run, root, rootWork, workspaceRoute, protocols, template, codeCheckProfile, planPaths, mapPaths, owned, identities, aspects, runVariables, mergeRequired, git, home } = prepared;
65
+ ensureWorkRegistry(context);
66
+ assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage: "plan", projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
67
+ fs.mkdirSync(root, { recursive: true });
68
+ const now = context.now();
48
69
  // Imported stage fixtures have a synthetic running root with no prior agent.
49
70
  // Bind it on the first real stage start so its child PLAN Work has a real parent.
50
71
  if (!context.db.get("SELECT 1 FROM work_sessions WHERE work_id = ? LIMIT 1", [rootWork.work_id])) {
51
72
  bindRunningWorkSession(context, { workId: rootWork.work_id, hookEventId: input.hookEventId, promptPath: path.join(root, "fixture-root.prompt.md") });
52
73
  }
53
- context.db.exec("BEGIN IMMEDIATE");
54
- let planWorkId;
55
- try {
56
- planWorkId = nextWorkId(context, project.id, "plan");
74
+ const planWorkId = context.db.writeTransaction(() => {
75
+ if (context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND task = ? AND status = 'running'", [project.id, run.id, planTask]))
76
+ throw new AppError("invalid_work_state", "PLAN already has a running Work", 1, { run_id: run.id });
77
+ const planWorkId = nextWorkId(context, project.id, "plan");
57
78
  context.db.run(`INSERT INTO works (work_id, project_id, run_id, parent_work_id, task, launch_policy, result_schema, depends_on_json, status, result, started_at, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, ?, 'reuse_allowed', NULL, '[]', 'running', NULL, ?, ?, ?, NULL)`, [planWorkId, project.id, run.id, rootWork.work_id, planTask, now, now, now]);
58
- context.db.exec("COMMIT");
59
- }
60
- catch (error) {
61
- context.db.exec("ROLLBACK");
62
- throw error;
63
- }
79
+ return planWorkId;
80
+ });
64
81
  // A Desktop task may start above the materialized repository. Lifecycle
65
82
  // prompts therefore hand agents write targets as absolute paths: relative
66
83
  // `.memory-bank/...` paths would otherwise silently land in the parent cwd.
67
- const planPaths = protocols.map((id) => path.join(run.workspace_root, ".memory-bank", "protocol", id, "plan.json"));
68
- const mapPaths = protocols.map((id) => `${path.join(root, id, "aspect-map.json")}`);
69
- const owned = protocolOwnership(home, protocols);
70
- const identities = protocols.map((protocolId) => planIdentity(home, run.id, protocolId, owned.get(protocolId) ?? []));
71
84
  planPaths.forEach((file, index) => ensurePlanSkeleton(file, protocols[index], identities[index]));
72
- mapPaths.forEach((file, index) => ensureAspectMapSkeleton(file, protocols[index], identities[index], run.workspace_root));
73
- const finishCommand = `${flowCommand(context)} stage finish ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json`;
85
+ mapPaths.forEach((file, index) => ensureAspectMapSkeleton(file, protocols[index], identities[index], aspects));
86
+ const finishCommand = managedLifecycleCommand(context, `${flowCommand(context)} stage finish ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json`);
74
87
  const pauseCommand = stagePauseCommand(context, { runId: run.id, stage: "plan", workId: planWorkId, projectRoot });
75
88
  const pauseCommandTemplate = stagePauseCommandTemplate(pauseCommand);
76
89
  const validationCommands = protocols.flatMap((_, index) => [
77
90
  `${flowCommand(context)} schema validate --schema vnext-protocol-plan --file ${JSON.stringify(planPaths[index])} --project-root ${JSON.stringify(run.workspace_root)} --run ${run.id} --json`,
78
91
  `${flowCommand(context)} schema validate --schema plan-aspect-map --file ${JSON.stringify(mapPaths[index])} --project-root ${JSON.stringify(run.workspace_root)} --run ${run.id} --json`
79
92
  ]);
80
- const runVariables = getFlowRunVariables(context, { projectRoot, runId: run.id });
81
93
  const measuredCapacity = runVariables.variables[subagentCapacityKey];
82
- const mergeRequired = runEndsAtMerge(context, projectRoot, run.id);
94
+ const planReviewMode = requestedPlanReviewMode(context, project.id, run.id);
83
95
  const capacityContext = typeof measuredCapacity === "number" && Number.isInteger(measuredCapacity) && measuredCapacity >= 0
84
96
  ? `- The qualified reviewer capacity is ${measuredCapacity}. This is a runtime fact for later PLAN-REVIEW dispatch; do not repeat qualification or invent a different value.`
85
97
  : "- Reviewer capacity is not qualified yet. PLAN must not qualify or launch reviewers; an external harness controller supplies it before fan-out.";
86
98
  const reviewGroupingRule = "Group only semantically compatible applicable aspects, preserving real trust, irreversible, high-risk and hard-dependency boundaries. Prefer the fewest groups that retain independent review value, normally one review wave. Put two or three compatible aspects in a group; do not create one group per aspect merely for convenience. A later PLAN-REVIEW dispatch uses externally qualified capacity to schedule these semantic groups into waves; do not invent a capacity value here.";
87
- const checkProfile = path.join(run.workspace_root, ".memory-bank", "spec", "engineering", "code-check-profile.json");
88
99
  const policyMergeAliases = codeCheckProfile?.mandatory_by_gate.merge ?? [];
89
100
  const mergeContract = mergeRequired
90
101
  ? ["<merge_gate_contract>", ...(policyMergeAliases.length
91
102
  ? [`This RUN must reach MERGE. Project policy already supplies the mandatory merge gate${policyMergeAliases.length === 1 ? "" : "s"}: ${policyMergeAliases.join(", ")}. Do not duplicate them in semantic checks[]. Add another merge check only when the task genuinely needs additional evidence.`]
92
103
  : ["This RUN must reach MERGE and project policy supplies no merge gate. Select at least one real top-level checks[] entry with run_at: merge. It may use an existing project alias or a planned alias materialised by a named P* provider Work. This is a planning obligation: do not defer it to CODE-REVIEW or MERGE."]), "The CLI validates the effective merge gate but never invents one or migrates an incompatible project policy.", "</merge_gate_contract>", ""]
93
104
  : [];
94
- const prompt = ["<stage_identity>", `- RUN: ${run.id}`, `- Work: ${planWorkId}`, "- stage: plan", "</stage_identity>", "", "<trusted_runtime_context>", "These facts were collected by dd-flow. Trust them; do not repeat CLI, Git, compatibility or permission discovery.", `- Project root: ${projectRoot}`, `- Workspace: ${run.workspace_root}`, `- Stage workspace: ${root}`, `- Git: ${JSON.stringify(gitFacts(run.workspace_root))}`, capacityContext, "</trusted_runtime_context>", "", "<workspace_contract>", `- route: ${workspaceRoute.route}`, `- feature branch: ${workspaceRoute.feature_branch ?? "not applicable"}`, `- base commit: ${workspaceRoute.base_ref ?? "not applicable"}`, `- write workspace: ${run.workspace_root}`, "The CLI has verified this frozen route. All project reads and writes for PLAN and later CODE happen in the write workspace; project root is only the stable runtime identity for lifecycle commands. Do not create, switch, merge or delete branches/worktrees.", "Keep the task runner's current cwd. Use the absolute paths in this packet instead of trying to set the provisioned workspace as a tool workdir.", "</workspace_contract>", "", "<accepted_inputs>", `- ${path.join(home, "01-specify", "specify.json")}`, `- ${path.join(home, "02-protocolize", "protocolize-result.json")}`, ...protocols.map((id) => `- ${path.join(run.workspace_root, ".memory-bank", "protocol", id, "summary.md")}`), "</accepted_inputs>", "", ...(fs.existsSync(checkProfile) ? ["<code_check_policy>", "You, not the CLI, select evidence for every accepted requirement and acceptance criterion. The profile only lists reusable aliases, mandatory project policy gates and guarded raw command prefixes. Inspect relevant package/test manifests before choosing a check. Do not classify checks by weight and do not omit a needed check because it looks expensive.", fs.readFileSync(checkProfile, "utf8").trim(), "</code_check_policy>", ""] : []), ...mergeContract, "<artifacts>", "The CLI has already materialized every artifact below as a partially filled draft. Edit these files in place; do not create replacements elsewhere.", "Prefilled and CLI-owned plan fields: schema_id, plan_id, protocol_id, initial revision and source_refs.", "Prefilled and CLI-owned aspect-map fields: schema_id, protocol_id, plan_id, plan revision, catalog_ref and every catalog aspect_id.", "You own the remaining semantic fields. Empty or missing semantic values are intentional draft markers and must be completed before validation.", ...planPaths.map((value) => `- partially filled plan: ${value}`), ...mapPaths.map((value) => `- partially filled aspect map: ${value}`), "</artifacts>", "", "<output_contract>", "Complete every named plan and aspect map in place. Do not create or edit code-work-batch.json: dd-flow derives it after validation.", "The CLI owns schema_id, plan_id, protocol_id, revision and source_refs. Preserve them exactly.", "Use protocol-plan@6. Its top-level checks[] is the single check catalog. Every check has id, command, purpose, run_at and availability. available means executable now. planned means one named P* Work first creates a NEW @check/... alias: planned therefore always needs provided_by and the exact alias definition. Every semantic @check alias, including an existing one, repeats its exact accepted profile command in definition so later stages can detect drift. Items and acceptance entries use check_refs only; never duplicate command declarations.", "For each R-* and AC-*, choose an actually relevant proof: an existing focused test, a new planned alias plus its provider Work, a project policy gate, or an honestly limited external/manual proof. Every plan item needs at least one check_ref. The CLI validates ids, provider ordering, materialization and guarded command policy; it never chooses a check for you. A provider Work may verify itself with the alias it has just created. A consumer must depend on that provider.", "Each plan item must name concrete existing source/test paths in required_read. planned_write_areas is optional: use stable component directories or files only when they help coordinate parallel Work; it is never a write allowlist. Reference every owned R-* and AC-* in one or more items; every AC-* needs an observable acceptance proof.", "For every selected check, inspect its command's launch path and the runtime entrypoints it starts. The fixture/reset process, service process and client process must observe one intended environment and data world. If a required runtime entrypoint needs a code change, make that change explicit in the Work task and its verification. Use planned_write_areas only to advertise likely concurrent overlap; do not treat it as ownership or assume another Work will repair an omitted change. If an independent infrastructure Work is clearer, plan that Work explicitly and order consumers after it.", reviewGroupingRule, "Complete compact contract and schema paths:", `- protocol plan schema: ${path.join(run.workspace_root, ".memory-bank", "dd-flow", "schemas", "vnext-protocol-plan.schema.json")}`, `- aspect map schema: ${path.join(run.workspace_root, ".memory-bank", "dd-flow", "schemas", "plan-aspect-map.schema.json")}`, "Minimal valid protocol-plan shape:", "```json", JSON.stringify(planExample(protocols[0]), null, 2), "```", "Minimal valid aspect-map shape:", "```json", JSON.stringify(aspectMapExample(protocols[0]), null, 2), "```", "</output_contract>", "", "<execution_commands>", "PLAN never launches independent reviewers or registers CODE Work.", "If PLAN needs a material user decision with no reasonable default, run this exact one-command heredoc, replacing only its placeholder body. The heredoc is the permitted stdin form; do not use cat, a pipe, a temporary file or a second shell command:", "```sh", pauseCommandTemplate, "```", "Ask the returned user_message, stop, and resume this same PLAN Work with the exact returned command.", "Validate both partially filled drafts after completing their semantic fields:", ...validationCommands.map((command) => `- ${command}`), "Finish PLAN only after all questions are resolved and both validation commands pass:", finishCommand, "The response returns the only PLAN-REVIEW start command. Follow it; do not start CODE directly.", "</execution_commands>", "", "<stage_instructions>", template, "</stage_instructions>", ""].join("\n");
105
+ const prompt = ["<stage_identity>", `- RUN: ${run.id}`, `- Work: ${planWorkId}`, "- stage: plan", "</stage_identity>", "", "<trusted_runtime_context>", "These facts were collected by dd-flow. Trust them; do not repeat CLI, Git, compatibility or permission discovery.", `- Project root: ${projectRoot}`, `- Workspace: ${run.workspace_root}`, `- Stage workspace: ${root}`, `- Git: ${JSON.stringify(git)}`, capacityContext, "</trusted_runtime_context>", "", "<workspace_contract>", `- route: ${workspaceRoute.route}`, `- feature branch: ${workspaceRoute.feature_branch ?? "not applicable"}`, `- base commit: ${workspaceRoute.base_ref ?? "not applicable"}`, `- write workspace: ${run.workspace_root}`, "The CLI has verified this frozen route. All project reads and writes for PLAN and later CODE happen in the write workspace; project root is only the stable runtime identity for lifecycle commands. Do not create, switch, merge or delete branches/worktrees.", "Keep the task runner's current cwd. Use the absolute paths in this packet instead of trying to set the provisioned workspace as a tool workdir.", "</workspace_contract>", "", "<accepted_inputs>", `- ${path.join(home, "01-specify", "specify.json")}`, `- ${path.join(home, "02-protocolize", "protocolize-result.json")}`, ...protocols.map((id) => `- ${path.join(run.workspace_root, ".memory-bank", "protocol", id, "summary.md")}`), "</accepted_inputs>", "", ...(codeCheckProfile ? ["<code_check_policy>", "You, not the CLI, select evidence for every accepted requirement and acceptance criterion. The profile only lists reusable aliases, mandatory project policy gates and guarded raw command prefixes. Inspect relevant package/test manifests before choosing a check. Do not classify checks by weight and do not omit a needed check because it looks expensive.", JSON.stringify(codeCheckProfile, null, 2), "</code_check_policy>", ""] : []), ...mergeContract, "<artifacts>", "The CLI has already materialized every artifact below as a partially filled draft. Edit these files in place; do not create replacements elsewhere.", "Prefilled and CLI-owned plan fields: schema_id, plan_id, protocol_id, initial revision and source_refs.", "Prefilled and CLI-owned aspect-map fields: schema_id, protocol_id, plan_id, plan revision, catalog_ref and every catalog aspect_id.", "You own the remaining semantic fields. Empty or missing semantic values are intentional draft markers and must be completed before validation.", ...planPaths.map((value) => `- partially filled plan: ${value}`), ...mapPaths.map((value) => `- partially filled aspect map: ${value}`), "</artifacts>", "", "<output_contract>", "Complete every named plan and aspect map in place. Do not create or edit code-work-batch.json: dd-flow derives it after validation.", "The CLI owns schema_id, plan_id, protocol_id, revision and source_refs. Preserve them exactly.", "Use protocol-plan@6. Its top-level checks[] is the single check catalog. Every check has id, command, purpose, run_at and availability. available means executable now. planned means one named P* Work first creates a NEW @check/... alias: planned therefore always needs provided_by and the exact alias definition. Every semantic @check alias, including an existing one, repeats its exact accepted profile command in definition so later stages can detect drift. Items and acceptance entries use check_refs only; never duplicate command declarations.", "For each R-* and AC-*, choose an actually relevant proof: an existing focused test, a new planned alias plus its provider Work, a project policy gate, or an autonomous executable check. Every plan item needs at least one check_ref. The CLI validates ids, provider ordering, materialization and guarded command policy; it never chooses a check for you. A provider Work may verify itself with the alias it has just created. A consumer must depend on that provider.", "Each plan item must name concrete existing source/test paths in required_read. planned_write_areas is optional: use stable component directories or files only when they help coordinate parallel Work; it is never a write allowlist. Reference every owned R-* and AC-* in one or more items; every AC-* needs an observable acceptance proof.", "For every selected check, inspect its command's launch path and the runtime entrypoints it starts. The fixture/reset process, service process and client process must observe one intended environment and data world. If a required runtime entrypoint needs a code change, make that change explicit in the Work task and its verification. Use planned_write_areas only to advertise likely concurrent overlap; do not treat it as ownership or assume another Work will repair an omitted change. If an independent infrastructure Work is clearer, plan that Work explicitly and order consumers after it.", reviewGroupingRule, "Complete compact contract and schema paths:", `- protocol plan schema: ${path.join(run.workspace_root, ".memory-bank", "dd-flow", "schemas", "vnext-protocol-plan.schema.json")}`, `- aspect map schema: ${path.join(run.workspace_root, ".memory-bank", "dd-flow", "schemas", "plan-aspect-map.schema.json")}`, "Minimal valid protocol-plan shape:", "```json", JSON.stringify(planExample(protocols[0]), null, 2), "```", "Minimal valid aspect-map shape:", "```json", JSON.stringify(aspectMapExample(protocols[0]), null, 2), "```", "</output_contract>", "", "<execution_commands>", "PLAN never launches independent reviewers or registers CODE Work.", "If PLAN needs a material user decision with no reasonable default, write the question packet to the named text file, then run the separate standalone lifecycle command below. Do not combine file creation and dd-flow in one shell command:", "```sh", pauseCommandTemplate, "```", "Ask the returned user_message, stop, and resume this same PLAN Work with the exact returned command.", "Validate both partially filled drafts after completing their semantic fields:", ...validationCommands.map((command) => `- ${command}`), "Finish PLAN only after all questions are resolved and both validation commands pass:", finishCommand, "The response returns the only PLAN-REVIEW start command. Follow it; do not start CODE directly.", "</execution_commands>", "", "<stage_instructions>", template, "</stage_instructions>", ""].join("\n");
95
106
  const artifactMaterialization = { status: "materialized", completeness: "partially_filled", plan_paths: planPaths, aspect_map_paths: mapPaths, cli_owned_plan_fields: ["schema_id", "plan_id", "protocol_id", "revision", "source_refs"], cli_owned_aspect_map_fields: ["schema_id", "protocol_id", "plan_id", "plan_revision", "catalog_ref", "aspects[].aspect_id"], validation_commands: validationCommands };
96
107
  const promptPath = path.join(root, "stage-prompt.md");
97
- fs.writeFileSync(promptPath, prompt);
108
+ // This explicit final rule supersedes historical pack wording: a flow gate
109
+ // has only executable autonomous evidence. Human or external confirmation
110
+ // is neither a check nor a permitted completion condition.
111
+ const reviewModeRule = planReviewMode === "standard" || planReviewMode === "deep"
112
+ ? `PLAN-REVIEW mode is ${planReviewMode}: assign at least one genuinely applicable aspect to a review group. Small feature size alone does not make every aspect not applicable; PLAN finish rejects an empty review set.`
113
+ : `PLAN-REVIEW mode is ${planReviewMode}: include review groups only for genuinely applicable aspects; an empty set is allowed.`;
114
+ fs.writeFileSync(promptPath, `${prompt}\n<review_mode_rule>${reviewModeRule}</review_mode_rule>\n<verification_rule>Every flow check must be an autonomous executable command. Do not declare external/manual proof or a human review as a check, evidence substitute, DEF, or gate. The only user interaction supported by this flow is an explicit stage pause for a material unanswered question.</verification_rule>\n${stageLifecycleInstruction}\n`);
98
115
  const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
99
116
  fs.writeFileSync(path.join(root, "work-context.json"), JSON.stringify({ schema_id: "dd-flow/work-context@1", system: { run_id: run.id, work_id: planWorkId, stage: "plan" }, workspace: { project_root: projectRoot, workspace_root: run.workspace_root, stage_root: root }, artifacts: artifactMaterialization, input: { protocols, owned_obligations: Object.fromEntries(owned) } }, null, 2));
100
117
  const binding = bindStageCoordinatorWork(context, { workId: planWorkId, hookEventId: input.hookEventId, stage: "plan", promptPath, resultPath: path.join(root, "stage-report.json"), ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
@@ -105,7 +122,21 @@ export function startVnextPlan(context, input) {
105
122
  appendFlowRunTimelineEvent(context, project.id, run.id, { type: "work_session_started", stage: "plan", work_id: planWorkId, id: workSessionId, session_id: sessionId });
106
123
  return { ok: true, run_id: run.id, work_id: planWorkId, id: workSessionId, artifact_materialization: artifactMaterialization, worker_prompt_markdown: fs.readFileSync(promptPath, "utf8"), prompt_path: promptPath, next_command: finishCommand, ...(externalContext ? { external_context: externalContext } : {}) };
107
124
  }
125
+ export function prepareVnextPlanFinish(context, input) {
126
+ const projectRoot = resolveProjectRoot(input.projectRoot);
127
+ const run = requireRun(context, projectRoot, input.runId), home = requireHome(run);
128
+ requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
129
+ const protocols = protocolIds(home);
130
+ assertProtocolWorkspace(run.workspace_root, protocols);
131
+ const prepared = prepareVnextPlanArtifacts(context, { projectRoot, workspaceRoot: run.workspace_root, runId: run.id, home, protocols });
132
+ if (prepared.failures.length)
133
+ throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: prepared.failures, phase: "prepare", effect: "no_effect", recoverable: true });
134
+ return prepared;
135
+ }
108
136
  export function finishVnextPlan(context, input) {
137
+ return finishVnextPlanOwned(context, input);
138
+ }
139
+ function finishVnextPlanOwned(context, input) {
109
140
  const projectRoot = resolveProjectRoot(input.projectRoot);
110
141
  const project = requireProjectByRoot(context, projectRoot);
111
142
  const run = requireRun(context, projectRoot, input.runId);
@@ -114,38 +145,59 @@ export function finishVnextPlan(context, input) {
114
145
  requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
115
146
  const protocols = protocolIds(home);
116
147
  if (!protocols.length)
117
- throw new AppError("not_found", "PLAN requires accepted PROTOCOLIZE protocols", 1);
148
+ throw new AppError("runtime_artifact_missing", "PLAN requires accepted PROTOCOLIZE protocols", 1);
118
149
  assertProtocolWorkspace(run.workspace_root, protocols);
119
150
  const planFiles = protocols.map((id) => path.join(run.workspace_root, ".memory-bank", "protocol", id, "plan.json"));
120
151
  const mapFiles = protocols.map((id) => path.join(root, id, "aspect-map.json"));
121
152
  const batch = path.join(root, "code-work-batch.json");
122
- const failures = validateVnextPlanArtifacts(context, { projectRoot, workspaceRoot: run.workspace_root, runId: run.id, home, protocols });
123
- if (failures.length)
124
- throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: failures });
153
+ const prepared = input.prepared ?? prepareVnextPlanFinish(context, input);
154
+ if (prepared.failures.length)
155
+ throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: prepared.failures, phase: "prepare", effect: "no_effect", recoverable: true });
125
156
  const work = context.db.get("SELECT work_id FROM works WHERE project_id = ? AND run_id = ? AND task = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [project.id, run.id, planTask]);
126
157
  if (!work)
127
158
  throw new AppError("invalid_work_state", "PLAN has no running Work", 1);
128
- const now = context.now();
129
- const batchChecksum = checksum(batch);
130
- context.db.run("UPDATE works SET status = 'completed', result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", ["PLAN accepted; awaiting PLAN-REVIEW", now, now, work.work_id]);
131
159
  const workSession = context.db.get("SELECT id, session_id FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
132
160
  if (!workSession?.session_id)
133
161
  throw new AppError("trusted_session_binding_required", "PLAN finish requires its bound Agent WorkSession", 1, { work_id: work.work_id });
134
- context.db.run("UPDATE work_sessions SET status = 'completed', result_path = ?, updated_at = ?, completed_at = ? WHERE id = ?", [path.join(root, "stage-report.json"), now, now, workSession.id]);
135
- refreshRunWorkProjection(context, project.id, run.id);
136
- const reviewCommand = `${flowCommand(context)} stage start ${run.id} --stage plan-review --project-root ${JSON.stringify(projectRoot)} --json`;
137
- const report = { schema_id: "dd-flow/stage-report@1", run_id: run.id, stage: "plan", generated_at: now, verdict: "done", semantic: { result: `Accepted ${protocols.length} executable PLAN artifact${protocols.length === 1 ? "" : "s"}.`, acceptance: protocols, changed_files: [...planFiles.map((file) => path.relative(projectRoot, file)), ...mapFiles.map((file) => runRef(run.id, home, file)), runRef(run.id, home, batch)], checks: ["protocol-plan schema", "aspect-map schema", "cross-artifact references", "generated CODE batch"], evidence: [runRef(run.id, home, path.join(root, "stage-report.json"))], next_action: "start_plan_review", plans: planFiles.map((file) => path.relative(projectRoot, file)), aspect_maps: mapFiles.map((file) => runRef(run.id, home, file)), code_work_batch: runRef(run.id, home, batch), batch_checksum: batchChecksum }, mechanical: { started_at: stageStartedAt(home, now), finished_at: now, wall_clock_ms: Math.max(0, Date.parse(now) - Date.parse(stageStartedAt(home, now))), git: gitFacts(run.workspace_root), session_stats_command: `${flowCommand(context)} stat run sessions ls --run ${run.id} --project-root ${JSON.stringify(projectRoot)} --json`, usage_stats_command: `${flowCommand(context)} stat usage --run ${run.id} --project-root ${JSON.stringify(projectRoot)} --json`, next_command: reviewCommand }, artifacts: { json: "stage-report.json", markdown: "stage-report.md", html: "stage-report.html", summary: "stage-report.md" }, validation: { permission_scope: "known_targets_only", memory_bank_scope: "changed_files_and_links_only", status: "passed" } };
138
- const reportJson = writeStageReport(root, report).json;
139
- validateSchema({ schemaName: "stage-report", file: reportJson, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: home });
140
- completeFlowRunStage(context, { projectRoot, runId: run.id, stage: "plan", status: "done", data: "stage-report.json", dataSchemaId: "dd-flow/stage-report@1", report: "stage-report.md", stageReport: "stage-report.html" });
141
- advanceFlowRun(context, { projectRoot, runId: run.id, status: "running", verdict: "planned", nextAction: "start_plan_review" });
142
- appendFlowRunTimelineEvent(context, project.id, run.id, { type: "plan_accepted", work_id: work.work_id, protocols, id: workSession.id, next_stage: "plan-review" });
143
- return { ok: true, run_id: run.id, protocols, next_action: "start_plan_review", next_command: reviewCommand, next: { kind: "start_stage", stage: "plan-review", command: reviewCommand } };
162
+ prepared.publish();
163
+ const now = context.now();
164
+ const batchChecksum = checksum(batch);
165
+ const reviewCommand = managedLifecycleCommand(context, `${flowCommand(context)} stage start ${run.id} --stage plan-review --project-root ${JSON.stringify(projectRoot)} --json`);
166
+ const startedAt = stageStartedAt(home, now);
167
+ const report = { schema_id: "dd-flow/stage-report@1", run_id: run.id, stage: "plan", generated_at: now, verdict: "done", semantic: { result: `Accepted ${protocols.length} executable PLAN artifact${protocols.length === 1 ? "" : "s"}.`, acceptance: protocols, changed_files: [...planFiles.map((file) => path.relative(projectRoot, file)), ...mapFiles.map((file) => runRef(run.id, home, file)), runRef(run.id, home, batch)], checks: ["protocol-plan schema", "aspect-map schema", "cross-artifact references", "generated CODE batch"], evidence: [runRef(run.id, home, path.join(root, "stage-report.json"))], next_action: "start_plan_review", plans: planFiles.map((file) => path.relative(projectRoot, file)), aspect_maps: mapFiles.map((file) => runRef(run.id, home, file)), code_work_batch: runRef(run.id, home, batch), batch_checksum: batchChecksum }, 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: `${flowCommand(context)} stat run sessions ls --run ${run.id} --project-root ${JSON.stringify(projectRoot)} --json`, usage_stats_command: `${flowCommand(context)} stat usage --run ${run.id} --project-root ${JSON.stringify(projectRoot)} --json`, next_command: reviewCommand }, artifacts: { json: "stage-report.json", markdown: "stage-report.md", html: "stage-report.html", summary: "stage-report.md" }, validation: { permission_scope: "known_targets_only", memory_bank_scope: "changed_files_and_links_only", status: "passed" } };
168
+ Object.assign(report.semantic, {
169
+ plan_checksums: planFiles.map((file) => ({ path: path.relative(run.workspace_root, file).split(path.sep).join("/"), sha256: checksum(file) })),
170
+ aspect_map_checksums: mapFiles.map((file) => ({ path: path.relative(home, file).split(path.sep).join("/"), sha256: checksum(file) }))
171
+ });
172
+ const preparedReport = prepareStageReport(report);
173
+ validateSchema({ schemaName: "stage-report", file: path.join(root, "stage-report.json"), data: preparedReport.normalized, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: home });
174
+ const completionInput = { projectRoot, runId: run.id, stage: "plan", 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 };
175
+ const preparedCompletion = prepareFlowRunStageCompletion(context, completionInput);
176
+ return withStageSettlement(context, () => {
177
+ const current = context.db.get("SELECT status FROM works WHERE work_id = ?", [work.work_id]);
178
+ if (current?.status !== "running")
179
+ throw new AppError("invalid_work_state", "PLAN Work changed during finish preparation", 1);
180
+ context.db.run("UPDATE works SET status = 'completed', result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", ["PLAN accepted; awaiting PLAN-REVIEW", now, now, work.work_id]);
181
+ context.db.run("UPDATE work_sessions SET status = 'completed', result_path = ?, updated_at = ?, completed_at = ? WHERE id = ?", [path.join(root, "stage-report.json"), now, now, workSession.id]);
182
+ acceptStageReport(context, { projectId: project.id, runId: run.id, stage: "plan", root, prepared: preparedReport });
183
+ completeFlowRunStage(context, completionInput, preparedCompletion);
184
+ refreshRunWorkProjection(context, project.id, run.id);
185
+ advanceFlowRun(context, { settlementStage: "plan", projectRoot, runId: run.id, status: "running", verdict: "planned", nextAction: "start_plan_review" });
186
+ appendFlowRunTimelineEvent(context, project.id, run.id, { type: "plan_accepted", work_id: work.work_id, protocols, id: workSession.id, next_stage: "plan-review" });
187
+ return { ok: true, run_id: run.id, protocols, next_action: "start_plan_review", next_command: reviewCommand, next: { kind: "start_stage", stage: "plan-review", command: reviewCommand } };
188
+ });
144
189
  }
145
190
  export function validateVnextPlanArtifacts(context, input) {
191
+ // Validation never repairs or republishes accepted artifacts. PLAN and
192
+ // PLAN-REVIEW finish explicitly publish their prepared projection on accept.
193
+ return prepareVnextPlanArtifacts(context, { ...input, publishBatch: false }).failures;
194
+ }
195
+ /** Validate in memory; publish only after the caller accepts its inputs. */
196
+ export function prepareVnextPlanArtifacts(context, input) {
146
197
  const workspaceRoot = input.workspaceRoot ?? input.projectRoot;
147
198
  const planFiles = input.protocols.map((id) => path.join(workspaceRoot, ".memory-bank", "protocol", id, "plan.json"));
148
199
  const mapFiles = input.protocols.map((id) => path.join(input.home, "03-plan", id, "aspect-map.json"));
200
+ let reviewGroupCount = 0;
149
201
  const batch = path.join(input.home, "03-plan", "code-work-batch.json");
150
202
  const ownership = protocolOwnership(input.home, input.protocols);
151
203
  const obligations = acceptedObligations(input.home);
@@ -155,14 +207,14 @@ export function validateVnextPlanArtifacts(context, input) {
155
207
  : []) : []) ?? [])
156
208
  : undefined;
157
209
  const failures = [];
210
+ const publications = new Map();
158
211
  const plans = [];
159
212
  for (const [index, file] of planFiles.entries()) {
160
213
  const protocolId = input.protocols[index];
161
214
  try {
162
- validateSchema({ schemaName: "vnext-protocol-plan", file, projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
163
- const value = readPlan(file);
215
+ const { value } = prepareJsonSchema(file, "PLAN", { schemaName: "vnext-protocol-plan", projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
164
216
  assertPlanIdentity(value, planIdentity(input.home, input.runId, protocolId, ownership.get(protocolId) ?? []), file);
165
- validatePlanSemantics(file, new Set(ownership.get(protocolId) ?? []), obligations);
217
+ validatePlanSemantics(file, value, new Set(ownership.get(protocolId) ?? []), obligations);
166
218
  validateCodeCheckCommands(workspaceRoot, value.checks.filter((check) => check.availability === "available").map((check) => check.command));
167
219
  for (const check of value.checks.filter((item) => item.availability === "available"))
168
220
  validateCheckDeclaration(workspaceRoot, check);
@@ -179,14 +231,25 @@ export function validateVnextPlanArtifacts(context, input) {
179
231
  }
180
232
  for (const file of mapFiles) {
181
233
  try {
182
- normalizeAspectMapRefs(file, workspaceRoot, input.home, input.runId);
183
- validateSchema({ schemaName: "plan-aspect-map", file, projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
184
- validateAspectMap(file, input.protocols, workspaceRoot);
234
+ const source = prepareJsonSchema(file, "PLAN aspect map", { schemaName: "plan-aspect-map", projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home }).text;
235
+ const bytes = normalizedAspectMapRefs(file, source, workspaceRoot, input.home, input.runId);
236
+ if (input.publishBatch === false && bytes !== source)
237
+ throw new AppError("validation", "Accepted aspect-map requires normalization; regenerate it in PLAN", 2, { file });
238
+ const value = JSON.parse(bytes);
239
+ validateAspectMap(file, input.protocols, workspaceRoot, value);
240
+ reviewGroupCount += Array.isArray(value.review_groups) ? value.review_groups.length : 0;
241
+ publications.set(file, bytes);
185
242
  }
186
243
  catch (error) {
187
244
  failures.push(validationFailure(file, error));
188
245
  }
189
246
  }
247
+ if (!failures.length && reviewGroupCount === 0) {
248
+ const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
249
+ const mode = requestedPlanReviewMode(context, project.id, input.runId);
250
+ if (mode === "standard" || mode === "deep")
251
+ failures.push(validationFailure(mapFiles[0] ?? batch, new AppError("validation", "Configured PLAN-REVIEW requires at least one applicable aspect and review group in the PLAN map", 2, { mode })));
252
+ }
190
253
  if (!failures.length) {
191
254
  try {
192
255
  validatePsetCheckIdentity(plans);
@@ -197,35 +260,52 @@ export function validateVnextPlanArtifacts(context, input) {
197
260
  }
198
261
  }
199
262
  if (!failures.length) {
200
- const temporaryBatch = `${batch}.tmp-${crypto.randomUUID()}`;
201
263
  try {
202
264
  const projection = projectCodeWorkBatch({ home: input.home, workspaceRoot, runId: input.runId, plans, protocols: input.protocols, ...(frozenDocumentBaselines ? { frozenDocumentBaselines } : {}) });
203
265
  validateProjectedPaths(projection, workspaceRoot, input.home, input.runId);
204
- fs.writeFileSync(temporaryBatch, `${JSON.stringify(projection, null, 2)}\n`);
205
- validateSchema({ schemaName: "code-work-batch", file: temporaryBatch, projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
206
- validateWorkBatchFile(temporaryBatch);
266
+ const bytes = `${JSON.stringify(projection, null, 2)}\n`;
267
+ validateSchema({ schemaName: "code-work-batch", file: batch, data: projection, projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
268
+ validateWorkBatch(projection);
207
269
  if (input.publishBatch !== false) {
208
- fs.renameSync(temporaryBatch, batch);
270
+ publications.set(batch, bytes);
209
271
  }
210
- else if (!fs.existsSync(batch) || checksum(temporaryBatch) !== checksum(batch)) {
272
+ else if (!fs.existsSync(batch) || crypto.createHash("sha256").update(bytes).digest("hex") !== checksum(batch)) {
211
273
  throw new AppError("stale_code_work_batch", "CODE batch no longer matches the accepted semantic PLAN", 2, { batch });
212
274
  }
213
275
  }
214
276
  catch (error) {
215
277
  failures.push(validationFailure(batch, error));
216
278
  }
217
- finally {
218
- fs.rmSync(temporaryBatch, { force: true });
219
- }
220
279
  }
221
- return failures;
280
+ return { failures, batchChecksum: publications.has(batch) ? crypto.createHash("sha256").update(publications.get(batch)).digest("hex") : null,
281
+ publish: () => {
282
+ if (failures.length)
283
+ throw new AppError("validation", "Cannot publish invalid PLAN artifacts", 2, { errors: failures });
284
+ const published = [];
285
+ try {
286
+ for (const [file, bytes] of publications) {
287
+ const temporary = `${file}.tmp-${crypto.randomUUID()}`;
288
+ try {
289
+ fs.writeFileSync(temporary, bytes);
290
+ fs.renameSync(temporary, file);
291
+ published.push(file);
292
+ }
293
+ finally {
294
+ fs.rmSync(temporary, { force: true });
295
+ }
296
+ }
297
+ }
298
+ catch (cause) {
299
+ throw new AppError("plan_publication_failed", cause instanceof Error ? cause.message : String(cause), 1, { effect: "unknown", published_files: published, business_commit: false });
300
+ }
301
+ }
302
+ };
222
303
  }
223
304
  /** CODE entry validates the same PLAN closure without changing an accepted batch. */
224
305
  export function validateVnextCodeHandoff(context, input) {
225
306
  return validateVnextPlanArtifacts(context, {
226
307
  ...input,
227
- protocols: protocolIds(input.home),
228
- publishBatch: false
308
+ protocols: protocolIds(input.home)
229
309
  });
230
310
  }
231
311
  const planTask = "Produce accepted plan.json and aspect-map.json artifacts.";
@@ -250,16 +330,18 @@ function assertProtocolWorkspace(workspaceRoot, protocols) {
250
330
  }
251
331
  }
252
332
  function read(file) { if (!fs.existsSync(file))
253
- throw new AppError("not_found", "vNext PLAN prompt is missing", 1, { file }); return fs.readFileSync(file, "utf8"); }
333
+ throw new AppError("runtime_artifact_missing", "vNext PLAN prompt is missing", 1, { file }); return fs.readFileSync(file, "utf8"); }
254
334
  function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
255
335
  function checksum(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
256
- function validateAspectMap(file, protocols, projectRoot) {
257
- let value;
258
- try {
259
- value = JSON.parse(fs.readFileSync(file, "utf8"));
260
- }
261
- catch {
262
- throw new AppError("schema_validation", "aspect-map.json must be valid JSON", 2, { file });
336
+ function validateAspectMap(file, protocols, projectRoot, prepared) {
337
+ let value = prepared;
338
+ if (value === undefined) {
339
+ try {
340
+ value = JSON.parse(fs.readFileSync(file, "utf8"));
341
+ }
342
+ catch {
343
+ throw new AppError("schema_validation", "aspect-map.json must be valid JSON", 2, { file });
344
+ }
263
345
  }
264
346
  const map = value;
265
347
  if (map.schema_id !== "dd-flow/plan-aspect-map@3" || typeof map.protocol_id !== "string" || !protocols.includes(map.protocol_id) || !Array.isArray(map.aspects))
@@ -304,7 +386,13 @@ function stageStartedAt(home, fallback) { try {
304
386
  catch {
305
387
  return fallback;
306
388
  } }
307
- function validationFailure(file, error) { return { file, message: error instanceof Error ? error.message : String(error), ...(error instanceof AppError ? { code: error.code, details: error.details } : {}) }; }
389
+ function validationFailure(file, error) {
390
+ // Aggregate diagnosed artifact mistakes only. Runtime/schema/storage failures
391
+ // must retain their original code rather than becoming a safe PLAN retry.
392
+ if (!(error instanceof AppError) || error.exitCode !== 2 || ["schema_not_found", "invalid_code_check_profile"].includes(error.code))
393
+ throw error;
394
+ return { file, message: error.message, code: error.code, details: error.details };
395
+ }
308
396
  function acceptedObligations(home) {
309
397
  const file = path.join(home, "01-specify", "specify.json");
310
398
  if (!fs.existsSync(file))
@@ -341,7 +429,7 @@ function ensurePlanSkeleton(file, protocolId, identity) {
341
429
  fs.mkdirSync(path.dirname(file), { recursive: true });
342
430
  writeJson(file, { ...identity, title: "", summary: "", goal: { outcome: "", constraints: [], non_goals: [] }, assessment: {}, decisions: [], document_updates: [], checks: [], items: [], acceptance: [] });
343
431
  }
344
- function ensureAspectMapSkeleton(file, protocolId, identity, workspaceRoot) {
432
+ function ensureAspectMapSkeleton(file, protocolId, identity, aspects) {
345
433
  if (fs.existsSync(file))
346
434
  return;
347
435
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -354,10 +442,9 @@ function ensureAspectMapSkeleton(file, protocolId, identity, workspaceRoot) {
354
442
  catalog_ref: { path: ".memory-bank/dd-flow/mb-sdlc/plan-aspects/aspects" },
355
443
  routing: { initial_state: "orchestrator_local", groups: [] },
356
444
  review_groups: [],
357
- aspects: aspectCatalog(workspaceRoot).map((aspectId) => ({ aspect_id: aspectId, planned_artifact_refs: [] }))
445
+ aspects: aspects.map((aspectId) => ({ aspect_id: aspectId, planned_artifact_refs: [] }))
358
446
  });
359
447
  }
360
- function readPlan(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
361
448
  function assertPlanIdentity(value, identity, file) {
362
449
  for (const key of ["schema_id", "plan_id", "protocol_id"])
363
450
  if (value[key] !== identity[key])
@@ -367,13 +454,17 @@ function assertPlanIdentity(value, identity, file) {
367
454
  if (JSON.stringify(value.source_refs) !== JSON.stringify(identity.source_refs))
368
455
  throw new AppError("validation", "PLAN must preserve CLI-owned source_refs", 2, { file });
369
456
  }
370
- function normalizeAspectMapRefs(file, projectRoot, runHome, runId) {
371
- const map = JSON.parse(fs.readFileSync(file, "utf8"));
457
+ function normalizedAspectMapRefs(file, bytes, projectRoot, runHome, runId) {
458
+ projectRoot = canonicalPath(projectRoot);
459
+ runHome = canonicalPath(runHome);
460
+ const map = JSON.parse(bytes);
461
+ if (!map || typeof map !== "object" || Array.isArray(map))
462
+ throw new AppError("schema_validation", "PLAN aspect map must be an object", 2, { file });
372
463
  let changed = false;
373
464
  const normalize = (value) => {
374
465
  if (!path.isAbsolute(value))
375
466
  return value;
376
- const source = path.resolve(value);
467
+ const source = canonicalPath(value, false);
377
468
  const inProject = source.startsWith(`${projectRoot}${path.sep}`);
378
469
  const inRun = source.startsWith(`${runHome}${path.sep}`);
379
470
  if (!inProject && !inRun)
@@ -386,8 +477,7 @@ function normalizeAspectMapRefs(file, projectRoot, runHome, runId) {
386
477
  for (const aspect of map.aspects ?? [])
387
478
  if (Array.isArray(aspect.planned_artifact_refs))
388
479
  aspect.planned_artifact_refs = aspect.planned_artifact_refs.map(normalize);
389
- if (changed)
390
- fs.writeFileSync(file, `${JSON.stringify(map, null, 2)}\n`);
480
+ return changed ? `${JSON.stringify(map, null, 2)}\n` : bytes;
391
481
  }
392
482
  function projectCodeWorkBatch(input) {
393
483
  const obligationMap = acceptedObligationMap(input.home);
@@ -431,7 +521,7 @@ function projectCodeWorkBatch(input) {
431
521
  provides_checks: value.checks.filter((check) => check.availability === "planned" && check.provided_by === item.id),
432
522
  stop_conditions: item.execution_context.stop_conditions,
433
523
  depends_on: item.depends_on.map((dependency) => `${protocolId}:${dependency}`),
434
- result_schema: "dd-flow/code-work-result@2"
524
+ result_schema: "dd-flow/code-work-result@3"
435
525
  });
436
526
  }));
437
527
  const byProtocol = new Map(input.plans.map((plan) => [plan.protocolId, plan.value.items]));
@@ -503,8 +593,7 @@ function resolvePortablePath(value, workspaceRoot, home, runId) {
503
593
  }
504
594
  function writeJson(file, value) { const temporary = `${file}.${crypto.randomUUID()}.tmp`; fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`); fs.renameSync(temporary, file); }
505
595
  function runRef(runId, runHome, file) { return `run://${runId}/${path.relative(runHome, file).split(path.sep).join("/")}`; }
506
- function validatePlanSemantics(file, ownedRefs, acceptedRefs) {
507
- const plan = readPlan(file);
596
+ function validatePlanSemantics(file, plan, ownedRefs, acceptedRefs) {
508
597
  const items = plan.items ?? [];
509
598
  const ids = new Set(items.map((item) => item.id).filter((id) => Boolean(id)));
510
599
  if (ids.size !== items.length)
@@ -593,6 +682,10 @@ function validatePsetCheckIdentity(plans) {
593
682
  owners.set(check.id, plan.protocolId);
594
683
  }
595
684
  }
685
+ function requestedPlanReviewMode(context, projectId, runId) {
686
+ const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
687
+ return JSON.parse(row?.index_json ?? "{}").settings?.plan_review?.mode ?? "auto";
688
+ }
596
689
  function runEndsAtMerge(context, projectRoot, runId) {
597
690
  const project = requireProjectByRoot(context, resolveProjectRoot(projectRoot));
598
691
  const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, runId]);