@deksden-com/dd-flow-cli 0.9.0-beta.10 → 0.9.0-beta.103
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 +491 -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/run-cli.js +1437 -384
- package/dist/cli.js +6 -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 +25 -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 +502 -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 +387 -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 +640 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +978 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +135 -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 +296 -0
- package/dist/harness-runtime/lib/model-observations.mjs +77 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -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/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 +57 -13
- package/dist/services/cli-operation-classifier.js +22 -24
- package/dist/services/code-checks.js +583 -99
- 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 +165 -0
- package/dist/services/dashboard.js +103 -31
- package/dist/services/engines.js +121 -76
- package/dist/services/eval-snapshots.js +952 -83
- package/dist/services/execution-policy.js +170 -0
- package/dist/services/external-work-launch.js +165 -0
- package/dist/services/harness-adapter.js +147 -24
- package/dist/services/harness-config.js +2 -0
- package/dist/services/hooks.js +596 -300
- package/dist/services/lanes.js +61 -53
- package/dist/services/lifecycle-command.js +103 -17
- package/dist/services/lifecycle-contract.js +30 -0
- package/dist/services/lifecycle-invocations.js +1128 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-processes.js +283 -27
- package/dist/services/merge-queue.js +179 -104
- package/dist/services/merge-server.js +73 -28
- package/dist/services/migrations.js +14 -9
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/plan-runtime.js +19 -8
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +18 -5
- package/dist/services/prompts.js +25 -16
- package/dist/services/protocols.js +64 -20
- package/dist/services/recovery-observation-budget.js +61 -0
- package/dist/services/recovery-snapshot-database.js +107 -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 +368 -0
- package/dist/services/run-control.js +876 -0
- package/dist/services/run-controller-adapter.js +231 -0
- package/dist/services/run-controller-capture.js +136 -0
- package/dist/services/run-controller-process.js +189 -0
- package/dist/services/run-controller-recovery.js +222 -0
- package/dist/services/run-controller-state.js +36 -0
- package/dist/services/run-controller.js +803 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +138 -0
- package/dist/services/run-observations.js +112 -0
- package/dist/services/run-recovery-runtime.js +69 -0
- package/dist/services/run-recovery.js +343 -0
- package/dist/services/runs.js +371 -74
- package/dist/services/runtime-budget.js +439 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +50 -0
- package/dist/services/runtime-scope-control.js +450 -0
- package/dist/services/runtime-scope-resume.js +565 -0
- package/dist/services/runtime-scope-stop.js +159 -0
- package/dist/services/runtime-scope-worker.js +243 -0
- package/dist/services/runtime-service.js +97 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/sessions.js +35 -69
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +44 -18
- package/dist/services/stage-lifecycle.js +99 -102
- package/dist/services/stage-pause.js +84 -55
- package/dist/services/stage-work-graph.js +35 -0
- package/dist/services/usage.js +37 -93
- package/dist/services/vnext-code-review.js +190 -80
- package/dist/services/vnext-code.js +283 -248
- package/dist/services/vnext-execution-profile.js +5 -3
- package/dist/services/vnext-fanout.js +172 -17
- package/dist/services/vnext-merge.js +296 -105
- package/dist/services/vnext-plan-review.js +141 -94
- package/dist/services/vnext-plan.js +142 -69
- package/dist/services/vnext-protocolize.js +132 -57
- package/dist/services/vnext-specify.js +95 -65
- package/dist/services/work-registry.js +891 -162
- 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 +459 -32
- package/dist/storage/paths.js +17 -4
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +77 -0
- package/dist/storage/writer-migration.js +102 -0
- package/package.json +24 -13
- package/tools/repair-paused-run-status.mjs +59 -0
|
@@ -1,13 +1,16 @@
|
|
|
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 } 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,
|
|
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";
|
|
@@ -15,44 +18,63 @@ import { readVnextSpecifyResult } from "./vnext-specify.js";
|
|
|
15
18
|
import { nextWorkId } from "./ids.js";
|
|
16
19
|
import { vnextStageDirectory } from "../domain/stage-catalog.js";
|
|
17
20
|
import { writeStageReport } from "./stage-report-renderer.js";
|
|
18
|
-
import { applyExternalStageContext } from "./stage-context.js";
|
|
21
|
+
import { applyExternalStageContext, prepareExternalStageContext } from "./stage-context.js";
|
|
19
22
|
import { subagentCapacityKey } from "./vnext-fanout.js";
|
|
20
23
|
export function isVnextPlanRun(context, input) {
|
|
21
24
|
const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
|
|
22
25
|
return Boolean(context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ? AND flow_kind = 'vnext_protocolize'", [project.id, input.runId]));
|
|
23
26
|
}
|
|
24
|
-
export function
|
|
25
|
-
ensureWorkRegistry(context);
|
|
27
|
+
export function prepareVnextPlanStart(context, input) {
|
|
26
28
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
27
29
|
const project = requireProjectByRoot(context, projectRoot);
|
|
28
30
|
const run = requireRun(context, projectRoot, input.runId);
|
|
29
31
|
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
32
|
const workspaceRoute = requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
|
|
32
33
|
const protocols = protocolIds(home);
|
|
33
34
|
if (!protocols.length)
|
|
34
|
-
throw new AppError("
|
|
35
|
+
throw new AppError("runtime_artifact_missing", "PLAN requires accepted PROTOCOLIZE protocols", 1);
|
|
35
36
|
// Static inputs are checked before PLAN creates a Work or materializes a
|
|
36
|
-
// draft.
|
|
37
|
+
// draft. Retained corruption is still an infrastructure failure, not a typo.
|
|
37
38
|
const template = read(path.join(projectRoot, ".memory-bank", "dd-flow", "vnext", "plan.md"));
|
|
38
39
|
assertProtocolWorkspace(run.workspace_root, protocols);
|
|
39
40
|
const { profile: codeCheckProfile } = readCodeCheckProfile(run.workspace_root);
|
|
40
41
|
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
42
|
throw new AppError("invalid_work_state", "PLAN already has a running Work", 1, { run_id: run.id });
|
|
43
|
+
prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage: "plan", dir: "03-plan", status: "running", dataSchemaId: "dd-flow/protocol-plan@6" });
|
|
42
44
|
const root = path.join(home, vnextStageDirectory("plan"));
|
|
43
|
-
|
|
44
|
-
|
|
45
|
+
if (input.externalContext)
|
|
46
|
+
prepareExternalStageContext({ stageRoot: root, loaded: input.externalContext });
|
|
45
47
|
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
48
|
if (!rootWork)
|
|
47
49
|
throw new AppError("runtime_missing", "vNext RUN has no root Work", 1);
|
|
50
|
+
const planPaths = protocols.map(id => path.join(run.workspace_root, ".memory-bank", "protocol", id, "plan.json"));
|
|
51
|
+
const mapPaths = protocols.map(id => path.join(root, id, "aspect-map.json"));
|
|
52
|
+
const owned = protocolOwnership(home, protocols);
|
|
53
|
+
const identities = protocols.map(protocolId => planIdentity(home, run.id, protocolId, owned.get(protocolId) ?? []));
|
|
54
|
+
const aspects = aspectCatalog(run.workspace_root);
|
|
55
|
+
const runVariables = getFlowRunVariables(context, { projectRoot, runId: run.id });
|
|
56
|
+
const mergeRequired = runEndsAtMerge(context, projectRoot, run.id);
|
|
57
|
+
const git = gitFacts(run.workspace_root);
|
|
58
|
+
for (const file of [...planPaths, ...mapPaths, ...["stage-prompt.md", "work-context.json", "fixture-root.prompt.md"].map(name => path.join(root, name))])
|
|
59
|
+
prepareOutputFile(file);
|
|
60
|
+
return { projectRoot, project, run, home, root, rootWork, workspaceRoute, protocols, template, codeCheckProfile, planPaths, mapPaths, owned, identities, aspects, runVariables, mergeRequired, git };
|
|
61
|
+
}
|
|
62
|
+
export function startVnextPlan(context, input, prepared = prepareVnextPlanStart(context, input)) {
|
|
63
|
+
const { projectRoot, project, run, root, rootWork, workspaceRoute, protocols, template, codeCheckProfile, planPaths, mapPaths, owned, identities, aspects, runVariables, mergeRequired, git, home } = prepared;
|
|
64
|
+
ensureWorkRegistry(context);
|
|
65
|
+
assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage: "plan", projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
66
|
+
fs.mkdirSync(root, { recursive: true });
|
|
67
|
+
const now = context.now();
|
|
48
68
|
// Imported stage fixtures have a synthetic running root with no prior agent.
|
|
49
69
|
// Bind it on the first real stage start so its child PLAN Work has a real parent.
|
|
50
70
|
if (!context.db.get("SELECT 1 FROM work_sessions WHERE work_id = ? LIMIT 1", [rootWork.work_id])) {
|
|
51
71
|
bindRunningWorkSession(context, { workId: rootWork.work_id, hookEventId: input.hookEventId, promptPath: path.join(root, "fixture-root.prompt.md") });
|
|
52
72
|
}
|
|
53
|
-
context.db.
|
|
73
|
+
context.db.beginWriteTransaction();
|
|
54
74
|
let planWorkId;
|
|
55
75
|
try {
|
|
76
|
+
if (context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND task = ? AND status = 'running'", [project.id, run.id, planTask]))
|
|
77
|
+
throw new AppError("invalid_work_state", "PLAN already has a running Work", 1, { run_id: run.id });
|
|
56
78
|
planWorkId = nextWorkId(context, project.id, "plan");
|
|
57
79
|
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
80
|
context.db.exec("COMMIT");
|
|
@@ -64,37 +86,33 @@ export function startVnextPlan(context, input) {
|
|
|
64
86
|
// A Desktop task may start above the materialized repository. Lifecycle
|
|
65
87
|
// prompts therefore hand agents write targets as absolute paths: relative
|
|
66
88
|
// `.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
89
|
planPaths.forEach((file, index) => ensurePlanSkeleton(file, protocols[index], identities[index]));
|
|
72
|
-
mapPaths.forEach((file, index) => ensureAspectMapSkeleton(file, protocols[index], identities[index],
|
|
73
|
-
const finishCommand = `${flowCommand(context)} stage finish ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json
|
|
90
|
+
mapPaths.forEach((file, index) => ensureAspectMapSkeleton(file, protocols[index], identities[index], aspects));
|
|
91
|
+
const finishCommand = managedLifecycleCommand(context, `${flowCommand(context)} stage finish ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json`);
|
|
74
92
|
const pauseCommand = stagePauseCommand(context, { runId: run.id, stage: "plan", workId: planWorkId, projectRoot });
|
|
75
93
|
const pauseCommandTemplate = stagePauseCommandTemplate(pauseCommand);
|
|
76
94
|
const validationCommands = protocols.flatMap((_, index) => [
|
|
77
95
|
`${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
96
|
`${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
97
|
]);
|
|
80
|
-
const runVariables = getFlowRunVariables(context, { projectRoot, runId: run.id });
|
|
81
98
|
const measuredCapacity = runVariables.variables[subagentCapacityKey];
|
|
82
|
-
const mergeRequired = runEndsAtMerge(context, projectRoot, run.id);
|
|
83
99
|
const capacityContext = typeof measuredCapacity === "number" && Number.isInteger(measuredCapacity) && measuredCapacity >= 0
|
|
84
100
|
? `- 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
101
|
: "- Reviewer capacity is not qualified yet. PLAN must not qualify or launch reviewers; an external harness controller supplies it before fan-out.";
|
|
86
102
|
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
103
|
const policyMergeAliases = codeCheckProfile?.mandatory_by_gate.merge ?? [];
|
|
89
104
|
const mergeContract = mergeRequired
|
|
90
105
|
? ["<merge_gate_contract>", ...(policyMergeAliases.length
|
|
91
106
|
? [`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
107
|
: ["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
108
|
: [];
|
|
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(
|
|
109
|
+
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
110
|
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
111
|
const promptPath = path.join(root, "stage-prompt.md");
|
|
97
|
-
|
|
112
|
+
// This explicit final rule supersedes historical pack wording: a flow gate
|
|
113
|
+
// has only executable autonomous evidence. Human or external confirmation
|
|
114
|
+
// is neither a check nor a permitted completion condition.
|
|
115
|
+
fs.writeFileSync(promptPath, `${prompt}\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`);
|
|
98
116
|
const externalContext = applyExternalStageContext({ stageRoot: root, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
|
|
99
117
|
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
118
|
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 +123,21 @@ export function startVnextPlan(context, input) {
|
|
|
105
123
|
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "work_session_started", stage: "plan", work_id: planWorkId, id: workSessionId, session_id: sessionId });
|
|
106
124
|
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
125
|
}
|
|
126
|
+
export function prepareVnextPlanFinish(context, input) {
|
|
127
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
128
|
+
const run = requireRun(context, projectRoot, input.runId), home = requireHome(run);
|
|
129
|
+
requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
|
|
130
|
+
const protocols = protocolIds(home);
|
|
131
|
+
assertProtocolWorkspace(run.workspace_root, protocols);
|
|
132
|
+
const prepared = prepareVnextPlanArtifacts(context, { projectRoot, workspaceRoot: run.workspace_root, runId: run.id, home, protocols });
|
|
133
|
+
if (prepared.failures.length)
|
|
134
|
+
throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: prepared.failures });
|
|
135
|
+
return prepared;
|
|
136
|
+
}
|
|
108
137
|
export function finishVnextPlan(context, input) {
|
|
138
|
+
return withStageSettlement(context, () => finishVnextPlanOwned(context, input));
|
|
139
|
+
}
|
|
140
|
+
function finishVnextPlanOwned(context, input) {
|
|
109
141
|
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
110
142
|
const project = requireProjectByRoot(context, projectRoot);
|
|
111
143
|
const run = requireRun(context, projectRoot, input.runId);
|
|
@@ -114,35 +146,46 @@ export function finishVnextPlan(context, input) {
|
|
|
114
146
|
requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: home, workspaceRoot: run.workspace_root, stage: "plan" });
|
|
115
147
|
const protocols = protocolIds(home);
|
|
116
148
|
if (!protocols.length)
|
|
117
|
-
throw new AppError("
|
|
149
|
+
throw new AppError("runtime_artifact_missing", "PLAN requires accepted PROTOCOLIZE protocols", 1);
|
|
118
150
|
assertProtocolWorkspace(run.workspace_root, protocols);
|
|
119
151
|
const planFiles = protocols.map((id) => path.join(run.workspace_root, ".memory-bank", "protocol", id, "plan.json"));
|
|
120
152
|
const mapFiles = protocols.map((id) => path.join(root, id, "aspect-map.json"));
|
|
121
153
|
const batch = path.join(root, "code-work-batch.json");
|
|
122
|
-
const
|
|
123
|
-
if (failures.length)
|
|
124
|
-
throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: failures });
|
|
154
|
+
const prepared = input.prepared ?? prepareVnextPlanFinish(context, input);
|
|
155
|
+
if (prepared.failures.length)
|
|
156
|
+
throw new AppError("validation", "PLAN artifacts have validation errors", 2, { errors: prepared.failures });
|
|
125
157
|
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
158
|
if (!work)
|
|
127
159
|
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
160
|
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
161
|
if (!workSession?.session_id)
|
|
133
162
|
throw new AppError("trusted_session_binding_required", "PLAN finish requires its bound Agent WorkSession", 1, { work_id: work.work_id });
|
|
163
|
+
prepared.publish();
|
|
164
|
+
const now = context.now();
|
|
165
|
+
const batchChecksum = checksum(batch);
|
|
166
|
+
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]);
|
|
134
167
|
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
168
|
refreshRunWorkProjection(context, project.id, run.id);
|
|
136
|
-
const reviewCommand = `${flowCommand(context)} stage start ${run.id} --stage plan-review --project-root ${JSON.stringify(projectRoot)} --json
|
|
169
|
+
const reviewCommand = managedLifecycleCommand(context, `${flowCommand(context)} stage start ${run.id} --stage plan-review --project-root ${JSON.stringify(projectRoot)} --json`);
|
|
137
170
|
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" } };
|
|
171
|
+
Object.assign(report.semantic, {
|
|
172
|
+
plan_checksums: planFiles.map((file) => ({ path: path.relative(run.workspace_root, file).split(path.sep).join("/"), sha256: checksum(file) })),
|
|
173
|
+
aspect_map_checksums: mapFiles.map((file) => ({ path: path.relative(home, file).split(path.sep).join("/"), sha256: checksum(file) }))
|
|
174
|
+
});
|
|
138
175
|
const reportJson = writeStageReport(root, report).json;
|
|
139
176
|
validateSchema({ schemaName: "stage-report", file: reportJson, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: home });
|
|
140
177
|
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" });
|
|
178
|
+
advanceFlowRun(context, { settlementStage: "plan", projectRoot, runId: run.id, status: "running", verdict: "planned", nextAction: "start_plan_review" });
|
|
142
179
|
appendFlowRunTimelineEvent(context, project.id, run.id, { type: "plan_accepted", work_id: work.work_id, protocols, id: workSession.id, next_stage: "plan-review" });
|
|
143
180
|
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 } };
|
|
144
181
|
}
|
|
145
182
|
export function validateVnextPlanArtifacts(context, input) {
|
|
183
|
+
// Validation never repairs or republishes accepted artifacts. PLAN and
|
|
184
|
+
// PLAN-REVIEW finish explicitly publish their prepared projection on accept.
|
|
185
|
+
return prepareVnextPlanArtifacts(context, { ...input, publishBatch: false }).failures;
|
|
186
|
+
}
|
|
187
|
+
/** Validate in memory; publish only after the caller accepts its inputs. */
|
|
188
|
+
export function prepareVnextPlanArtifacts(context, input) {
|
|
146
189
|
const workspaceRoot = input.workspaceRoot ?? input.projectRoot;
|
|
147
190
|
const planFiles = input.protocols.map((id) => path.join(workspaceRoot, ".memory-bank", "protocol", id, "plan.json"));
|
|
148
191
|
const mapFiles = input.protocols.map((id) => path.join(input.home, "03-plan", id, "aspect-map.json"));
|
|
@@ -155,14 +198,14 @@ export function validateVnextPlanArtifacts(context, input) {
|
|
|
155
198
|
: []) : []) ?? [])
|
|
156
199
|
: undefined;
|
|
157
200
|
const failures = [];
|
|
201
|
+
const publications = new Map();
|
|
158
202
|
const plans = [];
|
|
159
203
|
for (const [index, file] of planFiles.entries()) {
|
|
160
204
|
const protocolId = input.protocols[index];
|
|
161
205
|
try {
|
|
162
|
-
|
|
163
|
-
const value = readPlan(file);
|
|
206
|
+
const { value } = prepareJsonSchema(file, "PLAN", { schemaName: "vnext-protocol-plan", projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
|
|
164
207
|
assertPlanIdentity(value, planIdentity(input.home, input.runId, protocolId, ownership.get(protocolId) ?? []), file);
|
|
165
|
-
validatePlanSemantics(file, new Set(ownership.get(protocolId) ?? []), obligations);
|
|
208
|
+
validatePlanSemantics(file, value, new Set(ownership.get(protocolId) ?? []), obligations);
|
|
166
209
|
validateCodeCheckCommands(workspaceRoot, value.checks.filter((check) => check.availability === "available").map((check) => check.command));
|
|
167
210
|
for (const check of value.checks.filter((item) => item.availability === "available"))
|
|
168
211
|
validateCheckDeclaration(workspaceRoot, check);
|
|
@@ -179,9 +222,13 @@ export function validateVnextPlanArtifacts(context, input) {
|
|
|
179
222
|
}
|
|
180
223
|
for (const file of mapFiles) {
|
|
181
224
|
try {
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
225
|
+
const source = prepareJsonSchema(file, "PLAN aspect map", { schemaName: "plan-aspect-map", projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home }).text;
|
|
226
|
+
const bytes = normalizedAspectMapRefs(file, source, workspaceRoot, input.home, input.runId);
|
|
227
|
+
if (input.publishBatch === false && bytes !== source)
|
|
228
|
+
throw new AppError("validation", "Accepted aspect-map requires normalization; regenerate it in PLAN", 2, { file });
|
|
229
|
+
const value = JSON.parse(bytes);
|
|
230
|
+
validateAspectMap(file, input.protocols, workspaceRoot, value);
|
|
231
|
+
publications.set(file, bytes);
|
|
185
232
|
}
|
|
186
233
|
catch (error) {
|
|
187
234
|
failures.push(validationFailure(file, error));
|
|
@@ -197,35 +244,52 @@ export function validateVnextPlanArtifacts(context, input) {
|
|
|
197
244
|
}
|
|
198
245
|
}
|
|
199
246
|
if (!failures.length) {
|
|
200
|
-
const temporaryBatch = `${batch}.tmp-${crypto.randomUUID()}`;
|
|
201
247
|
try {
|
|
202
248
|
const projection = projectCodeWorkBatch({ home: input.home, workspaceRoot, runId: input.runId, plans, protocols: input.protocols, ...(frozenDocumentBaselines ? { frozenDocumentBaselines } : {}) });
|
|
203
249
|
validateProjectedPaths(projection, workspaceRoot, input.home, input.runId);
|
|
204
|
-
|
|
205
|
-
validateSchema({ schemaName: "code-work-batch", file:
|
|
206
|
-
|
|
250
|
+
const bytes = `${JSON.stringify(projection, null, 2)}\n`;
|
|
251
|
+
validateSchema({ schemaName: "code-work-batch", file: batch, data: projection, projectRoot: workspaceRoot, ddFlowHome: context.ddFlowHome, runId: input.runId, runRoot: input.home });
|
|
252
|
+
validateWorkBatch(projection);
|
|
207
253
|
if (input.publishBatch !== false) {
|
|
208
|
-
|
|
254
|
+
publications.set(batch, bytes);
|
|
209
255
|
}
|
|
210
|
-
else if (!fs.existsSync(batch) ||
|
|
256
|
+
else if (!fs.existsSync(batch) || crypto.createHash("sha256").update(bytes).digest("hex") !== checksum(batch)) {
|
|
211
257
|
throw new AppError("stale_code_work_batch", "CODE batch no longer matches the accepted semantic PLAN", 2, { batch });
|
|
212
258
|
}
|
|
213
259
|
}
|
|
214
260
|
catch (error) {
|
|
215
261
|
failures.push(validationFailure(batch, error));
|
|
216
262
|
}
|
|
217
|
-
finally {
|
|
218
|
-
fs.rmSync(temporaryBatch, { force: true });
|
|
219
|
-
}
|
|
220
263
|
}
|
|
221
|
-
return failures
|
|
264
|
+
return { failures, batchChecksum: publications.has(batch) ? crypto.createHash("sha256").update(publications.get(batch)).digest("hex") : null,
|
|
265
|
+
publish: () => {
|
|
266
|
+
if (failures.length)
|
|
267
|
+
throw new AppError("validation", "Cannot publish invalid PLAN artifacts", 2, { errors: failures });
|
|
268
|
+
const published = [];
|
|
269
|
+
try {
|
|
270
|
+
for (const [file, bytes] of publications) {
|
|
271
|
+
const temporary = `${file}.tmp-${crypto.randomUUID()}`;
|
|
272
|
+
try {
|
|
273
|
+
fs.writeFileSync(temporary, bytes);
|
|
274
|
+
fs.renameSync(temporary, file);
|
|
275
|
+
published.push(file);
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
fs.rmSync(temporary, { force: true });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
catch (cause) {
|
|
283
|
+
throw new AppError("plan_publication_failed", cause instanceof Error ? cause.message : String(cause), 1, { effect: "unknown", published_files: published, business_commit: false });
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
};
|
|
222
287
|
}
|
|
223
288
|
/** CODE entry validates the same PLAN closure without changing an accepted batch. */
|
|
224
289
|
export function validateVnextCodeHandoff(context, input) {
|
|
225
290
|
return validateVnextPlanArtifacts(context, {
|
|
226
291
|
...input,
|
|
227
|
-
protocols: protocolIds(input.home)
|
|
228
|
-
publishBatch: false
|
|
292
|
+
protocols: protocolIds(input.home)
|
|
229
293
|
});
|
|
230
294
|
}
|
|
231
295
|
const planTask = "Produce accepted plan.json and aspect-map.json artifacts.";
|
|
@@ -250,16 +314,18 @@ function assertProtocolWorkspace(workspaceRoot, protocols) {
|
|
|
250
314
|
}
|
|
251
315
|
}
|
|
252
316
|
function read(file) { if (!fs.existsSync(file))
|
|
253
|
-
throw new AppError("
|
|
317
|
+
throw new AppError("runtime_artifact_missing", "vNext PLAN prompt is missing", 1, { file }); return fs.readFileSync(file, "utf8"); }
|
|
254
318
|
function readJson(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
|
255
319
|
function checksum(file) { return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex"); }
|
|
256
|
-
function validateAspectMap(file, protocols, projectRoot) {
|
|
257
|
-
let value;
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
320
|
+
function validateAspectMap(file, protocols, projectRoot, prepared) {
|
|
321
|
+
let value = prepared;
|
|
322
|
+
if (value === undefined) {
|
|
323
|
+
try {
|
|
324
|
+
value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
throw new AppError("schema_validation", "aspect-map.json must be valid JSON", 2, { file });
|
|
328
|
+
}
|
|
263
329
|
}
|
|
264
330
|
const map = value;
|
|
265
331
|
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 +370,13 @@ function stageStartedAt(home, fallback) { try {
|
|
|
304
370
|
catch {
|
|
305
371
|
return fallback;
|
|
306
372
|
} }
|
|
307
|
-
function validationFailure(file, error) {
|
|
373
|
+
function validationFailure(file, error) {
|
|
374
|
+
// Aggregate diagnosed artifact mistakes only. Runtime/schema/storage failures
|
|
375
|
+
// must retain their original code rather than becoming a safe PLAN retry.
|
|
376
|
+
if (!(error instanceof AppError) || error.exitCode !== 2 || ["schema_not_found", "invalid_code_check_profile"].includes(error.code))
|
|
377
|
+
throw error;
|
|
378
|
+
return { file, message: error.message, code: error.code, details: error.details };
|
|
379
|
+
}
|
|
308
380
|
function acceptedObligations(home) {
|
|
309
381
|
const file = path.join(home, "01-specify", "specify.json");
|
|
310
382
|
if (!fs.existsSync(file))
|
|
@@ -341,7 +413,7 @@ function ensurePlanSkeleton(file, protocolId, identity) {
|
|
|
341
413
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
342
414
|
writeJson(file, { ...identity, title: "", summary: "", goal: { outcome: "", constraints: [], non_goals: [] }, assessment: {}, decisions: [], document_updates: [], checks: [], items: [], acceptance: [] });
|
|
343
415
|
}
|
|
344
|
-
function ensureAspectMapSkeleton(file, protocolId, identity,
|
|
416
|
+
function ensureAspectMapSkeleton(file, protocolId, identity, aspects) {
|
|
345
417
|
if (fs.existsSync(file))
|
|
346
418
|
return;
|
|
347
419
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
@@ -354,10 +426,9 @@ function ensureAspectMapSkeleton(file, protocolId, identity, workspaceRoot) {
|
|
|
354
426
|
catalog_ref: { path: ".memory-bank/dd-flow/mb-sdlc/plan-aspects/aspects" },
|
|
355
427
|
routing: { initial_state: "orchestrator_local", groups: [] },
|
|
356
428
|
review_groups: [],
|
|
357
|
-
aspects:
|
|
429
|
+
aspects: aspects.map((aspectId) => ({ aspect_id: aspectId, planned_artifact_refs: [] }))
|
|
358
430
|
});
|
|
359
431
|
}
|
|
360
|
-
function readPlan(file) { return JSON.parse(fs.readFileSync(file, "utf8")); }
|
|
361
432
|
function assertPlanIdentity(value, identity, file) {
|
|
362
433
|
for (const key of ["schema_id", "plan_id", "protocol_id"])
|
|
363
434
|
if (value[key] !== identity[key])
|
|
@@ -367,13 +438,17 @@ function assertPlanIdentity(value, identity, file) {
|
|
|
367
438
|
if (JSON.stringify(value.source_refs) !== JSON.stringify(identity.source_refs))
|
|
368
439
|
throw new AppError("validation", "PLAN must preserve CLI-owned source_refs", 2, { file });
|
|
369
440
|
}
|
|
370
|
-
function
|
|
371
|
-
|
|
441
|
+
function normalizedAspectMapRefs(file, bytes, projectRoot, runHome, runId) {
|
|
442
|
+
projectRoot = canonicalPath(projectRoot);
|
|
443
|
+
runHome = canonicalPath(runHome);
|
|
444
|
+
const map = JSON.parse(bytes);
|
|
445
|
+
if (!map || typeof map !== "object" || Array.isArray(map))
|
|
446
|
+
throw new AppError("schema_validation", "PLAN aspect map must be an object", 2, { file });
|
|
372
447
|
let changed = false;
|
|
373
448
|
const normalize = (value) => {
|
|
374
449
|
if (!path.isAbsolute(value))
|
|
375
450
|
return value;
|
|
376
|
-
const source =
|
|
451
|
+
const source = canonicalPath(value, false);
|
|
377
452
|
const inProject = source.startsWith(`${projectRoot}${path.sep}`);
|
|
378
453
|
const inRun = source.startsWith(`${runHome}${path.sep}`);
|
|
379
454
|
if (!inProject && !inRun)
|
|
@@ -386,8 +461,7 @@ function normalizeAspectMapRefs(file, projectRoot, runHome, runId) {
|
|
|
386
461
|
for (const aspect of map.aspects ?? [])
|
|
387
462
|
if (Array.isArray(aspect.planned_artifact_refs))
|
|
388
463
|
aspect.planned_artifact_refs = aspect.planned_artifact_refs.map(normalize);
|
|
389
|
-
|
|
390
|
-
fs.writeFileSync(file, `${JSON.stringify(map, null, 2)}\n`);
|
|
464
|
+
return changed ? `${JSON.stringify(map, null, 2)}\n` : bytes;
|
|
391
465
|
}
|
|
392
466
|
function projectCodeWorkBatch(input) {
|
|
393
467
|
const obligationMap = acceptedObligationMap(input.home);
|
|
@@ -431,7 +505,7 @@ function projectCodeWorkBatch(input) {
|
|
|
431
505
|
provides_checks: value.checks.filter((check) => check.availability === "planned" && check.provided_by === item.id),
|
|
432
506
|
stop_conditions: item.execution_context.stop_conditions,
|
|
433
507
|
depends_on: item.depends_on.map((dependency) => `${protocolId}:${dependency}`),
|
|
434
|
-
result_schema: "dd-flow/code-work-result@
|
|
508
|
+
result_schema: "dd-flow/code-work-result@3"
|
|
435
509
|
});
|
|
436
510
|
}));
|
|
437
511
|
const byProtocol = new Map(input.plans.map((plan) => [plan.protocolId, plan.value.items]));
|
|
@@ -503,8 +577,7 @@ function resolvePortablePath(value, workspaceRoot, home, runId) {
|
|
|
503
577
|
}
|
|
504
578
|
function writeJson(file, value) { const temporary = `${file}.${crypto.randomUUID()}.tmp`; fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`); fs.renameSync(temporary, file); }
|
|
505
579
|
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);
|
|
580
|
+
function validatePlanSemantics(file, plan, ownedRefs, acceptedRefs) {
|
|
508
581
|
const items = plan.items ?? [];
|
|
509
582
|
const ids = new Set(items.map((item) => item.id).filter((id) => Boolean(id)));
|
|
510
583
|
if (ids.size !== items.length)
|