@deksden-com/dd-flow-cli 0.9.0-beta.9 → 0.9.0-beta.91

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 (144) hide show
  1. package/CHANGELOG.md +467 -0
  2. package/README.md +65 -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 +82 -0
  7. package/dist/cli/input-preparation.js +116 -0
  8. package/dist/cli/run-cli.js +1421 -384
  9. package/dist/cli.js +6 -2
  10. package/dist/harness-runtime/bin/dd-agy.mjs +37 -0
  11. package/dist/harness-runtime/bin/dd-codex.mjs +25 -0
  12. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  13. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  14. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  15. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  16. package/dist/harness-runtime/lib/daemon-operations.mjs +215 -0
  17. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +423 -0
  18. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  19. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  20. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +146 -0
  21. package/dist/harness-runtime/lib/dd-codex.mjs +562 -0
  22. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  23. package/dist/harness-runtime/lib/dd-droid.mjs +471 -0
  24. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +274 -0
  25. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  26. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +198 -0
  27. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  28. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +644 -0
  29. package/dist/harness-runtime/lib/dd-zcode.mjs +910 -0
  30. package/dist/harness-runtime/lib/delegation-instructions.d.mts +10 -0
  31. package/dist/harness-runtime/lib/delegation-instructions.mjs +130 -0
  32. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  33. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  34. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  35. package/dist/harness-runtime/lib/managed-daemon.mjs +260 -0
  36. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  37. package/dist/harness-runtime/lib/native-hook-command.d.mts +1 -0
  38. package/dist/harness-runtime/lib/native-hook-command.mjs +34 -0
  39. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  40. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  41. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  42. package/dist/harness-runtime/lib/process-json.mjs +70 -0
  43. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  44. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  45. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  46. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  47. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  48. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  49. package/dist/schemas/agent-profile.schema.json +1 -1
  50. package/dist/schemas/code-review-result.schema.json +2 -2
  51. package/dist/schemas/code-work-batch.schema.json +4 -3
  52. package/dist/schemas/code-work-result.schema.json +4 -4
  53. package/dist/schemas/plan-review-result.schema.json +2 -2
  54. package/dist/schemas/run-control-receipt.schema.json +99 -0
  55. package/dist/schemas/run-control-request.schema.json +36 -0
  56. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  57. package/dist/services/canon.js +11 -8
  58. package/dist/services/cleanup.js +57 -13
  59. package/dist/services/cli-operation-classifier.js +22 -24
  60. package/dist/services/code-checks.js +543 -96
  61. package/dist/services/codex-hook-delivery.js +28 -0
  62. package/dist/services/command-context.js +80 -0
  63. package/dist/services/config.js +11 -8
  64. package/dist/services/continuation-outcome.js +20 -0
  65. package/dist/services/controller-fanout.js +132 -0
  66. package/dist/services/dashboard.js +103 -31
  67. package/dist/services/engines.js +121 -76
  68. package/dist/services/eval-snapshots.js +750 -73
  69. package/dist/services/execution-policy.js +170 -0
  70. package/dist/services/external-work-launch.js +110 -0
  71. package/dist/services/harness-adapter.js +147 -24
  72. package/dist/services/harness-config.js +2 -0
  73. package/dist/services/hooks.js +587 -299
  74. package/dist/services/lanes.js +61 -53
  75. package/dist/services/lifecycle-command.js +103 -17
  76. package/dist/services/lifecycle-contract.js +30 -0
  77. package/dist/services/lifecycle-invocations.js +1122 -0
  78. package/dist/services/managed-daemon-binding.js +38 -0
  79. package/dist/services/managed-processes.js +283 -27
  80. package/dist/services/merge-queue.js +179 -104
  81. package/dist/services/merge-server.js +73 -28
  82. package/dist/services/migrations.js +14 -9
  83. package/dist/services/native-daemon-history.js +49 -0
  84. package/dist/services/native-session-control.js +39 -0
  85. package/dist/services/plan-runtime.js +19 -8
  86. package/dist/services/plans.js +28 -25
  87. package/dist/services/projects.js +18 -5
  88. package/dist/services/prompts.js +23 -16
  89. package/dist/services/protocols.js +64 -20
  90. package/dist/services/recovery-observation-budget.js +61 -0
  91. package/dist/services/recovery-snapshot-database.js +107 -0
  92. package/dist/services/repair-intents.js +40 -0
  93. package/dist/services/run-control-receipt.js +56 -0
  94. package/dist/services/run-control-worker.js +363 -0
  95. package/dist/services/run-control.js +876 -0
  96. package/dist/services/run-controller-adapter.js +222 -0
  97. package/dist/services/run-controller-capture.js +134 -0
  98. package/dist/services/run-controller-process.js +189 -0
  99. package/dist/services/run-controller-recovery.js +222 -0
  100. package/dist/services/run-controller-state.js +36 -0
  101. package/dist/services/run-controller.js +793 -0
  102. package/dist/services/run-engine-bindings.js +1 -1
  103. package/dist/services/run-fork.js +138 -0
  104. package/dist/services/run-observations.js +112 -0
  105. package/dist/services/run-recovery-runtime.js +69 -0
  106. package/dist/services/run-recovery.js +343 -0
  107. package/dist/services/runs.js +368 -74
  108. package/dist/services/runtime-budget.js +434 -0
  109. package/dist/services/runtime-command.js +43 -0
  110. package/dist/services/runtime-scope-capture.js +50 -0
  111. package/dist/services/runtime-scope-control.js +450 -0
  112. package/dist/services/runtime-scope-resume.js +565 -0
  113. package/dist/services/runtime-scope-stop.js +99 -0
  114. package/dist/services/runtime-scope-worker.js +243 -0
  115. package/dist/services/runtime-service.js +97 -0
  116. package/dist/services/schema-validation.js +10 -8
  117. package/dist/services/sessions.js +35 -69
  118. package/dist/services/stage-blocker.js +17 -7
  119. package/dist/services/stage-context.js +44 -18
  120. package/dist/services/stage-lifecycle.js +99 -102
  121. package/dist/services/stage-pause.js +84 -55
  122. package/dist/services/stage-work-graph.js +35 -0
  123. package/dist/services/usage.js +37 -93
  124. package/dist/services/vnext-code-review.js +195 -88
  125. package/dist/services/vnext-code.js +285 -252
  126. package/dist/services/vnext-execution-profile.js +5 -3
  127. package/dist/services/vnext-fanout.js +160 -17
  128. package/dist/services/vnext-merge.js +291 -104
  129. package/dist/services/vnext-plan-review.js +139 -81
  130. package/dist/services/vnext-plan.js +138 -69
  131. package/dist/services/vnext-protocolize.js +129 -56
  132. package/dist/services/vnext-specify.js +88 -65
  133. package/dist/services/work-registry.js +716 -168
  134. package/dist/services/workspace-bootstrap.js +76 -0
  135. package/dist/services/worktrees.js +85 -35
  136. package/dist/shared/entity-references.js +8 -0
  137. package/dist/shared/errors.js +12 -0
  138. package/dist/storage/database.js +459 -32
  139. package/dist/storage/paths.js +17 -4
  140. package/dist/storage/work-references.js +23 -0
  141. package/dist/storage/writer-contract.js +77 -0
  142. package/dist/storage/writer-migration.js +102 -0
  143. package/package.json +24 -13
  144. package/tools/repair-paused-run-status.mjs +59 -0
@@ -1,56 +1,82 @@
1
1
  import fs from "node:fs";
2
+ import { resolveCommandPaths, resolveCommandProjectRoot } from "../services/command-context.js";
3
+ import { assertAuxiliaryCommandScope } from "../services/lifecycle-invocations.js";
2
4
  import path from "node:path";
5
+ import { randomUUID } from "node:crypto";
6
+ import { quote } from "shell-quote";
7
+ import { observeLifecycleCommand, observedLifecycleNativeEvent } from "../services/lifecycle-invocations.js";
8
+ import { verifyCodexHookDelivery } from "../services/codex-hook-delivery.js";
9
+ import { assertLifecycleInvocationCurrent, awaitLifecycleInvocation, expandLifecycleInvocationArgs, issueLifecycleInvocation, prepareLifecycleIssuance, lifecycleInvocationScope, observedLifecycleDiagnostic, observedLifecycleInvocation, resolveObservedLifecycleArgs, settleLifecycleInvocation, settleLifecyclePreparationRejection, settleLifecycleRejection, validateLifecyclePathAliases } from "../services/lifecycle-invocations.js";
3
10
  import { createContext, createRouterContext } from "../runtime/context.js";
11
+ import { migrateStoreWriter } from "../storage/writer-migration.js";
4
12
  import { helpForArgs } from "./help.js";
5
13
  import { AppError, isAppError } from "../shared/errors.js";
14
+ import { entityReferenceVariants } from "../shared/entity-references.js";
6
15
  import { writeJson } from "../shared/json.js";
7
- import { archiveProject, getProjectStatus, migrateProjectIds, registerProject, resolveProject } from "../services/projects.js";
8
- import { cancelProtocol, getProtocolBlockers, getProtocolStatus, getReadyProtocols, implementProtocol, readyForMerge, registerProtocol, requireProtocol, syncProtocolFromRun, transitionProtocol } from "../services/protocols.js";
9
- import { blockPlanItem, completePlanItem, getPlanStatus, skipPlanItem, startPlanItem } from "../services/plans.js";
10
- import { cancelMergeQueueJob, claimNextMergeJob, claimMergeJob, claimMergeBundle, completeMergeBundle, completeMergeJob, failMergeBundle, failMergeJob, getMergeBundleStatus, getMergeQueueStatus, noteMergeJob, waitNextMergeJob } from "../services/merge-queue.js";
16
+ import { archiveProject, prepareProjectArchive, getProjectStatus, migrateProjectIds, registerProject, resolveProject } from "../services/projects.js";
17
+ import { cancelProtocol, getProtocolBlockers, getProtocolStatus, getReadyProtocols, implementProtocol, readyForMerge, registerProtocol, prepareProtocolRegistration, requireProtocol, syncProtocolFromRun, prepareProtocolTransition, transitionProtocol } from "../services/protocols.js";
18
+ import { getPlanStatus, preparePlanItemMutation, updatePlanItem } from "../services/plans.js";
19
+ import { cancelMergeQueueJob, prepareMergeQueueCancellation, prepareMergeQueueWait, prepareMergeClaim, prepareMergeBundleClaim, claimNextMergeJob, claimMergeJob, claimMergeBundle, completeMergeBundle, prepareMergeBundleCompletion, completeMergeJob, prepareMergeJobCompletion, failMergeBundle, prepareMergeBundleFailure, failMergeJob, prepareMergeJobFailure, getMergeBundleStatus, getMergeQueueStatus, noteMergeJob, prepareMergeJobNote, waitNextMergeJob } from "../services/merge-queue.js";
11
20
  import { getMergeWorkerStatus, oneShotMergeClaim, startMergeWorker, stopProjectMergeWorker } from "../services/merge-worker.js";
12
- import { cleanupApply, cleanupScan } from "../services/cleanup.js";
13
- import { getCodexHomeStatus, getCodexHooksStatus, handleCodexHook, handleAgyEvent, handleGrokEvent, handleOpenCodeEvent, handleZcodeEvent, isolatedDdFlowHomeFromHookStdin, claimBootstrapHookEvent, findRecentMatchingHookEvent, stageStartMatchKey, initCodexHome, installCodexHooks, planCodexHome, printCodexHomeEnv, printCodexHooks, removeCodexHome, removeCodexHooks } from "../services/hooks.js";
14
- import { bootstrapWorktree, closeWorktree, createWorktreeRecord, getWorktreeStatus, planWorktree } from "../services/worktrees.js";
15
- import { acquireLaneLock, cancelLaneWaiter, checkLaneWorkspace, getLaneWaiters, getLaneStatus, heartbeatLaneLock, releaseLaneLock, setLaneWorkspace, waitAcquireLaneLock, waitForLaneLock } from "../services/lanes.js";
16
- import { getProjectConfigStatus, setProjectConfigValue } from "../services/config.js";
17
- import { getCanonStatus, registerCanonRoot, resolveCanonRoot } from "../services/canon.js";
21
+ import { cleanupApply, cleanupScan, prepareCleanupApply } from "../services/cleanup.js";
22
+ import { getCodexHomeStatus, getCodexHooksStatus, handleCodexHook, handleAgyEvent, handleDroidEvent, handleGrokEvent, handleOpenCodeEvent, handleZcodeHook, handleZcodeEvent, isolatedDdFlowHomeFromHookStdin, claimBootstrapHookEvent, findRecentMatchingHookEvent, stageStartMatchKey, initCodexHome, prepareCodexHome, prepareCodexHooks, installCodexHooks, planCodexHome, printCodexHomeEnv, printCodexHooks, removeCodexHome, prepareCodexHomeRemoval, removeCodexHooks } from "../services/hooks.js";
23
+ import { bootstrapWorktree, closeWorktree, createWorktreeRecord, prepareWorktreeCreate, prepareWorktreeBootstrap, prepareWorktreeClose, getWorktreeStatus, planWorktree } from "../services/worktrees.js";
24
+ import { acquireLaneLock, cancelLaneWaiter, prepareLaneWaiterCancellation, checkLaneWorkspace, getLaneWaiters, getLaneStatus, heartbeatLaneLock, releaseLaneLock, setLaneWorkspace, prepareLaneWorkspace, prepareLaneLock, waitAcquireLaneLock, waitForLaneLock } from "../services/lanes.js";
25
+ import { getProjectConfigStatus, prepareProjectConfigValue, setProjectConfigValue } from "../services/config.js";
26
+ import { getCanonStatus, registerCanonRoot, resolveCanonRoot, prepareCanonRegistration } from "../services/canon.js";
18
27
  import { getRuntimeStatus } from "../services/status.js";
19
28
  import { getCliVersionReport } from "../services/build-info.js";
20
29
  import { parseCommandArgs } from "../services/lifecycle-command.js";
21
- import { autoRefreshDashboards, dashboardData, getCmuxStatus, openDashboard, openGlobalDashboard, openProtocolDashboard, refreshAllDashboards, refreshDashboard, refreshGlobalDashboard, renderDashboard, renderGlobalDashboard } from "../services/dashboard.js";
30
+ import { prepareError, prepareJsonFile, prepareJsonSchema, prepareJsonText, prepareTextFile } from "./input-preparation.js";
31
+ import { autoRefreshDashboards, dashboardData, getCmuxStatus, openDashboard, openGlobalDashboard, openProtocolDashboard, refreshAllDashboards, prepareDashboardRefresh, prepareDashboardRender, prepareGlobalDashboardRender, prepareDashboardOptions, refreshDashboard, refreshGlobalDashboard, renderDashboard, renderGlobalDashboard } from "../services/dashboard.js";
22
32
  import { dashboardTargetSummary, preferredDashboardCommand, relatedDashboardCommands, resolveDashboardTarget } from "../services/dashboard-targets.js";
23
- import { getFlowSessionStatus, registerFlowSession, stopFlowSession, stopMergeWorker, syncFlowSessionUsage } from "../services/sessions.js";
33
+ import { getFlowSessionStatus, prepareFlowSessionPayload, registerFlowSession, stopFlowSession, stopMergeWorker, syncFlowSessionUsage } from "../services/sessions.js";
24
34
  import { getProtocolBranchContext } from "../services/branch-context.js";
25
- import { attachFlowRunStage, completeFlowRun, completeFlowRunStage, getFlowRunSessions, getFlowRunTimeline, getStoredFlowRunUsage, getFlowRunFlagsStatus, getFlowRunStatus, getFlowRunConfig, getFlowRunVariables, listFlowRuns, reviseFlowRunFlags, setFlowRunConfig, setFlowRunVariable, startFlowRun } from "../services/runs.js";
35
+ import { attachFlowRunStage, prepareFlowRunStageAttachment, prepareFlowRunStageCompletion, completeFlowRun, prepareFlowRunCompletion, completeFlowRunStage, getFlowRunSessions, getFlowRunTimeline, getStoredFlowRunUsage, getFlowRunFlagsStatus, getFlowRunStatus, getFlowRunConfig, getFlowRunVariables, listFlowRuns, reviseFlowRunFlags, setFlowRunConfig, prepareFlowRunConfig, prepareFlowRunVariable, setFlowRunVariable, startFlowRun, prepareFlowRunStart } from "../services/runs.js";
26
36
  import { previewNextEntityId } from "../services/ids.js";
27
37
  import { validateSchema } from "../services/schema-validation.js";
28
38
  import { preflightMemoryPermissions } from "../services/memory-permissions.js";
29
- import { ingestAgyUsage, ingestGrokUsage, ingestOpenCodeUsage, ingestZcodeUsage } from "../services/usage.js";
30
- import { applyMigration, assessMigrationImpact, assertUpgradeRunStorageReady, planMigration, verifyMigrationReport } from "../services/migrations.js";
39
+ import { ingestDroidUsage, ingestAgyUsage, ingestGrokUsage, ingestOpenCodeUsage, ingestZcodeUsage } from "../services/usage.js";
40
+ import { applyMigration, assessMigrationImpact, assertUpgradeRunStorageReady, planMigration, prepareMigrationApply, verifyMigrationReport } from "../services/migrations.js";
31
41
  import { publishProjectSummary } from "../services/project-summary.js";
32
42
  import { requireProjectByRoot } from "../services/projects.js";
33
43
  import { resolveProjectRoot } from "../storage/paths.js";
34
- import { doctorEngines, bindRunEngine, engineInfo, installCurrentEngine, listEngines, resolveEngine, resolveExplicitProjectRoot, resolveOperationProjectRoot, routeArgsThroughEngine } from "../services/engines.js";
44
+ import { doctorEngines, bindRunEngine, prepareRunEngineBind, engineInfo, installCurrentEngine, listEngines, resolveEngine, resolveExplicitProjectRoot, resolveOperationProjectRoot, routeArgsThroughEngine } from "../services/engines.js";
35
45
  import { preflightCliCompatibility } from "../services/compatibility-preflight.js";
36
- import { finishVnextSpecifyStage, getVnextWorkStatus, isVnextSpecifyFlow, isVnextSpecifyRun, launchVnextSpecify } from "../services/vnext-specify.js";
37
- import { finishVnextProtocolize, isVnextProtocolizeRun, startVnextProtocolize } from "../services/vnext-protocolize.js";
38
- import { finishVnextPlan, isVnextPlanRun, startVnextPlan } from "../services/vnext-plan.js";
39
- import { dispatchVnextPlanReview, finishVnextPlanReview, isVnextPlanReviewRun, recordVnextPlanReviewCapacity, startVnextPlanReview } from "../services/vnext-plan-review.js";
40
- import { addVnextCodeRepair, finishVnextCode, startVnextCode } from "../services/vnext-code.js";
41
- import { addVnextCodeReviewRepair, finishVnextCodeReview, isVnextCodeReviewRun, startVnextCodeReview } from "../services/vnext-code-review.js";
42
- import { applyVnextMerge, finishVnextMerge, getVnextMergeRequest, isVnextMergeRun, routeVnextMergeRequest, startVnextMerge } from "../services/vnext-merge.js";
46
+ import { finishVnextSpecifyStage, getVnextWorkStatus, isVnextSpecifyFlow, isVnextSpecifyRun, launchVnextSpecify, prepareVnextSpecifyStart } from "../services/vnext-specify.js";
47
+ import { finishVnextProtocolize, isVnextProtocolizeRun, prepareProtocolizeResultPath, prepareVnextProtocolizeStart, startVnextProtocolize } from "../services/vnext-protocolize.js";
48
+ import { finishVnextPlan, isVnextPlanRun, startVnextPlan, prepareVnextPlanStart, prepareVnextPlanFinish } from "../services/vnext-plan.js";
49
+ import { dispatchVnextPlanReview, finishVnextPlanReview, isVnextPlanReviewRun, prepareVnextPlanReviewStart, recordVnextPlanReviewCapacity, startVnextPlanReview } from "../services/vnext-plan-review.js";
50
+ import { addVnextCodeRepair, finishVnextCode, prepareVnextCodeRepair, prepareVnextCodeStart, startVnextCode } from "../services/vnext-code.js";
51
+ import { finishVnextCodeReview, isVnextCodeReviewRun, prepareCodeReviewDecision, prepareVnextCodeReviewRepair, prepareVnextCodeReviewStart, startVnextCodeReview } from "../services/vnext-code-review.js";
52
+ import { applyVnextMerge, finishVnextMerge, getVnextMergeRequest, isVnextMergeRun, prepareVnextMergeFinish, prepareVnextMergeStart, repairVnextMerge, routeVnextMergeRequest, startVnextMerge } from "../services/vnext-merge.js";
43
53
  import { mergeServerStatus, serveMergeRequests, stopMergeServer } from "../services/merge-server.js";
44
- import { getVnextFanoutStatus } from "../services/vnext-fanout.js";
45
- import { pauseStageForUser, resumeStageAfterUser } from "../services/stage-pause.js";
46
- import { blockStageForRuntime, unblockStageAfterRuntimeRepair } from "../services/stage-blocker.js";
54
+ import { getVnextFanoutStatus, observeVnextNativeChildren, prepareNativeObservations, reconcileVnextFanout } from "../services/vnext-fanout.js";
55
+ import { pauseStageForUser, resumeStageAfterUser, prepareStagePause, prepareStageResume } from "../services/stage-pause.js";
56
+ import { blockStageForRuntime, unblockStageAfterRuntimeRepair, prepareStageRuntimeBlock, prepareStageRuntimeUnblock } from "../services/stage-blocker.js";
47
57
  import { classifyCliOperation, requiresExplicitUpgradeAuthorization } from "../services/cli-operation-classifier.js";
48
- import { renderWorkerPrompt } from "../services/prompts.js";
49
- import { finishStage, startStage } from "../services/stage-lifecycle.js";
50
- import { addWorkBatch, cancelWork, deleteWork, failWork, finishWork, listWorks, mutateWorkDeps, retryWork, showWork, startWork } from "../services/work-registry.js";
51
- import { createEvalBootstrapSnapshot, createEvalRunSnapshot, prepareVnextSpecifyRun, restoreEvalBootstrapSnapshot, restoreEvalRunSnapshot } from "../services/eval-snapshots.js";
52
- import { loadExternalStageContext } from "../services/stage-context.js";
53
- import { confirmManagedProcess, finishManagedProcess, heartbeatManagedProcess, managedProcessStatus, reconcileExpiredManagedProcesses, registerManagedProcess } from "../services/managed-processes.js";
58
+ import { prepareWorkerPrompt, renderWorkerPrompt } from "../services/prompts.js";
59
+ import { finishStage, prepareStageFinish, startStage, prepareLegacyStageStart } from "../services/stage-lifecycle.js";
60
+ import { addWorkBatch, prepareWorkBatch, prepareWorkDeps, prepareWorkDelete, prepareWorkSettlement, prepareWorkRetry, assertStageLifecycleOwner, assertWorkLifecycleOwner, cancelWork, deleteWork, failWork, finishWork, listWorks, mutateWorkDeps, prepareWorkResult, retryWork, showWork, startWork } from "../services/work-registry.js";
61
+ import { launchExternalWork } from "../services/external-work-launch.js";
62
+ import { createEvalBootstrapSnapshot, prepareEvalBootstrapSnapshot, createEvalRunSnapshot, prepareEvalRunSnapshotCreation, prepareVnextSpecifyRun, prepareEvalRunRestore, prepareEvalBootstrapRestore, restoreEvalBootstrapSnapshot, restoreEvalRunSnapshot } from "../services/eval-snapshots.js";
63
+ import { forkRunFromSnapshot, prepareRunFork } from "../services/run-fork.js";
64
+ import { acceptRunRecovery, assertRunMutationAllowed, beginRunRecovery, inspectRunRecovery, prepareRecoveryCapture, prepareRecoveryPayload, prepareRunRecoveryResume, recordRecoveryCapture, recoveryGuard, resumeRunRecovery, sealRunRecovery } from "../services/run-recovery.js";
65
+ import { recoveryRuntimeAdmission } from "../services/run-recovery-runtime.js";
66
+ import { loadExternalStageContext, prepareExternalStageContext } from "../services/stage-context.js";
67
+ import { vnextStageDirectory } from "../domain/stage-catalog.js";
68
+ import { prepareCommandRoute } from "./command-inputs.js";
69
+ import { parseLifecycleCommand } from "../services/lifecycle-command.js";
70
+ import { prepareManagedProcessRegistration, prepareManagedProcessConfirmation, prepareManagedProcessHeartbeat, prepareManagedProcessFinish, prepareManagedProcessStopOperation, prepareManagedProcessReconcile, stopManagedProcess, confirmManagedProcess, finishManagedProcess, heartbeatManagedProcess, managedProcessRuntimeHome, managedProcessStatus, processIsAlive, reconcileExpiredManagedProcesses, registerManagedProcess } from "../services/managed-processes.js";
71
+ import { fenceRuntimeBudget, runtimeBudgetStatus, admitRuntimeCheck, parseRuntimeBudget, prepareRuntimeScopeControl, prepareRuntimeScopeFence, reserveProviderTurn, releaseProviderTurns, prepareProviderTurnRelease } from "../services/runtime-budget.js";
72
+ import { stopRuntimeScope } from "../services/runtime-scope-stop.js";
73
+ import { launchRuntimeScopeControl, launchRuntimeScopeResume, prepareRuntimeScopeReconciliation, prepareRuntimeScopeServing, reconcileRuntimeScopeControl, serveRuntimeScopeControl } from "../services/runtime-scope-worker.js";
74
+ import { prepareRuntimeScopeResumeRequest } from "../services/runtime-scope-resume.js";
75
+ import { launchRunController, prepareRunControllerLaunch, resumeRunController, serveRunController, runControllerStatus, answerRunController, prepareRunControllerAnswer, supplyRunControllerContext, prepareRunControllerContext } from "../services/run-controller.js";
76
+ import { controllerHitlAdmission } from "../services/run-controller-adapter.js";
77
+ import { controlLifecycleReply, runControlStatus } from "../services/run-control.js";
78
+ import { reconcileRunControl, requestRunControl, serveRunControl } from "../services/run-control-worker.js";
79
+ import { startRuntimeService, prepareRuntimeService } from "../services/runtime-service.js";
54
80
  const defaultIo = {
55
81
  stdout: process.stdout,
56
82
  stderr: process.stderr,
@@ -58,9 +84,20 @@ const defaultIo = {
58
84
  };
59
85
  const flagValue = "__dd_flow_flag__";
60
86
  export async function runCli(args, io = defaultIo, env = process.env) {
61
- const output = parseOutputOptions(args);
87
+ let output;
88
+ try {
89
+ output = parseOutputOptions(args);
90
+ }
91
+ catch (error) {
92
+ const message = error instanceof Error ? error.message : String(error);
93
+ writeJson(io.stderr, { ok: false, error: { code: "usage", message } });
94
+ return 2;
95
+ }
62
96
  const progress = progressForCommand(output.args);
63
97
  let heartbeat;
98
+ let invocationSettlement;
99
+ let settleHook;
100
+ let diagnosticHome;
64
101
  try {
65
102
  if (output.args.length === 1 && output.args[0] === "--version") {
66
103
  const payload = getCliVersionReport();
@@ -75,6 +112,16 @@ export async function runCli(args, io = defaultIo, env = process.env) {
75
112
  io.stdout.write(`${help}\n`);
76
113
  return 0;
77
114
  }
115
+ const suppliedInvocationId = optionalOption(parseArgs(output.args.slice(2)), "invocation-id");
116
+ if (output.args[0] === "run" && ["drive", "control"].includes(output.args[1] ?? "")) {
117
+ const controlArgs = parseArgs(output.args.slice(2));
118
+ requiredOption(controlArgs, "run");
119
+ requiredOption(controlArgs, "project-root");
120
+ }
121
+ if (io.stdin?.isTTY && ["work", "stage"].includes(output.args[0] ?? "") && output.args[1] === "finish"
122
+ && hasOption(parseArgs(output.args.slice(2)), "result-stdin")) {
123
+ throw new AppError("usage", "--result-stdin requires non-interactive input. Pipe or redirect the complete JSON into this command, or use --result-file; interactive terminals can truncate long JSON and wait indefinitely for EOF.", 2);
124
+ }
78
125
  const classification = classifyCliOperation(output.args, env);
79
126
  if (requiresExplicitUpgradeAuthorization(output.args) && classification.mode !== "mb_upgrade") {
80
127
  throw new AppError("upgrade_authorization_required", "This mb-upgrade command requires the explicit mb-upgrade authorization marker and allowlisted target context", 1, {
@@ -83,25 +130,143 @@ export async function runCli(args, io = defaultIo, env = process.env) {
83
130
  });
84
131
  }
85
132
  const routerContext = createRouterContext(env);
133
+ const publicCommand = quote(["dd-flow", ...output.args]);
134
+ const lifecycleCommand = parseLifecycleCommand(publicCommand);
135
+ if (lifecycleCommand.kind === "standalone")
136
+ validateLifecyclePathAliases(output.args, lifecycleCommand.invocation.operation);
137
+ const observedInvocation = observedLifecycleInvocation(routerContext, publicCommand, env.DD_FLOW_DAEMON_ID);
138
+ if (!observedInvocation && !suppliedInvocationId && env.DD_FLOW_DAEMON_ID && lifecycleCommand.kind === "standalone") {
139
+ const diagnostic = observedLifecycleDiagnostic(routerContext, publicCommand, env.DD_FLOW_DAEMON_ID);
140
+ if (diagnostic)
141
+ throw new AppError("lifecycle_shell_syntax_invalid", `Native observer rejected the shell form: ${String(diagnostic.reason ?? "unsupported shell composition")}. Write structured input to a file and run the returned dd-flow command separately.`, 2, { ...diagnostic, phase: "prepare", effect: "no_effect", recoverable: true });
142
+ const nativeEvent = observedLifecycleNativeEvent(routerContext, publicCommand, env.DD_FLOW_DAEMON_ID);
143
+ throw new AppError(nativeEvent ? "invocation_assignment_missing" : "invocation_receipt_missing", nativeEvent ? "Native call was observed, but its arguments do not match an issued lifecycle assignment" : "Managed lifecycle command has no committed native receipt", 1, { effect: "no_effect", recoverable: false });
144
+ }
145
+ const invocationId = observedInvocation?.id ?? suppliedInvocationId;
146
+ let boundInvocationArgs;
147
+ try {
148
+ boundInvocationArgs = observedInvocation
149
+ ? resolveObservedLifecycleArgs(routerContext, observedInvocation.id, output.args)
150
+ : invocationId && invocationId !== suppliedInvocationId
151
+ ? [...output.args.filter((_, index, values) => values[index - 1] !== "--invocation-id" && values[index] !== "--invocation-id"), "--invocation-id", invocationId]
152
+ : output.args;
153
+ }
154
+ catch (error) {
155
+ if (!(observedInvocation && error instanceof AppError))
156
+ throw error;
157
+ const rejectionContext = createContext({ ...env }, "hook");
158
+ try {
159
+ Object.assign(error.details, settleLifecyclePreparationRejection(rejectionContext, observedInvocation.id, error));
160
+ }
161
+ finally {
162
+ rejectionContext.db.close?.();
163
+ }
164
+ throw error;
165
+ }
166
+ const observedOperation = lifecycleCommand.kind === "standalone" ? lifecycleCommand.invocation.operation : null;
167
+ if (observedInvocation && !observedOperation)
168
+ throw new AppError("invocation_command_invalid", "Observed lifecycle command could not be parsed", 1);
169
+ const invocationScope = invocationId ? lifecycleInvocationScope({ ...routerContext, env }, invocationId) : undefined;
170
+ const expandedInvocationArgs = invocationScope && observedOperation
171
+ ? expandLifecycleInvocationArgs(routerContext, boundInvocationArgs, invocationScope, observedOperation)
172
+ : boundInvocationArgs;
173
+ const retainedOutput = observedInvocation ? parseOutputOptions(expandedInvocationArgs) : null;
174
+ if (retainedOutput?.responseFile)
175
+ output.responseFile = retainedOutput.responseFile;
176
+ let invocationArgs = retainedOutput?.args ?? expandedInvocationArgs;
86
177
  emitHumanProgress(io, output, progress, "start");
87
178
  if (output.progressJsonl) {
88
179
  writeProgressJsonl(io, "start", `Starting ${output.args.slice(0, 3).join(" ")}`);
89
180
  heartbeat = setInterval(() => writeProgressJsonl(io, "running", "Command is still running"), 15_000);
90
181
  }
91
- const scopeProjectRoot = resolveProjectRootBeforeRouting(output.args, env);
92
- const routedArgs = output.responseFile ? [...output.args, "--response-file", output.responseFile] : output.args;
182
+ // Route by retained authority, so a mistyped project path reaches the CLI
183
+ // validator instead of selecting a different engine or failing preflight.
184
+ const scopeProjectRoot = invocationScope?.projectRoot ?? resolveCommandProjectRoot(routerContext, output.args, resolveProjectRootBeforeRouting(output.args, env));
185
+ assertAuxiliaryCommandScope({ ...routerContext, env }, publicCommand, scopeProjectRoot);
186
+ invocationArgs = resolveCommandPaths(routerContext, invocationArgs, scopeProjectRoot);
187
+ const routedArgs = output.responseFile ? [...invocationArgs, "--response-file", output.responseFile] : invocationArgs;
93
188
  const routed = await routeArgsThroughEngine(routerContext, output.json ? [...routedArgs, "--json", ...(output.progressJsonl ? ["--progress-jsonl"] : [])] : routedArgs, io, io.stdin, env, scopeProjectRoot);
94
189
  if (routed?.routed && !routed.inProcess) {
95
190
  if (heartbeat)
96
191
  clearInterval(heartbeat);
97
- emitHumanProgress(io, output, progress, "done");
192
+ emitHumanProgress(io, output, progress, routed.exitCode === 0 ? "done" : "failed");
193
+ if (output.progressJsonl && routed.exitCode !== 0)
194
+ writeProgressJsonl(io, "failed", "Routed engine failed", { exit_code: routed.exitCode });
98
195
  return routed.exitCode;
99
196
  }
197
+ let preparedInput;
198
+ let preparedRoute;
199
+ if (!invocationId) {
200
+ const preparationContext = createContext({ ...env }, "read_existing");
201
+ try {
202
+ preparedInput = await prepareCliInput(invocationArgs, preparationContext, io, scopeProjectRoot, output.responseFile);
203
+ }
204
+ finally {
205
+ preparationContext.db.close?.();
206
+ }
207
+ }
100
208
  const dispatchContext = routed?.inProcess
101
- ? createContext({ ...env, DD_FLOW_ENGINE_MODE: "1", DD_FLOW_ENGINE_HOME: "in-process", DD_FLOW_ROUTED_FROM: getCliVersionReport().cli.version }, databaseModeForCommand(output.args, classification))
102
- : createContext(env, databaseModeForCommand(output.args, classification));
103
- preflightCliCompatibility(dispatchContext, output.args, env, scopeProjectRoot);
104
- const result = await dispatch(output.args, dispatchContext, io, scopeProjectRoot, classification, output);
209
+ ? createContext({ ...env, DD_FLOW_ENGINE_MODE: "1", DD_FLOW_ENGINE_HOME: "in-process", DD_FLOW_ROUTED_FROM: getCliVersionReport().cli.version }, databaseModeForCommand(invocationArgs, classification))
210
+ : createContext({ ...env }, databaseModeForCommand(invocationArgs, classification));
211
+ diagnosticHome = dispatchContext.ddFlowHome;
212
+ dispatchContext.env.DD_FLOW_INVOCATION_READONLY = classification.mode === "read_only_diagnostics" ? "1" : undefined;
213
+ let dispatchArgs = invocationArgs;
214
+ let retainedOutcome;
215
+ // Issued transports may deliver their receipt asynchronously. Observe only
216
+ // after admission; retained outcomes must not need a fresh hook receipt.
217
+ if (invocationId) {
218
+ const command = quote(["dd-flow", ...invocationArgs]);
219
+ const admission = await awaitLifecycleInvocation(dispatchContext, { id: invocationId, command,
220
+ validateArgs: () => {
221
+ try {
222
+ preparedRoute = prepareCommandRoute(invocationArgs);
223
+ }
224
+ catch (error) {
225
+ if (error instanceof AppError && error.code === "usage" && ["invocation-id", "hook-event-id"].includes(String(error.details.parameter ?? ""))) {
226
+ throw new AppError("lifecycle_contract_invalid", `The runtime generated arguments rejected by its own CLI contract: ${error.message}`, 1, { ...error.details, recoverable: false, operation: observedOperation });
227
+ }
228
+ throw error;
229
+ }
230
+ },
231
+ prepare: async () => { preparedInput = await prepareCliInput(invocationArgs, dispatchContext, io, scopeProjectRoot, output.responseFile, preparedRoute); },
232
+ assertCurrent: scope => assertLifecycleInvocationCurrent(dispatchContext, scope, command) });
233
+ if (admission.replay) {
234
+ retainedOutcome = admission.outcome;
235
+ settleHook = undefined;
236
+ delete dispatchContext.observeLifecycleHook;
237
+ }
238
+ else {
239
+ invocationSettlement = { context: dispatchContext, id: invocationId };
240
+ dispatchArgs = [...invocationArgs, "--hook-event-id", admission.eventKey];
241
+ preparedInput?.route?.parsed.options.set("hook-event-id", [admission.eventKey]);
242
+ dispatchContext.env.DD_FLOW_INVOCATION_SCOPE = JSON.stringify(lifecycleInvocationScope(dispatchContext, invocationId));
243
+ dispatchContext.env.DD_FLOW_CURRENT_INVOCATION = invocationId;
244
+ }
245
+ }
246
+ if (retainedOutcome?.error) {
247
+ const error = retainedOutcome.error;
248
+ throw new AppError(error.code, error.message, error.exitCode, error.details);
249
+ }
250
+ if (!retainedOutcome && !preparedInput)
251
+ preparedInput = await prepareCliInput(invocationArgs, dispatchContext, io, scopeProjectRoot, output.responseFile);
252
+ if (!retainedOutcome)
253
+ preflightCliCompatibility(dispatchContext, invocationArgs, env, scopeProjectRoot);
254
+ if (!retainedOutcome) {
255
+ const command = lifecycleCommand.kind === "none" ? publicCommand : quote(["dd-flow", ...dispatchArgs]);
256
+ const event = lifecycleCommand.kind === "none" && env.DD_FLOW_DAEMON_ID ? observedLifecycleNativeEvent(dispatchContext, command, env.DD_FLOW_DAEMON_ID) : null;
257
+ settleHook = observeLifecycleCommand(dispatchContext, command, event ?? undefined);
258
+ }
259
+ const result = retainedOutcome ? retainedOutcome.result : await dispatch(dispatchArgs, dispatchContext, io, scopeProjectRoot, classification, output, preparedInput);
260
+ const completedHook = settleHook;
261
+ settleHook = undefined;
262
+ completedHook?.({ result });
263
+ if (invocationSettlement) {
264
+ const completed = invocationSettlement;
265
+ invocationSettlement = undefined;
266
+ // A failure to persist an already completed result is an unknown reply,
267
+ // not a failed operation eligible for a new productive retry.
268
+ settleLifecycleInvocation(completed.context, completed.id, { result });
269
+ }
105
270
  const refreshWarnings = refreshDashboardsAfterMutation(dispatchContext, output.args, result, scopeProjectRoot);
106
271
  const resultWithWarnings = addWarnings(result, refreshWarnings);
107
272
  if (heartbeat)
@@ -117,17 +282,76 @@ export async function runCli(args, io = defaultIo, env = process.env) {
117
282
  io.stdout.write(renderHumanResult(output.args, payload));
118
283
  return completedCommandExitCode(payload);
119
284
  }
120
- catch (error) {
285
+ catch (caught) {
286
+ const error = isAppError(caught) ? caught : new AppError("unexpected", caught instanceof Error ? caught.message : String(caught), 1, { effect: "unknown", cause: { code: caught?.code ?? null, sqlite_extended_code: caught?.errcode ?? null } });
287
+ if (!settleHook && !invocationSettlement && env.DD_FLOW_DAEMON_ID) {
288
+ let earlyContext;
289
+ try {
290
+ const command = quote(["dd-flow", ...output.args]);
291
+ const event = observedLifecycleNativeEvent(createRouterContext(env), command, env.DD_FLOW_DAEMON_ID);
292
+ if (event) {
293
+ earlyContext = createContext({ ...env }, "hook");
294
+ observeLifecycleCommand(earlyContext, command, event)({ error });
295
+ }
296
+ }
297
+ catch (persistence) {
298
+ error.details.lifecycle_diagnostic_error = String(persistence);
299
+ }
300
+ finally {
301
+ earlyContext?.db.close?.();
302
+ }
303
+ }
304
+ if (diagnosticHome && (!isAppError(caught) || error.code === "storage_write_failed")) {
305
+ try {
306
+ const directory = path.join(diagnosticHome, "diagnostics", "cli");
307
+ fs.mkdirSync(directory, { recursive: true });
308
+ const artifact = path.join(directory, `${randomUUID()}.json`);
309
+ fs.writeFileSync(artifact, JSON.stringify({ code: error.code, message: error.message, details: error.details, stack: caught instanceof Error ? caught.stack : null }), { flag: "wx", mode: 0o600 });
310
+ error.details.diagnostic_artifact = artifact;
311
+ }
312
+ catch (secondary) {
313
+ io.stderr.write(`CLI diagnostic persistence failed: ${String(secondary)}\n`);
314
+ }
315
+ }
121
316
  if (heartbeat)
122
317
  clearInterval(heartbeat);
318
+ if (invocationSettlement && error.details.effect !== "committed") {
319
+ try {
320
+ if (isAppError(error))
321
+ settleLifecycleRejection(invocationSettlement.context, invocationSettlement.id, { code: error.code, message: error.message, exitCode: error.exitCode, details: error.details });
322
+ else
323
+ settleLifecycleInvocation(invocationSettlement.context, invocationSettlement.id, { error: { code: "unexpected", message: String(error), exitCode: 1, details: {} } });
324
+ }
325
+ catch (persistenceError) {
326
+ io.stderr.write(`Invocation settlement persistence failed: ${String(persistenceError)}\n`);
327
+ }
328
+ }
329
+ if (settleHook) {
330
+ try {
331
+ settleHook({ error: isAppError(error) ? error : { code: "unexpected", message: String(error), details: {} } });
332
+ }
333
+ catch (persistence) {
334
+ io.stderr.write(`${JSON.stringify({ primary: String(error), lifecycle_persistence_error: String(persistence) })}\n`);
335
+ }
336
+ }
123
337
  const payload = isAppError(error)
124
338
  ? { ok: false, error: { code: error.code, message: error.message, details: error.details } }
125
339
  : { ok: false, error: { code: "unexpected", message: String(error) } };
340
+ progress.splice(0, progress.length, ...progress.filter(event => event.phase !== "done"));
341
+ if (progress.length)
342
+ progress.push({ phase: "failed", message: payload.error.message, at: new Date().toISOString() });
126
343
  emitHumanProgress(io, output, progress, "failed");
127
344
  if (output.progressJsonl)
128
345
  writeProgressJsonl(io, "failed", payload.error.message, { code: payload.error.code });
129
346
  const errorPayload = attachProgress(payload, progress, output);
130
- const visible = writeResponseFile(errorPayload, output);
347
+ let visible = errorPayload;
348
+ try {
349
+ if (error.details.parameter !== "response-file")
350
+ visible = writeResponseFile(errorPayload, output);
351
+ }
352
+ catch (publication) {
353
+ error.details.response_publication_error = { code: publication?.code ?? "response_publication_failed", message: publication instanceof Error ? publication.message : String(publication) };
354
+ }
131
355
  if (output.json && output.progressJsonl)
132
356
  writeJson(io.stdout, errorPayload);
133
357
  else if (output.json)
@@ -151,7 +375,22 @@ function resolveProjectRootBeforeRouting(args, env) {
151
375
  }
152
376
  function databaseModeForCommand(args, classification) {
153
377
  const [family, command] = args;
378
+ // Managed attempts are issued only from a prepared store. Opening that
379
+ // existing writer must not run migrations before their input is admitted.
380
+ if (parseArgs(args.slice(2)).options.has("invocation-id"))
381
+ return "hook";
382
+ // Native hook ingress must remain synchronous, but it must not run schema
383
+ // migration/VACUUM while the provider is waiting for its decision. Startup
384
+ // prepares the store; the hook mode only verifies the prepared contract and
385
+ // records the receipt.
386
+ if (family === "codex" && command === "hook" && args[2] === "handle") {
387
+ // Only the participating PreToolUse ingress needs the prepared hot-path
388
+ // contract. SessionStart/Stop/PostToolUse are observational no-ops here
389
+ // and retain the ordinary startup path for backwards compatibility.
390
+ return optionalOption(parseArgs(args.slice(3)), "event") === "PreToolUse" ? "hook" : "initialize";
391
+ }
154
392
  if (family === "engine" ||
393
+ family === "storage" && command === "migrate-writer" ||
155
394
  family === "version" ||
156
395
  family === "schema" ||
157
396
  family === "canon" && command === "resolve" ||
@@ -207,8 +446,10 @@ function parseOutputOptions(args) {
207
446
  continue;
208
447
  }
209
448
  if (arg === "--response-file") {
449
+ if (responseFile !== null)
450
+ throw new AppError("usage", "--response-file may be supplied only once", 2);
210
451
  const file = args[++index];
211
- if (!file)
452
+ if (!file?.trim() || file.startsWith("--"))
212
453
  throw new AppError("usage", "--response-file requires a path", 2);
213
454
  responseFile = file;
214
455
  continue;
@@ -220,6 +461,33 @@ function parseOutputOptions(args) {
220
461
  const hookJsonOnly = stripped[0] === "codex" && stripped[1] === "hook" && stripped[2] === "handle";
221
462
  return { json: json || hookJsonOnly, progressJsonl, args: stripped, hookJsonOnly, responseFile };
222
463
  }
464
+ /** Validate the response destination without creating it. The response is an
465
+ * optional publication, but a known-bad destination should never be found
466
+ * only after a successful lifecycle mutation. */
467
+ function prepareResponseDestination(value) {
468
+ const file = path.resolve(value);
469
+ const parent = path.dirname(file);
470
+ try {
471
+ let ancestor = parent;
472
+ for (;;) {
473
+ try {
474
+ if (!fs.statSync(ancestor).isDirectory())
475
+ throw new AppError("response_file_parent_invalid", "--response-file parent must be a directory", 2, { file, parent });
476
+ break;
477
+ }
478
+ catch (error) {
479
+ if (error.code !== "ENOENT" || path.dirname(ancestor) === ancestor)
480
+ throw error;
481
+ ancestor = path.dirname(ancestor);
482
+ }
483
+ }
484
+ if (fs.existsSync(file) && !fs.statSync(file).isFile())
485
+ throw new AppError("response_file_invalid", "--response-file must name a regular file", 2, { file });
486
+ }
487
+ catch (error) {
488
+ return prepareError(error, { parameter: "response-file", file, parent });
489
+ }
490
+ }
223
491
  /** Persist the complete machine response for harnesses that cap tool output.
224
492
  * The visible response keeps routing fields but omits the potentially large
225
493
  * rendered prompt; an agent can safely read the named file without rerunning
@@ -500,27 +768,650 @@ function stringValue(value) {
500
768
  function shortSha(value) {
501
769
  return value ? value.slice(0, 12) : "unknown";
502
770
  }
503
- async function dispatch(args, context, io, scopeProjectRoot = null, classification = classifyCliOperation(args, context.env), output = parseOutputOptions(args)) {
504
- const [family, command, ...rest] = args;
505
- const parsed = parseArgs(rest);
771
+ /** All caller supplied file/stdin data is consumed here, before a managed
772
+ * invocation is allowed to claim execution or a stage claims its hook event. */
773
+ async function prepareCliInput(...args) {
774
+ try {
775
+ return await prepareCliInputValue(...args);
776
+ }
777
+ catch (error) {
778
+ return prepareError(error);
779
+ }
780
+ }
781
+ async function prepareCliInputValue(args, context, io, scopeProjectRoot, responseFile = null, route = prepareCommandRoute(args)) {
782
+ const { family, command, parsed } = route;
783
+ const prepared = { route };
784
+ if (optionalOption(parsed, "reason-file")) {
785
+ const value = prepareJsonFile(requiredOption(parsed, "reason-file"), "Check recovery evidence").value;
786
+ if (!value || typeof value.reason !== "string" || !value.reason.trim() || Object.keys(value).some(key => key !== "reason"))
787
+ throw new AppError("validation", "Recovery evidence must be a JSON object with one nonempty reason", 2);
788
+ prepared.retryReason = value.reason;
789
+ }
790
+ else if (optionalOption(parsed, "retry-check"))
791
+ prepared.retryReason = optionalOption(parsed, "reason");
792
+ if (route.key === "project register")
793
+ resolveProjectRoot(requiredOption(parsed, "root"));
794
+ if (route.key === "project archive")
795
+ prepareProjectArchive(context, { idOrAlias: parsed.positional[0], root: optionalOption(parsed, "root"), reason: requiredOption(parsed, "reason") });
796
+ if (route.key === "protocol register")
797
+ prepareProtocolRegistration(context, { handshakeId: requiredPosition(parsed, 0, "handshake-id"), projectRoot: requiredOption(parsed, "project-root"), workspacePath: optionalOption(parsed, "workspace-path") });
798
+ if (route.key === "canon register")
799
+ prepared.canonRegistration = prepareCanonRegistration(context, { root: requiredOption(parsed, "root") });
800
+ if (route.key === "run attach-stage")
801
+ prepareFlowRunStageAttachment(context, stageAttachmentInput(parsed));
802
+ if (route.key === "run complete-stage")
803
+ prepareFlowRunStageCompletion(context, stageCompletionInput(parsed));
804
+ if (route.key === "run override")
805
+ prepareFlowRunCompletion(context, runOverrideInput(parsed));
806
+ if (route.key === "engine bind-run")
807
+ prepared.engineBind = prepareRunEngineBind(context, engineBindInput(parsed));
808
+ if (route.key === "worktree create")
809
+ prepared.worktreeCreate = prepareWorktreeCreate(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "worktree create"), branch: requiredOption(parsed, "branch"), base: requiredOption(parsed, "base"), path: requiredOption(parsed, "path") });
810
+ if (route.key === "worktree bootstrap")
811
+ prepared.worktreeBootstrap = prepareWorktreeBootstrap(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "worktree bootstrap") });
812
+ if (route.key === "worktree close")
813
+ prepareWorktreeClose(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "worktree close"), mode: requiredOption(parsed, "mode") });
814
+ if (route.key.startsWith("plan item "))
815
+ preparePlanItemMutation(context, planItemInput(parsed, requiredScopeProjectRoot(scopeProjectRoot, route.key)));
816
+ if (route.key === "lane workspace set")
817
+ prepareLaneWorkspace(context, laneWorkspaceInput(parsed));
818
+ if (route.key === "lane waiter cancel")
819
+ prepareLaneWaiterCancellation(context, laneWaiterCancelInput(parsed));
820
+ if (route.key === "merge-queue complete")
821
+ prepareMergeJobCompletion(context, { ...mergeJobTarget(parsed, scopeProjectRoot), summary: requiredOption(parsed, "summary") });
822
+ if (route.key === "merge-queue cancel")
823
+ prepareMergeQueueCancellation(context, mergeCancellationInput(parsed, scopeProjectRoot));
824
+ if (route.key === "merge-queue wait-next")
825
+ prepareMergeQueueWait(context, mergeWaitInput(parsed, scopeProjectRoot));
826
+ if (route.key === "merge-queue next" || route.key === "merge-queue claim")
827
+ prepareMergeClaim(context, { projectRoot: requiredOptionOrScope(parsed, scopeProjectRoot, "project-root"), workerId: requiredWorkerId(parsed), workspacePath: workspacePathOption(parsed), ...(route.key === "merge-queue claim" ? { protocolId: requiredPosition(parsed, 0, "protocol-id") } : {}) });
828
+ if (route.key === "merge-queue note")
829
+ prepareMergeJobNote(context, { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue note"), workerId: requiredWorkerId(parsed), summary: requiredOption(parsed, "summary") });
830
+ if (route.key === "merge bundle complete")
831
+ prepareMergeBundleCompletion(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed), summary: requiredOption(parsed, "summary") });
832
+ if (route.key === "merge bundle claim")
833
+ prepareMergeBundleClaim(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed) });
834
+ if (route.key === "merge bundle fail")
835
+ prepareMergeBundleFailure(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed), reason: requiredOption(parsed, "reason"), requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue") });
836
+ if (route.key === "merge-queue fail")
837
+ prepareMergeJobFailure(context, { ...mergeJobTarget(parsed, scopeProjectRoot), reason: requiredOption(parsed, "reason"), requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue") });
838
+ if (route.key.startsWith("lane lock ") && route.key !== "lane lock status") {
839
+ const action = requiredPosition(parsed, 0, "lane lock action");
840
+ prepareLaneLock(context, {
841
+ projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workerId: requiredOption(parsed, "worker-id"),
842
+ workspacePath: workspacePathOption(parsed), leaseToken: optionalOption(parsed, "lease-token"), reason: optionalOption(parsed, "reason"),
843
+ ttlSeconds: optionalNumber(parsed, "ttl"), timeoutSeconds: optionalNumber(parsed, "timeout"), pollIntervalSeconds: optionalNumber(parsed, "poll-interval")
844
+ }, action);
845
+ }
846
+ if (route.key === "run recovery begin")
847
+ prepared.recoveryPayload = prepareRecoveryPayload(requiredOption(parsed, "interruption-json"), "interruption");
848
+ if (route.key === "run recovery seal")
849
+ prepared.recoveryPayload = prepareRecoveryPayload(requiredOption(parsed, "settlement-json"), "settlement");
850
+ if (route.key === "run recovery capture")
851
+ prepared.recoveryCapture = prepareRecoveryCapture(context, recoveryCaptureInput(parsed));
852
+ if (route.key === "run recovery resume")
853
+ prepared.recoveryResume = prepareRunRecoveryResume(context, recoveryResumeInput(parsed));
854
+ if (route.key === "run drive answer")
855
+ prepared.controllerAnswer = prepareRunControllerAnswer(context, controllerAnswerInput(parsed));
856
+ if (route.key === "run drive launch")
857
+ prepared.controllerLaunch = prepareRunControllerLaunch(context, controllerLaunchInput(parsed));
858
+ if (route.key === "run drive context")
859
+ prepared.controllerContext = prepareRunControllerContext(context, controllerContextInput(parsed));
860
+ if (route.key === "protocol transition" || route.key === "transition")
861
+ prepared.protocolTransition = prepareProtocolTransition(context, protocolTransitionInput(parsed, scopeProjectRoot ?? resolveOperationProjectRoot(context, args)));
862
+ if (route.key === "codex home init")
863
+ prepared.codexHome = prepareCodexHome(context, codexHomeInput(parsed));
864
+ if (route.key === "codex home remove")
865
+ prepareCodexHomeRemoval(context, { projectRoot: requiredOption(parsed, "project-root"), profile: optionalOption(parsed, "profile"), mode: requiredOption(parsed, "mode") });
866
+ if (["codex hooks install", "codex hooks remove"].includes(route.key))
867
+ prepared.codexHooks = prepareCodexHooks(context, { projectRoot: requiredOption(parsed, "project-root"), target: optionalOption(parsed, "target"), profile: optionalOption(parsed, "profile"), yes: hasOption(parsed, "yes") });
868
+ if (route.key === "migration apply")
869
+ prepared.migrationApply = prepareMigrationApply(context, migrationApplyInput(parsed, classifyCliOperation(args, context.env)));
870
+ if (route.key === "migration verify")
871
+ prepared.migrationVerification = verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
872
+ if (responseFile)
873
+ prepareResponseDestination(responseFile);
874
+ if (family === "dashboard") {
875
+ const action = dashboardAction(command);
876
+ prepareDashboardOptions({ format: optionalOption(parsed, "format"), viewer: optionalOption(parsed, "viewer"), open: optionalOption(parsed, "open") });
877
+ const target = resolveDashboardTarget(context, { action, project: optionalOption(parsed, "project"), projectRoot: optionalOption(parsed, "project-root"), protocol: optionalOption(parsed, "protocol"), all: hasOption(parsed, "all"), global: hasOption(parsed, "global") || command?.endsWith("-global") });
878
+ if (action === "refresh" && target.kind !== "global" && optionalOption(parsed, "output") !== undefined) {
879
+ throw new AppError("validation", "--output is supported only for global dashboard refresh; use dashboard render for a custom project/protocol output", 2, { parameter: "output" });
880
+ }
881
+ if (target.kind === "protocol")
882
+ requireProtocol(context, target.protocolId, target.project.id);
883
+ if (action !== "data") {
884
+ if (target.kind === "global" || target.kind === "all_projects") {
885
+ prepareGlobalDashboardRender(context, { output: optionalOption(parsed, "output"), format: optionalOption(parsed, "format") ?? (command?.endsWith("-global") ? undefined : "html") });
886
+ }
887
+ else {
888
+ const format = optionalOption(parsed, "format") ?? (action === "open" || hasOption(parsed, "project") ? "html" : undefined);
889
+ const input = { projectRoot: target.project.root, format, ...(target.kind === "protocol" ? { protocol: target.protocolId } : {}) };
890
+ if (action === "refresh")
891
+ prepareDashboardRefresh(context, { ...input, open: optionalOption(parsed, "open") });
892
+ else if (action === "render")
893
+ prepareDashboardRender(context, { ...input, output: optionalOption(parsed, "output") });
894
+ else if (target.kind === "protocol") {
895
+ if (format !== "html")
896
+ throw new AppError("validation", "Protocol dashboard open supports --format html", 2, { protocol: target.protocolId });
897
+ prepareDashboardRender(context, input);
898
+ }
899
+ }
900
+ }
901
+ }
902
+ if (route.key === "prompt render") {
903
+ const input = workerPromptInput(parsed);
904
+ prepared.workerPrompt = { input, value: prepareWorkerPrompt(context, input) };
905
+ }
906
+ if (route.key === "run snapshot restore" || route.key === "run snapshot bootstrap restore") {
907
+ try {
908
+ const input = snapshotRestoreInput(parsed);
909
+ if (route.key === "run snapshot restore")
910
+ prepared.snapshotRestore = prepareEvalRunRestore(context, input);
911
+ else
912
+ prepared.bootstrapRestore = prepareEvalBootstrapRestore(input);
913
+ }
914
+ catch (error) {
915
+ return prepareError(error, { parameter: "snapshot/project-root" });
916
+ }
917
+ }
918
+ if (route.key === "run snapshot bootstrap create") {
919
+ try {
920
+ prepareEvalBootstrapSnapshot(context, { projectRoot: requiredOption(parsed, "project-root"), output: requiredOption(parsed, "output") });
921
+ }
922
+ catch (error) {
923
+ return prepareError(error, { parameter: "project-root/output" });
924
+ }
925
+ }
926
+ if (route.key === "run snapshot create") {
927
+ prepareEvalRunSnapshotCreation(context, snapshotCreateInput(parsed));
928
+ }
929
+ if (route.key === "run start") {
930
+ try {
931
+ const input = runStartInput(parsed);
932
+ prepared.runStart = { input, value: prepareFlowRunStart(context, input) };
933
+ }
934
+ catch (error) {
935
+ return prepareError(error, { parameter: "run start" });
936
+ }
937
+ }
938
+ if (route.key === "run fork") {
939
+ try {
940
+ prepared.runFork = prepareRunFork(runForkInput(parsed));
941
+ }
942
+ catch (error) {
943
+ return prepareError(error, { parameter: "from/output" });
944
+ }
945
+ }
946
+ if (["runtime scope fence", "runtime scope stop"].includes(route.key))
947
+ prepareRuntimeScopeFence(requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id"));
948
+ if (route.key === "runtime scope resume")
949
+ prepareRuntimeScopeResumeRequest(context, runtimeScopeResumeInput(parsed));
950
+ if (route.key === "runtime scope reconcile")
951
+ prepareRuntimeScopeReconciliation(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")), requiredOption(parsed, "request-id"));
952
+ if (route.key === "runtime scope serve")
953
+ prepareRuntimeScopeServing(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")));
954
+ if (route.key === "runtime scope control") {
955
+ try {
956
+ const raw = optionalOption(parsed, "manifest-json");
957
+ prepared.runtimeManifest = prepareRuntimeScopeControl(requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id"), requiredOption(parsed, "mode"), raw === undefined ? undefined : prepareJsonText(raw, { file: "<manifest-json>", label: "scope manifest" }).value, context);
958
+ }
959
+ catch (error) {
960
+ return prepareError(error, { parameter: "scope-id/request-id/manifest-json" });
961
+ }
962
+ }
963
+ if (route.key === "runtime process register") {
964
+ prepareManagedProcessRegistration(context, runtimeProcessRegistrationInput(context, parsed));
965
+ }
966
+ if (route.key === "runtime process heartbeat")
967
+ prepareManagedProcessHeartbeat(context, runtimeProcessHeartbeatInput(parsed));
968
+ if (route.key === "runtime process finish")
969
+ prepareManagedProcessFinish(context, runtimeProcessFinishInput(parsed));
970
+ if (route.key === "runtime process confirm")
971
+ prepareManagedProcessConfirmation(context, runtimeProcessConfirmationInput(parsed));
972
+ if (route.key === "runtime process stop")
973
+ prepareManagedProcessStopOperation(context, runtimeProcessStopInput(parsed));
974
+ if (route.key === "runtime process reconcile")
975
+ prepareManagedProcessReconcile(requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms"));
976
+ if (route.key === "runtime process release-turn") {
977
+ prepared.providerTurnRelease = prepareProviderTurnRelease({ daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") });
978
+ }
979
+ if (route.key === "runtime process start") {
980
+ try {
981
+ prepareRuntimeService(context, runtimeServiceInput(parsed));
982
+ }
983
+ catch (error) {
984
+ return prepareError(error, { parameter: "runtime process start" });
985
+ }
986
+ }
987
+ if (family === "work" && command === "retry") {
988
+ try {
989
+ prepareWorkRetry(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
990
+ }
991
+ catch (error) {
992
+ return prepareError(error, { parameter: "work-id/reason" });
993
+ }
994
+ }
995
+ if (family === "work" && (command === "fail" || command === "cancel")) {
996
+ try {
997
+ prepareWorkSettlement(context, requiredPosition(parsed, 0, "work-id"), command === "fail" ? "failed" : "cancelled", requiredOption(parsed, "reason"));
998
+ }
999
+ catch (error) {
1000
+ return prepareError(error, { parameter: "work-id/reason" });
1001
+ }
1002
+ }
1003
+ if (family === "work" && (command === "deps" || command === "delete")) {
1004
+ try {
1005
+ if (command === "delete")
1006
+ prepareWorkDelete(context, requiredPosition(parsed, 0, "work-id"));
1007
+ else
1008
+ prepareWorkDeps(context, { workId: requiredPosition(parsed, 1, "work-id"), action: requiredPosition(parsed, 0, "action"), on: parsed.options.get("on") ?? [] });
1009
+ }
1010
+ catch (error) {
1011
+ return prepareError(error, { parameter: "work-id/on" });
1012
+ }
1013
+ }
1014
+ if (route.key === "cleanup apply") {
1015
+ const planFile = requiredOption(parsed, "plan-file");
1016
+ try {
1017
+ prepared.cleanup = prepareCleanupApply(context, { projectRoot: requiredOption(parsed, "project-root"), planFile, reason: requiredOption(parsed, "reason"), force: hasOption(parsed, "force") });
1018
+ }
1019
+ catch (error) {
1020
+ return prepareError(error, { parameter: "plan-file", file: planFile });
1021
+ }
1022
+ }
1023
+ if (route.key === "stage block" || route.key === "stage unblock") {
1024
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), workId: requiredOption(parsed, "work") };
1025
+ try {
1026
+ if (route.key === "stage block") {
1027
+ const summaryFile = optionalOption(parsed, "summary-file"), summaryStdin = hasOption(parsed, "summary-stdin");
1028
+ if (Boolean(summaryFile) === summaryStdin)
1029
+ throw new AppError("usage", "stage block requires exactly one of --summary-file or --summary-stdin", 2);
1030
+ prepared.interactionText = summaryFile ? prepareTextFile(summaryFile, "Runtime block summary").text : await readStdin(io.stdin);
1031
+ prepareStageRuntimeBlock(context, { ...input, kind: requiredOption(parsed, "kind"), code: requiredOption(parsed, "code"), summary: prepared.interactionText, retryable: hasOption(parsed, "retryable") });
1032
+ }
1033
+ else
1034
+ prepareStageRuntimeUnblock(context, input);
1035
+ }
1036
+ catch (error) {
1037
+ return prepareError(error, { parameter: "stage/work/summary" });
1038
+ }
1039
+ }
1040
+ if (route.key === "zcode invocation prepare") {
1041
+ const value = prepareJsonText(await readStdin(io.stdin), { file: "<stdin>", label: "invocation issuance" }).value;
1042
+ const payload = value && typeof value === "object" ? value : {};
1043
+ try {
1044
+ prepared.lifecycleIssuance = prepareLifecycleIssuance(payload.command, payload.scope);
1045
+ }
1046
+ catch (error) {
1047
+ if (error instanceof AppError && ["invocation_command_invalid", "invocation_scope_invalid"].includes(error.code))
1048
+ return prepareError(new AppError("usage", error.message, 2, { cause_code: error.code }), { parameter: "stdin" });
1049
+ throw error;
1050
+ }
1051
+ assertLifecycleInvocationCurrent(context, prepared.lifecycleIssuance.scope, prepared.lifecycleIssuance.command);
1052
+ }
1053
+ if (route.key === "work add-batch") {
1054
+ const file = requiredOption(parsed, "file");
1055
+ try {
1056
+ prepared.workBatch = prepareWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file });
1057
+ }
1058
+ catch (error) {
1059
+ return prepareError(error, { parameter: "file/parent", file });
1060
+ }
1061
+ }
1062
+ if (route.key === "work repair add") {
1063
+ const taskFile = optionalOption(parsed, "task-file"), taskStdin = hasOption(parsed, "task-stdin");
1064
+ if (Boolean(taskFile) === taskStdin)
1065
+ throw new AppError("usage", "work repair add requires exactly one of --task-file or --task-stdin", 2);
1066
+ if (taskStdin && io.stdin?.isTTY)
1067
+ throw new AppError("usage", "--task-stdin requires piped or redirected input", 2);
1068
+ const task = taskFile ? prepareTextFile(taskFile, "Repair task").text : await readStdin(io.stdin);
1069
+ prepared.workRepair = prepareCliWorkRepair(context, parsed, task, scopeProjectRoot);
1070
+ }
1071
+ if (route.key === "run config set" || route.key === "run vars set") {
1072
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), key: requiredOption(parsed, "key"), value: requiredOption(parsed, "value") };
1073
+ try {
1074
+ if (route.key === "run config set")
1075
+ prepareFlowRunConfig(context, { ...input, reason: requiredOption(parsed, "reason") });
1076
+ else
1077
+ prepareFlowRunVariable(context, input);
1078
+ }
1079
+ catch (error) {
1080
+ return prepareError(error, { parameter: "run config/vars" });
1081
+ }
1082
+ }
1083
+ if (route.key === "schema validate") {
1084
+ try {
1085
+ prepared.schemaValidation = dispatchSchema(context, command, parsed);
1086
+ }
1087
+ catch (error) {
1088
+ return prepareError(error, { parameter: "file", file: requiredOption(parsed, "file") });
1089
+ }
1090
+ }
1091
+ if (route.key === "project config set") {
1092
+ try {
1093
+ prepareProjectConfigValue(requiredOption(parsed, "key"), requiredOption(parsed, "value"));
1094
+ }
1095
+ catch (error) {
1096
+ return prepareError(error, { parameter: "key/value" });
1097
+ }
1098
+ }
1099
+ if (family === "session" && command === "register") {
1100
+ try {
1101
+ prepared.sessionPayload = prepareFlowSessionPayload({ payloadBase64: optionalOption(parsed, "payload-base64"), payloadFile: optionalOption(parsed, "payload-file"), payloadJson: optionalOption(parsed, "payload-json") });
1102
+ }
1103
+ catch (error) {
1104
+ return prepareError(error, { parameter: "session payload" });
1105
+ }
1106
+ }
1107
+ const run = (projectRoot, runId) => {
1108
+ try {
1109
+ const project = requireProjectByRoot(context, resolveProjectRoot(projectRoot));
1110
+ const row = context.db.get("SELECT run_root, workspace_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, runId]);
1111
+ if (!row)
1112
+ throw new AppError("not_found", "RUN is not registered", 2, { run_id: runId });
1113
+ if (!row.run_root)
1114
+ throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1, { run_id: runId });
1115
+ return { runRoot: row.run_root, workspaceRoot: row.workspace_root, indexJson: row.index_json };
1116
+ }
1117
+ catch (error) {
1118
+ return prepareError(error, { parameter: "run-id", run_id: runId });
1119
+ }
1120
+ };
1121
+ const json = (file, stdin, label, schema) => {
1122
+ if (stdin) {
1123
+ // The caller awaits this helper; the synchronous facade below is only
1124
+ // used for file inputs. Keep stdin handling in the stage branch.
1125
+ throw new AppError("usage", `${label} stdin preparation must be awaited`, 2);
1126
+ }
1127
+ if (!file)
1128
+ throw new AppError("usage", `${label} input is required`, 2);
1129
+ return prepareJsonSchema(file, label, schema);
1130
+ };
1131
+ if (family === "stage" && command === "start") {
1132
+ const stage = requiredOption(parsed, "stage");
1133
+ if (stage !== "specify" && ["bootstrap", "intake-file", "intake-stdin"].some(option => hasOption(parsed, option)))
1134
+ throw new AppError("usage", "--bootstrap and intake inputs are only supported for SPECIFY", 2);
1135
+ requiredOption(parsed, "project-root");
1136
+ if (!hasOption(parsed, "bootstrap"))
1137
+ requiredPosition(parsed, 0, "run-id");
1138
+ if (hasOption(parsed, "session-id"))
1139
+ throw new AppError("usage", "--session-id is managed by the harness lifecycle adapter and is not accepted", 2);
1140
+ const contextFile = optionalOption(parsed, "context-file"), contextSha256 = optionalOption(parsed, "context-sha256");
1141
+ if (Boolean(contextFile) !== Boolean(contextSha256))
1142
+ throw new AppError("usage", "stage start requires --context-file together with --context-sha256", 2);
1143
+ if ([hasOption(parsed, "intake-file"), hasOption(parsed, "intake-stdin"), Boolean(contextFile)].filter(Boolean).length > 1)
1144
+ throw new AppError("usage", "Use exactly one of --intake-file, --intake-stdin or --context-file", 2);
1145
+ if (contextFile && contextSha256) {
1146
+ try {
1147
+ prepared.stageStart = { externalContext: loadExternalStageContext({ file: contextFile, expectedSha256: contextSha256, stage }) };
1148
+ }
1149
+ catch (error) {
1150
+ return prepareError(error, { file: contextFile, parameter: "context-file" });
1151
+ }
1152
+ if (!hasOption(parsed, "bootstrap")) {
1153
+ const { runRoot } = run(requiredOption(parsed, "project-root"), requiredPosition(parsed, 0, "run-id"));
1154
+ prepareExternalStageContext({ stageRoot: path.join(runRoot, vnextStageDirectory(stage)), loaded: prepared.stageStart.externalContext });
1155
+ }
1156
+ }
1157
+ if (stage === "specify") {
1158
+ const intakeFile = optionalOption(parsed, "intake-file");
1159
+ if (intakeFile)
1160
+ prepared.stageStart = { intakeMarkdown: prepareTextFile(intakeFile, "SPECIFY intake").text };
1161
+ else if (hasOption(parsed, "intake-stdin"))
1162
+ prepared.stageStart = { intakeMarkdown: await readStdin(io.stdin) };
1163
+ else if (prepared.stageStart?.externalContext)
1164
+ prepared.stageStart.intakeMarkdown = runnerIntake(prepared.stageStart.externalContext);
1165
+ const projectRoot = requiredOption(parsed, "project-root");
1166
+ const bootstrap = hasOption(parsed, "bootstrap");
1167
+ if (isVnextSpecifyFlow(projectRoot) && (bootstrap || isVnextSpecifyRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") }))) {
1168
+ prepared.specifyStart = prepareVnextSpecifyStart(context, { projectRoot, ...(prepared.stageStart?.intakeMarkdown !== undefined ? { intakeMarkdown: prepared.stageStart.intakeMarkdown } : {}), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}), slug: optionalOption(parsed, "subject"), ...(!bootstrap ? { runId: requiredPosition(parsed, 0, "run-id") } : {}) });
1169
+ }
1170
+ else if (bootstrap) {
1171
+ if (hasOption(parsed, "intake-stdin") || contextFile)
1172
+ throw new AppError("usage", "Legacy SPECIFY bootstrap supports --intake-file, not stdin or runner context", 2);
1173
+ prepared.legacyStageStart = prepareLegacyStageStart(context, { projectRoot, stage, bootstrap: { subject: requiredOption(parsed, "subject"), ...(intakeFile ? { intakeFile } : {}) }, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}) }, prepared.stageStart?.intakeMarkdown);
1174
+ }
1175
+ }
1176
+ if (stage === "merge" && isVnextMergeRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1177
+ prepared.mergeStart = prepareVnextMergeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1178
+ }
1179
+ if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1180
+ prepared.protocolizeStart = prepareVnextProtocolizeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1181
+ }
1182
+ if (stage === "plan" && isVnextPlanRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1183
+ prepared.planStart = prepareVnextPlanStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1184
+ }
1185
+ if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1186
+ prepared.planReviewStart = prepareVnextPlanReviewStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1187
+ }
1188
+ if (stage === "code" && isVnextPlanRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1189
+ prepared.codeStart = prepareVnextCodeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1190
+ }
1191
+ if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1192
+ prepared.codeReviewStart = prepareVnextCodeReviewStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1193
+ }
1194
+ if (![prepared.specifyStart, prepared.protocolizeStart, prepared.planStart, prepared.planReviewStart, prepared.codeStart, prepared.codeReviewStart, prepared.mergeStart, prepared.legacyStageStart].some(Boolean)) {
1195
+ if (prepared.stageStart?.externalContext)
1196
+ throw new AppError("usage", "--context-file is currently supported only by vNext flow stages", 2);
1197
+ prepared.legacyStageStart = prepareLegacyStageStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}) });
1198
+ }
1199
+ }
1200
+ if (family === "stage" && (command === "pause" || command === "resume")) {
1201
+ requiredPosition(parsed, 0, "run-id");
1202
+ requiredOption(parsed, "project-root");
1203
+ requiredOption(parsed, "stage");
1204
+ requiredOption(parsed, "work");
1205
+ const fileParameter = command === "pause" ? "question-file" : "answer-file";
1206
+ const stdinParameter = command === "pause" ? "question-stdin" : "answer-stdin";
1207
+ const inputFile = optionalOption(parsed, fileParameter);
1208
+ const fromStdin = hasOption(parsed, stdinParameter);
1209
+ if (Boolean(inputFile) === fromStdin)
1210
+ throw new AppError("usage", `stage ${command} requires exactly one of --${fileParameter} or --${stdinParameter}`, 2);
1211
+ if (fromStdin && io.stdin?.isTTY)
1212
+ throw new AppError("usage", `--${stdinParameter} requires piped or redirected input`, 2);
1213
+ prepared.interactionText = inputFile ? prepareTextFile(inputFile, command === "pause" ? "User question" : "User answer").text : await readStdin(io.stdin);
1214
+ if (!prepared.interactionText.trim())
1215
+ return prepareError(new AppError("validation", `stage ${command} requires non-empty input`, 2), { parameter: inputFile ? fileParameter : stdinParameter });
1216
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), workId: requiredOption(parsed, "work") };
1217
+ try {
1218
+ if (command === "pause")
1219
+ prepareStagePause(context, { ...input, question: prepared.interactionText });
1220
+ else
1221
+ prepared.resumeEvidence = prepareStageResume(context, { ...input, answer: prepared.interactionText }).evidence;
1222
+ }
1223
+ catch (error) {
1224
+ return prepareError(error, { parameter: "stage/work" });
1225
+ }
1226
+ }
1227
+ if (family === "work" && command === "finish") {
1228
+ const retryReceiptId = optionalOption(parsed, "retry-check"), retryReason = prepared.retryReason;
1229
+ if (Boolean(retryReceiptId) !== Boolean(retryReason))
1230
+ throw new AppError("usage", "--retry-check and --reason must be supplied together", 2);
1231
+ const resultFile = optionalOption(parsed, "result-file");
1232
+ const resultStdin = hasOption(parsed, "result-stdin");
1233
+ if (Boolean(resultFile) === resultStdin)
1234
+ throw new AppError("usage", "work finish requires exactly one of --result-file or --result-stdin", 2);
1235
+ prepared.workFinish = { result: resultFile ? prepareTextFile(resultFile, "Work result").text : await readStdin(io.stdin) };
1236
+ prepareWorkResult(context, requiredPosition(parsed, 0, "work-id"), prepared.workFinish.result);
1237
+ }
1238
+ if (family === "stage" && command === "fanout" && requiredPosition(parsed, 0, "fanout action") === "reconcile") {
1239
+ prepared.observations = prepareNativeObservations(prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value);
1240
+ }
1241
+ if (family === "stage" && command === "native" && requiredPosition(parsed, 0, "native action") === "observe") {
1242
+ prepared.observations = prepareNativeObservations(prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value);
1243
+ }
1244
+ if (family !== "stage" || command !== "finish")
1245
+ return prepared;
1246
+ const projectRoot = requiredOption(parsed, "project-root");
1247
+ const runId = requiredPosition(parsed, 0, "run-id");
1248
+ const stage = requiredOption(parsed, "stage");
1249
+ if (hasOption(parsed, "status"))
1250
+ throw new AppError("usage", "Stage status belongs in the semantic input file", 2);
1251
+ if (["result-file", "semantic-file", "data", "result-stdin"].filter(key => hasOption(parsed, key)).length > 1)
1252
+ throw new AppError("usage", "Use exactly one result input: --result-file, --semantic-file, --data or --result-stdin", 2);
1253
+ if (Boolean(optionalOption(parsed, "retry-check")) !== Boolean(prepared.retryReason))
1254
+ throw new AppError("usage", "--retry-check requires recovery evidence", 2);
1255
+ const resultStdin = hasOption(parsed, "result-stdin");
1256
+ const semanticFile = optionalOption(parsed, "semantic-file") ?? optionalOption(parsed, "data");
1257
+ const resultFile = optionalOption(parsed, "result-file") ?? semanticFile;
1258
+ const runtime = run(projectRoot, runId);
1259
+ const terminalReplay = (name) => {
1260
+ let index;
1261
+ try {
1262
+ index = JSON.parse(runtime.indexJson);
1263
+ }
1264
+ catch (error) {
1265
+ throw new AppError("runtime_artifact_invalid", "RUN index is not valid retained JSON", 1, { run_id: runId, cause: error instanceof Error ? error.message : String(error) });
1266
+ }
1267
+ return index.stage_runs?.some(entry => entry.stage === name && entry.status === "done") === true
1268
+ && fs.existsSync(path.join(runtime.runRoot, vnextStageDirectory(name), "stage-report.json"));
1269
+ };
1270
+ const acceptStageInputs = (allowed) => {
1271
+ const options = allowed.split(" ");
1272
+ for (const name of ["dir", "semantic-file", "data", "result-file", "result-stdin", "outcome", "decision-file", "verification-file", "retry-check", "reason", "reason-file", "request", "work"]) {
1273
+ if (hasOption(parsed, name) && !options.includes(name === "reason-file" ? "reason" : name))
1274
+ throw new AppError("usage", `stage finish ${stage} does not accept --${name} for this flow`, 2, { parameter: name });
1275
+ }
1276
+ };
1277
+ const fromStdin = async (label, schema) => {
1278
+ const value = prepareJsonText(await readStdin(io.stdin), { file: "<stdin>", label });
1279
+ try {
1280
+ validateSchema({ ...schema, file: value.file, data: value.value });
1281
+ }
1282
+ catch (error) {
1283
+ return prepareError(error, { file: value.file, label });
1284
+ }
1285
+ return value;
1286
+ };
1287
+ if (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId })) {
1288
+ acceptStageInputs("result-file semantic-file data result-stdin outcome");
1289
+ const outcome = optionalOption(parsed, "outcome");
1290
+ if (!outcome || !["specified", "failed", "cancelled"].includes(outcome))
1291
+ throw new AppError("usage", "vNext SPECIFY requires --outcome specified|failed|cancelled; use stage pause for a user question", 2);
1292
+ if (Boolean(resultFile) === resultStdin)
1293
+ throw new AppError("usage", "vNext SPECIFY finish requires exactly one result input", 2);
1294
+ const schema = { schemaName: "vnext-specify", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot };
1295
+ const input = resultStdin ? await fromStdin("SPECIFY result", schema) : json(resultFile, false, "SPECIFY result", schema);
1296
+ prepared.stageFinish = { value: input.value, text: input.text };
1297
+ }
1298
+ else if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId })) {
1299
+ acceptStageInputs("result-file semantic-file data");
1300
+ if (!resultFile || resultStdin || hasOption(parsed, "outcome"))
1301
+ throw new AppError("usage", "vNext PROTOCOLIZE requires exactly --result-file", 2);
1302
+ let absolute;
1303
+ try {
1304
+ absolute = prepareProtocolizeResultPath(runtime.runRoot, resultFile);
1305
+ }
1306
+ catch (error) {
1307
+ return prepareError(error, { file: resultFile });
1308
+ }
1309
+ const input = json(absolute, false, "PROTOCOLIZE result", { schemaName: "vnext-protocolize-result", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1310
+ prepared.stageFinish = { value: input.value, text: input.text };
1311
+ }
1312
+ else if (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId })) {
1313
+ acceptStageInputs("");
1314
+ if (hasOption(parsed, "code-work-batch-file"))
1315
+ throw new AppError("usage", "vNext PLAN derives its CODE batch from accepted semantic plans; do not supply a batch file", 2);
1316
+ try {
1317
+ prepared.planFinish = prepareVnextPlanFinish(context, { projectRoot, runId });
1318
+ }
1319
+ catch (error) {
1320
+ return prepareError(error, { parameter: "PLAN artifacts" });
1321
+ }
1322
+ }
1323
+ else if (stage === "merge" && isVnextMergeRun(context, { projectRoot, runId })) {
1324
+ acceptStageInputs("request work retry-check reason");
1325
+ if (resultStdin || resultFile || hasOption(parsed, "outcome"))
1326
+ throw new AppError("usage", "vNext MERGE uses the Work result path returned by stage start", 2);
1327
+ requiredOption(parsed, "request");
1328
+ requiredOption(parsed, "work");
1329
+ try {
1330
+ prepared.mergeFinish = prepareVnextMergeFinish(context, { projectRoot, runId, requestId: requiredOption(parsed, "request"), workId: requiredOption(parsed, "work"), ...(optionalOption(parsed, "retry-check") ? { retryCheckId: optionalOption(parsed, "retry-check"), retryReason: prepared.retryReason } : {}) });
1331
+ }
1332
+ catch (error) {
1333
+ return prepareError(error, { parameter: "MERGE finish" });
1334
+ }
1335
+ }
1336
+ else if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId })) {
1337
+ acceptStageInputs("decision-file");
1338
+ if (resultStdin || hasOption(parsed, "outcome"))
1339
+ throw new AppError("usage", "vNext PLAN-REVIEW uses --decision-file", 2);
1340
+ const decision = optionalOption(parsed, "decision-file") ?? path.join(runtime.runRoot, "04-plan-review", "decision.json");
1341
+ const input = json(decision, false, "PLAN-REVIEW decision", { schemaName: "plan-review-decision", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1342
+ prepared.stageFinish = { value: input.value, text: input.text };
1343
+ }
1344
+ else if (stage === "code" && isVnextPlanRun(context, { projectRoot, runId })) {
1345
+ acceptStageInputs("verification-file retry-check reason");
1346
+ if (semanticFile || resultFile || resultStdin || hasOption(parsed, "outcome"))
1347
+ throw new AppError("usage", "vNext CODE finish accepts only --verification-file", 2);
1348
+ const verification = optionalOption(parsed, "verification-file");
1349
+ if (!verification)
1350
+ throw new AppError("usage", "vNext CODE finish requires --verification-file", 2);
1351
+ if (!terminalReplay(stage)) {
1352
+ const input = json(verification, false, "CODE verification", { schemaName: "code-verification", projectRoot: runtime.workspaceRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1353
+ prepared.stageFinish = { value: input.value, text: input.text };
1354
+ }
1355
+ }
1356
+ else if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId })) {
1357
+ acceptStageInputs("decision-file retry-check reason");
1358
+ if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
1359
+ throw new AppError("usage", "vNext CODE-REVIEW uses --decision-file", 2);
1360
+ const decision = optionalOption(parsed, "decision-file") ?? path.join(runtime.runRoot, "06-code-review", "decision.json");
1361
+ if (!terminalReplay(stage)) {
1362
+ const input = prepareCodeReviewDecision(runtime.runRoot, optionalOption(parsed, "decision-file"));
1363
+ try {
1364
+ validateSchema({ schemaName: "code-review-decision", file: decision, data: input.value, projectRoot: runtime.workspaceRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1365
+ }
1366
+ catch (error) {
1367
+ return prepareError(error, { file: decision, label: "CODE-REVIEW decision" });
1368
+ }
1369
+ prepared.stageFinish = input;
1370
+ }
1371
+ }
1372
+ else {
1373
+ acceptStageInputs("dir semantic-file data");
1374
+ if (hasOption(parsed, "outcome") || hasOption(parsed, "result-file") || resultStdin)
1375
+ throw new AppError("usage", "--outcome, --result-file and --result-stdin are only available for vNext SPECIFY", 2);
1376
+ prepared.legacyStageFinish = prepareStageFinish(context, { projectRoot, runId, stage, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}), ...(semanticFile ? { semanticFile } : {}) });
1377
+ }
1378
+ return prepared;
1379
+ }
1380
+ async function dispatch(args, context, io, scopeProjectRoot = null, classification = classifyCliOperation(args, context.env), output = parseOutputOptions(args), prepared = {}) {
1381
+ if (!prepared.route)
1382
+ throw new AppError("command_not_prepared", "Command dispatch requires prepared arguments", 1);
1383
+ const { family, command, parsed } = prepared.route;
1384
+ if (family === "zcode" && command === "invocation" && parsed.positional[0] === "prepare") {
1385
+ const payload = prepared.lifecycleIssuance;
1386
+ if (!payload)
1387
+ throw new AppError("command_not_prepared", "Invocation issuance requires prepared input", 1);
1388
+ assertLifecycleInvocationCurrent(context, payload.scope, payload.command);
1389
+ return { ok: true, ...issueLifecycleInvocation(context, payload.command, payload.scope) };
1390
+ }
1391
+ if (family === "storage" && command === "migrate-writer") {
1392
+ if (parsed.positional.length || [...parsed.options.keys()].some(key => !["database", "backup", "offline"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
1393
+ throw new AppError("usage", "Usage: dd-flow storage migrate-writer --database ABSOLUTE_DB --backup NEW_ABSOLUTE_FILE --offline", 2);
1394
+ if (parsed.options.get("offline")?.[0] !== flagValue)
1395
+ throw new AppError("usage", "Writer migration requires --offline after draining all local and external runtime owners", 2);
1396
+ return { ok: true, ...migrateStoreWriter(requiredOption(parsed, "database"), requiredOption(parsed, "backup")) };
1397
+ }
506
1398
  if (family === "engine") {
507
- return dispatchEngine(context, command, parsed, classification);
1399
+ return dispatchEngine(context, command, parsed, classification, prepared);
508
1400
  }
509
1401
  if (family === "status") {
510
- const rootParsed = parseArgs([command ?? "", ...rest]);
511
1402
  return getRuntimeStatus(context, {
512
- projectRoot: optionalOption(rootParsed, "project-root") ?? optionalOption(rootParsed, "root"),
513
- checkRegistry: hasOption(rootParsed, "check-registry")
1403
+ projectRoot: optionalOption(parsed, "project-root") ?? optionalOption(parsed, "root"),
1404
+ checkRegistry: hasOption(parsed, "check-registry")
514
1405
  });
515
1406
  }
516
1407
  if (family === "version") {
517
1408
  return getCliVersionReport();
518
1409
  }
519
1410
  if (family === "runtime") {
520
- return await dispatchRuntime(context, command, parsed);
1411
+ return await dispatchRuntime(context, command, parsed, commandProgress(io, output), prepared);
521
1412
  }
522
1413
  if (family === "canon") {
523
- return dispatchCanon(context, command, parsed);
1414
+ return dispatchCanon(context, command, parsed, prepared);
524
1415
  }
525
1416
  if (family === "project" && command === "register") {
526
1417
  return registerProject(context, { root: requiredOption(parsed, "root") });
@@ -597,16 +1488,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
597
1488
  return readyForMerge(context, { protocolId, projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "protocol ready-for-merge") });
598
1489
  }
599
1490
  if (family === "protocol" && command === "transition") {
600
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
601
- const reason = optionalOption(parsed, "reason");
602
- return transitionProtocol(context, {
603
- protocolId,
604
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "protocol transition"),
605
- to: requiredOption(parsed, "to"),
606
- jsonFile: requiredOptionAlias(parsed, ["payload-file", "json-file"]),
607
- force: hasOption(parsed, "force"),
608
- ...(reason ? { reason } : {})
609
- });
1491
+ return transitionProtocol(context, protocolTransitionInput(parsed, scopeProjectRoot), prepared.protocolTransition);
610
1492
  }
611
1493
  if (family === "protocol" && command === "sync-from-run") {
612
1494
  const protocolId = requiredPosition(parsed, 0, "protocol-id");
@@ -631,17 +1513,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
631
1513
  });
632
1514
  }
633
1515
  if (family === "transition") {
634
- const transitionParsed = parseArgs([command ?? "", ...rest]);
635
- const protocolId = requiredPosition(transitionParsed, 0, "protocol-id");
636
- const reason = optionalOption(transitionParsed, "reason");
637
- return transitionProtocol(context, {
638
- protocolId,
639
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "transition"),
640
- to: requiredOption(transitionParsed, "to"),
641
- jsonFile: requiredOptionAlias(transitionParsed, ["payload-file", "json-file"]),
642
- force: hasOption(transitionParsed, "force"),
643
- ...(reason ? { reason } : {})
644
- });
1516
+ return transitionProtocol(context, protocolTransitionInput(parsed, scopeProjectRoot), prepared.protocolTransition);
645
1517
  }
646
1518
  if (family === "plan" && command === "status") {
647
1519
  const protocolId = requiredPosition(parsed, 0, "protocol-id");
@@ -660,12 +1532,19 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
660
1532
  const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "stage fanout");
661
1533
  if (action === "status")
662
1534
  return getVnextFanoutStatus(context, { projectRoot, runId, stage });
1535
+ if (action === "reconcile")
1536
+ return reconcileVnextFanout(context, { projectRoot, runId, stage, observations: prepared.observations ?? prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value });
663
1537
  if (action === "dispatch") {
664
1538
  if (stage === "plan-review")
665
1539
  return dispatchVnextPlanReview(context, { projectRoot, runId });
666
1540
  return getVnextFanoutStatus(context, { projectRoot, runId, stage });
667
1541
  }
668
- throw new AppError("usage", "Use: dd-flow stage fanout <status|dispatch> <RUN> --stage <stage> --project-root <path>", 2);
1542
+ throw new AppError("usage", "Use: dd-flow stage fanout <status|dispatch|reconcile> <RUN> --stage <stage> --project-root <path>; reconcile requires --observations-file <native-observations.json>", 2);
1543
+ }
1544
+ if (family === "stage" && command === "native") {
1545
+ if (requiredPosition(parsed, 0, "native action") !== "observe")
1546
+ throw new AppError("usage", "Use: dd-flow stage native observe <RUN> --stage <stage> --observations-file <native-observations.json> --project-root <path>", 2);
1547
+ return observeVnextNativeChildren(context, { projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "stage native observe"), runId: requiredPosition(parsed, 1, "run-id"), stage: requiredOption(parsed, "stage"), observations: prepared.observations ?? prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value });
669
1548
  }
670
1549
  if (family === "run" && command === "capacity") {
671
1550
  if (requiredPosition(parsed, 0, "capacity action") !== "record")
@@ -677,16 +1556,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
677
1556
  return dispatchPlanItem(context, parsed, requiredScopeProjectRoot(scopeProjectRoot, "plan item"));
678
1557
  }
679
1558
  if (family === "prompt" && command === "render") {
680
- const workspaceRoot = optionalOption(parsed, "workspace-root");
681
- const taskFile = optionalOption(parsed, "task-file");
682
- return renderWorkerPrompt(context, {
683
- projectRoot: requiredOption(parsed, "project-root"),
684
- runId: requiredOption(parsed, "run"),
685
- stage: requiredOption(parsed, "stage"),
686
- profile: requiredOption(parsed, "profile"),
687
- ...(taskFile ? { taskFile } : { planItemId: requiredOption(parsed, "plan-item") }),
688
- ...(workspaceRoot ? { workspaceRoot } : {})
689
- });
1559
+ return renderWorkerPrompt(context, prepared.workerPrompt?.input ?? workerPromptInput(parsed), prepared.workerPrompt?.value);
690
1560
  }
691
1561
  if (family === "work" && command === "status") {
692
1562
  return getVnextWorkStatus(context, {
@@ -695,7 +1565,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
695
1565
  });
696
1566
  }
697
1567
  if (family === "work" && command === "add-batch") {
698
- return addWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file: requiredOption(parsed, "file") });
1568
+ return addWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file: requiredOption(parsed, "file"), prepared: prepared.workBatch });
699
1569
  }
700
1570
  if (family === "work" && command === "ls") {
701
1571
  return listWorks(context, { ...(optionalOption(parsed, "run") ? { runId: optionalOption(parsed, "run") } : {}), ...(optionalOption(parsed, "parent") ? { parentWorkId: optionalOption(parsed, "parent") } : {}), ...(optionalOption(parsed, "status") ? { status: optionalOption(parsed, "status") } : {}), ...(hasOption(parsed, "ready") ? { ready: true } : {}), ...(hasOption(parsed, "include-results") ? { includeResults: true } : {}), ...(optionalOption(parsed, "limit") ? { limit: Number(optionalOption(parsed, "limit")) } : {}) });
@@ -703,48 +1573,9 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
703
1573
  if (family === "work" && command === "show")
704
1574
  return showWork(context, requiredPosition(parsed, 0, "work-id"));
705
1575
  if (family === "work" && command === "repair" && requiredPosition(parsed, 0, "action") === "add") {
706
- if (!hasOption(parsed, "task-stdin"))
707
- throw new AppError("usage", "work repair add requires --task-stdin", 2);
708
- const origins = parsed.options.get("origin-work") ?? [];
709
- const findings = parsed.options.get("from-finding") ?? [];
710
- const unresolved = parsed.options.get("from-unresolved") ?? [];
711
- if (!origins.length && !findings.length)
712
- throw new AppError("usage", "work repair add requires --from-check with --origin-work, --from-finding, or --from-unresolved with --origin-work", 2);
713
- if (findings.length)
714
- return addVnextCodeReviewRepair(context, {
715
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"),
716
- runId: requiredOption(parsed, "run"),
717
- findingIds: findings,
718
- checkRefsByFinding: Object.fromEntries(findings.map((finding) => [finding, parsed.options.get("check-ref") ?? []])),
719
- objective: await readStdin(io.stdin)
720
- });
721
- if (unresolved.length) {
722
- if (!origins.length)
723
- throw new AppError("usage", "semantic repair requires at least one --origin-work", 2);
724
- const verificationPath = requiredOption(parsed, "verification-file");
725
- return addVnextCodeRepair(context, {
726
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"),
727
- runId: requiredOption(parsed, "run"),
728
- originWorkIds: origins,
729
- semanticUnresolved: unresolved,
730
- verificationPath,
731
- objective: await readStdin(io.stdin)
732
- });
733
- }
734
- if (!hasOption(parsed, "from-check"))
735
- throw new AppError("usage", "check repair requires --from-check", 2);
736
- if (!origins.length)
737
- throw new AppError("usage", "check repair requires at least one --origin-work", 2);
738
- const receipts = parsed.options.get("from-check") ?? [];
739
- if (receipts.length !== 1)
740
- throw new AppError("usage", "check repair accepts exactly one --from-check; create one causal repair Work per failed receipt", 2);
741
- return addVnextCodeRepair(context, {
742
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"),
743
- runId: requiredOption(parsed, "run"),
744
- checkReceiptId: receipts[0],
745
- originWorkIds: origins,
746
- objective: await readStdin(io.stdin)
747
- });
1576
+ if (!prepared.workRepair)
1577
+ throw new AppError("cli_input_unprepared", "Repair input was not prepared", 1);
1578
+ return addVnextCodeRepair(context, prepared.workRepair.input, prepared.workRepair.value);
748
1579
  }
749
1580
  if (family === "work" && command === "deps") {
750
1581
  const on = parsed.options.get("on") ?? [];
@@ -752,21 +1583,34 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
752
1583
  }
753
1584
  if (family === "work" && command === "delete")
754
1585
  return deleteWork(context, requiredPosition(parsed, 0, "work-id"));
1586
+ if (family === "work" && command === "launch")
1587
+ return await launchExternalWork(context, { workId: requiredPosition(parsed, 0, "work-id"), ...(optionalOption(parsed, "stage") ? { stage: optionalOption(parsed, "stage") } : {}), progress: commandProgress(io, output) });
755
1588
  if (family === "work" && command === "start") {
756
1589
  const hookEventId = optionalOption(parsed, "hook-event-id");
1590
+ const recoveryId = optionalOption(parsed, "recovery-id");
757
1591
  const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work start");
758
- return startWork(context, requiredPosition(parsed, 0, "work-id"), { ...(hookEventId ? { hookEventId } : {}), projectRoot });
1592
+ return startWork(context, requiredPosition(parsed, 0, "work-id"), { ...(hookEventId ? { hookEventId } : {}), ...(recoveryId ? { recoveryId } : {}), projectRoot });
759
1593
  }
760
1594
  if (family === "work" && command === "finish") {
761
1595
  const resultFile = optionalOption(parsed, "result-file");
762
1596
  const resultStdin = hasOption(parsed, "result-stdin");
763
1597
  if (Boolean(resultFile) === resultStdin)
764
1598
  throw new AppError("usage", "work finish requires exactly one of --result-file or --result-stdin", 2);
765
- const result = resultFile ? fs.readFileSync(path.resolve(resultFile), "utf8") : await readStdin(io.stdin);
766
- return await finishWork(context, requiredPosition(parsed, 0, "work-id"), result, commandProgress(io, output));
1599
+ const workId = requiredPosition(parsed, 0, "work-id");
1600
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work finish");
1601
+ assertWorkLifecycleOwner(context, { workId, projectRoot, operation: "work_finish", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
1602
+ const retryReceiptId = optionalOption(parsed, "retry-check"), retryReason = prepared.retryReason;
1603
+ if (Boolean(retryReceiptId) !== Boolean(retryReason))
1604
+ throw new AppError("usage", "--retry-check and --reason must be supplied together", 2);
1605
+ const result = prepared.workFinish?.result ?? (resultFile ? prepareTextFile(resultFile, "Work result").text : await readStdin(io.stdin));
1606
+ return await finishWork(context, workId, result, commandProgress(io, output), retryReceiptId ? { receiptId: retryReceiptId, reason: retryReason } : undefined);
1607
+ }
1608
+ if (family === "work" && command === "fail") {
1609
+ const workId = requiredPosition(parsed, 0, "work-id");
1610
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work fail");
1611
+ assertWorkLifecycleOwner(context, { workId, projectRoot, operation: "work_fail", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
1612
+ return failWork(context, workId, requiredOption(parsed, "reason"));
767
1613
  }
768
- if (family === "work" && command === "fail")
769
- return failWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
770
1614
  if (family === "work" && command === "cancel")
771
1615
  return cancelWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
772
1616
  if (family === "work" && command === "retry")
@@ -788,12 +1632,12 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
788
1632
  const requireSessionBinding = hasOption(parsed, "require-session-binding");
789
1633
  const projectRoot = requiredOption(parsed, "project-root");
790
1634
  const stage = requiredOption(parsed, "stage");
791
- const externalContext = contextFile && contextSha256 ? loadExternalStageContext({ file: contextFile, expectedSha256: contextSha256, stage }) : undefined;
1635
+ const externalContext = prepared.stageStart?.externalContext;
792
1636
  const claimVnextStageStart = (runId) => {
793
1637
  registerProject(context, { root: projectRoot });
794
1638
  return findRecentMatchingHookEvent(context, {
795
1639
  projectId: requireProjectByRoot(context, resolveProjectRoot(projectRoot)).id,
796
- matchKey: stageStartMatchKey(runId, stage, projectRoot, contextSha256),
1640
+ matchKey: entityReferenceVariants(runId).map((reference) => stageStartMatchKey(reference, stage, projectRoot, contextSha256)),
797
1641
  errorCode: "trusted_session_binding_required",
798
1642
  operation: `vNext ${stage.toUpperCase()} start`
799
1643
  }).eventKey;
@@ -819,37 +1663,37 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
819
1663
  }
820
1664
  const result = launchVnextSpecify(context, {
821
1665
  projectRoot,
822
- ...(externalContext ? { intakeMarkdown: runnerIntake(externalContext) } : intakeFile ? { intakeFile } : { intakeMarkdown: await readStdin(io.stdin) }),
1666
+ ...(prepared.stageStart?.intakeMarkdown !== undefined ? { intakeMarkdown: prepared.stageStart.intakeMarkdown } : externalContext ? { intakeMarkdown: runnerIntake(externalContext) } : intakeFile ? { intakeFile } : { intakeMarkdown: await readStdin(io.stdin) }),
823
1667
  hookEventId,
824
1668
  ...(subject ? { slug: subject } : {}),
825
1669
  ...(externalContext ? { externalContext } : {}),
826
1670
  ...(!bootstrap ? { runId: requiredPosition(parsed, 0, "run-id") } : {})
827
- });
1671
+ }, prepared.specifyStart);
828
1672
  return attachExternalStageContext(result, externalContext);
829
1673
  }
830
1674
  if (!bootstrap && stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
831
1675
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
832
- return attachExternalStageContext(startVnextProtocolize(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1676
+ return attachExternalStageContext(startVnextProtocolize(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.protocolizeStart), externalContext);
833
1677
  }
834
1678
  if (!bootstrap && stage === "plan" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
835
1679
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
836
- return attachExternalStageContext(startVnextPlan(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1680
+ return attachExternalStageContext(startVnextPlan(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.planStart), externalContext);
837
1681
  }
838
1682
  if (!bootstrap && stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
839
1683
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
840
- return attachExternalStageContext(startVnextPlanReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1684
+ return attachExternalStageContext(startVnextPlanReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.planReviewStart), externalContext);
841
1685
  }
842
1686
  if (!bootstrap && stage === "code" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
843
1687
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
844
- return attachExternalStageContext(await startVnextCode(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, progress: commandProgress(io, output), ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1688
+ return attachExternalStageContext(await startVnextCode(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, progress: commandProgress(io, output), ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.codeStart), externalContext);
845
1689
  }
846
1690
  if (!bootstrap && stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
847
1691
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
848
- return attachExternalStageContext(startVnextCodeReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1692
+ return attachExternalStageContext(startVnextCodeReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.codeReviewStart), externalContext);
849
1693
  }
850
1694
  if (!bootstrap && stage === "merge" && isVnextMergeRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
851
1695
  hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
852
- return attachExternalStageContext(await startVnextMerge(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, progress: commandProgress(io, output), ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
1696
+ return attachExternalStageContext(await startVnextMerge(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, progress: commandProgress(io, output), ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.mergeStart), externalContext);
853
1697
  }
854
1698
  if (intakeStdin) {
855
1699
  throw new AppError("usage", "--intake-stdin is only available for vNext SPECIFY", 2);
@@ -864,7 +1708,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
864
1708
  ...(hookEventId ? { hookEventId } : {}),
865
1709
  ...(requireSessionBinding ? { requireSessionBinding: true } : {}),
866
1710
  ...(dir ? { dir } : {})
867
- });
1711
+ }, prepared.legacyStageStart);
868
1712
  }
869
1713
  if (family === "stage" && command === "finish") {
870
1714
  const dir = optionalOption(parsed, "dir");
@@ -874,9 +1718,23 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
874
1718
  const projectRoot = requiredOption(parsed, "project-root");
875
1719
  const runId = requiredPosition(parsed, 0, "run-id");
876
1720
  const stage = requiredOption(parsed, "stage");
1721
+ const controlledReply = (result) => controlLifecycleReply(context, { projectRoot, runId }, result);
877
1722
  const semanticFile = optionalOption(parsed, "semantic-file") ?? optionalOption(parsed, "data");
878
1723
  const resultFile = optionalOption(parsed, "result-file") ?? semanticFile;
879
1724
  const resultStdin = hasOption(parsed, "result-stdin");
1725
+ const retryCheckId = optionalOption(parsed, "retry-check");
1726
+ const retryReason = prepared.retryReason;
1727
+ const hookEventId = optionalOption(parsed, "hook-event-id");
1728
+ if (retryCheckId && !retryReason?.trim())
1729
+ throw new AppError("usage", "--retry-check requires --reason explaining the recovered environment", 2);
1730
+ const protectedLifecycle = (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId }))
1731
+ || (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId }))
1732
+ || (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId }))
1733
+ || (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId }))
1734
+ || (stage === "code" && isVnextPlanRun(context, { projectRoot, runId }))
1735
+ || (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId }));
1736
+ if (protectedLifecycle)
1737
+ assertStageLifecycleOwner(context, { projectRoot, runId, stage, operation: "stage_finish", ...(hookEventId ? { hookEventId } : {}) });
880
1738
  if (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId })) {
881
1739
  const outcome = optionalOption(parsed, "outcome");
882
1740
  if (!outcome || !["specified", "failed", "cancelled"].includes(outcome)) {
@@ -888,84 +1746,92 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
888
1746
  if (!resultFile && !resultStdin) {
889
1747
  throw new AppError("usage", "vNext SPECIFY finish requires --result-file or --result-stdin", 2);
890
1748
  }
891
- return finishVnextSpecifyStage(context, {
1749
+ return controlledReply(await finishVnextSpecifyStage(context, {
892
1750
  projectRoot,
893
1751
  runId,
894
- ...(resultFile ? { resultFile } : { resultJson: await readStdin(io.stdin) }),
1752
+ ...(resultFile ? { resultFile } : prepared.stageFinish?.value ? {} : { resultJson: await readStdin(io.stdin) }),
1753
+ ...(prepared.stageFinish?.value ? { result: prepared.stageFinish.value } : {}),
895
1754
  outcome: outcome
896
- });
1755
+ }));
897
1756
  }
898
1757
  if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId })) {
899
1758
  if (!resultFile || resultStdin || hasOption(parsed, "outcome")) {
900
1759
  throw new AppError("usage", "vNext PROTOCOLIZE requires exactly --result-file", 2);
901
1760
  }
902
- return finishVnextProtocolize(context, { projectRoot, runId, resultFile });
1761
+ return controlledReply(await finishVnextProtocolize(context, { projectRoot, runId, resultFile, ...(prepared.stageFinish?.value ? { result: prepared.stageFinish.value } : {}) }));
903
1762
  }
904
1763
  if (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId })) {
905
1764
  if (optionalOption(parsed, "code-work-batch-file"))
906
1765
  throw new AppError("usage", "vNext PLAN derives its CODE batch from accepted semantic plans; do not supply a batch file", 2);
907
- return finishVnextPlan(context, { projectRoot, runId });
1766
+ return controlledReply(await finishVnextPlan(context, { projectRoot, runId, ...(prepared.planFinish ? { prepared: prepared.planFinish } : {}) }));
908
1767
  }
909
1768
  if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId })) {
910
1769
  if (resultStdin || hasOption(parsed, "outcome"))
911
1770
  throw new AppError("usage", "vNext PLAN-REVIEW uses --decision-file", 2);
912
1771
  const decisionFile = optionalOption(parsed, "decision-file");
913
- return finishVnextPlanReview(context, { projectRoot, runId, ...(decisionFile ? { decisionFile } : {}) });
1772
+ return controlledReply(await finishVnextPlanReview(context, { projectRoot, runId, ...(decisionFile ? { decisionFile } : {}), ...(prepared.stageFinish?.value ? { decision: prepared.stageFinish.value, decisionText: prepared.stageFinish.text } : {}) }));
914
1773
  }
915
1774
  if (stage === "code" && isVnextPlanRun(context, { projectRoot, runId })) {
916
1775
  if (semanticFile || resultFile || resultStdin || hasOption(parsed, "outcome")) {
917
1776
  throw new AppError("usage", "vNext CODE finish accepts only --verification-file", 2);
918
1777
  }
919
- return await finishVnextCode(context, { projectRoot, runId, verificationFile: optionalOption(parsed, "verification-file") ?? path.join("<missing>", "code-verification.json"), progress: commandProgress(io, output) });
1778
+ return controlledReply(await finishVnextCode(context, { projectRoot, runId, verificationFile: optionalOption(parsed, "verification-file") ?? path.join("<missing>", "code-verification.json"), ...(prepared.stageFinish?.value ? { verification: prepared.stageFinish.value } : {}), ...(retryCheckId ? { retryCheckId, retryReason: retryReason } : {}), progress: commandProgress(io, output) }));
920
1779
  }
921
1780
  if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId })) {
922
1781
  if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
923
1782
  throw new AppError("usage", "vNext CODE-REVIEW uses --decision-file", 2);
924
- return await finishVnextCodeReview(context, { projectRoot, runId, ...(optionalOption(parsed, "decision-file") ? { decisionFile: optionalOption(parsed, "decision-file") } : {}), progress: commandProgress(io, output) });
1783
+ return controlledReply(await finishVnextCodeReview(context, { projectRoot, runId, ...(optionalOption(parsed, "decision-file") ? { decisionFile: optionalOption(parsed, "decision-file") } : {}), ...(prepared.stageFinish?.value ? { decision: prepared.stageFinish.value, decisionText: prepared.stageFinish.text } : {}), ...(retryCheckId ? { retryCheckId, retryReason: retryReason } : {}), progress: commandProgress(io, output) }));
925
1784
  }
926
1785
  if (stage === "merge" && isVnextMergeRun(context, { projectRoot, runId })) {
927
1786
  if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
928
1787
  throw new AppError("usage", "vNext MERGE uses the Work result path returned by stage start", 2);
929
- return await finishVnextMerge(context, { projectRoot, runId, requestId: requiredOption(parsed, "request"), workId: requiredOption(parsed, "work"), progress: commandProgress(io, output) });
1788
+ return controlledReply(await finishVnextMerge(context, { projectRoot, runId, requestId: requiredOption(parsed, "request"), workId: requiredOption(parsed, "work"), ...(retryCheckId ? { retryCheckId, retryReason: retryReason } : {}), progress: commandProgress(io, output) }, prepared.mergeFinish));
930
1789
  }
931
1790
  if (hasOption(parsed, "outcome") || hasOption(parsed, "result-file") || resultStdin) {
932
1791
  throw new AppError("usage", "--outcome, --result-file and --result-stdin are only available for vNext SPECIFY", 2);
933
1792
  }
934
- return finishStage(context, {
1793
+ return controlledReply(await finishStage(context, {
935
1794
  projectRoot,
936
1795
  runId,
937
1796
  stage,
938
1797
  ...(dir ? { dir } : {}),
939
1798
  ...(semanticFile ? { semanticFile } : {})
940
- });
1799
+ }, prepared.legacyStageFinish));
941
1800
  }
942
1801
  if (family === "stage" && command === "pause") {
943
- if (!hasOption(parsed, "question-stdin"))
944
- throw new AppError("usage", "stage pause requires --question-stdin", 2);
1802
+ const projectRoot = requiredOption(parsed, "project-root");
1803
+ const runId = requiredPosition(parsed, 0, "run-id");
1804
+ const stage = requiredOption(parsed, "stage");
1805
+ const workId = requiredOption(parsed, "work");
1806
+ const protectedLifecycle = (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId }))
1807
+ || (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId }))
1808
+ || (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId }))
1809
+ || (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId }))
1810
+ || (stage === "code" && isVnextPlanRun(context, { projectRoot, runId }))
1811
+ || (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId }));
1812
+ if (protectedLifecycle)
1813
+ assertStageLifecycleOwner(context, { projectRoot, runId, stage, workId, operation: "stage_pause", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
945
1814
  return pauseStageForUser(context, {
946
- projectRoot: requiredOption(parsed, "project-root"),
947
- runId: requiredPosition(parsed, 0, "run-id"),
948
- stage: requiredOption(parsed, "stage"),
949
- workId: requiredOption(parsed, "work"),
950
- question: await readStdin(io.stdin)
1815
+ projectRoot,
1816
+ runId,
1817
+ stage,
1818
+ workId,
1819
+ question: prepared.interactionText ?? await readStdin(io.stdin)
951
1820
  });
952
1821
  }
953
1822
  if (family === "stage" && command === "resume") {
954
- if (!hasOption(parsed, "answer-stdin"))
955
- throw new AppError("usage", "stage resume requires --answer-stdin", 2);
956
1823
  const hookEventId = optionalOption(parsed, "hook-event-id");
957
1824
  return resumeStageAfterUser(context, {
958
1825
  projectRoot: requiredOption(parsed, "project-root"),
959
1826
  runId: requiredPosition(parsed, 0, "run-id"),
960
1827
  stage: requiredOption(parsed, "stage"),
961
1828
  workId: requiredOption(parsed, "work"),
962
- answer: await readStdin(io.stdin),
1829
+ answer: prepared.interactionText ?? await readStdin(io.stdin),
1830
+ evidence: prepared.resumeEvidence,
963
1831
  ...(hookEventId ? { hookEventId } : {})
964
1832
  });
965
1833
  }
966
1834
  if (family === "stage" && command === "block") {
967
- if (!hasOption(parsed, "summary-stdin"))
968
- throw new AppError("usage", "stage block requires --summary-stdin", 2);
969
1835
  const kind = requiredOption(parsed, "kind");
970
1836
  if (kind !== "engine" && kind !== "harness" && kind !== "environment")
971
1837
  throw new AppError("usage", "--kind must be engine, harness or environment", 2);
@@ -976,7 +1842,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
976
1842
  workId: requiredOption(parsed, "work"),
977
1843
  kind,
978
1844
  code: requiredOption(parsed, "code"),
979
- summary: await readStdin(io.stdin),
1845
+ summary: prepared.interactionText ?? await readStdin(io.stdin),
980
1846
  retryable: hasOption(parsed, "retryable")
981
1847
  });
982
1848
  }
@@ -1001,13 +1867,55 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1001
1867
  return dispatchMergeWorker(context, command, parsed);
1002
1868
  }
1003
1869
  if (family === "cleanup") {
1004
- return dispatchCleanup(context, command, parsed);
1870
+ return dispatchCleanup(context, command, parsed, prepared.cleanup);
1005
1871
  }
1006
1872
  if (family === "session") {
1007
- return dispatchSession(context, command, parsed);
1873
+ return dispatchSession(context, command, parsed, prepared.sessionPayload);
1008
1874
  }
1009
1875
  if (family === "run") {
1010
- return dispatchRun(context, command, parsed);
1876
+ if (command === "control") {
1877
+ const action = requiredPosition(parsed, 0, "control action");
1878
+ const scope = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run") };
1879
+ if (action === "status")
1880
+ return runControlStatus(context, scope);
1881
+ if (action === "reconcile") {
1882
+ if ([...parsed.options.keys()].some(key => !["run", "project-root", "control-id", "request-id"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
1883
+ throw new AppError("usage", "Use run control reconcile --run ID --project-root PATH --control-id ID --request-id ID", 2);
1884
+ return await reconcileRunControl(context, { ...scope, controlId: requiredOption(parsed, "control-id"), requestId: requiredOption(parsed, "request-id") });
1885
+ }
1886
+ if (action === "resume") {
1887
+ if (["force", "grace-ms", "escalate"].some(option => hasOption(parsed, option)))
1888
+ throw new AppError("usage", "Resume does not accept stop or pause escalation options", 2);
1889
+ return await resumeRunController(context, { ...scope, requestId: requiredOption(parsed, "request-id"), controlId: requiredOption(parsed, "from"), ...(hasOption(parsed, "wait-ms") ? { waitMs: Number(requiredOption(parsed, "wait-ms")) } : {}) });
1890
+ }
1891
+ if (action === "serve")
1892
+ return await serveRunControl(context, { ...scope, controlId: requiredOption(parsed, "control-id") });
1893
+ if (action === "pause" || action === "stop")
1894
+ return await requestRunControl(context, {
1895
+ ...scope, action, requestId: requiredOption(parsed, "request-id"),
1896
+ ...(hasOption(parsed, "force") ? { force: true } : {}),
1897
+ ...(hasOption(parsed, "grace-ms") ? { graceMs: Number(requiredOption(parsed, "grace-ms")) } : {}),
1898
+ ...(hasOption(parsed, "escalate") ? { escalate: requiredOption(parsed, "escalate") } : {}),
1899
+ ...(hasOption(parsed, "wait-ms") ? { waitMs: Number(requiredOption(parsed, "wait-ms")) } : {})
1900
+ });
1901
+ throw new AppError("usage", "Use: dd-flow run control pause|stop|resume|reconcile|status", 2);
1902
+ }
1903
+ if (command === "drive") {
1904
+ const action = requiredPosition(parsed, 0, "drive action");
1905
+ const scope = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run") };
1906
+ if (action === "status")
1907
+ return runControllerStatus(context, { ...scope, ...(optionalOption(parsed, "after") ? { after: Number(optionalOption(parsed, "after")) } : {}) });
1908
+ if (action === "launch")
1909
+ return await launchRunController(context, controllerLaunchInput(parsed), prepared.controllerLaunch);
1910
+ if (action === "serve")
1911
+ return await serveRunController(context, { ...scope, controllerId: requiredOption(parsed, "controller-id") });
1912
+ if (action === "answer")
1913
+ return answerRunController(context, controllerAnswerInput(parsed), prepared.controllerAnswer);
1914
+ if (action === "context")
1915
+ return supplyRunControllerContext(context, controllerContextInput(parsed), prepared.controllerContext);
1916
+ throw new AppError("usage", "Use: dd-flow run drive launch|status|answer|context", 2);
1917
+ }
1918
+ return dispatchRun(context, command, parsed, prepared);
1011
1919
  }
1012
1920
  if (family === "stat") {
1013
1921
  return dispatchStat(context, command, parsed);
@@ -1022,23 +1930,26 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1022
1930
  return dispatchDashboard(context, command, parsed);
1023
1931
  }
1024
1932
  if (family === "schema") {
1025
- return dispatchSchema(context, command, parsed);
1933
+ return prepared.schemaValidation;
1026
1934
  }
1027
1935
  if (family === "memory") {
1028
1936
  return dispatchMemory(command, parsed);
1029
1937
  }
1030
1938
  if (family === "migration") {
1031
- return dispatchMigration(context, command, parsed, classification);
1939
+ return dispatchMigration(context, command, parsed, classification, prepared);
1032
1940
  }
1033
1941
  if (family === "codex" && command === "hooks") {
1034
- return dispatchCodexHooks(context, parsed);
1942
+ return dispatchCodexHooks(context, parsed, prepared);
1035
1943
  }
1036
1944
  if (family === "codex" && command === "home") {
1037
- return dispatchCodexHome(context, parsed);
1945
+ return dispatchCodexHome(context, parsed, prepared);
1038
1946
  }
1039
1947
  if (family === "codex" && command === "hook") {
1040
1948
  return dispatchCodexHook(context, parsed, await readStdin(io.stdin));
1041
1949
  }
1950
+ if (family === "zcode" && command === "hook") {
1951
+ return dispatchZcodeHook(context, parsed, await readStdin(io.stdin));
1952
+ }
1042
1953
  if (family === "zcode" && command === "event") {
1043
1954
  return dispatchZcodeEvent(context, parsed, await readStdin(io.stdin));
1044
1955
  }
@@ -1063,6 +1974,16 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1063
1974
  throw new AppError("usage", "Unknown opencode usage action", 2);
1064
1975
  return ingestOpenCodeUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1065
1976
  }
1977
+ if (family === "droid" && command === "event") {
1978
+ if (requiredPosition(parsed, 0, "droid event action") !== "handle")
1979
+ throw new AppError("usage", "Unknown droid event action", 2);
1980
+ return handleDroidEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1981
+ }
1982
+ if (family === "droid" && command === "usage") {
1983
+ if (requiredPosition(parsed, 0, "droid usage action") !== "ingest")
1984
+ throw new AppError("usage", "Unknown droid usage action", 2);
1985
+ return ingestDroidUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1986
+ }
1066
1987
  if (family === "agy" && command === "event")
1067
1988
  return dispatchAgyEvent(context, parsed, await readStdin(io.stdin));
1068
1989
  if (family === "agy" && command === "usage") {
@@ -1071,11 +1992,14 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1071
1992
  return ingestAgyUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1072
1993
  }
1073
1994
  if (family === "worktree") {
1074
- return dispatchWorktree(context, command, parsed, requiredScopeProjectRoot(scopeProjectRoot, `worktree ${command ?? ""}`));
1995
+ return dispatchWorktree(context, command, parsed, requiredScopeProjectRoot(scopeProjectRoot, `worktree ${command ?? ""}`), prepared);
1075
1996
  }
1076
1997
  throw new AppError("usage", `Unknown command: ${args.join(" ") || "<empty>"}`, 2);
1077
1998
  }
1078
- function dispatchEngine(context, command, parsed, classification) {
1999
+ function engineBindInput(parsed) {
2000
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), packageName: optionalOption(parsed, "package"), engineVersion: requiredOption(parsed, "engine-version"), integrityChecksum: optionalOption(parsed, "integrity-checksum"), reason: requiredOption(parsed, "reason") };
2001
+ }
2002
+ function dispatchEngine(context, command, parsed, classification, prepared) {
1079
2003
  if (command === "install") {
1080
2004
  return installCurrentEngine(context, { force: hasOption(parsed, "force") });
1081
2005
  }
@@ -1100,18 +2024,11 @@ function dispatchEngine(context, command, parsed, classification) {
1100
2024
  });
1101
2025
  }
1102
2026
  if (command === "bind-run") {
1103
- return bindRunEngine(context, {
1104
- projectRoot: requiredOption(parsed, "project-root"),
1105
- runId: requiredPosition(parsed, 0, "run-id"),
1106
- packageName: optionalOption(parsed, "package"),
1107
- engineVersion: requiredOption(parsed, "engine-version"),
1108
- integrityChecksum: optionalOption(parsed, "integrity-checksum"),
1109
- reason: requiredOption(parsed, "reason")
1110
- });
2027
+ return bindRunEngine(context, engineBindInput(parsed), prepared.engineBind);
1111
2028
  }
1112
2029
  throw new AppError("usage", `Unknown engine command: ${command ?? "<empty>"}`, 2);
1113
2030
  }
1114
- function dispatchMigration(context, command, parsed, classification) {
2031
+ function dispatchMigration(context, command, parsed, classification, prepared) {
1115
2032
  if (command === "impact")
1116
2033
  return assessMigrationImpact(context, { projectRoot: requiredOption(parsed, "project-root"), ...(optionalOption(parsed, "target-version") ? { targetVersion: optionalOption(parsed, "target-version") } : {}), ...(optionalOption(parsed, "mode") ? { mode: optionalOption(parsed, "mode") } : {}) });
1117
2034
  if (command === "plan" || command === "report") {
@@ -1127,26 +2044,42 @@ function dispatchMigration(context, command, parsed, classification) {
1127
2044
  });
1128
2045
  }
1129
2046
  if (command === "verify") {
1130
- return verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
2047
+ return prepared.migrationVerification ?? verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
1131
2048
  }
1132
2049
  if (command === "apply") {
1133
- return applyMigration(context, {
1134
- projectRoot: requiredOption(parsed, "project-root"),
1135
- sourceVersion: optionalOption(parsed, "source-version"),
1136
- targetVersion: optionalOption(parsed, "target-version"),
1137
- runId: optionalOption(parsed, "run"),
1138
- backupPath: optionalOption(parsed, "backup-path"),
1139
- backupCreatedAt: optionalOption(parsed, "backup-created-at"),
1140
- reportFile: optionalOption(parsed, "file"),
1141
- allowActive: false,
1142
- classification
1143
- });
2050
+ return applyMigration(context, migrationApplyInput(parsed, classification), prepared.migrationApply);
1144
2051
  }
1145
2052
  throw new AppError("usage", `Unknown migration command: ${command ?? "<empty>"}`, 2);
1146
2053
  }
1147
- function dispatchCanon(context, command, parsed) {
2054
+ function protocolTransitionInput(parsed, scopeProjectRoot) {
2055
+ const reason = optionalOption(parsed, "reason");
2056
+ return { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "protocol transition"), to: requiredOption(parsed, "to"), jsonFile: requiredOptionAlias(parsed, ["payload-file", "json-file"]), force: hasOption(parsed, "force"), ...(reason ? { reason } : {}) };
2057
+ }
2058
+ function controllerAnswerInput(parsed) {
2059
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run"), requestId: requiredOption(parsed, "request-id"), pauseId: requiredOption(parsed, "pause-id"), answerFile: requiredOption(parsed, "answer-file") };
2060
+ }
2061
+ function controllerLaunchInput(parsed) {
2062
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run"), requestId: requiredOption(parsed, "request-id"), contextFile: requiredOption(parsed, "context-file"), contextSha256: requiredOption(parsed, "context-sha256"), ...(optionalOption(parsed, "stop-after") ? { stopAfter: optionalOption(parsed, "stop-after") } : {}), ...(optionalOption(parsed, "capture-root") ? { captureRoot: optionalOption(parsed, "capture-root") } : {}) };
2063
+ }
2064
+ function controllerContextInput(parsed) {
2065
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run"), controllerId: requiredOption(parsed, "controller-id"), requestId: requiredOption(parsed, "request-id"), stage: requiredOption(parsed, "stage"), contextFile: requiredOption(parsed, "context-file"), contextSha256: requiredOption(parsed, "context-sha256") };
2066
+ }
2067
+ function migrationApplyInput(parsed, classification) {
2068
+ return {
2069
+ projectRoot: requiredOption(parsed, "project-root"),
2070
+ sourceVersion: optionalOption(parsed, "source-version"),
2071
+ targetVersion: optionalOption(parsed, "target-version"),
2072
+ runId: optionalOption(parsed, "run"),
2073
+ backupPath: optionalOption(parsed, "backup-path"),
2074
+ backupCreatedAt: optionalOption(parsed, "backup-created-at"),
2075
+ reportFile: optionalOption(parsed, "file"),
2076
+ allowActive: false,
2077
+ classification
2078
+ };
2079
+ }
2080
+ function dispatchCanon(context, command, parsed, prepared) {
1148
2081
  if (command === "register") {
1149
- return registerCanonRoot(context, { root: requiredOption(parsed, "root") });
2082
+ return registerCanonRoot(context, { root: requiredOption(parsed, "root") }, prepared.canonRegistration);
1150
2083
  }
1151
2084
  if (command === "status") {
1152
2085
  return getCanonStatus(context, { root: optionalOption(parsed, "root") });
@@ -1156,6 +2089,15 @@ function dispatchCanon(context, command, parsed) {
1156
2089
  }
1157
2090
  throw new AppError("usage", `Unknown canon command: ${command ?? "<empty>"}`, 2);
1158
2091
  }
2092
+ function mergeJobTarget(parsed, scopeProjectRoot) {
2093
+ return { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue"), workerId: requiredWorkerId(parsed), workspacePath: workspacePathOption(parsed) };
2094
+ }
2095
+ function mergeCancellationInput(parsed, scopeProjectRoot) {
2096
+ return { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue cancel"), reason: requiredOption(parsed, "reason"), workerId: optionalOption(parsed, "worker-id"), workspacePath: optionalOption(parsed, "path"), force: hasOption(parsed, "force") };
2097
+ }
2098
+ function mergeWaitInput(parsed, scopeProjectRoot) {
2099
+ return { projectRoot: requiredOptionOrScope(parsed, scopeProjectRoot, "project-root"), workerId: requiredWorkerId(parsed), timeoutSeconds: optionalNumber(parsed, "timeout"), pollIntervalSeconds: optionalNumber(parsed, "poll-interval"), workspacePath: workspacePathOption(parsed), acquireLock: parseOptionalBoolean(optionalOption(parsed, "acquire-lock"), "acquire-lock") ?? false };
2100
+ }
1159
2101
  function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1160
2102
  if (hasOption(parsed, "session-id")) {
1161
2103
  throw new AppError("usage", "--session-id is no longer accepted on merge-queue commands; use --worker-id", 2);
@@ -1179,32 +2121,17 @@ function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1179
2121
  });
1180
2122
  }
1181
2123
  if (command === "wait-next") {
1182
- return waitNextMergeJob(context, {
1183
- projectRoot: requiredOptionOrScope(parsed, scopeProjectRoot, "project-root"),
1184
- workerId: requiredWorkerId(parsed),
1185
- timeoutSeconds: optionalNumber(parsed, "timeout"),
1186
- pollIntervalSeconds: optionalNumber(parsed, "poll-interval"),
1187
- workspacePath: workspacePathOption(parsed),
1188
- acquireLock: parseOptionalBoolean(optionalOption(parsed, "acquire-lock"), "acquire-lock") ?? false
1189
- });
2124
+ return waitNextMergeJob(context, mergeWaitInput(parsed, scopeProjectRoot));
1190
2125
  }
1191
2126
  if (command === "complete") {
1192
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
1193
2127
  return completeMergeJob(context, {
1194
- protocolId,
1195
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue complete"),
1196
- workerId: requiredWorkerId(parsed),
1197
- workspacePath: workspacePathOption(parsed),
2128
+ ...mergeJobTarget(parsed, scopeProjectRoot),
1198
2129
  summary: requiredOption(parsed, "summary")
1199
2130
  });
1200
2131
  }
1201
2132
  if (command === "fail") {
1202
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
1203
2133
  return failMergeJob(context, {
1204
- protocolId,
1205
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue fail"),
1206
- workerId: requiredWorkerId(parsed),
1207
- workspacePath: workspacePathOption(parsed),
2134
+ ...mergeJobTarget(parsed, scopeProjectRoot),
1208
2135
  reason: requiredOption(parsed, "reason"),
1209
2136
  requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue")
1210
2137
  });
@@ -1219,15 +2146,7 @@ function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1219
2146
  });
1220
2147
  }
1221
2148
  if (command === "cancel") {
1222
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
1223
- return cancelMergeQueueJob(context, {
1224
- protocolId,
1225
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue cancel"),
1226
- reason: requiredOption(parsed, "reason"),
1227
- workerId: optionalOption(parsed, "worker-id"),
1228
- workspacePath: optionalOption(parsed, "path"),
1229
- force: hasOption(parsed, "force")
1230
- });
2149
+ return cancelMergeQueueJob(context, mergeCancellationInput(parsed, scopeProjectRoot));
1231
2150
  }
1232
2151
  throw new AppError("usage", `Unknown merge-queue command: ${command ?? "<empty>"}`, 2);
1233
2152
  }
@@ -1247,6 +2166,8 @@ async function dispatchMerge(context, command, parsed, progress) {
1247
2166
  }
1248
2167
  if (command === "apply")
1249
2168
  return applyVnextMerge(context, { projectRoot: requiredOption(parsed, "project-root"), requestId: requiredPosition(parsed, 0, "merge-request-id"), workId: requiredOption(parsed, "work"), ...(progress ? { progress } : {}) });
2169
+ if (command === "repair")
2170
+ return await repairVnextMerge(context, { projectRoot: requiredOption(parsed, "project-root"), requestId: requiredPosition(parsed, 0, "merge-request-id") });
1250
2171
  if (command === "request") {
1251
2172
  const action = requiredPosition(parsed, 0, "request action");
1252
2173
  const requestId = requiredPosition(parsed, 1, "merge-request-id");
@@ -1343,7 +2264,7 @@ function completedCommandExitCode(payload) {
1343
2264
  const exitCode = payload.exit_code;
1344
2265
  return typeof exitCode === "number" && Number.isInteger(exitCode) ? exitCode : 0;
1345
2266
  }
1346
- function dispatchCleanup(context, command, parsed) {
2267
+ function dispatchCleanup(context, command, parsed, prepared) {
1347
2268
  if (command === "scan") {
1348
2269
  return cleanupScan(context, { projectRoot: requiredOption(parsed, "project-root") });
1349
2270
  }
@@ -1351,6 +2272,7 @@ function dispatchCleanup(context, command, parsed) {
1351
2272
  return cleanupApply(context, {
1352
2273
  projectRoot: requiredOption(parsed, "project-root"),
1353
2274
  planFile: requiredOption(parsed, "plan-file"),
2275
+ prepared,
1354
2276
  reason: requiredOption(parsed, "reason"),
1355
2277
  force: hasOption(parsed, "force")
1356
2278
  });
@@ -1371,12 +2293,14 @@ function dispatchProjectConfig(context, parsed) {
1371
2293
  }
1372
2294
  throw new AppError("usage", `Unknown project config action: ${action}`, 2);
1373
2295
  }
1374
- function dispatchSession(context, command, parsed) {
2296
+ function dispatchSession(context, command, parsed, preparedPayload) {
1375
2297
  if (command === "register") {
1376
2298
  return registerFlowSession(context, {
2299
+ ...(preparedPayload ? { preparedPayload } : {}),
1377
2300
  payloadBase64: optionalOption(parsed, "payload-base64"),
1378
2301
  payloadJson: optionalOption(parsed, "payload-json"),
1379
2302
  payloadFile: optionalOption(parsed, "payload-file"),
2303
+ hookEventId: optionalOption(parsed, "hook-event-id"),
1380
2304
  sessionId: optionalOption(parsed, "session-id")
1381
2305
  });
1382
2306
  }
@@ -1409,7 +2333,45 @@ function dispatchSession(context, command, parsed) {
1409
2333
  }
1410
2334
  throw new AppError("usage", `Unknown session command: ${command ?? "<empty>"}`, 2);
1411
2335
  }
1412
- function dispatchRun(context, command, parsed) {
2336
+ function snapshotCreateInput(parsed) {
2337
+ const recoveryId = optionalOption(parsed, "recovery-id"), stageEntry = optionalOption(parsed, "stage-entry");
2338
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), output: requiredOption(parsed, "output"), candidate: parsed.options.has("candidate"), incomplete: parsed.options.has("incomplete"), ...(recoveryId !== undefined ? { recoveryId } : {}), ...(stageEntry !== undefined ? { stageEntry } : {}) };
2339
+ }
2340
+ function snapshotRestoreInput(parsed) {
2341
+ return { snapshot: requiredOption(parsed, "snapshot"), projectRoot: requiredOption(parsed, "project-root"), executionRoutingFile: optionalOption(parsed, "execution-routing-file"), ...(optionalOption(parsed, "recovery-id") ? { recoveryId: requiredOption(parsed, "recovery-id") } : {}) };
2342
+ }
2343
+ function runStartInput(parsed) {
2344
+ const protocolOverrides = readOptionalJsonFile(optionalOption(parsed, "protocol-override-file"));
2345
+ return { projectRoot: requiredOption(parsed, "project-root"), workspaceRoot: optionalOption(parsed, "workspace-root"), flowKind: requiredOption(parsed, "flow-kind"), subjectType: requiredOption(parsed, "subject-type"), subjectId: requiredOption(parsed, "subject-id"), slug: requiredOption(parsed, "slug"), nextAction: optionalOption(parsed, "next-action"), preset: optionalOption(parsed, "preset"), taskProfile: readOptionalJsonFile(optionalOption(parsed, "task-profile-file")), executionRoutingFile: optionalOption(parsed, "execution-routing-file"), ...(protocolOverrides !== undefined ? { protocolOverrides } : {}), runOverrides: parseFlowFlagOverrides(allOptions(parsed, "flag")) };
2346
+ }
2347
+ function runForkInput(parsed) {
2348
+ return { snapshot: requiredOption(parsed, "from"), output: requiredOption(parsed, "output"), engineVersion: requiredOption(parsed, "engine-version"), requestId: requiredOption(parsed, "request-id"), ...(optionalOption(parsed, "integrity-checksum") ? { integrityChecksum: optionalOption(parsed, "integrity-checksum") } : {}) };
2349
+ }
2350
+ function recoveryCaptureInput(parsed) {
2351
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), recoveryId: requiredOption(parsed, "recovery-id"), capturePath: requiredOption(parsed, "capture-path") };
2352
+ }
2353
+ function recoveryResumeInput(parsed) {
2354
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), recoveryId: requiredOption(parsed, "recovery-id"), daemonId: requiredOption(parsed, "daemon-id"), harness: requiredOption(parsed, "harness"), nativeSessionId: requiredOption(parsed, "native-session-id") };
2355
+ }
2356
+ function dispatchRun(context, command, parsed, prepared = {}) {
2357
+ if (command === "recovery") {
2358
+ const action = requiredPosition(parsed, 0, "recovery action");
2359
+ const projectRoot = requiredOption(parsed, "project-root");
2360
+ const runId = requiredPosition(parsed, 1, "run-id");
2361
+ if (action === "inspect")
2362
+ return inspectRunRecovery(context, { projectRoot, runId });
2363
+ if (action === "begin")
2364
+ return beginRunRecovery(context, { projectRoot, runId, interruption: requiredOption(parsed, "interruption-json") }, prepared.recoveryPayload);
2365
+ if (action === "seal")
2366
+ return sealRunRecovery(context, { projectRoot, runId, recoveryId: requiredOption(parsed, "recovery-id"), settlement: requiredOption(parsed, "settlement-json") }, prepared.recoveryPayload);
2367
+ if (action === "capture")
2368
+ return recordRecoveryCapture(context, recoveryCaptureInput(parsed), prepared.recoveryCapture);
2369
+ if (action === "resume")
2370
+ return resumeRunRecovery(context, recoveryResumeInput(parsed), prepared.recoveryResume);
2371
+ if (action === "accept")
2372
+ return acceptRunRecovery(context, { projectRoot, runId, recoveryId: requiredOption(parsed, "recovery-id"), ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
2373
+ throw new AppError("usage", "Use: dd-flow run recovery inspect|begin|seal|capture|resume|accept", 2);
2374
+ }
1413
2375
  if (command === "snapshot") {
1414
2376
  const action = requiredPosition(parsed, 0, "snapshot action");
1415
2377
  if (action === "bootstrap") {
@@ -1420,56 +2382,27 @@ function dispatchRun(context, command, parsed) {
1420
2382
  output: requiredOption(parsed, "output")
1421
2383
  });
1422
2384
  if (bootstrapAction === "restore")
1423
- return restoreEvalBootstrapSnapshot(context, {
1424
- snapshot: requiredOption(parsed, "snapshot"),
1425
- projectRoot: requiredOption(parsed, "project-root")
1426
- });
2385
+ return restoreEvalBootstrapSnapshot(context, snapshotRestoreInput(parsed), prepared.bootstrapRestore);
1427
2386
  throw new AppError("usage", "Use: dd-flow run snapshot bootstrap create|restore", 2);
1428
2387
  }
1429
2388
  if (action === "create") {
1430
- const candidate = parsed.options.has("candidate");
1431
- const stageEntry = optionalOption(parsed, "stage-entry");
1432
- if (candidate && stageEntry !== undefined)
1433
- throw new AppError("usage", "Use either --candidate or --stage-entry, not both", 2);
1434
- if (!candidate && stageEntry === undefined)
1435
- throw new AppError("usage", "Snapshot create requires --candidate or --stage-entry", 2);
1436
- const input = {
1437
- projectRoot: requiredOption(parsed, "project-root"),
1438
- runId: requiredPosition(parsed, 1, "run-id"),
1439
- output: requiredOption(parsed, "output")
1440
- };
1441
- return candidate
1442
- ? createEvalRunSnapshot(context, { ...input, candidate: true })
1443
- : createEvalRunSnapshot(context, { ...input, stageEntry: stageEntry });
2389
+ return createEvalRunSnapshot(context, snapshotCreateInput(parsed));
1444
2390
  }
1445
2391
  if (action === "restore")
1446
- return restoreEvalRunSnapshot(context, {
1447
- snapshot: requiredOption(parsed, "snapshot"),
1448
- projectRoot: requiredOption(parsed, "project-root")
1449
- });
2392
+ return restoreEvalRunSnapshot(context, snapshotRestoreInput(parsed), prepared.snapshotRestore);
1450
2393
  throw new AppError("usage", "Use: dd-flow run snapshot bootstrap create|restore | dd-flow run snapshot create <RUN> (--stage-entry <stage>|--candidate) --project-root <path> --output <directory> | dd-flow run snapshot restore --snapshot <directory> --project-root <path>", 2);
1451
2394
  }
2395
+ if (command === "fork") {
2396
+ return forkRunFromSnapshot(context, runForkInput(parsed), prepared.runFork);
2397
+ }
1452
2398
  if (command === "prepare-vnext-specify") {
1453
- return prepareVnextSpecifyRun(context, { projectRoot: requiredOption(parsed, "project-root"), slug: requiredOption(parsed, "slug") });
2399
+ return prepareVnextSpecifyRun(context, { projectRoot: requiredOption(parsed, "project-root"), slug: requiredOption(parsed, "slug"), executionRoutingFile: optionalOption(parsed, "execution-routing-file") });
1454
2400
  }
1455
2401
  if (command === "start") {
1456
2402
  if (optionalOption(parsed, "flow-kind") === "mb-upgrade") {
1457
2403
  assertUpgradeRunStorageReady(context, requiredOption(parsed, "project-root"));
1458
2404
  }
1459
- const protocolOverrides = readOptionalJsonFile(optionalOption(parsed, "protocol-override-file"));
1460
- return startFlowRun(context, {
1461
- projectRoot: requiredOption(parsed, "project-root"),
1462
- workspaceRoot: optionalOption(parsed, "workspace-root"),
1463
- flowKind: requiredOption(parsed, "flow-kind"),
1464
- subjectType: requiredOption(parsed, "subject-type"),
1465
- subjectId: requiredOption(parsed, "subject-id"),
1466
- slug: requiredOption(parsed, "slug"),
1467
- nextAction: optionalOption(parsed, "next-action"),
1468
- preset: optionalOption(parsed, "preset"),
1469
- taskProfile: readOptionalJsonFile(optionalOption(parsed, "task-profile-file")),
1470
- ...(protocolOverrides ? { protocolOverrides } : {}),
1471
- runOverrides: parseFlowFlagOverrides(allOptions(parsed, "flag"))
1472
- });
2405
+ return startFlowRun(context, prepared.runStart?.input ?? runStartInput(parsed), prepared.runStart?.value);
1473
2406
  }
1474
2407
  if (command === "status") {
1475
2408
  return getFlowRunStatus(context, {
@@ -1539,83 +2472,163 @@ function dispatchRun(context, command, parsed) {
1539
2472
  throw new AppError("usage", `Unknown run flags command: ${action}`, 2);
1540
2473
  }
1541
2474
  if (command === "attach-stage") {
1542
- return attachFlowRunStage(context, {
1543
- projectRoot: requiredOption(parsed, "project-root"),
1544
- runId: requiredPosition(parsed, 0, "run-id"),
1545
- stage: requiredOption(parsed, "stage"),
1546
- dir: requiredOption(parsed, "dir"),
1547
- status: requiredOption(parsed, "status"),
1548
- dataSchemaId: optionalOption(parsed, "data-schema-id")
1549
- });
2475
+ return attachFlowRunStage(context, stageAttachmentInput(parsed));
1550
2476
  }
1551
2477
  if (command === "complete-stage") {
1552
- const stageReport = optionalOption(parsed, "stage-report") ?? optionalOption(parsed, "dashboard");
1553
- return completeFlowRunStage(context, {
1554
- projectRoot: requiredOption(parsed, "project-root"),
1555
- runId: requiredPosition(parsed, 0, "run-id"),
1556
- stage: requiredOption(parsed, "stage"),
1557
- status: requiredOption(parsed, "status"),
1558
- stageReport,
1559
- data: optionalOption(parsed, "data"),
1560
- dataSchemaId: optionalOption(parsed, "data-schema-id"),
1561
- report: optionalOption(parsed, "report"),
1562
- aliases: allOptions(parsed, "alias")
1563
- });
2478
+ return completeFlowRunStage(context, stageCompletionInput(parsed));
1564
2479
  }
1565
2480
  if (command === "complete") {
1566
2481
  throw new AppError("usage", "run complete is retired; only an operator may use run override", 2);
1567
2482
  }
1568
2483
  if (command === "override") {
1569
- const status = requiredOption(parsed, "status");
1570
- if (!['cancelled', 'failed'].includes(status)) {
1571
- throw new AppError("usage", "run override status must be cancelled or failed", 2, { status });
1572
- }
1573
- return completeFlowRun(context, {
1574
- projectRoot: requiredOption(parsed, "project-root"),
1575
- runId: requiredPosition(parsed, 0, "run-id"),
1576
- status,
1577
- verdict: optionalOption(parsed, "verdict"),
1578
- nextAction: optionalOption(parsed, "next-action"),
1579
- manualOverrideReason: requiredOption(parsed, "reason")
1580
- });
2484
+ return completeFlowRun(context, runOverrideInput(parsed));
1581
2485
  }
1582
2486
  throw new AppError("usage", `Unknown run command: ${command ?? "<empty>"}`, 2);
1583
2487
  }
1584
- async function dispatchRuntime(context, command, parsed) {
2488
+ function stageAttachmentInput(parsed) {
2489
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), dir: requiredOption(parsed, "dir"), status: requiredOption(parsed, "status"), dataSchemaId: optionalOption(parsed, "data-schema-id") };
2490
+ }
2491
+ function runOverrideInput(parsed) {
2492
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), status: requiredOption(parsed, "status"), verdict: optionalOption(parsed, "verdict"), nextAction: optionalOption(parsed, "next-action"), manualOverrideReason: requiredOption(parsed, "reason") };
2493
+ }
2494
+ function stageCompletionInput(parsed) {
2495
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), status: requiredOption(parsed, "status"), stageReport: optionalOption(parsed, "stage-report") ?? optionalOption(parsed, "dashboard"), data: optionalOption(parsed, "data"), dataSchemaId: optionalOption(parsed, "data-schema-id"), report: optionalOption(parsed, "report"), aliases: allOptions(parsed, "alias") };
2496
+ }
2497
+ function runtimeServiceInput(parsed) {
2498
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run"), command: requiredOption(parsed, "command"), ports: requiredOption(parsed, "ports").split(","), readyPort: requiredOption(parsed, "ready-port"), readyPath: optionalOption(parsed, "ready-path") ?? "/", timeoutMs: optionalPositiveNumber(parsed, "ready-timeout-ms", true) ?? 30_000 };
2499
+ }
2500
+ function runtimeProcessStopInput(parsed) {
2501
+ const graceMs = optionalNumber(parsed, "grace-ms");
2502
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(graceMs !== undefined ? { graceMs } : {}) };
2503
+ }
2504
+ function runtimeScopeResumeInput(parsed) {
2505
+ return { scopeId: requiredOption(parsed, "scope-id"), requestId: requiredOption(parsed, "request-id"), generation: Number(requiredOption(parsed, "generation")), captureKey: requiredOption(parsed, "capture-key") };
2506
+ }
2507
+ function runtimeProcessRegistrationInput(context, parsed) {
2508
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
2509
+ const budget = parseRuntimeBudget(optionalOption(parsed, "budget-json"));
2510
+ const kind = requiredOption(parsed, "kind");
2511
+ const projectId = optionalOption(parsed, "project-id") ?? null, runId = optionalOption(parsed, "run") ?? null;
2512
+ const guard = projectId && runId ? recoveryGuard(context, projectId, runId) : null;
2513
+ const run = projectId && runId ? context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]) : null;
2514
+ return {
2515
+ kind, ownerId: requiredOption(parsed, "owner"), uniqueActiveOperation: kind === "eval-observer",
2516
+ ...(kind === "eval-observer" ? { pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(optionalPositiveNumber(parsed, "process-group-id", true) ? { processGroupId: optionalPositiveNumber(parsed, "process-group-id", true) } : {}) } : {}),
2517
+ ownerPid: optionalPositiveNumber(parsed, "owner-pid", true), projectId, runId,
2518
+ workId: optionalOption(parsed, "work") ?? null, checkId: optionalOption(parsed, "check") ?? null,
2519
+ operationId: optionalOption(parsed, "operation") ?? null, stdoutPath: optionalOption(parsed, "stdout") ?? null,
2520
+ stderrPath: optionalOption(parsed, "stderr") ?? null, ...(leaseMs !== undefined ? { leaseMs } : {}),
2521
+ metadata: { ...(budget ? { budget, harness: optionalOption(parsed, "harness") ?? null } : {}), ...(projectId && runId ? { run_generation: guard?.generation ?? 0, run_admitted: Boolean(run) && !["draining", "sealed", "resuming"].includes(guard?.status ?? "") } : {}), ...(optionalOption(parsed, "dispatch-barrier") ? { dispatch_barrier: optionalOption(parsed, "dispatch-barrier") } : {}), ...(optionalOption(parsed, "role") ? { role: optionalOption(parsed, "role") } : {}), ...(optionalOption(parsed, "state-dir") ? { state_dir: optionalOption(parsed, "state-dir") } : {}), ...(optionalOption(parsed, "adapter-executable") ? { adapter_executable: optionalOption(parsed, "adapter-executable") } : {}) }
2522
+ };
2523
+ }
2524
+ function runtimeProcessConfirmationInput(parsed) {
2525
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true), processGroupId = optionalPositiveNumber(parsed, "process-group-id", true);
2526
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ownerPid: optionalPositiveNumber(parsed, "owner-pid", true), pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(processGroupId !== undefined ? { processGroupId } : {}), ...(leaseMs !== undefined ? { leaseMs } : {}) };
2527
+ }
2528
+ function runtimeProcessHeartbeatInput(parsed) {
2529
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
2530
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(leaseMs !== undefined ? { leaseMs } : {}) };
2531
+ }
2532
+ function runtimeProcessFinishInput(parsed) {
2533
+ const state = requiredOption(parsed, "state");
2534
+ if (state !== "stopped" && state !== "failed")
2535
+ throw new AppError("validation", "--state must be stopped or failed", 2);
2536
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), state, reason: optionalOption(parsed, "reason") ?? null };
2537
+ }
2538
+ async function dispatchRuntime(context, command, parsed, progress, prepared = {}) {
2539
+ if (command === "scope") {
2540
+ if (parsed.positional.length === 1 && parsed.positional[0] === "reconcile") {
2541
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "generation"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2542
+ throw new AppError("usage", "Use runtime scope reconcile --scope-id ID --generation N --request-id ID", 2);
2543
+ return { ok: true, ...await reconcileRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")), requiredOption(parsed, "request-id")) };
2544
+ }
2545
+ if (parsed.positional.length === 1 && parsed.positional[0] === "resume") {
2546
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "generation", "capture-key"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2547
+ throw new AppError("usage", "Use runtime scope resume --scope-id ID --request-id ID --generation N --capture-key SHA256", 2);
2548
+ return { ok: true, ...await launchRuntimeScopeResume(context, runtimeScopeResumeInput(parsed)) };
2549
+ }
2550
+ if (parsed.positional.length === 1 && parsed.positional[0] === "control") {
2551
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "mode", "manifest-json"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2552
+ throw new AppError("usage", "Use runtime scope control --scope-id ID --request-id ID --mode pause|stop [--manifest-json JSON]", 2);
2553
+ const mode = requiredOption(parsed, "mode");
2554
+ if (mode !== "pause" && mode !== "stop")
2555
+ throw new AppError("usage", "Scope control mode must be pause or stop", 2);
2556
+ return { ok: true, ...await launchRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id"), mode, undefined, undefined, undefined, prepared.runtimeManifest) };
2557
+ }
2558
+ if (parsed.positional.length === 1 && parsed.positional[0] === "serve") {
2559
+ if ([...parsed.options.keys()].some(key => !["scope-id", "generation"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2560
+ throw new AppError("usage", "Invalid internal scope worker arguments", 2);
2561
+ return { ok: true, ...await serveRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation"))) };
2562
+ }
2563
+ if (parsed.positional.length === 1 && parsed.positional[0] === "stop") {
2564
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2565
+ throw new AppError("usage", "Usage: dd-flow runtime scope stop --scope-id EVAL_ID --request-id ID", 2);
2566
+ return { ok: true, ...await stopRuntimeScope(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id")) };
2567
+ }
2568
+ if (parsed.positional.length === 1 && parsed.positional[0] === "status") {
2569
+ if ([...parsed.options.keys()].some(key => key !== "scope-id") || [...parsed.options.values()].some(values => values.length !== 1))
2570
+ throw new AppError("usage", "Usage: dd-flow runtime scope status --scope-id EVAL_ID", 2);
2571
+ return { ok: true, ...runtimeBudgetStatus(context, requiredOption(parsed, "scope-id")) };
2572
+ }
2573
+ if (parsed.positional.length !== 1 || parsed.positional[0] !== "fence" || [...parsed.options.keys()].some(key => !["scope-id", "request-id"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2574
+ throw new AppError("usage", "Usage: dd-flow runtime scope fence --scope-id EVAL_ID --request-id ID", 2);
2575
+ return { ok: true, ...fenceRuntimeBudget(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id")) };
2576
+ }
1585
2577
  if (command !== "process")
1586
- throw new AppError("usage", "Usage: dd-flow runtime process <register|confirm|heartbeat|finish|status|reconcile>", 2);
2578
+ throw new AppError("usage", "Usage: dd-flow runtime <scope|process>; see dd-flow runtime scope --help", 2);
1587
2579
  const action = requiredPosition(parsed, 0, "runtime process action");
2580
+ if (action === "check-admission")
2581
+ return { ok: true, ...admitRuntimeCheck(context, requiredOption(parsed, "id"), requiredOption(parsed, "lease-token")) };
2582
+ if (action === "start")
2583
+ return await startRuntimeService(context, { ...runtimeServiceInput(parsed), progress });
2584
+ if (action === "stop")
2585
+ return { ok: true, process: await stopManagedProcess(context, runtimeProcessStopInput(parsed)) };
1588
2586
  if (action === "register") {
1589
- const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
1590
- const process = registerManagedProcess(context, {
1591
- kind: requiredOption(parsed, "kind"), ownerId: requiredOption(parsed, "owner"),
1592
- projectId: optionalOption(parsed, "project-id") ?? null, runId: optionalOption(parsed, "run") ?? null,
1593
- workId: optionalOption(parsed, "work") ?? null, checkId: optionalOption(parsed, "check") ?? null,
1594
- operationId: optionalOption(parsed, "operation") ?? null, stdoutPath: optionalOption(parsed, "stdout") ?? null,
1595
- stderrPath: optionalOption(parsed, "stderr") ?? null, ...(leaseMs ? { leaseMs } : {})
1596
- });
2587
+ const process = registerManagedProcess(context, runtimeProcessRegistrationInput(context, parsed));
1597
2588
  return { ok: true, process };
1598
2589
  }
1599
- if (action === "confirm") {
1600
- const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
1601
- const processGroupId = optionalPositiveNumber(parsed, "process-group-id", true);
1602
- return { ok: true, process: confirmManagedProcess(context, { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(processGroupId ? { processGroupId } : {}), ...(leaseMs ? { leaseMs } : {}) }) };
1603
- }
1604
- if (action === "heartbeat") {
1605
- const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
1606
- return { ok: heartbeatManagedProcess(context, { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(leaseMs ? { leaseMs } : {}) }) };
2590
+ if (action === "confirm")
2591
+ return { ok: true, process: confirmManagedProcess(context, runtimeProcessConfirmationInput(parsed)) };
2592
+ if (action === "heartbeat")
2593
+ return { ok: heartbeatManagedProcess(context, runtimeProcessHeartbeatInput(parsed)) };
2594
+ if (action === "admission") {
2595
+ const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
2596
+ if (!record || record.lease_token !== requiredOption(parsed, "lease-token") || record.owner_id !== requiredOption(parsed, "owner") || record.state !== "running" || !record.pid || !record.pid_started_at || !processIsAlive(record))
2597
+ throw new AppError("process_ownership_unknown", "Productive dispatch requires its current confirmed runtime owner", 1);
2598
+ const metadata = JSON.parse(record.metadata_json);
2599
+ if (metadata.state_dir !== requiredOption(parsed, "state-dir"))
2600
+ throw new AppError("process_ownership_unknown", "Runtime admission belongs to another state directory", 1);
2601
+ if (record.project_id && record.run_id) {
2602
+ if (managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
2603
+ throw new AppError("process_runtime_scope_mismatch", "Runtime admission belongs to another or unproven flow home", 1);
2604
+ const recovering = recoveryRuntimeAdmission(context, record, { stateDir: requiredOption(parsed, "state-dir"), daemonId: optionalOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), operation: optionalOption(parsed, "operation"), nativeSessionId: optionalOption(parsed, "native-session-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
2605
+ if (!recovering) {
2606
+ if (metadata.run_admitted !== true || !Number.isSafeInteger(metadata.run_generation))
2607
+ throw new AppError("run_recovery_guarded", "Runtime was not admitted before the RUN fence; reconcile its launch", 1);
2608
+ assertRunMutationAllowed(context, record.project_id, record.run_id, metadata.run_generation);
2609
+ }
2610
+ const run = context.db.get("SELECT status FROM runs WHERE project_id = ? AND id = ?", [record.project_id, record.run_id]);
2611
+ const retainedHitlPrompt = recovering && ["paused", "waiting_for_user"].includes(run?.status ?? "") && ["session.prompt", "session.resume"].includes(optionalOption(parsed, "operation") ?? "") && context.db.get("SELECT 1 FROM run_recovery_bindings b JOIN run_recovery_guards g ON g.recovery_id = b.recovery_id WHERE g.project_id = ? AND g.run_id = ? AND g.generation = ? AND b.daemon_id = ? AND b.provider_session_id = ?", [record.project_id, record.run_id, metadata.run_generation, optionalOption(parsed, "daemon-id"), optionalOption(parsed, "native-session-id")]);
2612
+ const acceptedHitlPrompt = ["paused", "waiting_for_user"].includes(run?.status ?? "") && controllerHitlAdmission(context, record, { stateDir: requiredOption(parsed, "state-dir"), operationId: optionalOption(parsed, "operation-id"), operation: optionalOption(parsed, "operation"), nativeSessionId: optionalOption(parsed, "native-session-id"), promptSha256: optionalOption(parsed, "prompt-sha256") });
2613
+ if (!run || run.status !== "running" && !retainedHitlPrompt && !acceptedHitlPrompt && !["judge", "probe"].includes(metadata.role ?? ""))
2614
+ throw new AppError("invalid_run_state", "Subject dispatch requires a running RUN or its retained recovery/HITL prompt", 1);
2615
+ }
2616
+ const budget = reserveProviderTurn(context, record, { operationId: optionalOption(parsed, "operation-id") ?? "", operation: optionalOption(parsed, "operation") ?? "", sessionId: optionalOption(parsed, "native-session-id"), daemonId: optionalOption(parsed, "daemon-id") });
2617
+ return { ok: true, ...budget, process_id: record.id, generation: metadata.run_generation ?? null };
1607
2618
  }
1608
- if (action === "finish") {
1609
- const state = requiredOption(parsed, "state");
1610
- if (state !== "stopped" && state !== "failed")
1611
- throw new AppError("validation", "--state must be stopped or failed", 2);
1612
- return { ok: finishManagedProcess(context, { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), state: state, reason: optionalOption(parsed, "reason") ?? null }) };
2619
+ if (action === "release-turn") {
2620
+ const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
2621
+ if (!record || record.lease_token !== requiredOption(parsed, "lease-token") || record.owner_id !== requiredOption(parsed, "owner") || managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
2622
+ throw new AppError("process_ownership_unknown", "Budget release requires its retained physical owner", 1);
2623
+ return releaseProviderTurns(context, record, { daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") }, prepared.providerTurnRelease);
1613
2624
  }
2625
+ if (action === "finish")
2626
+ return { ok: finishManagedProcess(context, runtimeProcessFinishInput(parsed)) };
1614
2627
  if (action === "status")
1615
2628
  return { ok: true, processes: managedProcessStatus(context) };
1616
2629
  if (action === "reconcile")
1617
- return { ok: true, processes: await reconcileExpiredManagedProcesses(context, requiredOption(parsed, "owner"), optionalPositiveNumber(parsed, "grace-ms", true)) };
1618
- throw new AppError("usage", "Usage: dd-flow runtime process <register|confirm|heartbeat|finish|status|reconcile>", 2);
2630
+ return { ok: true, processes: await reconcileExpiredManagedProcesses(context, requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms")) };
2631
+ throw new AppError("usage", "Usage: dd-flow runtime process <start|stop|register|confirm|heartbeat|admission|finish|status|reconcile>", 2);
1619
2632
  }
1620
2633
  function dispatchStat(context, command, parsed) {
1621
2634
  if (command === "usage") {
@@ -1802,7 +2815,9 @@ function dispatchSchema(context, command, parsed) {
1802
2815
  // searching project directories: run_id is a structural field in the
1803
2816
  // submitted artifact and the database owns its materialized run_root.
1804
2817
  const explicitRunId = optionalOption(parsed, "run");
1805
- const declaredRunId = explicitRunId ?? readRunId(file);
2818
+ const data = prepareJsonFile(file, "schema input").value;
2819
+ const declared = data && typeof data === "object" && "run_id" in data ? data.run_id : undefined;
2820
+ const declaredRunId = explicitRunId ?? (typeof declared === "string" && declared.trim() ? declared : undefined);
1806
2821
  const fileRunRoot = path.basename(file) === "run.json" ? path.dirname(path.resolve(file)) : undefined;
1807
2822
  const bound = projectRoot
1808
2823
  ? context.db.get("SELECT r.id, r.run_root FROM runs r JOIN projects p ON p.id = r.project_id WHERE p.root = ? AND (r.id = ? OR r.run_root = ?) LIMIT 1", [fs.realpathSync(projectRoot), declaredRunId ?? "", fileRunRoot ?? ""])
@@ -1810,6 +2825,7 @@ function dispatchSchema(context, command, parsed) {
1810
2825
  return validateSchema({
1811
2826
  schemaName: requiredOption(parsed, "schema"),
1812
2827
  file,
2828
+ data,
1813
2829
  ...(schemaDir ? { schemaDir } : {}),
1814
2830
  ...(projectRoot ? { projectRoot } : {}),
1815
2831
  ...(declaredRunId || bound?.id ? { runId: declaredRunId ?? bound.id } : {}),
@@ -1819,14 +2835,11 @@ function dispatchSchema(context, command, parsed) {
1819
2835
  }
1820
2836
  throw new AppError("usage", `Unknown schema command: ${command ?? "<empty>"}`, 2);
1821
2837
  }
1822
- function readRunId(file) {
1823
- try {
1824
- const value = JSON.parse(fs.readFileSync(file, "utf8"));
1825
- return typeof value.run_id === "string" && value.run_id.trim() ? value.run_id : undefined;
1826
- }
1827
- catch {
1828
- return undefined;
1829
- }
2838
+ function laneWorkspaceInput(parsed) {
2839
+ return { projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workspacePath: requiredOption(parsed, "path"), branch: optionalOption(parsed, "branch") };
2840
+ }
2841
+ function laneWaiterCancelInput(parsed) {
2842
+ return { projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workerId: requiredOption(parsed, "worker-id"), reason: requiredOption(parsed, "reason") };
1830
2843
  }
1831
2844
  async function dispatchLane(context, command, parsed) {
1832
2845
  if (command === "status") {
@@ -1838,24 +2851,14 @@ async function dispatchLane(context, command, parsed) {
1838
2851
  if (command === "waiter") {
1839
2852
  const action = requiredPosition(parsed, 0, "lane waiter action");
1840
2853
  if (action === "cancel") {
1841
- return cancelLaneWaiter(context, {
1842
- projectRoot: requiredOption(parsed, "project-root"),
1843
- lane: requiredOption(parsed, "lane"),
1844
- workerId: requiredOption(parsed, "worker-id"),
1845
- reason: requiredOption(parsed, "reason")
1846
- });
2854
+ return cancelLaneWaiter(context, laneWaiterCancelInput(parsed));
1847
2855
  }
1848
2856
  throw new AppError("usage", `Unknown lane waiter action: ${action}`, 2);
1849
2857
  }
1850
2858
  if (command === "workspace") {
1851
2859
  const action = requiredPosition(parsed, 0, "lane workspace action");
1852
2860
  if (action === "set") {
1853
- return setLaneWorkspace(context, {
1854
- projectRoot: requiredOption(parsed, "project-root"),
1855
- lane: requiredOption(parsed, "lane"),
1856
- workspacePath: requiredOption(parsed, "path"),
1857
- branch: optionalOption(parsed, "branch")
1858
- });
2861
+ return setLaneWorkspace(context, laneWorkspaceInput(parsed));
1859
2862
  }
1860
2863
  if (action === "check") {
1861
2864
  return checkLaneWorkspace(context, {
@@ -1927,7 +2930,7 @@ async function dispatchLane(context, command, parsed) {
1927
2930
  }
1928
2931
  throw new AppError("usage", `Unknown lane command: ${command ?? "<empty>"}`, 2);
1929
2932
  }
1930
- function dispatchCodexHooks(context, parsed) {
2933
+ function dispatchCodexHooks(context, parsed, prepared) {
1931
2934
  const action = requiredPosition(parsed, 0, "codex hooks action");
1932
2935
  if (action === "print") {
1933
2936
  return printCodexHooks(context, {
@@ -1949,7 +2952,7 @@ function dispatchCodexHooks(context, parsed) {
1949
2952
  target: optionalOption(parsed, "target"),
1950
2953
  profile: optionalOption(parsed, "profile"),
1951
2954
  yes: hasOption(parsed, "yes")
1952
- });
2955
+ }, prepared.codexHooks);
1953
2956
  }
1954
2957
  if (action === "remove") {
1955
2958
  return removeCodexHooks(context, {
@@ -1957,11 +2960,14 @@ function dispatchCodexHooks(context, parsed) {
1957
2960
  target: optionalOption(parsed, "target"),
1958
2961
  profile: optionalOption(parsed, "profile"),
1959
2962
  yes: hasOption(parsed, "yes")
1960
- });
2963
+ }, prepared.codexHooks);
1961
2964
  }
1962
2965
  throw new AppError("usage", `Unknown codex hooks action: ${action}`, 2);
1963
2966
  }
1964
- function dispatchCodexHome(context, parsed) {
2967
+ function codexHomeInput(parsed) {
2968
+ return { projectRoot: requiredOption(parsed, "project-root"), profile: optionalOption(parsed, "profile"), sourceHome: optionalOption(parsed, "source-home"), targetHome: optionalOption(parsed, "target-home") };
2969
+ }
2970
+ function dispatchCodexHome(context, parsed, prepared) {
1965
2971
  const action = requiredPosition(parsed, 0, "codex home action");
1966
2972
  if (action === "plan") {
1967
2973
  return planCodexHome(context, {
@@ -1972,12 +2978,7 @@ function dispatchCodexHome(context, parsed) {
1972
2978
  });
1973
2979
  }
1974
2980
  if (action === "init") {
1975
- return initCodexHome(context, {
1976
- projectRoot: requiredOption(parsed, "project-root"),
1977
- profile: optionalOption(parsed, "profile"),
1978
- sourceHome: optionalOption(parsed, "source-home"),
1979
- targetHome: optionalOption(parsed, "target-home")
1980
- });
2981
+ return initCodexHome(context, codexHomeInput(parsed), prepared.codexHome);
1981
2982
  }
1982
2983
  if (action === "status") {
1983
2984
  return getCodexHomeStatus(context, {
@@ -2000,11 +3001,14 @@ function dispatchCodexHome(context, parsed) {
2000
3001
  }
2001
3002
  throw new AppError("usage", `Unknown codex home action: ${action}`, 2);
2002
3003
  }
2003
- function dispatchCodexHook(context, parsed, stdin) {
3004
+ async function dispatchCodexHook(context, parsed, stdin) {
2004
3005
  const action = requiredPosition(parsed, 0, "codex hook action");
2005
3006
  if (action === "handle") {
2006
3007
  const isolatedHome = isolatedDdFlowHomeFromHookStdin(stdin);
2007
- const hookContext = isolatedHome ? createContext({ ...context.env, DD_FLOW_HOME: isolatedHome }) : context;
3008
+ const hookContext = isolatedHome ? createContext({ ...context.env, DD_FLOW_HOME: isolatedHome }, "hook") : context;
3009
+ const proof = await verifyCodexHookDelivery(hookContext.env, JSON.parse(stdin || "{}"));
3010
+ if (proof)
3011
+ hookContext.codexHookProof = proof;
2008
3012
  const result = handleCodexHook(hookContext, {
2009
3013
  event: requiredOption(parsed, "event"),
2010
3014
  projectRoot: optionalOption(parsed, "project-root"),
@@ -2027,6 +3031,15 @@ function dispatchZcodeEvent(context, parsed, stdin) {
2027
3031
  }
2028
3032
  throw new AppError("usage", `Unknown zcode event action: ${action}`, 2);
2029
3033
  }
3034
+ function dispatchZcodeHook(context, parsed, stdin) {
3035
+ if (requiredPosition(parsed, 0, "zcode hook action") !== "handle")
3036
+ throw new AppError("usage", "Unknown zcode hook action", 2);
3037
+ const result = handleZcodeHook(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
3038
+ if (result && typeof result === "object" && !Array.isArray(result) && "hookSpecificOutput" in result) {
3039
+ return { hookSpecificOutput: result.hookSpecificOutput };
3040
+ }
3041
+ return {};
3042
+ }
2030
3043
  function dispatchGrokEvent(context, parsed, stdin) {
2031
3044
  const action = requiredPosition(parsed, 0, "grok event action");
2032
3045
  if (action === "handle") {
@@ -2050,7 +3063,7 @@ function dispatchAgyEvent(context, parsed, stdin) {
2050
3063
  return handleAgyEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
2051
3064
  throw new AppError("usage", `Unknown agy event action: ${action}`, 2);
2052
3065
  }
2053
- function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
3066
+ function dispatchWorktree(context, command, parsed, scopeProjectRoot, prepared) {
2054
3067
  if (command === "plan") {
2055
3068
  return planWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
2056
3069
  }
@@ -2061,13 +3074,13 @@ function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
2061
3074
  branch: requiredOption(parsed, "branch"),
2062
3075
  base: requiredOption(parsed, "base"),
2063
3076
  path: requiredOption(parsed, "path")
2064
- });
3077
+ }, prepared.worktreeCreate);
2065
3078
  }
2066
3079
  if (command === "status") {
2067
3080
  return getWorktreeStatus(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
2068
3081
  }
2069
3082
  if (command === "bootstrap") {
2070
- return bootstrapWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
3083
+ return bootstrapWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot }, prepared.worktreeBootstrap);
2071
3084
  }
2072
3085
  if (command === "close") {
2073
3086
  return closeWorktree(context, {
@@ -2079,52 +3092,50 @@ function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
2079
3092
  throw new AppError("usage", `Unknown worktree command: ${command ?? "<empty>"}`, 2);
2080
3093
  }
2081
3094
  function dispatchPlanItem(context, parsed, projectRoot) {
3095
+ return updatePlanItem(context, planItemInput(parsed, projectRoot));
3096
+ }
3097
+ function planItemInput(parsed, projectRoot) {
2082
3098
  const action = requiredPosition(parsed, 0, "plan item action");
2083
3099
  const protocolId = requiredPosition(parsed, 1, "protocol-id");
2084
3100
  const itemId = requiredPosition(parsed, 2, "item-id");
2085
3101
  if (action === "start") {
2086
- return startPlanItem(context, { protocolId, projectRoot, itemId });
3102
+ return { protocolId, projectRoot, itemId, action };
2087
3103
  }
2088
3104
  if (action === "done") {
2089
- return completePlanItem(context, {
3105
+ return {
3106
+ action,
2090
3107
  protocolId,
2091
3108
  projectRoot,
2092
3109
  itemId,
2093
3110
  summary: requiredOption(parsed, "summary"),
2094
3111
  evidence: parsed.options.get("evidence") ?? []
2095
- });
3112
+ };
2096
3113
  }
2097
3114
  if (action === "block") {
2098
- return blockPlanItem(context, {
3115
+ return {
3116
+ action,
2099
3117
  protocolId,
2100
3118
  projectRoot,
2101
3119
  itemId,
2102
3120
  reason: requiredOption(parsed, "reason"),
2103
3121
  userRequired: parseBoolean(requiredOption(parsed, "user-required"), "user-required")
2104
- });
3122
+ };
2105
3123
  }
2106
3124
  if (action === "skip") {
2107
- return skipPlanItem(context, {
3125
+ return {
3126
+ action,
2108
3127
  protocolId,
2109
3128
  projectRoot,
2110
3129
  itemId,
2111
3130
  reason: requiredOption(parsed, "reason")
2112
- });
3131
+ };
2113
3132
  }
2114
3133
  throw new AppError("usage", `Unknown plan item action: ${action}`, 2);
2115
3134
  }
2116
3135
  function readOptionalJsonFile(file) {
2117
3136
  if (!file)
2118
3137
  return undefined;
2119
- if (!fs.existsSync(file)) {
2120
- throw new AppError("not_found", `JSON file does not exist: ${file}`, 1);
2121
- }
2122
- try {
2123
- return JSON.parse(fs.readFileSync(file, "utf8"));
2124
- }
2125
- catch {
2126
- throw new AppError("validation", `JSON file is malformed: ${file}`, 2);
2127
- }
3138
+ return prepareJsonFile(file, "JSON input").value;
2128
3139
  }
2129
3140
  function parseFlowFlagOverrides(values) {
2130
3141
  const result = {};
@@ -2159,7 +3170,11 @@ function requiredPosition(parsed, index, label) {
2159
3170
  function optionalOption(parsed, key) {
2160
3171
  const values = parsed.options.get(key);
2161
3172
  const value = values?.[values.length - 1];
2162
- return value === flagValue ? undefined : value;
3173
+ if (value === flagValue)
3174
+ throw new AppError("usage", `--${key} requires a value`, 2);
3175
+ if (value !== undefined && !value.trim())
3176
+ throw new AppError("usage", `--${key} requires a non-empty value`, 2);
3177
+ return value;
2163
3178
  }
2164
3179
  function allOptions(parsed, key) {
2165
3180
  return (parsed.options.get(key) ?? []).filter((value) => value !== flagValue);
@@ -2324,8 +3339,8 @@ function projectRootForMutation(context, args, result, resolvedScope) {
2324
3339
  if (family === "merge-queue") {
2325
3340
  return projectRootForMergeQueueMutation(context, command, parsed);
2326
3341
  }
2327
- if (family === "merge" && ["one-shot", "apply", "request"].includes(command ?? "")) {
2328
- return requiredOption(parsed, "project-root");
3342
+ if (family === "merge" && ["one-shot", "apply", "repair", "request"].includes(command ?? "")) {
3343
+ return resolvedScope ?? requiredOption(parsed, "project-root");
2329
3344
  }
2330
3345
  if (family === "merge-worker" && ["start", "stop"].includes(command ?? "")) {
2331
3346
  return requiredOption(parsed, "project-root");
@@ -2343,7 +3358,7 @@ function projectRootForMutation(context, args, result, resolvedScope) {
2343
3358
  return requiredOption(parsed, "project-root");
2344
3359
  }
2345
3360
  if (family === "stage" && ["start", "pause", "resume", "finish"].includes(command ?? "")) {
2346
- return requiredOption(parsed, "project-root");
3361
+ return resolvedScope ?? requiredOption(parsed, "project-root");
2347
3362
  }
2348
3363
  if (family === "worktree" && ["create", "bootstrap", "close"].includes(command ?? "")) {
2349
3364
  return protocolProjectRoot(context, requiredOption(parsed, "protocol-id"));
@@ -2357,7 +3372,7 @@ function projectRootForMutation(context, args, result, resolvedScope) {
2357
3372
  if (family === "opencode" && ((command === "event" && requiredPosition(parsed, 0, "opencode event action") === "handle") || command === "usage")) {
2358
3373
  return requiredOption(parsed, "project-root");
2359
3374
  }
2360
- if (family === "agy" && ((command === "event" && requiredPosition(parsed, 0, "agy event action") === "handle") || command === "usage"))
3375
+ if (["agy", "droid"].includes(family ?? "") && ((command === "event" && requiredPosition(parsed, 0, `${family} event action`) === "handle") || command === "usage"))
2361
3376
  return requiredOption(parsed, "project-root");
2362
3377
  if (family === "codex" && command === "hooks") {
2363
3378
  const action = requiredPosition(parsed, 0, "codex hooks action");
@@ -2394,14 +3409,36 @@ function projectRootForMergeQueueMutation(context, command, parsed) {
2394
3409
  function protocolProjectRoot(context, protocolId) {
2395
3410
  return requireProtocol(context, protocolId).project_root;
2396
3411
  }
3412
+ function prepareCliWorkRepair(context, parsed, objective, scopeProjectRoot) {
3413
+ const origins = parsed.options.get("origin-work") ?? [], findings = parsed.options.get("from-finding") ?? [], unresolved = parsed.options.get("from-unresolved") ?? [], receipts = parsed.options.get("from-check") ?? [];
3414
+ if ([findings.length > 0, unresolved.length > 0, receipts.length > 0].filter(Boolean).length !== 1)
3415
+ throw new AppError("usage", "Repair requires exactly one source: --from-check, --from-finding or --from-unresolved", 2);
3416
+ const scope = { projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"), runId: requiredOption(parsed, "run"), objective };
3417
+ if (findings.length) {
3418
+ if (origins.length || hasOption(parsed, "verification-file"))
3419
+ throw new AppError("usage", "Finding repair derives its origins and cannot accept --origin-work or --verification-file", 2);
3420
+ return prepareVnextCodeReviewRepair(context, { ...scope, findingIds: findings, checkRefsByFinding: Object.fromEntries(findings.map(finding => [finding, parsed.options.get("check-ref") ?? []])) });
3421
+ }
3422
+ if (!origins.length)
3423
+ throw new AppError("usage", "Repair requires at least one --origin-work", 2);
3424
+ if (hasOption(parsed, "check-ref"))
3425
+ throw new AppError("usage", "--check-ref is only supported with --from-finding", 2);
3426
+ if (receipts.length > 1)
3427
+ throw new AppError("usage", "Create one repair Work per --from-check receipt", 2);
3428
+ if (!unresolved.length && hasOption(parsed, "verification-file"))
3429
+ throw new AppError("usage", "--verification-file is only supported with --from-unresolved", 2);
3430
+ const input = { ...scope, originWorkIds: origins, ...(unresolved.length ? { semanticUnresolved: unresolved, verificationPath: requiredOption(parsed, "verification-file") } : { checkReceiptId: receipts[0] }) };
3431
+ return { input, value: prepareVnextCodeRepair(context, input) };
3432
+ }
3433
+ function workerPromptInput(parsed) {
3434
+ const workspaceRoot = optionalOption(parsed, "workspace-root"), taskFile = optionalOption(parsed, "task-file");
3435
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run"), stage: requiredOption(parsed, "stage"), profile: requiredOption(parsed, "profile"), ...(taskFile ? { taskFile } : { planItemId: requiredOption(parsed, "plan-item") }), ...(workspaceRoot ? { workspaceRoot } : {}) };
3436
+ }
2397
3437
  function runnerIntake(context) {
2398
3438
  const input = context.value.task_input?.[0];
2399
3439
  if (!input?.path)
2400
3440
  throw new AppError("validation", "Runner SPECIFY context requires one ordered task_input file", 2);
2401
- const file = path.resolve(input.path);
2402
- if (!fs.existsSync(file) || !fs.statSync(file).isFile())
2403
- throw new AppError("not_found", "Runner SPECIFY task input is missing", 2, { task_input: file });
2404
- return fs.readFileSync(file, "utf8");
3441
+ return prepareTextFile(input.path, "Runner SPECIFY task input").text;
2405
3442
  }
2406
3443
  /** Stage services install context before their lifecycle transition. Keeping
2407
3444
  * this check here makes an incomplete service migration fail closed instead of