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

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 +520 -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 +388 -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,36 +1,49 @@
1
+ import { managedLifecycleCommand } from "./lifecycle-invocations.js";
1
2
  import crypto from "node:crypto";
2
3
  import fs from "node:fs";
4
+ import os from "node:os";
3
5
  import path from "node:path";
4
6
  import { AppError } from "../shared/errors.js";
5
7
  import { projectFeatureWorktreePath, resolveProjectRoot } from "../storage/paths.js";
6
8
  import { previewNextEntityId } from "./ids.js";
7
9
  import { registerProtocol } from "./protocols.js";
8
10
  import { requireProjectByRoot } from "./projects.js";
9
- import { advanceFlowRun, appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRunStage, gitFacts, rebindFlowRunWorkspace } from "./runs.js";
11
+ import { advanceFlowRun, appendFlowRunTimelineEvent, attachFlowRunStage, completeFlowRunStage, prepareFlowRunStageAttachment, prepareFlowRunStageCompletion, withStageSettlement, gitFacts, rebindFlowRunWorkspace } from "./runs.js";
12
+ import { resolveStageTransition, stageExecutionCwd } from "./execution-policy.js";
10
13
  import { validateSchema } from "./schema-validation.js";
11
14
  import { assertStageStartHookEvent, hookSessionIdentity } from "./hooks.js";
12
15
  import { bindStageCoordinatorWork, refreshRunWorkProjection } from "./work-registry.js";
13
16
  import { runTargetedMemoryBankLint } from "./stage-lifecycle.js";
14
- import { bootstrapManagedWorktree, createManagedWorktree, recordManagedWorktree } from "./worktrees.js";
17
+ import { bootstrapManagedWorktree, createManagedWorktree, prepareManagedWorktree, prepareManagedWorktreeBootstrapSources, recordManagedWorktree } from "./worktrees.js";
15
18
  import { loadVnextWorkspacePolicy, requireVnextWorkspaceRoute, vnextRunBranch } from "./vnext-workspace-policy.js";
16
19
  import { readVnextSpecifyResult } from "./vnext-specify.js";
17
20
  import { flowCommand, stagePauseCommand, stagePauseCommandTemplate } from "./stage-pause.js";
18
- import { writeStageReport } from "./stage-report-renderer.js";
19
- import { applyExternalStageContext } from "./stage-context.js";
21
+ import { acceptStageReport, prepareStageReport, publishStageReport } from "./stage-report-renderer.js";
22
+ import { applyExternalStageContext, prepareExternalStageContext } from "./stage-context.js";
23
+ import { prepareJsonSchema, prepareOutputFile } from "../cli/input-preparation.js";
24
+ import { stageLifecycleInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
25
+ import { withProjectionLock } from "../storage/projection-lock.js";
20
26
  const stage = "protocolize";
21
- function stageSessionMode(context, run) {
27
+ function stageSessionMode(context, run, projectRoot, targetWorkspaceRoot) {
22
28
  const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [run.project_id, run.id]);
23
29
  const value = row ? JSON.parse(row.index_json) : null;
24
- const mode = value?.execution_profile?.settings?.stage_session_mode;
30
+ const profile = value?.execution_profile;
31
+ const mode = profile?.settings.stage_session_mode;
25
32
  if (mode !== "same_session" && mode !== "new_session")
26
33
  throw new AppError("execution_profile_invalid", "RUN is missing its frozen stage session mode", 1, { run_id: run.id });
27
- return mode;
34
+ if (profile?.settings.execution) {
35
+ if (!profile.agent_profiles)
36
+ throw new AppError("execution_profile_not_frozen", "Stage handoff requires frozen RUN profiles", 1);
37
+ return resolveStageTransition({ ddFlowHome: context.ddFlowHome, policy: profile.settings.execution, profiles: profile.agent_profiles, projectRoot, workspaceRoot: targetWorkspaceRoot, fromStage: "protocolize", stage: "plan", stageSessionMode: mode, mergeMode: profile.settings.merge_mode }).session_mode;
38
+ }
39
+ return stageExecutionCwd({ stage: "protocolize", projectRoot, workspaceRoot: targetWorkspaceRoot })
40
+ === stageExecutionCwd({ stage: "plan", projectRoot, workspaceRoot: targetWorkspaceRoot }) ? mode : "new_session";
28
41
  }
29
42
  export function isVnextProtocolizeRun(context, input) {
30
43
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
31
44
  return Boolean(context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ? AND flow_kind = 'vnext_protocolize'", [project.id, input.runId]));
32
45
  }
33
- export function prepareVnextProtocolize(context, input) {
46
+ export function prepareVnextProtocolizeArtifacts(context, input) {
34
47
  const projectRoot = resolveProjectRoot(input.projectRoot);
35
48
  const project = requireProjectByRoot(context, projectRoot);
36
49
  const run = requireRun(context, projectRoot, input.runId);
@@ -42,45 +55,52 @@ export function prepareVnextProtocolize(context, input) {
42
55
  const specifyPath = path.join(runHome, "01-specify", "specify.json");
43
56
  const specifyMarkdownPath = path.join(runHome, "01-specify", "specify.md");
44
57
  const obligations = acceptedSpecifyObligations(context, projectRoot, run.id, specifyPath);
45
- fs.mkdirSync(stageRoot, { recursive: true });
46
58
  const resultPath = path.join(stageRoot, "protocolize-result.json");
47
59
  const promptPath = path.join(stageRoot, "prompt.md");
48
- const policy = provisionWorkspaceForProtocolize(context, projectRoot, project.id, run, stageRoot);
60
+ const templatePath = path.join(projectRoot, ".memory-bank", "dd-flow", "vnext", "protocolize.md");
61
+ if (!fs.existsSync(templatePath))
62
+ throw new AppError("runtime_artifact_missing", "vNext PROTOCOLIZE prompt template is missing", 1, { path: templatePath });
63
+ const template = fs.readFileSync(templatePath, "utf8");
64
+ const projectCatalog = catalog(projectRoot);
65
+ if (!["same_session", "new_session"].includes(input.handoff?.stage_handoff?.effective))
66
+ throw new AppError("runtime_context_invalid", "PROTOCOLIZE requires a frozen handoff policy", 1);
67
+ for (const file of [promptPath, path.join(stageRoot, "work-context.json"), ...(!fs.existsSync(resultPath) ? [resultPath] : [])])
68
+ prepareOutputFile(file);
69
+ const workspace = prepareWorkspaceForProtocolize(context, projectRoot, project.id, run, stageRoot);
70
+ return { projectRoot, project, run, work, stageRoot, specifyPath, specifyMarkdownPath, obligations, resultPath, promptPath, template, projectCatalog, workspace };
71
+ }
72
+ /** Materialize the next-stage packet; this is execution, not read-only CLI preparation. */
73
+ export function prepareVnextProtocolize(context, input, prepared = prepareVnextProtocolizeArtifacts(context, input)) {
74
+ const { projectRoot, project, run, work, stageRoot, specifyPath, specifyMarkdownPath, obligations, resultPath, promptPath, template, projectCatalog } = prepared;
75
+ fs.mkdirSync(stageRoot, { recursive: true });
76
+ const policy = provisionWorkspaceForProtocolize(context, projectRoot, run, prepared.workspace);
49
77
  const routedRun = requireRun(context, projectRoot, run.id);
50
- writeJson(path.join(stageRoot, "work-context.json"), { schema_id: "dd-flow/vnext-protocolize-context@2", system: { run_id: run.id, work_id: work.work_id, stage, handoff: input.handoff }, input: { accepted_specify_json: specifyPath, accepted_specify_markdown: specifyMarkdownPath }, catalog: catalog(projectRoot), workspace: { project_root: projectRoot, workspace_root: routedRun.workspace_root, stage_root: stageRoot, git_policy: policy } });
78
+ writeJson(path.join(stageRoot, "work-context.json"), { schema_id: "dd-flow/vnext-protocolize-context@2", system: { run_id: run.id, work_id: work.work_id, stage, handoff: input.handoff }, input: { accepted_specify_json: specifyPath, accepted_specify_markdown: specifyMarkdownPath }, catalog: projectCatalog, workspace: { project_root: projectRoot, workspace_root: routedRun.workspace_root, stage_root: stageRoot, git_policy: policy } });
51
79
  if (!fs.existsSync(resultPath))
52
80
  writeJson(resultPath, resultTemplate(obligations));
53
- const templatePath = path.join(projectRoot, ".memory-bank", "dd-flow", "vnext", "protocolize.md");
54
- if (!fs.existsSync(templatePath))
55
- throw new AppError("not_found", "vNext PROTOCOLIZE prompt template is missing", 1, { path: templatePath });
56
81
  const pauseCommand = stagePauseCommand(context, { runId: run.id, stage, workId: work.work_id, projectRoot });
57
- const prompt = renderPrompt({ projectRoot, runId: run.id, workId: work.work_id, specifyPath, obligations, resultPath, handoff: input.handoff, catalog: catalog(projectRoot), policy, template: fs.readFileSync(templatePath, "utf8"), pauseCommand, pauseCommandTemplate: stagePauseCommandTemplate(pauseCommand), flow: flowCommand(context) });
58
- fs.writeFileSync(promptPath, prompt);
59
- // Preparation is deliberately non-productive: the standalone stage-start
60
- // command atomically installs external context, binds the worker and opens
61
- // the lifecycle Stage. Do not make this prompt an implicit running stage.
82
+ const prompt = renderPrompt({ projectRoot, runId: run.id, workId: work.work_id, specifyPath, obligations, resultPath, handoff: input.handoff, catalog: projectCatalog, policy, template, pauseCommand, pauseCommandTemplate: stagePauseCommandTemplate(pauseCommand), finishCommand: managedLifecycleCommand(context, `${flowCommand(context)} stage finish ${run.id} --stage protocolize --project-root ${JSON.stringify(projectRoot)} --result-file ${JSON.stringify(resultPath)} --json`) });
83
+ const workspaceContract = ["<workspace_contract>", `- stage artifact directory: ${stageRoot}`, `- provisioned project workspace for later stages: ${policy.worktree_path ?? projectRoot}`, `- this PROTOCOLIZE Session remains in its launch directory: ${projectRoot}`, `Write only the named result file in the stage artifact directory; do not write project files, another RUN, another native home, branches, worktrees or Git commits. Do not change the Session directory to the newly provisioned worktree.`, "The CLI performs all protocol document materialization after the result is accepted.", "</workspace_contract>"].join("\n");
84
+ const promptWithWorkspaceContract = prompt.replace("</work_context>", `</work_context>\n\n${workspaceContract}`);
85
+ fs.writeFileSync(promptPath, promptWithWorkspaceContract);
86
+ // Packet publication does not itself bind a Session or open the Stage.
62
87
  appendFlowRunTimelineEvent(context, project.id, run.id, { type: "stage_prepared", work_id: work.work_id, stage, handoff_mode: input.handoff.stage_handoff.effective });
63
- const directive = input.handoff.stage_handoff.effective === "same_session" ? { kind: "continue_current_session", stage, prompt_path: promptPath, worker_prompt_markdown: prompt } : { kind: "await_new_session", stage, work_id: work.work_id, prompt_path: promptPath, resume_command: `${flowCommand(context)} stage start ${run.id} --stage protocolize --project-root ${JSON.stringify(projectRoot)} --json` };
88
+ const directive = input.handoff.stage_handoff.effective === "same_session" ? { kind: "continue_current_session", stage, prompt_path: promptPath, worker_prompt_markdown: promptWithWorkspaceContract } : { kind: "await_new_session", stage, work_id: work.work_id, prompt_path: promptPath, resume_command: managedLifecycleCommand(context, `${flowCommand(context)} stage start ${run.id} --stage protocolize --project-root ${JSON.stringify(projectRoot)} --json`) };
64
89
  return { directive, prompt_path: promptPath };
65
90
  }
66
- export function startVnextProtocolize(context, input) {
91
+ export function prepareVnextProtocolizeStart(context, input) {
67
92
  const projectRoot = resolveProjectRoot(input.projectRoot);
68
93
  const project = requireProjectByRoot(context, projectRoot);
69
94
  const run = requireRun(context, projectRoot, input.runId);
70
- assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
71
95
  const work = context.db.get("SELECT * FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id IS NULL ORDER BY created_at LIMIT 1", [project.id, run.id]);
72
96
  if (!work || work.status !== "running")
73
97
  throw new AppError("invalid_work_state", "PROTOCOLIZE is not ready for an Agent WorkSession", 1, { run_id: run.id });
74
98
  const protocolizeRoot = path.join(requireRunHome(run), "02-protocolize");
75
99
  const contextPath = path.join(protocolizeRoot, "work-context.json");
76
- if (!fs.existsSync(contextPath)) {
77
- const handoff = specifyHandoff(path.join(requireRunHome(run), "01-specify", "work-context.json"), work.work_id);
78
- prepareVnextProtocolize(context, { projectRoot, runId: run.id, workId: work.work_id, handoff });
79
- }
80
- const handoff = JSON.parse(fs.readFileSync(contextPath, "utf8"));
81
- const frozenContext = JSON.parse(fs.readFileSync(contextPath, "utf8"));
82
- const previous = context.db.get("SELECT ws.session_id, s.stop_reason FROM work_sessions ws LEFT JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? ORDER BY ws.created_at DESC LIMIT 1", [project.id, work.work_id]);
83
- const activeWorkSession = context.db.get("SELECT * FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
100
+ const frozenContext = fs.existsSync(contextPath) ? readProtocolizeContext(contextPath) : null;
101
+ const handoff = frozenContext?.system?.handoff ?? specifyHandoff(path.join(requireRunHome(run), "01-specify", "work-context.json"), work.work_id);
102
+ const packetInput = { projectRoot, runId: run.id, workId: work.work_id, handoff };
103
+ const packet = frozenContext ? null : prepareVnextProtocolizeArtifacts(context, packetInput);
84
104
  const stageAttached = (() => {
85
105
  const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, run.id]);
86
106
  try {
@@ -88,12 +108,35 @@ export function startVnextProtocolize(context, input) {
88
108
  return index.stage_runs?.some((item) => item.stage === stage) ?? false;
89
109
  }
90
110
  catch {
91
- return false;
111
+ throw new AppError("runtime_artifact_invalid", "RUN stage index is malformed", 1);
92
112
  }
93
113
  })();
94
- const mode = handoff.system?.handoff?.stage_handoff.effective;
114
+ if (!stageAttached)
115
+ prepareFlowRunStageAttachment(context, { projectRoot, runId: run.id, stage, dir: "02-protocolize", status: "running", dataSchemaId: "dd-flow/vnext-protocolize-result@3" });
116
+ const mode = handoff.stage_handoff.effective;
95
117
  const promptPath = path.join(protocolizeRoot, "prompt.md");
96
- const externalContext = applyExternalStageContext({ stageRoot: protocolizeRoot, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
118
+ if (frozenContext)
119
+ fs.readFileSync(promptPath, "utf8");
120
+ if (input.externalContext) {
121
+ prepareExternalStageContext({ stageRoot: protocolizeRoot, loaded: input.externalContext });
122
+ prepareOutputFile(promptPath);
123
+ }
124
+ return { projectRoot, project, run, work, protocolizeRoot, contextPath, frozenContext, packetInput, packet, stageAttached, mode, promptPath };
125
+ }
126
+ function readProtocolizeContext(file) {
127
+ try {
128
+ const value = JSON.parse(fs.readFileSync(file, "utf8"));
129
+ if (["same_session", "new_session"].includes(value?.system?.handoff?.stage_handoff?.effective))
130
+ return value;
131
+ }
132
+ catch { /* retained context is not a caller argument */ }
133
+ throw new AppError("runtime_context_invalid", "PROTOCOLIZE context is missing a valid frozen handoff", 1, { file });
134
+ }
135
+ export function startVnextProtocolize(context, input, prepared = prepareVnextProtocolizeStart(context, input)) {
136
+ const { projectRoot, project, run, work, protocolizeRoot, contextPath, packetInput, packet, stageAttached, mode, promptPath } = prepared;
137
+ assertStageStartHookEvent(context, { projectId: project.id, eventKey: input.hookEventId, runId: run.id, stage, projectRoot, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
138
+ const previous = context.db.get("SELECT ws.session_id, s.stop_reason FROM work_sessions ws LEFT JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? ORDER BY ws.created_at DESC LIMIT 1", [project.id, work.work_id]);
139
+ const activeWorkSession = context.db.get("SELECT * FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
97
140
  const sessionId = hookSessionIdentity(context, project.id, input.hookEventId).sessionId;
98
141
  // A stage-entry eval snapshot deliberately stops the canonical binding. Its
99
142
  // Subject starts from a fork of the captured starter Session, so the stale
@@ -103,6 +146,10 @@ export function startVnextProtocolize(context, input) {
103
146
  throw new AppError("handoff_session_mismatch", "Project policy requires PROTOCOLIZE to continue in the SPECIFY session", 1);
104
147
  if (mode === "new_session" && previous?.session_id === sessionId)
105
148
  throw new AppError("handoff_session_mismatch", "Project policy requires PROTOCOLIZE to start in a fresh session", 1);
149
+ if (packet)
150
+ prepareVnextProtocolize(context, packetInput, packet);
151
+ const frozenContext = prepared.frozenContext ?? readProtocolizeContext(contextPath);
152
+ const externalContext = applyExternalStageContext({ stageRoot: protocolizeRoot, promptPath, ...(input.externalContext ? { loaded: input.externalContext } : {}) });
106
153
  const binding = bindStageCoordinatorWork(context, { workId: work.work_id, hookEventId: input.hookEventId, stage, promptPath, resultPath: path.join(requireRunHome(run), "02-protocolize", "stage-report.json"), ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
107
154
  // Same-session handoff deliberately reuses the root Work/Session that
108
155
  // SPECIFY opened. That is not evidence that PROTOCOLIZE is already attached.
@@ -133,26 +180,34 @@ export function finishVnextProtocolize(context, input) {
133
180
  if (!work)
134
181
  throw new AppError("not_found", "RUN has no PROTOCOLIZE Work", 1, { run_id: run.id });
135
182
  const root = path.join(requireRunHome(run), "02-protocolize");
136
- const resultFile = path.resolve(input.resultFile);
137
- inside(root, resultFile);
138
- validateSchema({ schemaName: "vnext-protocolize-result", file: resultFile, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireRunHome(run) });
139
- const result = readResult(resultFile);
140
- if (result.outcome !== "protocolized")
141
- throw new AppError("validation", "PROTOCOLIZE may finish only as protocolized; use stage pause for every user question", 2);
183
+ const resultFile = prepareProtocolizeResultPath(requireRunHome(run), input.resultFile);
184
+ const result = input.result ?? readResult(resultFile, { projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireRunHome(run) });
185
+ validateSchema({ schemaName: "vnext-protocolize-result", file: resultFile, data: result, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireRunHome(run) });
142
186
  const acceptedObligations = acceptedSpecifyObligations(context, projectRoot, run.id, path.join(requireRunHome(run), "01-specify", "specify.json"));
143
- const obligations = effectiveObligations(result, acceptedObligations);
144
- validateDelivery(projectRoot, result, obligations);
145
- const protocolIds = result.delivery.members.map((member) => allocateProtocolId(context, projectRoot, member.slug));
146
- const psetId = result.delivery.kind === "protocol_set" ? allocatePsetId(projectRoot, result.delivery.slug) : null;
187
+ let obligations;
188
+ try {
189
+ if (result.outcome !== "protocolized")
190
+ throw new AppError("validation", "PROTOCOLIZE may finish only as protocolized; use stage pause for every user question", 2);
191
+ obligations = effectiveObligations(result, acceptedObligations);
192
+ validateDelivery(projectRoot, result, obligations);
193
+ }
194
+ catch (error) {
195
+ if (!(error instanceof AppError) || error.code !== "validation" || error.exitCode !== 2)
196
+ throw error;
197
+ throw new AppError(error.code, error.message, error.exitCode, { ...error.details, phase: "prepare", effect: "no_effect", recoverable: true });
198
+ }
147
199
  const resolvedPolicy = requireVnextWorkspaceRoute({ projectRoot, runId: run.id, runHome: requireRunHome(run), workspaceRoot: run.workspace_root, stage: "protocolize" });
148
200
  const receipt = readWorkspaceRouteReceipt(root);
149
201
  const workspaceRoot = run.workspace_root;
150
- const changedFiles = materialize(workspaceRoot, run.id, requireRunHome(run), result, obligations, protocolIds, psetId);
202
+ const intent = prepareProtocolizeIntent(context, run, resultFile, result, obligations);
203
+ publishProtocolizeIntent(context, project.id, intent);
204
+ const protocolIds = intent.protocol_ids;
205
+ const changedFiles = intent.changed_files;
151
206
  for (const protocolId of protocolIds)
152
207
  registerProtocol(context, { handshakeId: protocolId, projectRoot, workspacePath: workspaceRoot });
153
208
  if (receipt.created && receipt.bootstrap) {
154
209
  for (const protocolId of protocolIds)
155
- recordManagedWorktree(context, { protocolId, projectRoot, branch: requiredPolicyValue(resolvedPolicy.feature_branch, "feature branch"), base: requiredPolicyValue(resolvedPolicy.base_ref, "base ref"), created: receipt.created, bootstrap: receipt.bootstrap });
210
+ ensureManagedWorktreeRecorded(context, { protocolId, projectRoot, branch: requiredPolicyValue(resolvedPolicy.feature_branch, "feature branch"), base: requiredPolicyValue(resolvedPolicy.base_ref, "base ref"), created: receipt.created, bootstrap: receipt.bootstrap });
156
211
  }
157
212
  const now = context.now();
158
213
  const workSession = completeWorkSession(context, work.work_id, resultFile, now);
@@ -161,15 +216,150 @@ export function finishVnextProtocolize(context, input) {
161
216
  const reportJson = path.join(root, "stage-report.json");
162
217
  const reportMarkdown = path.join(root, "stage-report.md");
163
218
  const reportHtml = path.join(root, "stage-report.html");
164
- writeStageReport(root, report);
165
- validateSchema({ schemaName: "stage-report", file: reportJson, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireRunHome(run) });
166
- completeFlowRunStage(context, { projectRoot, runId: run.id, stage, status: "done", data: "protocolize-result.json", dataSchemaId: "dd-flow/vnext-protocolize-result@3", report: "stage-report.md", stageReport: "stage-report.html" });
167
- appendFlowRunTimelineEvent(context, project.id, run.id, { type: "protocol_documents_materialized", work_id: work.work_id, protocol_ids: protocolIds, stage });
168
- advanceFlowRun(context, { projectRoot, runId: run.id, status: "running", verdict: "protocolized", nextAction: "start_plan" });
219
+ const currentIndex = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, run.id]).index_json);
220
+ const stageDone = currentIndex.stage_runs.some(item => item.stage === stage && item.status === "done");
221
+ if (stageDone) {
222
+ publishStageReport(context, project.id, run.id, stage, root);
223
+ if (!fs.existsSync(reportJson))
224
+ throw new AppError("protocolize_report_missing", "Completed PROTOCOLIZE has no accepted report to replay", 1, { run_id: run.id, report_path: reportJson });
225
+ }
226
+ else {
227
+ const preparedReport = prepareStageReport(report);
228
+ validateSchema({ schemaName: "stage-report", file: reportJson, data: preparedReport.normalized, projectRoot, ddFlowHome: context.ddFlowHome, runId: run.id, runRoot: requireRunHome(run) });
229
+ const completion = { projectRoot, runId: run.id, stage, status: "done", data: "protocolize-result.json", dataSchemaId: "dd-flow/vnext-protocolize-result@3", report: "stage-report.md", stageReport: "stage-report.html", dataSha256: crypto.createHash("sha256").update(fs.readFileSync(resultFile)).digest("hex") };
230
+ const preparedCompletion = prepareFlowRunStageCompletion(context, completion);
231
+ withStageSettlement(context, () => {
232
+ acceptStageReport(context, { projectId: project.id, runId: run.id, stage, root, prepared: preparedReport });
233
+ completeFlowRunStage(context, completion, preparedCompletion);
234
+ });
235
+ appendFlowRunTimelineEvent(context, project.id, run.id, { type: "protocol_documents_materialized", work_id: work.work_id, protocol_ids: protocolIds, stage });
236
+ }
237
+ if (currentIndex.verdict !== "protocolized")
238
+ advanceFlowRun(context, { settlementStage: "protocolize", projectRoot, runId: run.id, status: "running", verdict: "protocolized", nextAction: "start_plan" });
169
239
  refreshRunWorkProjection(context, project.id, run.id);
170
- const nextCommand = `${flowCommand(context)} stage start ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json`;
240
+ const nextCommand = managedLifecycleCommand(context, `${flowCommand(context)} stage start ${run.id} --stage plan --project-root ${JSON.stringify(projectRoot)} --json`);
171
241
  return { ok: true, outcome: "protocolized", run_id: run.id, protocol_ids: protocolIds, workspace_root: workspaceRoot, git_policy: resolvedPolicy, next_action: "await_plan", next_command: nextCommand, next: { kind: "start_stage", stage: "plan", command: nextCommand, cwd: workspaceRoot, session_mode: resolvedPolicy.stage_session_mode }, artifacts: { result: resultFile, report_json: reportJson, report_markdown: reportMarkdown, report_html: reportHtml, protocols: protocolIds.map((id) => path.join(workspaceRoot, ".memory-bank", "protocol", id, "summary.md")) } };
172
242
  }
243
+ function prepareProtocolizeIntent(context, run, resultFile, result, obligations) {
244
+ const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [run.project_id, run.id]);
245
+ const index = row ? JSON.parse(row.index_json) : null;
246
+ const attempt = index?.stage_runs?.find(item => item.stage === stage)?.attempt;
247
+ if (!attempt)
248
+ throw new AppError("protocolize_owner_missing", "PROTOCOLIZE has no owning Stage attempt", 1, { run_id: run.id });
249
+ const resultSha = sha256(fs.readFileSync(resultFile));
250
+ const retained = readProtocolizeIntent(context, run.project_id, run.id, attempt);
251
+ if (retained) {
252
+ if (retained.workspace_root !== run.workspace_root || retained.result_sha256 !== resultSha)
253
+ throw new AppError("protocolize_intent_conflict", "Accepted PROTOCOLIZE publication belongs to different result or workspace bytes", 1, { run_id: run.id, attempt });
254
+ return retained;
255
+ }
256
+ const projectRoot = run.workspace_root;
257
+ const protocolIds = allocateProtocolIds(context, run.project_id, projectRoot, result.delivery.members.map(member => member.slug));
258
+ const psetId = result.delivery.kind === "protocol_set" ? allocatePsetId(context, run.project_id, projectRoot, result.delivery.slug) : null;
259
+ const draft = fs.mkdtempSync(path.join(os.tmpdir(), "dd-flow-protocolize-"));
260
+ try {
261
+ // A draft must never follow a workspace symlink back into the live tree.
262
+ fs.cpSync(path.join(projectRoot, ".memory-bank"), path.join(draft, ".memory-bank"), { recursive: true, filter: source => !fs.lstatSync(source).isSymbolicLink() });
263
+ const feature = result.feature.epic_path && path.isAbsolute(result.feature.epic_path)
264
+ ? { ...result.feature, epic_path: path.join(draft, path.relative(projectRoot, result.feature.epic_path)) }
265
+ : result.feature;
266
+ const draftResult = { ...result, feature };
267
+ const changedFiles = materialize(draft, run.id, requireRunHome(run), draftResult, obligations, protocolIds, psetId);
268
+ const files = changedFiles.map(relative => {
269
+ const source = path.join(projectRoot, relative), target = path.join(draft, relative);
270
+ const bytes = fs.readFileSync(target, "utf8");
271
+ return { relative, before_sha256: fs.existsSync(source) ? sha256(fs.readFileSync(source)) : null, after_sha256: sha256(bytes), bytes };
272
+ });
273
+ const candidate = { run_id: run.id, attempt, workspace_root: projectRoot, result_sha256: resultSha, protocol_ids: protocolIds, pset_id: psetId, changed_files: changedFiles, files };
274
+ return context.db.writeTransaction(() => {
275
+ const raced = readProtocolizeIntent(context, run.project_id, run.id, attempt);
276
+ if (raced) {
277
+ if (raced.workspace_root !== projectRoot || raced.result_sha256 !== resultSha)
278
+ throw new AppError("protocolize_intent_conflict", "A competing PROTOCOLIZE publication was accepted", 1, { run_id: run.id, attempt });
279
+ return raced;
280
+ }
281
+ const reserved = new Set(context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.protocolize_intent'", [run.project_id])
282
+ .flatMap(row => { const prior = JSON.parse(row.payload_json); return [...prior.protocol_ids, ...(prior.pset_id ? [prior.pset_id] : [])]; }));
283
+ if ([...protocolIds, ...(psetId ? [psetId] : [])].some(id => reserved.has(id)))
284
+ throw new AppError("protocolize_id_reserved", "Another PROTOCOLIZE attempt reserved the selected document ID; retry to allocate a new one", 1, { run_id: run.id });
285
+ context.db.run("INSERT INTO audit_events (project_id, event_type, forced, payload_json, created_at) VALUES (?, 'flow_run.protocolize_intent', 0, ?, ?)", [run.project_id, JSON.stringify(candidate), context.now()]);
286
+ return candidate;
287
+ });
288
+ }
289
+ finally {
290
+ fs.rmSync(draft, { recursive: true, force: true });
291
+ }
292
+ }
293
+ function readProtocolizeIntent(context, projectId, runId, attempt) {
294
+ const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.protocolize_intent' ORDER BY id DESC", [projectId]);
295
+ return rows.map(row => JSON.parse(row.payload_json)).find(item => item.run_id === runId && item.attempt === attempt) ?? null;
296
+ }
297
+ function publishProtocolizeIntent(context, projectId, intent) {
298
+ const memory = path.join(intent.workspace_root, ".memory-bank");
299
+ withProjectionLock(path.join(context.ddFlowHome, "locks", `protocolize-${projectId}.publish-lock`), () => {
300
+ for (const file of intent.files) {
301
+ if (!file.relative.startsWith(".memory-bank/") || sha256(file.bytes) !== file.after_sha256)
302
+ throw new AppError("protocolize_intent_invalid", "Accepted PROTOCOLIZE file is invalid", 1, { relative: file.relative });
303
+ const target = path.resolve(intent.workspace_root, file.relative);
304
+ inside(memory, target);
305
+ assertNoSymlinkPath(memory, target);
306
+ const current = fs.existsSync(target) ? sha256(fs.readFileSync(target)) : null;
307
+ if (current !== file.before_sha256 && current !== file.after_sha256)
308
+ throw new AppError("protocolize_publication_conflict", "PROTOCOLIZE target changed since publication was accepted", 1, { target });
309
+ }
310
+ for (const file of intent.files) {
311
+ const target = path.resolve(intent.workspace_root, file.relative);
312
+ if (fs.existsSync(target) && sha256(fs.readFileSync(target)) === file.after_sha256)
313
+ continue;
314
+ fs.mkdirSync(path.dirname(target), { recursive: true });
315
+ const temporary = `${target}.${crypto.randomUUID()}.tmp`;
316
+ try {
317
+ fs.writeFileSync(temporary, file.bytes, { flag: "wx" });
318
+ if (file.before_sha256 === null) {
319
+ try {
320
+ fs.linkSync(temporary, target);
321
+ }
322
+ catch (error) {
323
+ if (error.code !== "EEXIST" || sha256(fs.readFileSync(target)) !== file.after_sha256)
324
+ throw error;
325
+ }
326
+ }
327
+ else {
328
+ if (sha256(fs.readFileSync(target)) !== file.before_sha256)
329
+ throw new AppError("protocolize_publication_conflict", "PROTOCOLIZE target changed during publication", 1, { target });
330
+ fs.renameSync(temporary, target);
331
+ }
332
+ }
333
+ finally {
334
+ fs.rmSync(temporary, { force: true });
335
+ }
336
+ }
337
+ });
338
+ }
339
+ function assertNoSymlinkPath(memory, target) {
340
+ for (let cursor = memory;; cursor = path.join(cursor, path.relative(cursor, target).split(path.sep)[0])) {
341
+ try {
342
+ if (fs.lstatSync(cursor).isSymbolicLink())
343
+ throw new AppError("protocolize_publication_conflict", "PROTOCOLIZE publication cannot follow a workspace symlink", 1, { target, symlink: cursor });
344
+ }
345
+ catch (error) {
346
+ if (error.code !== "ENOENT")
347
+ throw error;
348
+ }
349
+ if (cursor === target)
350
+ break;
351
+ }
352
+ }
353
+ function ensureManagedWorktreeRecorded(context, input) {
354
+ const existing = context.db.get("SELECT wr.feature_branch, wr.base_ref, wr.worktree_path FROM worktree_records wr JOIN protocols p ON p.project_id = wr.project_id AND p.id = wr.protocol_id WHERE p.project_root = ? AND p.id = ? AND wr.status = 'active' ORDER BY wr.created_at DESC LIMIT 1", [input.projectRoot, input.protocolId]);
355
+ if (existing) {
356
+ if (existing.feature_branch !== input.branch || existing.base_ref !== input.base || existing.worktree_path !== input.created.worktreePath)
357
+ throw new AppError("worktree_already_exists", "Existing managed worktree record conflicts with the accepted PROTOCOLIZE route", 1, { protocol_id: input.protocolId });
358
+ return;
359
+ }
360
+ recordManagedWorktree(context, input);
361
+ }
362
+ function sha256(bytes) { return crypto.createHash("sha256").update(bytes).digest("hex"); }
173
363
  function materialize(projectRoot, runId, runHome, result, obligations, ids, psetId) {
174
364
  const psetPath = psetId ? path.join(projectRoot, ".memory-bank", "protocol", "_set", `${psetId}.md`) : null;
175
365
  const created = [];
@@ -309,21 +499,27 @@ function appendIndexEntry(indexPath, childPath, label) {
309
499
  }
310
500
  function epicRootFor(projectRoot, value) { const resolved = path.resolve(projectRoot, value); const relative = path.relative(projectRoot, resolved); if (relative.startsWith("..") || path.isAbsolute(relative))
311
501
  throw new AppError("path_escape", "epic_path must stay inside the project", 2, { epic_path: value }); return path.basename(resolved) === "index.md" ? path.dirname(resolved) : resolved; }
312
- function readResult(file) {
313
- if (!fs.existsSync(file))
314
- throw new AppError("not_found", "PROTOCOLIZE result is missing", 1, { file });
315
- const value = JSON.parse(fs.readFileSync(file, "utf8"));
316
- return value;
502
+ function readResult(file, context) {
503
+ return prepareJsonSchema(file, "PROTOCOLIZE result", {
504
+ schemaName: "vnext-protocolize-result", projectRoot: context.projectRoot, ddFlowHome: context.ddFlowHome, runId: context.runId, runRoot: context.runRoot
505
+ }).value;
317
506
  }
318
507
  function acceptedSpecifyObligations(context, projectRoot, runId, specifyPath) {
319
508
  if (!fs.existsSync(specifyPath))
320
- throw new AppError("not_found", "PROTOCOLIZE requires accepted specify.json", 1, { path: specifyPath });
321
- validateSchema({ schemaName: "vnext-specify", file: specifyPath, projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: requireRunHome(requireRun(context, projectRoot, runId)) });
322
- const specify = readVnextSpecifyResult(specifyPath);
323
- return [
324
- ...specify.requirements.map((obligation) => ({ ...obligation, kind: "requirement" })),
325
- ...specify.acceptance_criteria.map((obligation) => ({ ...obligation, kind: "acceptance" }))
326
- ];
509
+ throw new AppError("runtime_artifact_missing", "PROTOCOLIZE requires accepted specify.json", 1, { path: specifyPath });
510
+ try {
511
+ const specify = readVnextSpecifyResult(specifyPath);
512
+ validateSchema({ schemaName: "vnext-specify", file: specifyPath, data: specify, projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: requireRunHome(requireRun(context, projectRoot, runId)) });
513
+ return [
514
+ ...specify.requirements.map((obligation) => ({ ...obligation, kind: "requirement" })),
515
+ ...specify.acceptance_criteria.map((obligation) => ({ ...obligation, kind: "acceptance" }))
516
+ ];
517
+ }
518
+ catch (error) {
519
+ if (!(error instanceof AppError) || !["validation", "schema_validation", "invalid_json"].includes(error.code))
520
+ throw error;
521
+ throw new AppError("runtime_artifact_invalid", "Accepted SPECIFY result is invalid", 1, { path: specifyPath, cause_code: error.code });
522
+ }
327
523
  }
328
524
  /** SPECIFY is historical input; only a HITL-backed protocol amendment may alter its effective wording. */
329
525
  function effectiveObligations(result, accepted) {
@@ -435,18 +631,19 @@ function resultTemplate(obligations = []) {
435
631
  }
436
632
  function renderPrompt(input) {
437
633
  const obligationList = input.obligations.map((obligation) => `- ${obligation.id}: ${obligation.statement}`).join("\n");
438
- return ["<work_context>", `- RUN: ${input.runId}`, `- Work: ${input.workId}`, `- Accepted SPECIFY JSON: ${input.specifyPath}`, `- Handoff: ${input.handoff.stage_handoff.effective}`, "</work_context>", "", "<accepted_obligations>", obligationList, "</accepted_obligations>", "", "<frozen_git_policy>", `- route: ${input.policy.route}`, `- integration branch: ${input.policy.integration_branch ?? "not applicable"}`, `- base ref: ${input.policy.base_ref ?? "not applicable"}`, `- feature branch: ${input.policy.feature_branch ?? "not applicable"}`, `- service worktree: ${input.policy.worktree_path ?? "not applicable"}`, `- bootstrap: ${input.policy.bootstrap_status}`, `- decision: ${input.policy.reason}`, "The CLI already created and bootstrapped this workspace at PROTOCOLIZE start. Do not create branches, worktrees, protocol files or Git commits yourself. This transition Work may run from the stable session; edit only the supplied RUN result file.", "</frozen_git_policy>", "", "<catalog>", input.catalog.length ? input.catalog.map((x) => `- ${x}`).join("\n") : "- inactive", "</catalog>", "", "<stage_instructions>", input.template.trim(), "</stage_instructions>", "", "<output_contract>", `Edit only ${input.resultPath}. Keep this exact JSON shape; CLI allocates ids and writes PRT/PSET/feature documents in the already provisioned workspace:\n\n\`\`\`json\n${JSON.stringify(resultTemplate(), null, 2)}\n\`\`\``, "Allocate every supplied R-* and AC-* exactly once in obligation_ownership. The CLI rejects unknown, duplicate or missing obligations, and every member must own at least one AC-*.", "If PROTOCOLIZE itself exposes a material user decision with no reasonable default, do not finish and do not return to SPECIFY. 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", input.pauseCommandTemplate, "```", "Ask the returned user_message and stop. Resume this same PROTOCOLIZE Work using the exact command returned by pause.", `When the answer is incorporated and the result is protocolized, finish:\n\n${input.flow} stage finish ${input.runId} --stage protocolize --project-root ${JSON.stringify(input.projectRoot)} --result-file ${JSON.stringify(input.resultPath)} --json`, "</output_contract>", ""].join("\n");
634
+ return ["<work_context>", `- RUN: ${input.runId}`, `- Work: ${input.workId}`, `- Accepted SPECIFY JSON: ${input.specifyPath}`, `- Handoff: ${input.handoff.stage_handoff.effective}`, "</work_context>", "", "<accepted_obligations>", obligationList, "</accepted_obligations>", "", "<frozen_git_policy>", `- route: ${input.policy.route}`, `- integration branch: ${input.policy.integration_branch ?? "not applicable"}`, `- base ref: ${input.policy.base_ref ?? "not applicable"}`, `- feature branch: ${input.policy.feature_branch ?? "not applicable"}`, `- service worktree: ${input.policy.worktree_path ?? "not applicable"}`, `- bootstrap: ${input.policy.bootstrap_status}`, `- decision: ${input.policy.reason}`, "The CLI already created and bootstrapped this workspace at PROTOCOLIZE start. Do not create branches, worktrees, protocol files or Git commits yourself. This transition Work may run from the stable session; edit only the supplied RUN result file.", "</frozen_git_policy>", "", "<catalog>", input.catalog.length ? input.catalog.map((x) => `- ${x}`).join("\n") : "- inactive", "</catalog>", "", "<stage_instructions>", input.template.trim(), "</stage_instructions>", "", "<output_contract>", `Edit only ${input.resultPath}. Keep this exact JSON shape; CLI allocates ids and writes PRT/PSET/feature documents in the already provisioned workspace:\n\n\`\`\`json\n${JSON.stringify(resultTemplate(input.obligations), null, 2)}\n\`\`\``, "obligation_id values and their one-per-obligation entries are prefilled by the CLI. Preserve those IDs exactly; change only member_keys when semantic ownership requires it. The CLI rejects unknown, duplicate or missing obligations, and every member must own at least one AC-*.", "If PROTOCOLIZE itself exposes a material user decision with no reasonable default, do not finish and do not return to SPECIFY. 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", input.pauseCommandTemplate, "```", "Ask the returned user_message and stop. Resume this same PROTOCOLIZE Work using the exact command returned by pause.", `When the answer is incorporated and the result is protocolized, finish:\n\n${input.finishCommand}`, stageLifecycleInstruction, "</output_contract>", ""].join("\n");
439
635
  }
440
- function provisionWorkspaceForProtocolize(context, projectRoot, projectId, run, stageRoot) {
636
+ function prepareWorkspaceForProtocolize(context, projectRoot, projectId, run, stageRoot) {
441
637
  const receiptPath = path.join(stageRoot, "workspace-route.json");
442
638
  if (fs.existsSync(receiptPath))
443
- return readWorkspaceRouteReceipt(stageRoot).policy;
639
+ return { kind: "retained", policy: readWorkspaceRouteReceipt(stageRoot).policy };
640
+ prepareOutputFile(receiptPath);
444
641
  const config = loadVnextWorkspacePolicy(projectRoot);
445
642
  const stableFacts = gitFacts(projectRoot);
446
643
  if (config.workspace.route === "integration_branch_direct") {
447
- const policy = { route: "integration_branch_direct", integration_branch: config.workspace.integration_branch, base_ref: stableFacts.head, feature_branch: null, worktree_path: null, reason: "Project workspace configuration explicitly selects the integration checkout.", provision_stage: "protocolize_start", stage_session_mode: stageSessionMode(context, run), provisioned: true, bootstrap_status: "not_applicable" };
448
- writeJson(receiptPath, { schema_id: "dd-flow/vnext-workspace-route@1", policy, created: null, bootstrap: null });
449
- return policy;
644
+ const sessionMode = stageSessionMode(context, run, projectRoot, projectRoot);
645
+ const policy = { route: "integration_branch_direct", integration_branch: config.workspace.integration_branch, base_ref: stableFacts.head, feature_branch: null, worktree_path: null, reason: "Project workspace configuration explicitly selects the integration checkout.", provision_stage: "protocolize_start", stage_session_mode: sessionMode, provisioned: true, bootstrap_status: "not_applicable" };
646
+ return { kind: "direct", receiptPath, policy };
450
647
  }
451
648
  if (stableFacts.status === "unavailable" || !stableFacts.head || stableFacts.branch !== config.workspace.integration_branch) {
452
649
  throw new AppError("workspace_route_invalid", "Configured feature worktree requires a clean, known integration checkout", 1, { expected_integration_branch: config.workspace.integration_branch, actual: stableFacts, project_root: projectRoot });
@@ -454,10 +651,32 @@ function provisionWorkspaceForProtocolize(context, projectRoot, projectId, run,
454
651
  const branch = vnextRunBranch(config, run);
455
652
  const holder = path.basename(projectRoot).replace(/[^a-zA-Z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "project";
456
653
  const worktreePath = projectFeatureWorktreePath(context.ddFlowHome, projectId, `RUN-${run.short_id}`, holder);
457
- const created = createManagedWorktree(context, { projectRoot, branch, base: stableFacts.head, path: worktreePath });
654
+ const sessionMode = stageSessionMode(context, run, projectRoot, worktreePath);
655
+ let create;
656
+ try {
657
+ create = prepareManagedWorktree({ projectRoot, branch, base: stableFacts.head, path: worktreePath });
658
+ }
659
+ catch (error) {
660
+ if (error instanceof AppError && error.exitCode === 2)
661
+ throw new AppError("workspace_route_invalid", "The frozen RUN workspace route cannot be provisioned", 1, { cause_code: error.code, run_id: run.id });
662
+ throw error;
663
+ }
664
+ prepareManagedWorktreeBootstrapSources(projectRoot);
665
+ return { kind: "feature", receiptPath, config, stableFacts, sessionMode, branch, create };
666
+ }
667
+ function provisionWorkspaceForProtocolize(context, projectRoot, run, prepared) {
668
+ if (prepared.kind === "retained")
669
+ return prepared.policy;
670
+ const { receiptPath } = prepared;
671
+ if (prepared.kind === "direct") {
672
+ writeJson(receiptPath, { schema_id: "dd-flow/vnext-workspace-route@1", policy: prepared.policy, created: null, bootstrap: null });
673
+ return prepared.policy;
674
+ }
675
+ const { config, stableFacts, sessionMode, branch, create } = prepared;
676
+ const created = createManagedWorktree(context, create, create);
458
677
  const bootstrap = bootstrapManagedWorktree(context, { projectRoot, worktreePath: created.worktreePath });
459
678
  rebindFlowRunWorkspace(context, { projectRoot, runId: run.id, workspaceRoot: created.worktreePath, reason: "PROTOCOLIZE start provisioned the configured feature-worktree route" });
460
- const policy = { route: "feature_worktree", integration_branch: config.workspace.integration_branch, base_ref: stableFacts.head, feature_branch: branch, worktree_path: created.worktreePath, reason: "Project workspace configuration requires a managed feature worktree before durable protocol documents exist.", provision_stage: "protocolize_start", stage_session_mode: stageSessionMode(context, run), provisioned: true, bootstrap_status: bootstrap.status };
679
+ const policy = { route: "feature_worktree", integration_branch: config.workspace.integration_branch, base_ref: stableFacts.head, feature_branch: branch, worktree_path: created.worktreePath, reason: "Project workspace configuration requires a managed feature worktree before durable protocol documents exist.", provision_stage: "protocolize_start", stage_session_mode: sessionMode, provisioned: true, bootstrap_status: bootstrap.status };
461
680
  writeJson(receiptPath, { schema_id: "dd-flow/vnext-workspace-route@1", policy, created, bootstrap });
462
681
  return policy;
463
682
  }
@@ -475,8 +694,27 @@ function readWorkspaceRouteReceipt(root) {
475
694
  }
476
695
  function requiredPolicyValue(value, label) { if (!value)
477
696
  throw new AppError("runtime_missing", `PROTOCOLIZE Git policy is missing ${label}`, 1); return value; }
478
- function allocateProtocolId(context, projectRoot, name) { return previewNextEntityId(context, { projectRoot, type: "protocol", slug: name }).entity.id; }
479
- function allocatePsetId(projectRoot, value) { const root = path.join(projectRoot, ".memory-bank", "protocol", "_set"); const used = fs.existsSync(root) ? fs.readdirSync(root).map((file) => /^PSET-(\d+)-/.exec(file)?.[1]).filter((item) => Boolean(item)).map(Number) : []; return `PSET-${String(Math.max(0, ...used) + 1).padStart(3, "0")}-${slug(value)}`; }
697
+ function allocateProtocolIds(context, projectId, projectRoot, names) {
698
+ if (!names.length)
699
+ return [];
700
+ const first = previewNextEntityId(context, { projectRoot, type: "protocol", slug: names[0] }).entity.id;
701
+ const used = protocolizeReservedNumbers(context, projectId, "protocol_ids", /^PRT-(\d+)-/);
702
+ const sequence = Math.max(Number(/^PRT-(\d+)-/.exec(first)?.[1] ?? 1) - 1, ...used) + 1;
703
+ return names.map((name, index) => `PRT-${String(sequence + index).padStart(3, "0")}-${slug(name)}`);
704
+ }
705
+ function allocatePsetId(context, projectId, projectRoot, value) {
706
+ const root = path.join(projectRoot, ".memory-bank", "protocol", "_set");
707
+ const used = fs.existsSync(root) ? fs.readdirSync(root).map((file) => /^PSET-(\d+)-/.exec(file)?.[1]).filter((item) => Boolean(item)).map(Number) : [];
708
+ return `PSET-${String(Math.max(0, ...used, ...protocolizeReservedNumbers(context, projectId, "pset_id", /^PSET-(\d+)-/)) + 1).padStart(3, "0")}-${slug(value)}`;
709
+ }
710
+ function protocolizeReservedNumbers(context, projectId, field, pattern) {
711
+ const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.protocolize_intent'", [projectId]);
712
+ return rows.flatMap(row => {
713
+ const value = JSON.parse(row.payload_json);
714
+ const ids = field === "protocol_ids" ? value.protocol_ids : value.pset_id ? [value.pset_id] : [];
715
+ return ids.map(id => Number(pattern.exec(id)?.[1])).filter(Number.isFinite);
716
+ });
717
+ }
480
718
  function catalog(projectRoot) {
481
719
  const memory = path.join(projectRoot, ".memory-bank");
482
720
  const candidates = [
@@ -502,7 +740,15 @@ function requireRun(context, projectRoot, id) { const project = requireProjectBy
502
740
  throw new AppError("not_found", "RUN is not registered", 1, { run_id: id }); return run; }
503
741
  function requireRunHome(run) { if (!run.run_root)
504
742
  throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1); return run.run_root; }
505
- function inside(root, file) { const relative = path.relative(root, file); if (relative.startsWith("..") || path.isAbsolute(relative))
743
+ export function prepareProtocolizeResultPath(runHome, file) {
744
+ const resolved = path.resolve(file);
745
+ inside(path.join(runHome, "02-protocolize"), resolved);
746
+ const canonical = path.join(runHome, "02-protocolize", "protocolize-result.json");
747
+ if (resolved !== canonical)
748
+ throw new AppError("protocolize_result_path_invalid", "PROTOCOLIZE result must be the canonical Stage data file named by its completion receipt", 2, { result_file: resolved, expected: canonical });
749
+ return resolved;
750
+ }
751
+ function inside(root, file) { const relative = path.relative(root, file); if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
506
752
  throw new AppError("path_escape", "Result must be inside the protocolize workspace", 2); }
507
753
  function writeJson(file, value) { const tmp = `${file}.${crypto.randomUUID()}.tmp`; fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`); fs.renameSync(tmp, file); }
508
754
  function slug(value) { const normalized = value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, ""); if (!normalized)