@deksden-com/dd-flow-cli 0.9.0-beta.8 → 0.9.0-beta.80

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 (136) hide show
  1. package/CHANGELOG.md +396 -0
  2. package/README.md +65 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +300 -0
  5. package/dist/cli/help.js +81 -9
  6. package/dist/cli/hook-ingress.js +82 -0
  7. package/dist/cli/input-preparation.js +115 -0
  8. package/dist/cli/run-cli.js +1342 -375
  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/config.js +11 -8
  63. package/dist/services/controller-fanout.js +116 -0
  64. package/dist/services/dashboard.js +103 -31
  65. package/dist/services/engines.js +121 -76
  66. package/dist/services/eval-snapshots.js +750 -73
  67. package/dist/services/execution-policy.js +170 -0
  68. package/dist/services/external-work-launch.js +110 -0
  69. package/dist/services/harness-adapter.js +147 -24
  70. package/dist/services/harness-config.js +2 -0
  71. package/dist/services/hooks.js +553 -285
  72. package/dist/services/lanes.js +61 -53
  73. package/dist/services/lifecycle-command.js +87 -7
  74. package/dist/services/lifecycle-invocations.js +828 -0
  75. package/dist/services/managed-daemon-binding.js +38 -0
  76. package/dist/services/managed-processes.js +283 -27
  77. package/dist/services/merge-queue.js +179 -104
  78. package/dist/services/merge-server.js +73 -28
  79. package/dist/services/migrations.js +14 -9
  80. package/dist/services/native-daemon-history.js +49 -0
  81. package/dist/services/native-session-control.js +39 -0
  82. package/dist/services/plan-runtime.js +19 -8
  83. package/dist/services/plans.js +28 -25
  84. package/dist/services/projects.js +18 -5
  85. package/dist/services/prompts.js +23 -16
  86. package/dist/services/protocols.js +64 -20
  87. package/dist/services/recovery-observation-budget.js +61 -0
  88. package/dist/services/recovery-snapshot-database.js +107 -0
  89. package/dist/services/run-control-receipt.js +56 -0
  90. package/dist/services/run-control-worker.js +363 -0
  91. package/dist/services/run-control.js +876 -0
  92. package/dist/services/run-controller-adapter.js +222 -0
  93. package/dist/services/run-controller-capture.js +134 -0
  94. package/dist/services/run-controller-process.js +189 -0
  95. package/dist/services/run-controller-recovery.js +222 -0
  96. package/dist/services/run-controller-state.js +36 -0
  97. package/dist/services/run-controller.js +779 -0
  98. package/dist/services/run-engine-bindings.js +1 -1
  99. package/dist/services/run-fork.js +138 -0
  100. package/dist/services/run-observations.js +112 -0
  101. package/dist/services/run-recovery-runtime.js +69 -0
  102. package/dist/services/run-recovery.js +342 -0
  103. package/dist/services/runs.js +368 -74
  104. package/dist/services/runtime-budget.js +434 -0
  105. package/dist/services/runtime-scope-capture.js +50 -0
  106. package/dist/services/runtime-scope-control.js +450 -0
  107. package/dist/services/runtime-scope-resume.js +565 -0
  108. package/dist/services/runtime-scope-stop.js +99 -0
  109. package/dist/services/runtime-scope-worker.js +243 -0
  110. package/dist/services/runtime-service.js +97 -0
  111. package/dist/services/schema-validation.js +10 -8
  112. package/dist/services/sessions.js +35 -69
  113. package/dist/services/stage-blocker.js +17 -7
  114. package/dist/services/stage-context.js +44 -18
  115. package/dist/services/stage-lifecycle.js +99 -102
  116. package/dist/services/stage-pause.js +65 -23
  117. package/dist/services/usage.js +37 -93
  118. package/dist/services/vnext-code-review.js +189 -85
  119. package/dist/services/vnext-code.js +257 -243
  120. package/dist/services/vnext-execution-profile.js +5 -3
  121. package/dist/services/vnext-fanout.js +134 -19
  122. package/dist/services/vnext-merge.js +285 -102
  123. package/dist/services/vnext-plan-review.js +148 -94
  124. package/dist/services/vnext-plan.js +141 -72
  125. package/dist/services/vnext-protocolize.js +129 -56
  126. package/dist/services/vnext-specify.js +87 -64
  127. package/dist/services/work-registry.js +707 -156
  128. package/dist/services/workspace-bootstrap.js +76 -0
  129. package/dist/services/worktrees.js +85 -35
  130. package/dist/shared/errors.js +12 -0
  131. package/dist/storage/database.js +444 -32
  132. package/dist/storage/paths.js +17 -4
  133. package/dist/storage/writer-contract.js +77 -0
  134. package/dist/storage/writer-migration.js +102 -0
  135. package/package.json +11 -4
  136. package/tools/repair-paused-run-status.mjs +59 -0
@@ -1,56 +1,79 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { quote } from "shell-quote";
5
+ import { observeLifecycleCommand } from "../services/lifecycle-invocations.js";
6
+ import { verifyCodexHookDelivery } from "../services/codex-hook-delivery.js";
7
+ import { assertLifecycleInvocationCurrent, awaitLifecycleInvocation, expandLifecycleInvocationArgs, issueLifecycleInvocation, prepareLifecycleIssuance, lifecycleInvocationScope, observedLifecycleInvocation, settleLifecycleInvocation, settleLifecycleRejection } from "../services/lifecycle-invocations.js";
3
8
  import { createContext, createRouterContext } from "../runtime/context.js";
9
+ import { migrateStoreWriter } from "../storage/writer-migration.js";
4
10
  import { helpForArgs } from "./help.js";
5
11
  import { AppError, isAppError } from "../shared/errors.js";
6
12
  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";
13
+ import { archiveProject, prepareProjectArchive, getProjectStatus, migrateProjectIds, registerProject, resolveProject } from "../services/projects.js";
14
+ import { cancelProtocol, getProtocolBlockers, getProtocolStatus, getReadyProtocols, implementProtocol, readyForMerge, registerProtocol, prepareProtocolRegistration, requireProtocol, syncProtocolFromRun, prepareProtocolTransition, transitionProtocol } from "../services/protocols.js";
15
+ import { getPlanStatus, preparePlanItemMutation, updatePlanItem } from "../services/plans.js";
16
+ 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
17
  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";
18
+ import { cleanupApply, cleanupScan, prepareCleanupApply } from "../services/cleanup.js";
19
+ 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";
20
+ import { bootstrapWorktree, closeWorktree, createWorktreeRecord, prepareWorktreeCreate, prepareWorktreeBootstrap, prepareWorktreeClose, getWorktreeStatus, planWorktree } from "../services/worktrees.js";
21
+ import { acquireLaneLock, cancelLaneWaiter, prepareLaneWaiterCancellation, checkLaneWorkspace, getLaneWaiters, getLaneStatus, heartbeatLaneLock, releaseLaneLock, setLaneWorkspace, prepareLaneWorkspace, prepareLaneLock, waitAcquireLaneLock, waitForLaneLock } from "../services/lanes.js";
22
+ import { getProjectConfigStatus, prepareProjectConfigValue, setProjectConfigValue } from "../services/config.js";
23
+ import { getCanonStatus, registerCanonRoot, resolveCanonRoot, prepareCanonRegistration } from "../services/canon.js";
18
24
  import { getRuntimeStatus } from "../services/status.js";
19
25
  import { getCliVersionReport } from "../services/build-info.js";
20
26
  import { parseCommandArgs } from "../services/lifecycle-command.js";
21
- import { autoRefreshDashboards, dashboardData, getCmuxStatus, openDashboard, openGlobalDashboard, openProtocolDashboard, refreshAllDashboards, refreshDashboard, refreshGlobalDashboard, renderDashboard, renderGlobalDashboard } from "../services/dashboard.js";
27
+ import { prepareError, prepareJsonFile, prepareJsonSchema, prepareJsonText, prepareTextFile } from "./input-preparation.js";
28
+ import { autoRefreshDashboards, dashboardData, getCmuxStatus, openDashboard, openGlobalDashboard, openProtocolDashboard, refreshAllDashboards, prepareDashboardRefresh, prepareDashboardRender, prepareGlobalDashboardRender, prepareDashboardOptions, refreshDashboard, refreshGlobalDashboard, renderDashboard, renderGlobalDashboard } from "../services/dashboard.js";
22
29
  import { dashboardTargetSummary, preferredDashboardCommand, relatedDashboardCommands, resolveDashboardTarget } from "../services/dashboard-targets.js";
23
- import { getFlowSessionStatus, registerFlowSession, stopFlowSession, stopMergeWorker, syncFlowSessionUsage } from "../services/sessions.js";
30
+ import { getFlowSessionStatus, prepareFlowSessionPayload, registerFlowSession, stopFlowSession, stopMergeWorker, syncFlowSessionUsage } from "../services/sessions.js";
24
31
  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";
32
+ 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
33
  import { previewNextEntityId } from "../services/ids.js";
27
34
  import { validateSchema } from "../services/schema-validation.js";
28
35
  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";
36
+ import { ingestDroidUsage, ingestAgyUsage, ingestGrokUsage, ingestOpenCodeUsage, ingestZcodeUsage } from "../services/usage.js";
37
+ import { applyMigration, assessMigrationImpact, assertUpgradeRunStorageReady, planMigration, prepareMigrationApply, verifyMigrationReport } from "../services/migrations.js";
31
38
  import { publishProjectSummary } from "../services/project-summary.js";
32
39
  import { requireProjectByRoot } from "../services/projects.js";
33
40
  import { resolveProjectRoot } from "../storage/paths.js";
34
- import { doctorEngines, bindRunEngine, engineInfo, installCurrentEngine, listEngines, resolveEngine, resolveExplicitProjectRoot, resolveOperationProjectRoot, routeArgsThroughEngine } from "../services/engines.js";
41
+ import { doctorEngines, bindRunEngine, prepareRunEngineBind, engineInfo, installCurrentEngine, listEngines, resolveEngine, resolveExplicitProjectRoot, resolveOperationProjectRoot, routeArgsThroughEngine } from "../services/engines.js";
35
42
  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";
43
+ import { finishVnextSpecifyStage, getVnextWorkStatus, isVnextSpecifyFlow, isVnextSpecifyRun, launchVnextSpecify, prepareVnextSpecifyStart } from "../services/vnext-specify.js";
44
+ import { finishVnextProtocolize, isVnextProtocolizeRun, prepareProtocolizeResultPath, prepareVnextProtocolizeStart, startVnextProtocolize } from "../services/vnext-protocolize.js";
45
+ import { finishVnextPlan, isVnextPlanRun, startVnextPlan, prepareVnextPlanStart, prepareVnextPlanFinish } from "../services/vnext-plan.js";
46
+ import { dispatchVnextPlanReview, finishVnextPlanReview, isVnextPlanReviewRun, prepareVnextPlanReviewStart, recordVnextPlanReviewCapacity, startVnextPlanReview } from "../services/vnext-plan-review.js";
47
+ import { addVnextCodeRepair, finishVnextCode, prepareVnextCodeRepair, prepareVnextCodeStart, startVnextCode } from "../services/vnext-code.js";
48
+ import { finishVnextCodeReview, isVnextCodeReviewRun, prepareCodeReviewDecision, prepareVnextCodeReviewRepair, prepareVnextCodeReviewStart, startVnextCodeReview } from "../services/vnext-code-review.js";
49
+ import { applyVnextMerge, finishVnextMerge, getVnextMergeRequest, isVnextMergeRun, prepareVnextMergeFinish, prepareVnextMergeStart, repairVnextMerge, routeVnextMergeRequest, startVnextMerge } from "../services/vnext-merge.js";
43
50
  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";
51
+ import { getVnextFanoutStatus, observeVnextNativeChildren, prepareNativeObservations, reconcileVnextFanout } from "../services/vnext-fanout.js";
52
+ import { pauseStageForUser, resumeStageAfterUser, prepareStagePause, prepareStageResume } from "../services/stage-pause.js";
53
+ import { blockStageForRuntime, unblockStageAfterRuntimeRepair, prepareStageRuntimeBlock, prepareStageRuntimeUnblock } from "../services/stage-blocker.js";
47
54
  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";
55
+ import { prepareWorkerPrompt, renderWorkerPrompt } from "../services/prompts.js";
56
+ import { finishStage, prepareStageFinish, startStage, prepareLegacyStageStart } from "../services/stage-lifecycle.js";
57
+ import { addWorkBatch, prepareWorkBatch, prepareWorkDeps, prepareWorkDelete, prepareWorkSettlement, prepareWorkRetry, assertStageLifecycleOwner, assertWorkLifecycleOwner, cancelWork, deleteWork, failWork, finishWork, listWorks, mutateWorkDeps, prepareWorkResult, retryWork, showWork, startWork } from "../services/work-registry.js";
58
+ import { launchExternalWork } from "../services/external-work-launch.js";
59
+ import { createEvalBootstrapSnapshot, prepareEvalBootstrapSnapshot, createEvalRunSnapshot, prepareEvalRunSnapshotCreation, prepareVnextSpecifyRun, prepareEvalRunRestore, prepareEvalBootstrapRestore, restoreEvalBootstrapSnapshot, restoreEvalRunSnapshot } from "../services/eval-snapshots.js";
60
+ import { forkRunFromSnapshot, prepareRunFork } from "../services/run-fork.js";
61
+ import { acceptRunRecovery, assertRunMutationAllowed, beginRunRecovery, inspectRunRecovery, prepareRecoveryCapture, prepareRecoveryPayload, prepareRunRecoveryResume, recordRecoveryCapture, recoveryGuard, resumeRunRecovery, sealRunRecovery } from "../services/run-recovery.js";
62
+ import { recoveryRuntimeAdmission } from "../services/run-recovery-runtime.js";
63
+ import { loadExternalStageContext, prepareExternalStageContext } from "../services/stage-context.js";
64
+ import { vnextStageDirectory } from "../domain/stage-catalog.js";
65
+ import { prepareCommandRoute } from "./command-inputs.js";
66
+ import { parseLifecycleCommand } from "../services/lifecycle-command.js";
67
+ import { prepareManagedProcessRegistration, prepareManagedProcessConfirmation, prepareManagedProcessHeartbeat, prepareManagedProcessFinish, prepareManagedProcessStopOperation, prepareManagedProcessReconcile, stopManagedProcess, confirmManagedProcess, finishManagedProcess, heartbeatManagedProcess, managedProcessRuntimeHome, managedProcessStatus, processIsAlive, reconcileExpiredManagedProcesses, registerManagedProcess } from "../services/managed-processes.js";
68
+ import { fenceRuntimeBudget, runtimeBudgetStatus, admitRuntimeCheck, parseRuntimeBudget, prepareRuntimeScopeControl, prepareRuntimeScopeFence, reserveProviderTurn, releaseProviderTurns, prepareProviderTurnRelease } from "../services/runtime-budget.js";
69
+ import { stopRuntimeScope } from "../services/runtime-scope-stop.js";
70
+ import { launchRuntimeScopeControl, launchRuntimeScopeResume, prepareRuntimeScopeReconciliation, prepareRuntimeScopeServing, reconcileRuntimeScopeControl, serveRuntimeScopeControl } from "../services/runtime-scope-worker.js";
71
+ import { prepareRuntimeScopeResumeRequest } from "../services/runtime-scope-resume.js";
72
+ import { launchRunController, prepareRunControllerLaunch, resumeRunController, serveRunController, runControllerStatus, answerRunController, prepareRunControllerAnswer, supplyRunControllerContext, prepareRunControllerContext } from "../services/run-controller.js";
73
+ import { controllerHitlAdmission } from "../services/run-controller-adapter.js";
74
+ import { controlLifecycleReply, runControlStatus } from "../services/run-control.js";
75
+ import { reconcileRunControl, requestRunControl, serveRunControl } from "../services/run-control-worker.js";
76
+ import { startRuntimeService, prepareRuntimeService } from "../services/runtime-service.js";
54
77
  const defaultIo = {
55
78
  stdout: process.stdout,
56
79
  stderr: process.stderr,
@@ -58,9 +81,20 @@ const defaultIo = {
58
81
  };
59
82
  const flagValue = "__dd_flow_flag__";
60
83
  export async function runCli(args, io = defaultIo, env = process.env) {
61
- const output = parseOutputOptions(args);
84
+ let output;
85
+ try {
86
+ output = parseOutputOptions(args);
87
+ }
88
+ catch (error) {
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ writeJson(io.stderr, { ok: false, error: { code: "usage", message } });
91
+ return 2;
92
+ }
62
93
  const progress = progressForCommand(output.args);
63
94
  let heartbeat;
95
+ let invocationSettlement;
96
+ let settleHook;
97
+ let diagnosticHome;
64
98
  try {
65
99
  if (output.args.length === 1 && output.args[0] === "--version") {
66
100
  const payload = getCliVersionReport();
@@ -75,6 +109,16 @@ export async function runCli(args, io = defaultIo, env = process.env) {
75
109
  io.stdout.write(`${help}\n`);
76
110
  return 0;
77
111
  }
112
+ const suppliedInvocationId = optionalOption(parseArgs(output.args.slice(2)), "invocation-id");
113
+ if (output.args[0] === "run" && ["drive", "control"].includes(output.args[1] ?? "")) {
114
+ const controlArgs = parseArgs(output.args.slice(2));
115
+ requiredOption(controlArgs, "run");
116
+ requiredOption(controlArgs, "project-root");
117
+ }
118
+ if (io.stdin?.isTTY && ["work", "stage"].includes(output.args[0] ?? "") && output.args[1] === "finish"
119
+ && hasOption(parseArgs(output.args.slice(2)), "result-stdin")) {
120
+ 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);
121
+ }
78
122
  const classification = classifyCliOperation(output.args, env);
79
123
  if (requiresExplicitUpgradeAuthorization(output.args) && classification.mode !== "mb_upgrade") {
80
124
  throw new AppError("upgrade_authorization_required", "This mb-upgrade command requires the explicit mb-upgrade authorization marker and allowlisted target context", 1, {
@@ -83,25 +127,101 @@ export async function runCli(args, io = defaultIo, env = process.env) {
83
127
  });
84
128
  }
85
129
  const routerContext = createRouterContext(env);
130
+ const publicCommand = quote(["dd-flow", ...output.args]);
131
+ const lifecycleCommand = parseLifecycleCommand(publicCommand);
132
+ const observedInvocation = observedLifecycleInvocation(routerContext, publicCommand);
133
+ if (!observedInvocation && !suppliedInvocationId && env.DD_FLOW_DAEMON_ID && lifecycleCommand.kind === "standalone") {
134
+ throw new AppError("invocation_receipt_missing", "Managed lifecycle command has no committed native receipt", 1, { effect: "no_effect", recoverable: false });
135
+ }
136
+ const invocationId = observedInvocation?.id ?? suppliedInvocationId;
137
+ const boundInvocationArgs = invocationId && invocationId !== suppliedInvocationId
138
+ ? [...output.args.filter((_, index, values) => values[index - 1] !== "--invocation-id" && values[index] !== "--invocation-id"), "--invocation-id", invocationId]
139
+ : output.args;
140
+ const observedOperation = lifecycleCommand.kind === "standalone" ? lifecycleCommand.invocation.operation : null;
141
+ if (observedInvocation && !observedOperation)
142
+ throw new AppError("invocation_command_invalid", "Observed lifecycle command could not be parsed", 1);
143
+ const invocationScope = invocationId ? lifecycleInvocationScope({ ...routerContext, env }, invocationId) : undefined;
144
+ const invocationArgs = invocationScope && observedOperation
145
+ ? expandLifecycleInvocationArgs(routerContext, boundInvocationArgs, invocationScope, observedOperation)
146
+ : boundInvocationArgs;
86
147
  emitHumanProgress(io, output, progress, "start");
87
148
  if (output.progressJsonl) {
88
149
  writeProgressJsonl(io, "start", `Starting ${output.args.slice(0, 3).join(" ")}`);
89
150
  heartbeat = setInterval(() => writeProgressJsonl(io, "running", "Command is still running"), 15_000);
90
151
  }
91
- const scopeProjectRoot = resolveProjectRootBeforeRouting(output.args, env);
92
- const routedArgs = output.responseFile ? [...output.args, "--response-file", output.responseFile] : output.args;
152
+ // Route by retained authority, so a mistyped project path reaches the CLI
153
+ // validator instead of selecting a different engine or failing preflight.
154
+ const scopeProjectRoot = invocationScope?.projectRoot ?? resolveProjectRootBeforeRouting(output.args, env);
155
+ const routedArgs = output.responseFile ? [...invocationArgs, "--response-file", output.responseFile] : invocationArgs;
93
156
  const routed = await routeArgsThroughEngine(routerContext, output.json ? [...routedArgs, "--json", ...(output.progressJsonl ? ["--progress-jsonl"] : [])] : routedArgs, io, io.stdin, env, scopeProjectRoot);
94
157
  if (routed?.routed && !routed.inProcess) {
95
158
  if (heartbeat)
96
159
  clearInterval(heartbeat);
97
- emitHumanProgress(io, output, progress, "done");
160
+ emitHumanProgress(io, output, progress, routed.exitCode === 0 ? "done" : "failed");
161
+ if (output.progressJsonl && routed.exitCode !== 0)
162
+ writeProgressJsonl(io, "failed", "Routed engine failed", { exit_code: routed.exitCode });
98
163
  return routed.exitCode;
99
164
  }
165
+ let preparedInput;
166
+ let preparedRoute;
167
+ if (!invocationId) {
168
+ const preparationContext = createContext({ ...env }, "read_existing");
169
+ try {
170
+ preparedInput = await prepareCliInput(invocationArgs, preparationContext, io, scopeProjectRoot, output.responseFile);
171
+ }
172
+ finally {
173
+ preparationContext.db.close?.();
174
+ }
175
+ }
100
176
  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);
177
+ ? createContext({ ...env, DD_FLOW_ENGINE_MODE: "1", DD_FLOW_ENGINE_HOME: "in-process", DD_FLOW_ROUTED_FROM: getCliVersionReport().cli.version }, databaseModeForCommand(invocationArgs, classification))
178
+ : createContext({ ...env }, databaseModeForCommand(invocationArgs, classification));
179
+ diagnosticHome = dispatchContext.ddFlowHome;
180
+ dispatchContext.env.DD_FLOW_INVOCATION_READONLY = classification.mode === "read_only_diagnostics" ? "1" : undefined;
181
+ let dispatchArgs = invocationArgs;
182
+ let retainedOutcome;
183
+ // Issued transports may deliver their receipt asynchronously. Observe only
184
+ // after admission; retained outcomes must not need a fresh hook receipt.
185
+ if (invocationId) {
186
+ const command = quote(["dd-flow", ...invocationArgs]);
187
+ const admission = await awaitLifecycleInvocation(dispatchContext, { id: invocationId, command,
188
+ validateArgs: () => { preparedRoute = prepareCommandRoute(invocationArgs); },
189
+ prepare: async () => { preparedInput = await prepareCliInput(invocationArgs, dispatchContext, io, scopeProjectRoot, output.responseFile, preparedRoute); },
190
+ assertCurrent: scope => assertLifecycleInvocationCurrent(dispatchContext, scope, command) });
191
+ if (admission.replay) {
192
+ retainedOutcome = admission.outcome;
193
+ settleHook = undefined;
194
+ delete dispatchContext.observeLifecycleHook;
195
+ }
196
+ else {
197
+ invocationSettlement = { context: dispatchContext, id: invocationId };
198
+ dispatchArgs = [...invocationArgs, "--hook-event-id", admission.eventKey];
199
+ preparedInput?.route?.parsed.options.set("hook-event-id", [admission.eventKey]);
200
+ dispatchContext.env.DD_FLOW_INVOCATION_SCOPE = JSON.stringify(lifecycleInvocationScope(dispatchContext, invocationId));
201
+ dispatchContext.env.DD_FLOW_CURRENT_INVOCATION = invocationId;
202
+ }
203
+ }
204
+ if (retainedOutcome?.error) {
205
+ const error = retainedOutcome.error;
206
+ throw new AppError(error.code, error.message, error.exitCode, error.details);
207
+ }
208
+ if (!retainedOutcome && !preparedInput)
209
+ preparedInput = await prepareCliInput(invocationArgs, dispatchContext, io, scopeProjectRoot, output.responseFile);
210
+ if (!retainedOutcome)
211
+ preflightCliCompatibility(dispatchContext, invocationArgs, env, scopeProjectRoot);
212
+ if (!retainedOutcome)
213
+ settleHook = observeLifecycleCommand(dispatchContext, quote(["dd-flow", ...dispatchArgs]));
214
+ const result = retainedOutcome ? retainedOutcome.result : await dispatch(dispatchArgs, dispatchContext, io, scopeProjectRoot, classification, output, preparedInput);
215
+ const completedHook = settleHook;
216
+ settleHook = undefined;
217
+ completedHook?.({ result });
218
+ if (invocationSettlement) {
219
+ const completed = invocationSettlement;
220
+ invocationSettlement = undefined;
221
+ // A failure to persist an already completed result is an unknown reply,
222
+ // not a failed operation eligible for a new productive retry.
223
+ settleLifecycleInvocation(completed.context, completed.id, { result });
224
+ }
105
225
  const refreshWarnings = refreshDashboardsAfterMutation(dispatchContext, output.args, result, scopeProjectRoot);
106
226
  const resultWithWarnings = addWarnings(result, refreshWarnings);
107
227
  if (heartbeat)
@@ -117,17 +237,59 @@ export async function runCli(args, io = defaultIo, env = process.env) {
117
237
  io.stdout.write(renderHumanResult(output.args, payload));
118
238
  return completedCommandExitCode(payload);
119
239
  }
120
- catch (error) {
240
+ catch (caught) {
241
+ 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 } });
242
+ if (diagnosticHome && (!isAppError(caught) || error.code === "storage_write_failed")) {
243
+ try {
244
+ const directory = path.join(diagnosticHome, "diagnostics", "cli");
245
+ fs.mkdirSync(directory, { recursive: true });
246
+ const artifact = path.join(directory, `${randomUUID()}.json`);
247
+ 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 });
248
+ error.details.diagnostic_artifact = artifact;
249
+ }
250
+ catch (secondary) {
251
+ io.stderr.write(`CLI diagnostic persistence failed: ${String(secondary)}\n`);
252
+ }
253
+ }
121
254
  if (heartbeat)
122
255
  clearInterval(heartbeat);
256
+ if (invocationSettlement && error.details.effect !== "committed") {
257
+ try {
258
+ if (isAppError(error))
259
+ settleLifecycleRejection(invocationSettlement.context, invocationSettlement.id, { code: error.code, message: error.message, exitCode: error.exitCode, details: error.details });
260
+ else
261
+ settleLifecycleInvocation(invocationSettlement.context, invocationSettlement.id, { error: { code: "unexpected", message: String(error), exitCode: 1, details: {} } });
262
+ }
263
+ catch (persistenceError) {
264
+ io.stderr.write(`Invocation settlement persistence failed: ${String(persistenceError)}\n`);
265
+ }
266
+ }
267
+ if (settleHook) {
268
+ try {
269
+ settleHook({ error: isAppError(error) ? error : { code: "unexpected", message: String(error), details: {} } });
270
+ }
271
+ catch (persistence) {
272
+ io.stderr.write(`${JSON.stringify({ primary: String(error), lifecycle_persistence_error: String(persistence) })}\n`);
273
+ }
274
+ }
123
275
  const payload = isAppError(error)
124
276
  ? { ok: false, error: { code: error.code, message: error.message, details: error.details } }
125
277
  : { ok: false, error: { code: "unexpected", message: String(error) } };
278
+ progress.splice(0, progress.length, ...progress.filter(event => event.phase !== "done"));
279
+ if (progress.length)
280
+ progress.push({ phase: "failed", message: payload.error.message, at: new Date().toISOString() });
126
281
  emitHumanProgress(io, output, progress, "failed");
127
282
  if (output.progressJsonl)
128
283
  writeProgressJsonl(io, "failed", payload.error.message, { code: payload.error.code });
129
284
  const errorPayload = attachProgress(payload, progress, output);
130
- const visible = writeResponseFile(errorPayload, output);
285
+ let visible = errorPayload;
286
+ try {
287
+ if (error.details.parameter !== "response-file")
288
+ visible = writeResponseFile(errorPayload, output);
289
+ }
290
+ catch (publication) {
291
+ error.details.response_publication_error = { code: publication?.code ?? "response_publication_failed", message: publication instanceof Error ? publication.message : String(publication) };
292
+ }
131
293
  if (output.json && output.progressJsonl)
132
294
  writeJson(io.stdout, errorPayload);
133
295
  else if (output.json)
@@ -151,7 +313,22 @@ function resolveProjectRootBeforeRouting(args, env) {
151
313
  }
152
314
  function databaseModeForCommand(args, classification) {
153
315
  const [family, command] = args;
316
+ // Managed attempts are issued only from a prepared store. Opening that
317
+ // existing writer must not run migrations before their input is admitted.
318
+ if (parseArgs(args.slice(2)).options.has("invocation-id"))
319
+ return "hook";
320
+ // Native hook ingress must remain synchronous, but it must not run schema
321
+ // migration/VACUUM while the provider is waiting for its decision. Startup
322
+ // prepares the store; the hook mode only verifies the prepared contract and
323
+ // records the receipt.
324
+ if (family === "codex" && command === "hook" && args[2] === "handle") {
325
+ // Only the participating PreToolUse ingress needs the prepared hot-path
326
+ // contract. SessionStart/Stop/PostToolUse are observational no-ops here
327
+ // and retain the ordinary startup path for backwards compatibility.
328
+ return optionalOption(parseArgs(args.slice(3)), "event") === "PreToolUse" ? "hook" : "initialize";
329
+ }
154
330
  if (family === "engine" ||
331
+ family === "storage" && command === "migrate-writer" ||
155
332
  family === "version" ||
156
333
  family === "schema" ||
157
334
  family === "canon" && command === "resolve" ||
@@ -207,8 +384,10 @@ function parseOutputOptions(args) {
207
384
  continue;
208
385
  }
209
386
  if (arg === "--response-file") {
387
+ if (responseFile !== null)
388
+ throw new AppError("usage", "--response-file may be supplied only once", 2);
210
389
  const file = args[++index];
211
- if (!file)
390
+ if (!file?.trim() || file.startsWith("--"))
212
391
  throw new AppError("usage", "--response-file requires a path", 2);
213
392
  responseFile = file;
214
393
  continue;
@@ -220,6 +399,33 @@ function parseOutputOptions(args) {
220
399
  const hookJsonOnly = stripped[0] === "codex" && stripped[1] === "hook" && stripped[2] === "handle";
221
400
  return { json: json || hookJsonOnly, progressJsonl, args: stripped, hookJsonOnly, responseFile };
222
401
  }
402
+ /** Validate the response destination without creating it. The response is an
403
+ * optional publication, but a known-bad destination should never be found
404
+ * only after a successful lifecycle mutation. */
405
+ function prepareResponseDestination(value) {
406
+ const file = path.resolve(value);
407
+ const parent = path.dirname(file);
408
+ try {
409
+ let ancestor = parent;
410
+ for (;;) {
411
+ try {
412
+ if (!fs.statSync(ancestor).isDirectory())
413
+ throw new AppError("response_file_parent_invalid", "--response-file parent must be a directory", 2, { file, parent });
414
+ break;
415
+ }
416
+ catch (error) {
417
+ if (error.code !== "ENOENT" || path.dirname(ancestor) === ancestor)
418
+ throw error;
419
+ ancestor = path.dirname(ancestor);
420
+ }
421
+ }
422
+ if (fs.existsSync(file) && !fs.statSync(file).isFile())
423
+ throw new AppError("response_file_invalid", "--response-file must name a regular file", 2, { file });
424
+ }
425
+ catch (error) {
426
+ return prepareError(error, { parameter: "response-file", file, parent });
427
+ }
428
+ }
223
429
  /** Persist the complete machine response for harnesses that cap tool output.
224
430
  * The visible response keeps routing fields but omits the potentially large
225
431
  * rendered prompt; an agent can safely read the named file without rerunning
@@ -500,27 +706,636 @@ function stringValue(value) {
500
706
  function shortSha(value) {
501
707
  return value ? value.slice(0, 12) : "unknown";
502
708
  }
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);
709
+ /** All caller supplied file/stdin data is consumed here, before a managed
710
+ * invocation is allowed to claim execution or a stage claims its hook event. */
711
+ async function prepareCliInput(...args) {
712
+ try {
713
+ return await prepareCliInputValue(...args);
714
+ }
715
+ catch (error) {
716
+ return prepareError(error);
717
+ }
718
+ }
719
+ async function prepareCliInputValue(args, context, io, scopeProjectRoot, responseFile = null, route = prepareCommandRoute(args)) {
720
+ const { family, command, parsed } = route;
721
+ const prepared = { route };
722
+ if (route.key === "project register")
723
+ resolveProjectRoot(requiredOption(parsed, "root"));
724
+ if (route.key === "project archive")
725
+ prepareProjectArchive(context, { idOrAlias: parsed.positional[0], root: optionalOption(parsed, "root"), reason: requiredOption(parsed, "reason") });
726
+ if (route.key === "protocol register")
727
+ prepareProtocolRegistration(context, { handshakeId: requiredPosition(parsed, 0, "handshake-id"), projectRoot: requiredOption(parsed, "project-root"), workspacePath: optionalOption(parsed, "workspace-path") });
728
+ if (route.key === "canon register")
729
+ prepared.canonRegistration = prepareCanonRegistration(context, { root: requiredOption(parsed, "root") });
730
+ if (route.key === "run attach-stage")
731
+ prepareFlowRunStageAttachment(context, stageAttachmentInput(parsed));
732
+ if (route.key === "run complete-stage")
733
+ prepareFlowRunStageCompletion(context, stageCompletionInput(parsed));
734
+ if (route.key === "run override")
735
+ prepareFlowRunCompletion(context, runOverrideInput(parsed));
736
+ if (route.key === "engine bind-run")
737
+ prepared.engineBind = prepareRunEngineBind(context, engineBindInput(parsed));
738
+ if (route.key === "worktree create")
739
+ 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") });
740
+ if (route.key === "worktree bootstrap")
741
+ prepared.worktreeBootstrap = prepareWorktreeBootstrap(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "worktree bootstrap") });
742
+ if (route.key === "worktree close")
743
+ prepareWorktreeClose(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "worktree close"), mode: requiredOption(parsed, "mode") });
744
+ if (route.key.startsWith("plan item "))
745
+ preparePlanItemMutation(context, planItemInput(parsed, requiredScopeProjectRoot(scopeProjectRoot, route.key)));
746
+ if (route.key === "lane workspace set")
747
+ prepareLaneWorkspace(context, laneWorkspaceInput(parsed));
748
+ if (route.key === "lane waiter cancel")
749
+ prepareLaneWaiterCancellation(context, laneWaiterCancelInput(parsed));
750
+ if (route.key === "merge-queue complete")
751
+ prepareMergeJobCompletion(context, { ...mergeJobTarget(parsed, scopeProjectRoot), summary: requiredOption(parsed, "summary") });
752
+ if (route.key === "merge-queue cancel")
753
+ prepareMergeQueueCancellation(context, mergeCancellationInput(parsed, scopeProjectRoot));
754
+ if (route.key === "merge-queue wait-next")
755
+ prepareMergeQueueWait(context, mergeWaitInput(parsed, scopeProjectRoot));
756
+ if (route.key === "merge-queue next" || route.key === "merge-queue claim")
757
+ 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") } : {}) });
758
+ if (route.key === "merge-queue note")
759
+ prepareMergeJobNote(context, { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue note"), workerId: requiredWorkerId(parsed), summary: requiredOption(parsed, "summary") });
760
+ if (route.key === "merge bundle complete")
761
+ prepareMergeBundleCompletion(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed), summary: requiredOption(parsed, "summary") });
762
+ if (route.key === "merge bundle claim")
763
+ prepareMergeBundleClaim(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed) });
764
+ if (route.key === "merge bundle fail")
765
+ prepareMergeBundleFailure(context, { projectRoot: requiredOption(parsed, "project-root"), workspacePath: workspacePathOption(parsed), workerId: requiredWorkerId(parsed), reason: requiredOption(parsed, "reason"), requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue") });
766
+ if (route.key === "merge-queue fail")
767
+ prepareMergeJobFailure(context, { ...mergeJobTarget(parsed, scopeProjectRoot), reason: requiredOption(parsed, "reason"), requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue") });
768
+ if (route.key.startsWith("lane lock ") && route.key !== "lane lock status") {
769
+ const action = requiredPosition(parsed, 0, "lane lock action");
770
+ prepareLaneLock(context, {
771
+ projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workerId: requiredOption(parsed, "worker-id"),
772
+ workspacePath: workspacePathOption(parsed), leaseToken: optionalOption(parsed, "lease-token"), reason: optionalOption(parsed, "reason"),
773
+ ttlSeconds: optionalNumber(parsed, "ttl"), timeoutSeconds: optionalNumber(parsed, "timeout"), pollIntervalSeconds: optionalNumber(parsed, "poll-interval")
774
+ }, action);
775
+ }
776
+ if (route.key === "run recovery begin")
777
+ prepared.recoveryPayload = prepareRecoveryPayload(requiredOption(parsed, "interruption-json"), "interruption");
778
+ if (route.key === "run recovery seal")
779
+ prepared.recoveryPayload = prepareRecoveryPayload(requiredOption(parsed, "settlement-json"), "settlement");
780
+ if (route.key === "run recovery capture")
781
+ prepared.recoveryCapture = prepareRecoveryCapture(context, recoveryCaptureInput(parsed));
782
+ if (route.key === "run recovery resume")
783
+ prepared.recoveryResume = prepareRunRecoveryResume(context, recoveryResumeInput(parsed));
784
+ if (route.key === "run drive answer")
785
+ prepared.controllerAnswer = prepareRunControllerAnswer(context, controllerAnswerInput(parsed));
786
+ if (route.key === "run drive launch")
787
+ prepared.controllerLaunch = prepareRunControllerLaunch(context, controllerLaunchInput(parsed));
788
+ if (route.key === "run drive context")
789
+ prepared.controllerContext = prepareRunControllerContext(context, controllerContextInput(parsed));
790
+ if (route.key === "protocol transition" || route.key === "transition")
791
+ prepared.protocolTransition = prepareProtocolTransition(context, protocolTransitionInput(parsed, scopeProjectRoot ?? resolveOperationProjectRoot(context, args)));
792
+ if (route.key === "codex home init")
793
+ prepared.codexHome = prepareCodexHome(context, codexHomeInput(parsed));
794
+ if (route.key === "codex home remove")
795
+ prepareCodexHomeRemoval(context, { projectRoot: requiredOption(parsed, "project-root"), profile: optionalOption(parsed, "profile"), mode: requiredOption(parsed, "mode") });
796
+ if (["codex hooks install", "codex hooks remove"].includes(route.key))
797
+ prepared.codexHooks = prepareCodexHooks(context, { projectRoot: requiredOption(parsed, "project-root"), target: optionalOption(parsed, "target"), profile: optionalOption(parsed, "profile"), yes: hasOption(parsed, "yes") });
798
+ if (route.key === "migration apply")
799
+ prepared.migrationApply = prepareMigrationApply(context, migrationApplyInput(parsed, classifyCliOperation(args, context.env)));
800
+ if (route.key === "migration verify")
801
+ prepared.migrationVerification = verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
802
+ if (responseFile)
803
+ prepareResponseDestination(responseFile);
804
+ if (family === "dashboard") {
805
+ const action = dashboardAction(command);
806
+ prepareDashboardOptions({ format: optionalOption(parsed, "format"), viewer: optionalOption(parsed, "viewer"), open: optionalOption(parsed, "open") });
807
+ 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") });
808
+ if (action === "refresh" && target.kind !== "global" && optionalOption(parsed, "output") !== undefined) {
809
+ throw new AppError("validation", "--output is supported only for global dashboard refresh; use dashboard render for a custom project/protocol output", 2, { parameter: "output" });
810
+ }
811
+ if (target.kind === "protocol")
812
+ requireProtocol(context, target.protocolId, target.project.id);
813
+ if (action !== "data") {
814
+ if (target.kind === "global" || target.kind === "all_projects") {
815
+ prepareGlobalDashboardRender(context, { output: optionalOption(parsed, "output"), format: optionalOption(parsed, "format") ?? (command?.endsWith("-global") ? undefined : "html") });
816
+ }
817
+ else {
818
+ const format = optionalOption(parsed, "format") ?? (action === "open" || hasOption(parsed, "project") ? "html" : undefined);
819
+ const input = { projectRoot: target.project.root, format, ...(target.kind === "protocol" ? { protocol: target.protocolId } : {}) };
820
+ if (action === "refresh")
821
+ prepareDashboardRefresh(context, { ...input, open: optionalOption(parsed, "open") });
822
+ else if (action === "render")
823
+ prepareDashboardRender(context, { ...input, output: optionalOption(parsed, "output") });
824
+ else if (target.kind === "protocol") {
825
+ if (format !== "html")
826
+ throw new AppError("validation", "Protocol dashboard open supports --format html", 2, { protocol: target.protocolId });
827
+ prepareDashboardRender(context, input);
828
+ }
829
+ }
830
+ }
831
+ }
832
+ if (route.key === "prompt render") {
833
+ const input = workerPromptInput(parsed);
834
+ prepared.workerPrompt = { input, value: prepareWorkerPrompt(context, input) };
835
+ }
836
+ if (route.key === "run snapshot restore" || route.key === "run snapshot bootstrap restore") {
837
+ try {
838
+ const input = snapshotRestoreInput(parsed);
839
+ if (route.key === "run snapshot restore")
840
+ prepared.snapshotRestore = prepareEvalRunRestore(context, input);
841
+ else
842
+ prepared.bootstrapRestore = prepareEvalBootstrapRestore(input);
843
+ }
844
+ catch (error) {
845
+ return prepareError(error, { parameter: "snapshot/project-root" });
846
+ }
847
+ }
848
+ if (route.key === "run snapshot bootstrap create") {
849
+ try {
850
+ prepareEvalBootstrapSnapshot(context, { projectRoot: requiredOption(parsed, "project-root"), output: requiredOption(parsed, "output") });
851
+ }
852
+ catch (error) {
853
+ return prepareError(error, { parameter: "project-root/output" });
854
+ }
855
+ }
856
+ if (route.key === "run snapshot create") {
857
+ prepareEvalRunSnapshotCreation(context, snapshotCreateInput(parsed));
858
+ }
859
+ if (route.key === "run start") {
860
+ try {
861
+ const input = runStartInput(parsed);
862
+ prepared.runStart = { input, value: prepareFlowRunStart(context, input) };
863
+ }
864
+ catch (error) {
865
+ return prepareError(error, { parameter: "run start" });
866
+ }
867
+ }
868
+ if (route.key === "run fork") {
869
+ try {
870
+ prepared.runFork = prepareRunFork(runForkInput(parsed));
871
+ }
872
+ catch (error) {
873
+ return prepareError(error, { parameter: "from/output" });
874
+ }
875
+ }
876
+ if (["runtime scope fence", "runtime scope stop"].includes(route.key))
877
+ prepareRuntimeScopeFence(requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id"));
878
+ if (route.key === "runtime scope resume")
879
+ prepareRuntimeScopeResumeRequest(context, runtimeScopeResumeInput(parsed));
880
+ if (route.key === "runtime scope reconcile")
881
+ prepareRuntimeScopeReconciliation(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")), requiredOption(parsed, "request-id"));
882
+ if (route.key === "runtime scope serve")
883
+ prepareRuntimeScopeServing(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")));
884
+ if (route.key === "runtime scope control") {
885
+ try {
886
+ const raw = optionalOption(parsed, "manifest-json");
887
+ 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);
888
+ }
889
+ catch (error) {
890
+ return prepareError(error, { parameter: "scope-id/request-id/manifest-json" });
891
+ }
892
+ }
893
+ if (route.key === "runtime process register") {
894
+ prepareManagedProcessRegistration(context, runtimeProcessRegistrationInput(context, parsed));
895
+ }
896
+ if (route.key === "runtime process heartbeat")
897
+ prepareManagedProcessHeartbeat(context, runtimeProcessHeartbeatInput(parsed));
898
+ if (route.key === "runtime process finish")
899
+ prepareManagedProcessFinish(context, runtimeProcessFinishInput(parsed));
900
+ if (route.key === "runtime process confirm")
901
+ prepareManagedProcessConfirmation(context, runtimeProcessConfirmationInput(parsed));
902
+ if (route.key === "runtime process stop")
903
+ prepareManagedProcessStopOperation(context, runtimeProcessStopInput(parsed));
904
+ if (route.key === "runtime process reconcile")
905
+ prepareManagedProcessReconcile(requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms"));
906
+ if (route.key === "runtime process release-turn") {
907
+ prepared.providerTurnRelease = prepareProviderTurnRelease({ daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") });
908
+ }
909
+ if (route.key === "runtime process start") {
910
+ try {
911
+ prepareRuntimeService(context, runtimeServiceInput(parsed));
912
+ }
913
+ catch (error) {
914
+ return prepareError(error, { parameter: "runtime process start" });
915
+ }
916
+ }
917
+ if (family === "work" && command === "retry") {
918
+ try {
919
+ prepareWorkRetry(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
920
+ }
921
+ catch (error) {
922
+ return prepareError(error, { parameter: "work-id/reason" });
923
+ }
924
+ }
925
+ if (family === "work" && (command === "fail" || command === "cancel")) {
926
+ try {
927
+ prepareWorkSettlement(context, requiredPosition(parsed, 0, "work-id"), command === "fail" ? "failed" : "cancelled", requiredOption(parsed, "reason"));
928
+ }
929
+ catch (error) {
930
+ return prepareError(error, { parameter: "work-id/reason" });
931
+ }
932
+ }
933
+ if (family === "work" && (command === "deps" || command === "delete")) {
934
+ try {
935
+ if (command === "delete")
936
+ prepareWorkDelete(context, requiredPosition(parsed, 0, "work-id"));
937
+ else
938
+ prepareWorkDeps(context, { workId: requiredPosition(parsed, 1, "work-id"), action: requiredPosition(parsed, 0, "action"), on: parsed.options.get("on") ?? [] });
939
+ }
940
+ catch (error) {
941
+ return prepareError(error, { parameter: "work-id/on" });
942
+ }
943
+ }
944
+ if (route.key === "cleanup apply") {
945
+ const planFile = requiredOption(parsed, "plan-file");
946
+ try {
947
+ prepared.cleanup = prepareCleanupApply(context, { projectRoot: requiredOption(parsed, "project-root"), planFile, reason: requiredOption(parsed, "reason"), force: hasOption(parsed, "force") });
948
+ }
949
+ catch (error) {
950
+ return prepareError(error, { parameter: "plan-file", file: planFile });
951
+ }
952
+ }
953
+ if (route.key === "stage block" || route.key === "stage unblock") {
954
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), workId: requiredOption(parsed, "work") };
955
+ try {
956
+ if (route.key === "stage block") {
957
+ if (!hasOption(parsed, "summary-stdin"))
958
+ throw new AppError("usage", "stage block requires --summary-stdin", 2);
959
+ prepared.interactionText = await readStdin(io.stdin);
960
+ prepareStageRuntimeBlock(context, { ...input, kind: requiredOption(parsed, "kind"), code: requiredOption(parsed, "code"), summary: prepared.interactionText, retryable: hasOption(parsed, "retryable") });
961
+ }
962
+ else
963
+ prepareStageRuntimeUnblock(context, input);
964
+ }
965
+ catch (error) {
966
+ return prepareError(error, { parameter: "stage/work/summary" });
967
+ }
968
+ }
969
+ if (route.key === "zcode invocation prepare") {
970
+ const value = prepareJsonText(await readStdin(io.stdin), { file: "<stdin>", label: "invocation issuance" }).value;
971
+ const payload = value && typeof value === "object" ? value : {};
972
+ try {
973
+ prepared.lifecycleIssuance = prepareLifecycleIssuance(payload.command, payload.scope);
974
+ }
975
+ catch (error) {
976
+ if (error instanceof AppError && ["invocation_command_invalid", "invocation_scope_invalid"].includes(error.code))
977
+ return prepareError(new AppError("usage", error.message, 2, { cause_code: error.code }), { parameter: "stdin" });
978
+ throw error;
979
+ }
980
+ assertLifecycleInvocationCurrent(context, prepared.lifecycleIssuance.scope, prepared.lifecycleIssuance.command);
981
+ }
982
+ if (route.key === "work add-batch") {
983
+ const file = requiredOption(parsed, "file");
984
+ try {
985
+ prepared.workBatch = prepareWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file });
986
+ }
987
+ catch (error) {
988
+ return prepareError(error, { parameter: "file/parent", file });
989
+ }
990
+ }
991
+ if (route.key === "work repair add") {
992
+ if (!hasOption(parsed, "task-stdin"))
993
+ throw new AppError("usage", "work repair add requires --task-stdin", 2);
994
+ if (io.stdin?.isTTY)
995
+ throw new AppError("usage", "--task-stdin requires piped or redirected input", 2);
996
+ prepared.workRepair = prepareCliWorkRepair(context, parsed, await readStdin(io.stdin), scopeProjectRoot);
997
+ }
998
+ if (route.key === "run config set" || route.key === "run vars set") {
999
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), key: requiredOption(parsed, "key"), value: requiredOption(parsed, "value") };
1000
+ try {
1001
+ if (route.key === "run config set")
1002
+ prepareFlowRunConfig(context, { ...input, reason: requiredOption(parsed, "reason") });
1003
+ else
1004
+ prepareFlowRunVariable(context, input);
1005
+ }
1006
+ catch (error) {
1007
+ return prepareError(error, { parameter: "run config/vars" });
1008
+ }
1009
+ }
1010
+ if (route.key === "schema validate") {
1011
+ try {
1012
+ prepared.schemaValidation = dispatchSchema(context, command, parsed);
1013
+ }
1014
+ catch (error) {
1015
+ return prepareError(error, { parameter: "file", file: requiredOption(parsed, "file") });
1016
+ }
1017
+ }
1018
+ if (route.key === "project config set") {
1019
+ try {
1020
+ prepareProjectConfigValue(requiredOption(parsed, "key"), requiredOption(parsed, "value"));
1021
+ }
1022
+ catch (error) {
1023
+ return prepareError(error, { parameter: "key/value" });
1024
+ }
1025
+ }
1026
+ if (family === "session" && command === "register") {
1027
+ try {
1028
+ prepared.sessionPayload = prepareFlowSessionPayload({ payloadBase64: optionalOption(parsed, "payload-base64"), payloadFile: optionalOption(parsed, "payload-file"), payloadJson: optionalOption(parsed, "payload-json") });
1029
+ }
1030
+ catch (error) {
1031
+ return prepareError(error, { parameter: "session payload" });
1032
+ }
1033
+ }
1034
+ const run = (projectRoot, runId) => {
1035
+ try {
1036
+ const project = requireProjectByRoot(context, resolveProjectRoot(projectRoot));
1037
+ const row = context.db.get("SELECT run_root, workspace_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, runId]);
1038
+ if (!row)
1039
+ throw new AppError("not_found", "RUN is not registered", 2, { run_id: runId });
1040
+ if (!row.run_root)
1041
+ throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1, { run_id: runId });
1042
+ return { runRoot: row.run_root, workspaceRoot: row.workspace_root, indexJson: row.index_json };
1043
+ }
1044
+ catch (error) {
1045
+ return prepareError(error, { parameter: "run-id", run_id: runId });
1046
+ }
1047
+ };
1048
+ const json = (file, stdin, label, schema) => {
1049
+ if (stdin) {
1050
+ // The caller awaits this helper; the synchronous facade below is only
1051
+ // used for file inputs. Keep stdin handling in the stage branch.
1052
+ throw new AppError("usage", `${label} stdin preparation must be awaited`, 2);
1053
+ }
1054
+ if (!file)
1055
+ throw new AppError("usage", `${label} input is required`, 2);
1056
+ return prepareJsonSchema(file, label, schema);
1057
+ };
1058
+ if (family === "stage" && command === "start") {
1059
+ const stage = requiredOption(parsed, "stage");
1060
+ if (stage !== "specify" && ["bootstrap", "intake-file", "intake-stdin"].some(option => hasOption(parsed, option)))
1061
+ throw new AppError("usage", "--bootstrap and intake inputs are only supported for SPECIFY", 2);
1062
+ requiredOption(parsed, "project-root");
1063
+ if (!hasOption(parsed, "bootstrap"))
1064
+ requiredPosition(parsed, 0, "run-id");
1065
+ if (hasOption(parsed, "session-id"))
1066
+ throw new AppError("usage", "--session-id is managed by the harness lifecycle adapter and is not accepted", 2);
1067
+ const contextFile = optionalOption(parsed, "context-file"), contextSha256 = optionalOption(parsed, "context-sha256");
1068
+ if (Boolean(contextFile) !== Boolean(contextSha256))
1069
+ throw new AppError("usage", "stage start requires --context-file together with --context-sha256", 2);
1070
+ if ([hasOption(parsed, "intake-file"), hasOption(parsed, "intake-stdin"), Boolean(contextFile)].filter(Boolean).length > 1)
1071
+ throw new AppError("usage", "Use exactly one of --intake-file, --intake-stdin or --context-file", 2);
1072
+ if (contextFile && contextSha256) {
1073
+ try {
1074
+ prepared.stageStart = { externalContext: loadExternalStageContext({ file: contextFile, expectedSha256: contextSha256, stage }) };
1075
+ }
1076
+ catch (error) {
1077
+ return prepareError(error, { file: contextFile, parameter: "context-file" });
1078
+ }
1079
+ if (!hasOption(parsed, "bootstrap")) {
1080
+ const { runRoot } = run(requiredOption(parsed, "project-root"), requiredPosition(parsed, 0, "run-id"));
1081
+ prepareExternalStageContext({ stageRoot: path.join(runRoot, vnextStageDirectory(stage)), loaded: prepared.stageStart.externalContext });
1082
+ }
1083
+ }
1084
+ if (stage === "specify") {
1085
+ const intakeFile = optionalOption(parsed, "intake-file");
1086
+ if (intakeFile)
1087
+ prepared.stageStart = { intakeMarkdown: prepareTextFile(intakeFile, "SPECIFY intake").text };
1088
+ else if (hasOption(parsed, "intake-stdin"))
1089
+ prepared.stageStart = { intakeMarkdown: await readStdin(io.stdin) };
1090
+ else if (prepared.stageStart?.externalContext)
1091
+ prepared.stageStart.intakeMarkdown = runnerIntake(prepared.stageStart.externalContext);
1092
+ const projectRoot = requiredOption(parsed, "project-root");
1093
+ const bootstrap = hasOption(parsed, "bootstrap");
1094
+ if (isVnextSpecifyFlow(projectRoot) && (bootstrap || isVnextSpecifyRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") }))) {
1095
+ 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") } : {}) });
1096
+ }
1097
+ else if (bootstrap) {
1098
+ if (hasOption(parsed, "intake-stdin") || contextFile)
1099
+ throw new AppError("usage", "Legacy SPECIFY bootstrap supports --intake-file, not stdin or runner context", 2);
1100
+ prepared.legacyStageStart = prepareLegacyStageStart(context, { projectRoot, stage, bootstrap: { subject: requiredOption(parsed, "subject"), ...(intakeFile ? { intakeFile } : {}) }, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}) }, prepared.stageStart?.intakeMarkdown);
1101
+ }
1102
+ }
1103
+ if (stage === "merge" && isVnextMergeRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1104
+ prepared.mergeStart = prepareVnextMergeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1105
+ }
1106
+ if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1107
+ prepared.protocolizeStart = prepareVnextProtocolizeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1108
+ }
1109
+ if (stage === "plan" && isVnextPlanRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1110
+ prepared.planStart = prepareVnextPlanStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1111
+ }
1112
+ if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1113
+ prepared.planReviewStart = prepareVnextPlanReviewStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1114
+ }
1115
+ if (stage === "code" && isVnextPlanRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1116
+ prepared.codeStart = prepareVnextCodeStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1117
+ }
1118
+ if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id") })) {
1119
+ prepared.codeReviewStart = prepareVnextCodeReviewStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), ...(prepared.stageStart?.externalContext ? { externalContext: prepared.stageStart.externalContext } : {}) });
1120
+ }
1121
+ if (![prepared.specifyStart, prepared.protocolizeStart, prepared.planStart, prepared.planReviewStart, prepared.codeStart, prepared.codeReviewStart, prepared.mergeStart, prepared.legacyStageStart].some(Boolean)) {
1122
+ if (prepared.stageStart?.externalContext)
1123
+ throw new AppError("usage", "--context-file is currently supported only by vNext flow stages", 2);
1124
+ prepared.legacyStageStart = prepareLegacyStageStart(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}) });
1125
+ }
1126
+ }
1127
+ if (family === "stage" && (command === "pause" || command === "resume")) {
1128
+ requiredPosition(parsed, 0, "run-id");
1129
+ requiredOption(parsed, "project-root");
1130
+ requiredOption(parsed, "stage");
1131
+ requiredOption(parsed, "work");
1132
+ const parameter = command === "pause" ? "question-stdin" : "answer-stdin";
1133
+ if (!hasOption(parsed, parameter))
1134
+ throw new AppError("usage", `stage ${command} requires --${parameter}`, 2);
1135
+ if (io.stdin?.isTTY)
1136
+ throw new AppError("usage", `--${parameter} requires piped or redirected input`, 2);
1137
+ prepared.interactionText = await readStdin(io.stdin);
1138
+ if (!prepared.interactionText.trim())
1139
+ return prepareError(new AppError("validation", `stage ${command} requires non-empty --${parameter}`, 2), { parameter });
1140
+ const input = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 0, "run-id"), stage: requiredOption(parsed, "stage"), workId: requiredOption(parsed, "work") };
1141
+ try {
1142
+ if (command === "pause")
1143
+ prepareStagePause(context, { ...input, question: prepared.interactionText });
1144
+ else
1145
+ prepared.resumeEvidence = prepareStageResume(context, { ...input, answer: prepared.interactionText }).evidence;
1146
+ }
1147
+ catch (error) {
1148
+ return prepareError(error, { parameter: "stage/work" });
1149
+ }
1150
+ }
1151
+ if (family === "work" && command === "finish") {
1152
+ const retryReceiptId = optionalOption(parsed, "retry-check"), retryReason = optionalOption(parsed, "reason");
1153
+ if (Boolean(retryReceiptId) !== Boolean(retryReason))
1154
+ throw new AppError("usage", "--retry-check and --reason must be supplied together", 2);
1155
+ const resultFile = optionalOption(parsed, "result-file");
1156
+ const resultStdin = hasOption(parsed, "result-stdin");
1157
+ if (Boolean(resultFile) === resultStdin)
1158
+ throw new AppError("usage", "work finish requires exactly one of --result-file or --result-stdin", 2);
1159
+ prepared.workFinish = { result: resultFile ? prepareTextFile(resultFile, "Work result").text : await readStdin(io.stdin) };
1160
+ prepareWorkResult(context, requiredPosition(parsed, 0, "work-id"), prepared.workFinish.result);
1161
+ }
1162
+ if (family === "stage" && command === "fanout" && requiredPosition(parsed, 0, "fanout action") === "reconcile") {
1163
+ prepared.observations = prepareNativeObservations(prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value);
1164
+ }
1165
+ if (family === "stage" && command === "native" && requiredPosition(parsed, 0, "native action") === "observe") {
1166
+ prepared.observations = prepareNativeObservations(prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value);
1167
+ }
1168
+ if (family !== "stage" || command !== "finish")
1169
+ return prepared;
1170
+ const projectRoot = requiredOption(parsed, "project-root");
1171
+ const runId = requiredPosition(parsed, 0, "run-id");
1172
+ const stage = requiredOption(parsed, "stage");
1173
+ if (hasOption(parsed, "status"))
1174
+ throw new AppError("usage", "Stage status belongs in the semantic input file", 2);
1175
+ if (["result-file", "semantic-file", "data", "result-stdin"].filter(key => hasOption(parsed, key)).length > 1)
1176
+ throw new AppError("usage", "Use exactly one result input: --result-file, --semantic-file, --data or --result-stdin", 2);
1177
+ if (Boolean(optionalOption(parsed, "retry-check")) !== Boolean(optionalOption(parsed, "reason")))
1178
+ throw new AppError("usage", "--retry-check and --reason must be supplied together", 2);
1179
+ const resultStdin = hasOption(parsed, "result-stdin");
1180
+ const semanticFile = optionalOption(parsed, "semantic-file") ?? optionalOption(parsed, "data");
1181
+ const resultFile = optionalOption(parsed, "result-file") ?? semanticFile;
1182
+ const runtime = run(projectRoot, runId);
1183
+ const terminalReplay = (name) => {
1184
+ let index;
1185
+ try {
1186
+ index = JSON.parse(runtime.indexJson);
1187
+ }
1188
+ catch (error) {
1189
+ 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) });
1190
+ }
1191
+ return index.stage_runs?.some(entry => entry.stage === name && entry.status === "done") === true
1192
+ && fs.existsSync(path.join(runtime.runRoot, vnextStageDirectory(name), "stage-report.json"));
1193
+ };
1194
+ const acceptStageInputs = (allowed) => {
1195
+ const options = allowed.split(" ");
1196
+ for (const name of ["dir", "semantic-file", "data", "result-file", "result-stdin", "outcome", "decision-file", "verification-file", "retry-check", "reason", "request", "work"]) {
1197
+ if (hasOption(parsed, name) && !options.includes(name))
1198
+ throw new AppError("usage", `stage finish ${stage} does not accept --${name} for this flow`, 2, { parameter: name });
1199
+ }
1200
+ };
1201
+ const fromStdin = async (label, schema) => {
1202
+ const value = prepareJsonText(await readStdin(io.stdin), { file: "<stdin>", label });
1203
+ try {
1204
+ validateSchema({ ...schema, file: value.file, data: value.value });
1205
+ }
1206
+ catch (error) {
1207
+ return prepareError(error, { file: value.file, label });
1208
+ }
1209
+ return value;
1210
+ };
1211
+ if (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId })) {
1212
+ acceptStageInputs("result-file semantic-file data result-stdin outcome");
1213
+ const outcome = optionalOption(parsed, "outcome");
1214
+ if (!outcome || !["specified", "failed", "cancelled"].includes(outcome))
1215
+ throw new AppError("usage", "vNext SPECIFY requires --outcome specified|failed|cancelled; use stage pause for a user question", 2);
1216
+ if (Boolean(resultFile) === resultStdin)
1217
+ throw new AppError("usage", "vNext SPECIFY finish requires exactly one result input", 2);
1218
+ const schema = { schemaName: "vnext-specify", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot };
1219
+ const input = resultStdin ? await fromStdin("SPECIFY result", schema) : json(resultFile, false, "SPECIFY result", schema);
1220
+ prepared.stageFinish = { value: input.value, text: input.text };
1221
+ }
1222
+ else if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId })) {
1223
+ acceptStageInputs("result-file semantic-file data");
1224
+ if (!resultFile || resultStdin || hasOption(parsed, "outcome"))
1225
+ throw new AppError("usage", "vNext PROTOCOLIZE requires exactly --result-file", 2);
1226
+ let absolute;
1227
+ try {
1228
+ absolute = prepareProtocolizeResultPath(runtime.runRoot, resultFile);
1229
+ }
1230
+ catch (error) {
1231
+ return prepareError(error, { file: resultFile });
1232
+ }
1233
+ const input = json(absolute, false, "PROTOCOLIZE result", { schemaName: "vnext-protocolize-result", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1234
+ prepared.stageFinish = { value: input.value, text: input.text };
1235
+ }
1236
+ else if (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId })) {
1237
+ acceptStageInputs("");
1238
+ if (hasOption(parsed, "code-work-batch-file"))
1239
+ throw new AppError("usage", "vNext PLAN derives its CODE batch from accepted semantic plans; do not supply a batch file", 2);
1240
+ try {
1241
+ prepared.planFinish = prepareVnextPlanFinish(context, { projectRoot, runId });
1242
+ }
1243
+ catch (error) {
1244
+ return prepareError(error, { parameter: "PLAN artifacts" });
1245
+ }
1246
+ }
1247
+ else if (stage === "merge" && isVnextMergeRun(context, { projectRoot, runId })) {
1248
+ acceptStageInputs("request work retry-check reason");
1249
+ if (resultStdin || resultFile || hasOption(parsed, "outcome"))
1250
+ throw new AppError("usage", "vNext MERGE uses the Work result path returned by stage start", 2);
1251
+ requiredOption(parsed, "request");
1252
+ requiredOption(parsed, "work");
1253
+ try {
1254
+ prepared.mergeFinish = prepareVnextMergeFinish(context, { projectRoot, runId, requestId: requiredOption(parsed, "request"), workId: requiredOption(parsed, "work"), ...(optionalOption(parsed, "retry-check") ? { retryCheckId: optionalOption(parsed, "retry-check"), retryReason: optionalOption(parsed, "reason") } : {}) });
1255
+ }
1256
+ catch (error) {
1257
+ return prepareError(error, { parameter: "MERGE finish" });
1258
+ }
1259
+ }
1260
+ else if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId })) {
1261
+ acceptStageInputs("decision-file");
1262
+ if (resultStdin || hasOption(parsed, "outcome"))
1263
+ throw new AppError("usage", "vNext PLAN-REVIEW uses --decision-file", 2);
1264
+ const decision = optionalOption(parsed, "decision-file") ?? path.join(runtime.runRoot, "04-plan-review", "decision.json");
1265
+ const input = json(decision, false, "PLAN-REVIEW decision", { schemaName: "plan-review-decision", projectRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1266
+ prepared.stageFinish = { value: input.value, text: input.text };
1267
+ }
1268
+ else if (stage === "code" && isVnextPlanRun(context, { projectRoot, runId })) {
1269
+ acceptStageInputs("verification-file retry-check reason");
1270
+ if (semanticFile || resultFile || resultStdin || hasOption(parsed, "outcome"))
1271
+ throw new AppError("usage", "vNext CODE finish accepts only --verification-file", 2);
1272
+ const verification = optionalOption(parsed, "verification-file");
1273
+ if (!verification)
1274
+ throw new AppError("usage", "vNext CODE finish requires --verification-file", 2);
1275
+ if (!terminalReplay(stage)) {
1276
+ const input = json(verification, false, "CODE verification", { schemaName: "code-verification", projectRoot: runtime.workspaceRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1277
+ prepared.stageFinish = { value: input.value, text: input.text };
1278
+ }
1279
+ }
1280
+ else if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId })) {
1281
+ acceptStageInputs("decision-file retry-check reason");
1282
+ if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
1283
+ throw new AppError("usage", "vNext CODE-REVIEW uses --decision-file", 2);
1284
+ const decision = optionalOption(parsed, "decision-file") ?? path.join(runtime.runRoot, "06-code-review", "decision.json");
1285
+ if (!terminalReplay(stage)) {
1286
+ const input = prepareCodeReviewDecision(runtime.runRoot, optionalOption(parsed, "decision-file"));
1287
+ try {
1288
+ validateSchema({ schemaName: "code-review-decision", file: decision, data: input.value, projectRoot: runtime.workspaceRoot, ddFlowHome: context.ddFlowHome, runId, runRoot: runtime.runRoot });
1289
+ }
1290
+ catch (error) {
1291
+ return prepareError(error, { file: decision, label: "CODE-REVIEW decision" });
1292
+ }
1293
+ prepared.stageFinish = input;
1294
+ }
1295
+ }
1296
+ else {
1297
+ acceptStageInputs("dir semantic-file data");
1298
+ if (hasOption(parsed, "outcome") || hasOption(parsed, "result-file") || resultStdin)
1299
+ throw new AppError("usage", "--outcome, --result-file and --result-stdin are only available for vNext SPECIFY", 2);
1300
+ prepared.legacyStageFinish = prepareStageFinish(context, { projectRoot, runId, stage, ...(optionalOption(parsed, "dir") ? { dir: optionalOption(parsed, "dir") } : {}), ...(semanticFile ? { semanticFile } : {}) });
1301
+ }
1302
+ return prepared;
1303
+ }
1304
+ async function dispatch(args, context, io, scopeProjectRoot = null, classification = classifyCliOperation(args, context.env), output = parseOutputOptions(args), prepared = {}) {
1305
+ if (!prepared.route)
1306
+ throw new AppError("command_not_prepared", "Command dispatch requires prepared arguments", 1);
1307
+ const { family, command, parsed } = prepared.route;
1308
+ if (family === "zcode" && command === "invocation" && parsed.positional[0] === "prepare") {
1309
+ const payload = prepared.lifecycleIssuance;
1310
+ if (!payload)
1311
+ throw new AppError("command_not_prepared", "Invocation issuance requires prepared input", 1);
1312
+ assertLifecycleInvocationCurrent(context, payload.scope, payload.command);
1313
+ return { ok: true, ...issueLifecycleInvocation(context, payload.command, payload.scope) };
1314
+ }
1315
+ if (family === "storage" && command === "migrate-writer") {
1316
+ if (parsed.positional.length || [...parsed.options.keys()].some(key => !["database", "backup", "offline"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
1317
+ throw new AppError("usage", "Usage: dd-flow storage migrate-writer --database ABSOLUTE_DB --backup NEW_ABSOLUTE_FILE --offline", 2);
1318
+ if (parsed.options.get("offline")?.[0] !== flagValue)
1319
+ throw new AppError("usage", "Writer migration requires --offline after draining all local and external runtime owners", 2);
1320
+ return { ok: true, ...migrateStoreWriter(requiredOption(parsed, "database"), requiredOption(parsed, "backup")) };
1321
+ }
506
1322
  if (family === "engine") {
507
- return dispatchEngine(context, command, parsed, classification);
1323
+ return dispatchEngine(context, command, parsed, classification, prepared);
508
1324
  }
509
1325
  if (family === "status") {
510
- const rootParsed = parseArgs([command ?? "", ...rest]);
511
1326
  return getRuntimeStatus(context, {
512
- projectRoot: optionalOption(rootParsed, "project-root") ?? optionalOption(rootParsed, "root"),
513
- checkRegistry: hasOption(rootParsed, "check-registry")
1327
+ projectRoot: optionalOption(parsed, "project-root") ?? optionalOption(parsed, "root"),
1328
+ checkRegistry: hasOption(parsed, "check-registry")
514
1329
  });
515
1330
  }
516
1331
  if (family === "version") {
517
1332
  return getCliVersionReport();
518
1333
  }
519
1334
  if (family === "runtime") {
520
- return await dispatchRuntime(context, command, parsed);
1335
+ return await dispatchRuntime(context, command, parsed, commandProgress(io, output), prepared);
521
1336
  }
522
1337
  if (family === "canon") {
523
- return dispatchCanon(context, command, parsed);
1338
+ return dispatchCanon(context, command, parsed, prepared);
524
1339
  }
525
1340
  if (family === "project" && command === "register") {
526
1341
  return registerProject(context, { root: requiredOption(parsed, "root") });
@@ -597,16 +1412,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
597
1412
  return readyForMerge(context, { protocolId, projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "protocol ready-for-merge") });
598
1413
  }
599
1414
  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
- });
1415
+ return transitionProtocol(context, protocolTransitionInput(parsed, scopeProjectRoot), prepared.protocolTransition);
610
1416
  }
611
1417
  if (family === "protocol" && command === "sync-from-run") {
612
1418
  const protocolId = requiredPosition(parsed, 0, "protocol-id");
@@ -631,17 +1437,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
631
1437
  });
632
1438
  }
633
1439
  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
- });
1440
+ return transitionProtocol(context, protocolTransitionInput(parsed, scopeProjectRoot), prepared.protocolTransition);
645
1441
  }
646
1442
  if (family === "plan" && command === "status") {
647
1443
  const protocolId = requiredPosition(parsed, 0, "protocol-id");
@@ -660,12 +1456,19 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
660
1456
  const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "stage fanout");
661
1457
  if (action === "status")
662
1458
  return getVnextFanoutStatus(context, { projectRoot, runId, stage });
1459
+ if (action === "reconcile")
1460
+ return reconcileVnextFanout(context, { projectRoot, runId, stage, observations: prepared.observations ?? prepareJsonFile(requiredOption(parsed, "observations-file"), "native observations").value });
663
1461
  if (action === "dispatch") {
664
1462
  if (stage === "plan-review")
665
1463
  return dispatchVnextPlanReview(context, { projectRoot, runId });
666
1464
  return getVnextFanoutStatus(context, { projectRoot, runId, stage });
667
1465
  }
668
- throw new AppError("usage", "Use: dd-flow stage fanout <status|dispatch> <RUN> --stage <stage> --project-root <path>", 2);
1466
+ 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);
1467
+ }
1468
+ if (family === "stage" && command === "native") {
1469
+ if (requiredPosition(parsed, 0, "native action") !== "observe")
1470
+ throw new AppError("usage", "Use: dd-flow stage native observe <RUN> --stage <stage> --observations-file <native-observations.json> --project-root <path>", 2);
1471
+ 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
1472
  }
670
1473
  if (family === "run" && command === "capacity") {
671
1474
  if (requiredPosition(parsed, 0, "capacity action") !== "record")
@@ -677,16 +1480,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
677
1480
  return dispatchPlanItem(context, parsed, requiredScopeProjectRoot(scopeProjectRoot, "plan item"));
678
1481
  }
679
1482
  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
- });
1483
+ return renderWorkerPrompt(context, prepared.workerPrompt?.input ?? workerPromptInput(parsed), prepared.workerPrompt?.value);
690
1484
  }
691
1485
  if (family === "work" && command === "status") {
692
1486
  return getVnextWorkStatus(context, {
@@ -695,7 +1489,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
695
1489
  });
696
1490
  }
697
1491
  if (family === "work" && command === "add-batch") {
698
- return addWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file: requiredOption(parsed, "file") });
1492
+ return addWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file: requiredOption(parsed, "file"), prepared: prepared.workBatch });
699
1493
  }
700
1494
  if (family === "work" && command === "ls") {
701
1495
  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 +1497,9 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
703
1497
  if (family === "work" && command === "show")
704
1498
  return showWork(context, requiredPosition(parsed, 0, "work-id"));
705
1499
  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
- });
1500
+ if (!prepared.workRepair)
1501
+ throw new AppError("cli_input_unprepared", "Repair input was not prepared", 1);
1502
+ return addVnextCodeRepair(context, prepared.workRepair.input, prepared.workRepair.value);
748
1503
  }
749
1504
  if (family === "work" && command === "deps") {
750
1505
  const on = parsed.options.get("on") ?? [];
@@ -752,21 +1507,34 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
752
1507
  }
753
1508
  if (family === "work" && command === "delete")
754
1509
  return deleteWork(context, requiredPosition(parsed, 0, "work-id"));
1510
+ if (family === "work" && command === "launch")
1511
+ return await launchExternalWork(context, { workId: requiredPosition(parsed, 0, "work-id"), ...(optionalOption(parsed, "stage") ? { stage: optionalOption(parsed, "stage") } : {}), progress: commandProgress(io, output) });
755
1512
  if (family === "work" && command === "start") {
756
1513
  const hookEventId = optionalOption(parsed, "hook-event-id");
1514
+ const recoveryId = optionalOption(parsed, "recovery-id");
757
1515
  const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work start");
758
- return startWork(context, requiredPosition(parsed, 0, "work-id"), { ...(hookEventId ? { hookEventId } : {}), projectRoot });
1516
+ return startWork(context, requiredPosition(parsed, 0, "work-id"), { ...(hookEventId ? { hookEventId } : {}), ...(recoveryId ? { recoveryId } : {}), projectRoot });
759
1517
  }
760
1518
  if (family === "work" && command === "finish") {
761
1519
  const resultFile = optionalOption(parsed, "result-file");
762
1520
  const resultStdin = hasOption(parsed, "result-stdin");
763
1521
  if (Boolean(resultFile) === resultStdin)
764
1522
  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));
1523
+ const workId = requiredPosition(parsed, 0, "work-id");
1524
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work finish");
1525
+ assertWorkLifecycleOwner(context, { workId, projectRoot, operation: "work_finish", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
1526
+ const retryReceiptId = optionalOption(parsed, "retry-check"), retryReason = optionalOption(parsed, "reason");
1527
+ if (Boolean(retryReceiptId) !== Boolean(retryReason))
1528
+ throw new AppError("usage", "--retry-check and --reason must be supplied together", 2);
1529
+ const result = prepared.workFinish?.result ?? (resultFile ? prepareTextFile(resultFile, "Work result").text : await readStdin(io.stdin));
1530
+ return await finishWork(context, workId, result, commandProgress(io, output), retryReceiptId ? { receiptId: retryReceiptId, reason: retryReason } : undefined);
1531
+ }
1532
+ if (family === "work" && command === "fail") {
1533
+ const workId = requiredPosition(parsed, 0, "work-id");
1534
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work fail");
1535
+ assertWorkLifecycleOwner(context, { workId, projectRoot, operation: "work_fail", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
1536
+ return failWork(context, workId, requiredOption(parsed, "reason"));
767
1537
  }
768
- if (family === "work" && command === "fail")
769
- return failWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
770
1538
  if (family === "work" && command === "cancel")
771
1539
  return cancelWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
772
1540
  if (family === "work" && command === "retry")
@@ -788,7 +1556,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
788
1556
  const requireSessionBinding = hasOption(parsed, "require-session-binding");
789
1557
  const projectRoot = requiredOption(parsed, "project-root");
790
1558
  const stage = requiredOption(parsed, "stage");
791
- const externalContext = contextFile && contextSha256 ? loadExternalStageContext({ file: contextFile, expectedSha256: contextSha256, stage }) : undefined;
1559
+ const externalContext = prepared.stageStart?.externalContext;
792
1560
  const claimVnextStageStart = (runId) => {
793
1561
  registerProject(context, { root: projectRoot });
794
1562
  return findRecentMatchingHookEvent(context, {
@@ -819,37 +1587,37 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
819
1587
  }
820
1588
  const result = launchVnextSpecify(context, {
821
1589
  projectRoot,
822
- ...(externalContext ? { intakeMarkdown: runnerIntake(externalContext) } : intakeFile ? { intakeFile } : { intakeMarkdown: await readStdin(io.stdin) }),
1590
+ ...(prepared.stageStart?.intakeMarkdown !== undefined ? { intakeMarkdown: prepared.stageStart.intakeMarkdown } : externalContext ? { intakeMarkdown: runnerIntake(externalContext) } : intakeFile ? { intakeFile } : { intakeMarkdown: await readStdin(io.stdin) }),
823
1591
  hookEventId,
824
1592
  ...(subject ? { slug: subject } : {}),
825
1593
  ...(externalContext ? { externalContext } : {}),
826
1594
  ...(!bootstrap ? { runId: requiredPosition(parsed, 0, "run-id") } : {})
827
- });
1595
+ }, prepared.specifyStart);
828
1596
  return attachExternalStageContext(result, externalContext);
829
1597
  }
830
1598
  if (!bootstrap && stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
831
1599
  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);
1600
+ return attachExternalStageContext(startVnextProtocolize(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.protocolizeStart), externalContext);
833
1601
  }
834
1602
  if (!bootstrap && stage === "plan" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
835
1603
  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);
1604
+ return attachExternalStageContext(startVnextPlan(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.planStart), externalContext);
837
1605
  }
838
1606
  if (!bootstrap && stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
839
1607
  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);
1608
+ return attachExternalStageContext(startVnextPlanReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.planReviewStart), externalContext);
841
1609
  }
842
1610
  if (!bootstrap && stage === "code" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
843
1611
  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);
1612
+ 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
1613
  }
846
1614
  if (!bootstrap && stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
847
1615
  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);
1616
+ return attachExternalStageContext(startVnextCodeReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }, prepared.codeReviewStart), externalContext);
849
1617
  }
850
1618
  if (!bootstrap && stage === "merge" && isVnextMergeRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
851
1619
  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);
1620
+ 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
1621
  }
854
1622
  if (intakeStdin) {
855
1623
  throw new AppError("usage", "--intake-stdin is only available for vNext SPECIFY", 2);
@@ -864,7 +1632,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
864
1632
  ...(hookEventId ? { hookEventId } : {}),
865
1633
  ...(requireSessionBinding ? { requireSessionBinding: true } : {}),
866
1634
  ...(dir ? { dir } : {})
867
- });
1635
+ }, prepared.legacyStageStart);
868
1636
  }
869
1637
  if (family === "stage" && command === "finish") {
870
1638
  const dir = optionalOption(parsed, "dir");
@@ -874,9 +1642,23 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
874
1642
  const projectRoot = requiredOption(parsed, "project-root");
875
1643
  const runId = requiredPosition(parsed, 0, "run-id");
876
1644
  const stage = requiredOption(parsed, "stage");
1645
+ const controlledReply = (result) => controlLifecycleReply(context, { projectRoot, runId }, result);
877
1646
  const semanticFile = optionalOption(parsed, "semantic-file") ?? optionalOption(parsed, "data");
878
1647
  const resultFile = optionalOption(parsed, "result-file") ?? semanticFile;
879
1648
  const resultStdin = hasOption(parsed, "result-stdin");
1649
+ const retryCheckId = optionalOption(parsed, "retry-check");
1650
+ const retryReason = optionalOption(parsed, "reason");
1651
+ const hookEventId = optionalOption(parsed, "hook-event-id");
1652
+ if (retryCheckId && !retryReason?.trim())
1653
+ throw new AppError("usage", "--retry-check requires --reason explaining the recovered environment", 2);
1654
+ const protectedLifecycle = (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId }))
1655
+ || (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId }))
1656
+ || (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId }))
1657
+ || (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId }))
1658
+ || (stage === "code" && isVnextPlanRun(context, { projectRoot, runId }))
1659
+ || (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId }));
1660
+ if (protectedLifecycle)
1661
+ assertStageLifecycleOwner(context, { projectRoot, runId, stage, operation: "stage_finish", ...(hookEventId ? { hookEventId } : {}) });
880
1662
  if (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId })) {
881
1663
  const outcome = optionalOption(parsed, "outcome");
882
1664
  if (!outcome || !["specified", "failed", "cancelled"].includes(outcome)) {
@@ -888,66 +1670,79 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
888
1670
  if (!resultFile && !resultStdin) {
889
1671
  throw new AppError("usage", "vNext SPECIFY finish requires --result-file or --result-stdin", 2);
890
1672
  }
891
- return finishVnextSpecifyStage(context, {
1673
+ return controlledReply(await finishVnextSpecifyStage(context, {
892
1674
  projectRoot,
893
1675
  runId,
894
- ...(resultFile ? { resultFile } : { resultJson: await readStdin(io.stdin) }),
1676
+ ...(resultFile ? { resultFile } : prepared.stageFinish?.value ? {} : { resultJson: await readStdin(io.stdin) }),
1677
+ ...(prepared.stageFinish?.value ? { result: prepared.stageFinish.value } : {}),
895
1678
  outcome: outcome
896
- });
1679
+ }));
897
1680
  }
898
1681
  if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId })) {
899
1682
  if (!resultFile || resultStdin || hasOption(parsed, "outcome")) {
900
1683
  throw new AppError("usage", "vNext PROTOCOLIZE requires exactly --result-file", 2);
901
1684
  }
902
- return finishVnextProtocolize(context, { projectRoot, runId, resultFile });
1685
+ return controlledReply(await finishVnextProtocolize(context, { projectRoot, runId, resultFile, ...(prepared.stageFinish?.value ? { result: prepared.stageFinish.value } : {}) }));
903
1686
  }
904
1687
  if (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId })) {
905
1688
  if (optionalOption(parsed, "code-work-batch-file"))
906
1689
  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 });
1690
+ return controlledReply(await finishVnextPlan(context, { projectRoot, runId, ...(prepared.planFinish ? { prepared: prepared.planFinish } : {}) }));
908
1691
  }
909
1692
  if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId })) {
910
1693
  if (resultStdin || hasOption(parsed, "outcome"))
911
1694
  throw new AppError("usage", "vNext PLAN-REVIEW uses --decision-file", 2);
912
1695
  const decisionFile = optionalOption(parsed, "decision-file");
913
- return finishVnextPlanReview(context, { projectRoot, runId, ...(decisionFile ? { decisionFile } : {}) });
1696
+ return controlledReply(await finishVnextPlanReview(context, { projectRoot, runId, ...(decisionFile ? { decisionFile } : {}), ...(prepared.stageFinish?.value ? { decision: prepared.stageFinish.value, decisionText: prepared.stageFinish.text } : {}) }));
914
1697
  }
915
1698
  if (stage === "code" && isVnextPlanRun(context, { projectRoot, runId })) {
916
1699
  if (semanticFile || resultFile || resultStdin || hasOption(parsed, "outcome")) {
917
1700
  throw new AppError("usage", "vNext CODE finish accepts only --verification-file", 2);
918
1701
  }
919
- return await finishVnextCode(context, { projectRoot, runId, verificationFile: optionalOption(parsed, "verification-file") ?? path.join("<missing>", "code-verification.json"), progress: commandProgress(io, output) });
1702
+ 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
1703
  }
921
1704
  if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId })) {
922
1705
  if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
923
1706
  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) });
1707
+ 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
1708
  }
926
1709
  if (stage === "merge" && isVnextMergeRun(context, { projectRoot, runId })) {
927
1710
  if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
928
1711
  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) });
1712
+ 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
1713
  }
931
1714
  if (hasOption(parsed, "outcome") || hasOption(parsed, "result-file") || resultStdin) {
932
1715
  throw new AppError("usage", "--outcome, --result-file and --result-stdin are only available for vNext SPECIFY", 2);
933
1716
  }
934
- return finishStage(context, {
1717
+ return controlledReply(await finishStage(context, {
935
1718
  projectRoot,
936
1719
  runId,
937
1720
  stage,
938
1721
  ...(dir ? { dir } : {}),
939
1722
  ...(semanticFile ? { semanticFile } : {})
940
- });
1723
+ }, prepared.legacyStageFinish));
941
1724
  }
942
1725
  if (family === "stage" && command === "pause") {
943
1726
  if (!hasOption(parsed, "question-stdin"))
944
1727
  throw new AppError("usage", "stage pause requires --question-stdin", 2);
1728
+ const projectRoot = requiredOption(parsed, "project-root");
1729
+ const runId = requiredPosition(parsed, 0, "run-id");
1730
+ const stage = requiredOption(parsed, "stage");
1731
+ const workId = requiredOption(parsed, "work");
1732
+ const protectedLifecycle = (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId }))
1733
+ || (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId }))
1734
+ || (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId }))
1735
+ || (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId }))
1736
+ || (stage === "code" && isVnextPlanRun(context, { projectRoot, runId }))
1737
+ || (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId }));
1738
+ if (protectedLifecycle)
1739
+ assertStageLifecycleOwner(context, { projectRoot, runId, stage, workId, operation: "stage_pause", ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
945
1740
  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)
1741
+ projectRoot,
1742
+ runId,
1743
+ stage,
1744
+ workId,
1745
+ question: prepared.interactionText ?? await readStdin(io.stdin)
951
1746
  });
952
1747
  }
953
1748
  if (family === "stage" && command === "resume") {
@@ -959,7 +1754,8 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
959
1754
  runId: requiredPosition(parsed, 0, "run-id"),
960
1755
  stage: requiredOption(parsed, "stage"),
961
1756
  workId: requiredOption(parsed, "work"),
962
- answer: await readStdin(io.stdin),
1757
+ answer: prepared.interactionText ?? await readStdin(io.stdin),
1758
+ evidence: prepared.resumeEvidence,
963
1759
  ...(hookEventId ? { hookEventId } : {})
964
1760
  });
965
1761
  }
@@ -976,7 +1772,7 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
976
1772
  workId: requiredOption(parsed, "work"),
977
1773
  kind,
978
1774
  code: requiredOption(parsed, "code"),
979
- summary: await readStdin(io.stdin),
1775
+ summary: prepared.interactionText ?? await readStdin(io.stdin),
980
1776
  retryable: hasOption(parsed, "retryable")
981
1777
  });
982
1778
  }
@@ -1001,13 +1797,55 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1001
1797
  return dispatchMergeWorker(context, command, parsed);
1002
1798
  }
1003
1799
  if (family === "cleanup") {
1004
- return dispatchCleanup(context, command, parsed);
1800
+ return dispatchCleanup(context, command, parsed, prepared.cleanup);
1005
1801
  }
1006
1802
  if (family === "session") {
1007
- return dispatchSession(context, command, parsed);
1803
+ return dispatchSession(context, command, parsed, prepared.sessionPayload);
1008
1804
  }
1009
1805
  if (family === "run") {
1010
- return dispatchRun(context, command, parsed);
1806
+ if (command === "control") {
1807
+ const action = requiredPosition(parsed, 0, "control action");
1808
+ const scope = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run") };
1809
+ if (action === "status")
1810
+ return runControlStatus(context, scope);
1811
+ if (action === "reconcile") {
1812
+ if ([...parsed.options.keys()].some(key => !["run", "project-root", "control-id", "request-id"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
1813
+ throw new AppError("usage", "Use run control reconcile --run ID --project-root PATH --control-id ID --request-id ID", 2);
1814
+ return await reconcileRunControl(context, { ...scope, controlId: requiredOption(parsed, "control-id"), requestId: requiredOption(parsed, "request-id") });
1815
+ }
1816
+ if (action === "resume") {
1817
+ if (["force", "grace-ms", "escalate"].some(option => hasOption(parsed, option)))
1818
+ throw new AppError("usage", "Resume does not accept stop or pause escalation options", 2);
1819
+ return await resumeRunController(context, { ...scope, requestId: requiredOption(parsed, "request-id"), controlId: requiredOption(parsed, "from"), ...(hasOption(parsed, "wait-ms") ? { waitMs: Number(requiredOption(parsed, "wait-ms")) } : {}) });
1820
+ }
1821
+ if (action === "serve")
1822
+ return await serveRunControl(context, { ...scope, controlId: requiredOption(parsed, "control-id") });
1823
+ if (action === "pause" || action === "stop")
1824
+ return await requestRunControl(context, {
1825
+ ...scope, action, requestId: requiredOption(parsed, "request-id"),
1826
+ ...(hasOption(parsed, "force") ? { force: true } : {}),
1827
+ ...(hasOption(parsed, "grace-ms") ? { graceMs: Number(requiredOption(parsed, "grace-ms")) } : {}),
1828
+ ...(hasOption(parsed, "escalate") ? { escalate: requiredOption(parsed, "escalate") } : {}),
1829
+ ...(hasOption(parsed, "wait-ms") ? { waitMs: Number(requiredOption(parsed, "wait-ms")) } : {})
1830
+ });
1831
+ throw new AppError("usage", "Use: dd-flow run control pause|stop|resume|reconcile|status", 2);
1832
+ }
1833
+ if (command === "drive") {
1834
+ const action = requiredPosition(parsed, 0, "drive action");
1835
+ const scope = { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run") };
1836
+ if (action === "status")
1837
+ return runControllerStatus(context, { ...scope, ...(optionalOption(parsed, "after") ? { after: Number(optionalOption(parsed, "after")) } : {}) });
1838
+ if (action === "launch")
1839
+ return await launchRunController(context, controllerLaunchInput(parsed), prepared.controllerLaunch);
1840
+ if (action === "serve")
1841
+ return await serveRunController(context, { ...scope, controllerId: requiredOption(parsed, "controller-id") });
1842
+ if (action === "answer")
1843
+ return answerRunController(context, controllerAnswerInput(parsed), prepared.controllerAnswer);
1844
+ if (action === "context")
1845
+ return supplyRunControllerContext(context, controllerContextInput(parsed), prepared.controllerContext);
1846
+ throw new AppError("usage", "Use: dd-flow run drive launch|status|answer|context", 2);
1847
+ }
1848
+ return dispatchRun(context, command, parsed, prepared);
1011
1849
  }
1012
1850
  if (family === "stat") {
1013
1851
  return dispatchStat(context, command, parsed);
@@ -1022,23 +1860,26 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1022
1860
  return dispatchDashboard(context, command, parsed);
1023
1861
  }
1024
1862
  if (family === "schema") {
1025
- return dispatchSchema(context, command, parsed);
1863
+ return prepared.schemaValidation;
1026
1864
  }
1027
1865
  if (family === "memory") {
1028
1866
  return dispatchMemory(command, parsed);
1029
1867
  }
1030
1868
  if (family === "migration") {
1031
- return dispatchMigration(context, command, parsed, classification);
1869
+ return dispatchMigration(context, command, parsed, classification, prepared);
1032
1870
  }
1033
1871
  if (family === "codex" && command === "hooks") {
1034
- return dispatchCodexHooks(context, parsed);
1872
+ return dispatchCodexHooks(context, parsed, prepared);
1035
1873
  }
1036
1874
  if (family === "codex" && command === "home") {
1037
- return dispatchCodexHome(context, parsed);
1875
+ return dispatchCodexHome(context, parsed, prepared);
1038
1876
  }
1039
1877
  if (family === "codex" && command === "hook") {
1040
1878
  return dispatchCodexHook(context, parsed, await readStdin(io.stdin));
1041
1879
  }
1880
+ if (family === "zcode" && command === "hook") {
1881
+ return dispatchZcodeHook(context, parsed, await readStdin(io.stdin));
1882
+ }
1042
1883
  if (family === "zcode" && command === "event") {
1043
1884
  return dispatchZcodeEvent(context, parsed, await readStdin(io.stdin));
1044
1885
  }
@@ -1063,6 +1904,16 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1063
1904
  throw new AppError("usage", "Unknown opencode usage action", 2);
1064
1905
  return ingestOpenCodeUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1065
1906
  }
1907
+ if (family === "droid" && command === "event") {
1908
+ if (requiredPosition(parsed, 0, "droid event action") !== "handle")
1909
+ throw new AppError("usage", "Unknown droid event action", 2);
1910
+ return handleDroidEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1911
+ }
1912
+ if (family === "droid" && command === "usage") {
1913
+ if (requiredPosition(parsed, 0, "droid usage action") !== "ingest")
1914
+ throw new AppError("usage", "Unknown droid usage action", 2);
1915
+ return ingestDroidUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1916
+ }
1066
1917
  if (family === "agy" && command === "event")
1067
1918
  return dispatchAgyEvent(context, parsed, await readStdin(io.stdin));
1068
1919
  if (family === "agy" && command === "usage") {
@@ -1071,11 +1922,14 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
1071
1922
  return ingestAgyUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
1072
1923
  }
1073
1924
  if (family === "worktree") {
1074
- return dispatchWorktree(context, command, parsed, requiredScopeProjectRoot(scopeProjectRoot, `worktree ${command ?? ""}`));
1925
+ return dispatchWorktree(context, command, parsed, requiredScopeProjectRoot(scopeProjectRoot, `worktree ${command ?? ""}`), prepared);
1075
1926
  }
1076
1927
  throw new AppError("usage", `Unknown command: ${args.join(" ") || "<empty>"}`, 2);
1077
1928
  }
1078
- function dispatchEngine(context, command, parsed, classification) {
1929
+ function engineBindInput(parsed) {
1930
+ 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") };
1931
+ }
1932
+ function dispatchEngine(context, command, parsed, classification, prepared) {
1079
1933
  if (command === "install") {
1080
1934
  return installCurrentEngine(context, { force: hasOption(parsed, "force") });
1081
1935
  }
@@ -1100,18 +1954,11 @@ function dispatchEngine(context, command, parsed, classification) {
1100
1954
  });
1101
1955
  }
1102
1956
  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
- });
1957
+ return bindRunEngine(context, engineBindInput(parsed), prepared.engineBind);
1111
1958
  }
1112
1959
  throw new AppError("usage", `Unknown engine command: ${command ?? "<empty>"}`, 2);
1113
1960
  }
1114
- function dispatchMigration(context, command, parsed, classification) {
1961
+ function dispatchMigration(context, command, parsed, classification, prepared) {
1115
1962
  if (command === "impact")
1116
1963
  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
1964
  if (command === "plan" || command === "report") {
@@ -1127,26 +1974,42 @@ function dispatchMigration(context, command, parsed, classification) {
1127
1974
  });
1128
1975
  }
1129
1976
  if (command === "verify") {
1130
- return verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
1977
+ return prepared.migrationVerification ?? verifyMigrationReport(context, { file: requiredOption(parsed, "file") });
1131
1978
  }
1132
1979
  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
- });
1980
+ return applyMigration(context, migrationApplyInput(parsed, classification), prepared.migrationApply);
1144
1981
  }
1145
1982
  throw new AppError("usage", `Unknown migration command: ${command ?? "<empty>"}`, 2);
1146
1983
  }
1147
- function dispatchCanon(context, command, parsed) {
1984
+ function protocolTransitionInput(parsed, scopeProjectRoot) {
1985
+ const reason = optionalOption(parsed, "reason");
1986
+ 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 } : {}) };
1987
+ }
1988
+ function controllerAnswerInput(parsed) {
1989
+ 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") };
1990
+ }
1991
+ function controllerLaunchInput(parsed) {
1992
+ 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") } : {}) };
1993
+ }
1994
+ function controllerContextInput(parsed) {
1995
+ 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") };
1996
+ }
1997
+ function migrationApplyInput(parsed, classification) {
1998
+ return {
1999
+ projectRoot: requiredOption(parsed, "project-root"),
2000
+ sourceVersion: optionalOption(parsed, "source-version"),
2001
+ targetVersion: optionalOption(parsed, "target-version"),
2002
+ runId: optionalOption(parsed, "run"),
2003
+ backupPath: optionalOption(parsed, "backup-path"),
2004
+ backupCreatedAt: optionalOption(parsed, "backup-created-at"),
2005
+ reportFile: optionalOption(parsed, "file"),
2006
+ allowActive: false,
2007
+ classification
2008
+ };
2009
+ }
2010
+ function dispatchCanon(context, command, parsed, prepared) {
1148
2011
  if (command === "register") {
1149
- return registerCanonRoot(context, { root: requiredOption(parsed, "root") });
2012
+ return registerCanonRoot(context, { root: requiredOption(parsed, "root") }, prepared.canonRegistration);
1150
2013
  }
1151
2014
  if (command === "status") {
1152
2015
  return getCanonStatus(context, { root: optionalOption(parsed, "root") });
@@ -1156,6 +2019,15 @@ function dispatchCanon(context, command, parsed) {
1156
2019
  }
1157
2020
  throw new AppError("usage", `Unknown canon command: ${command ?? "<empty>"}`, 2);
1158
2021
  }
2022
+ function mergeJobTarget(parsed, scopeProjectRoot) {
2023
+ return { protocolId: requiredPosition(parsed, 0, "protocol-id"), projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue"), workerId: requiredWorkerId(parsed), workspacePath: workspacePathOption(parsed) };
2024
+ }
2025
+ function mergeCancellationInput(parsed, scopeProjectRoot) {
2026
+ 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") };
2027
+ }
2028
+ function mergeWaitInput(parsed, scopeProjectRoot) {
2029
+ 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 };
2030
+ }
1159
2031
  function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1160
2032
  if (hasOption(parsed, "session-id")) {
1161
2033
  throw new AppError("usage", "--session-id is no longer accepted on merge-queue commands; use --worker-id", 2);
@@ -1179,32 +2051,17 @@ function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1179
2051
  });
1180
2052
  }
1181
2053
  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
- });
2054
+ return waitNextMergeJob(context, mergeWaitInput(parsed, scopeProjectRoot));
1190
2055
  }
1191
2056
  if (command === "complete") {
1192
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
1193
2057
  return completeMergeJob(context, {
1194
- protocolId,
1195
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue complete"),
1196
- workerId: requiredWorkerId(parsed),
1197
- workspacePath: workspacePathOption(parsed),
2058
+ ...mergeJobTarget(parsed, scopeProjectRoot),
1198
2059
  summary: requiredOption(parsed, "summary")
1199
2060
  });
1200
2061
  }
1201
2062
  if (command === "fail") {
1202
- const protocolId = requiredPosition(parsed, 0, "protocol-id");
1203
2063
  return failMergeJob(context, {
1204
- protocolId,
1205
- projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "merge-queue fail"),
1206
- workerId: requiredWorkerId(parsed),
1207
- workspacePath: workspacePathOption(parsed),
2064
+ ...mergeJobTarget(parsed, scopeProjectRoot),
1208
2065
  reason: requiredOption(parsed, "reason"),
1209
2066
  requeue: parseBoolean(requiredOption(parsed, "requeue"), "requeue")
1210
2067
  });
@@ -1219,15 +2076,7 @@ function dispatchMergeQueue(context, command, parsed, scopeProjectRoot) {
1219
2076
  });
1220
2077
  }
1221
2078
  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
- });
2079
+ return cancelMergeQueueJob(context, mergeCancellationInput(parsed, scopeProjectRoot));
1231
2080
  }
1232
2081
  throw new AppError("usage", `Unknown merge-queue command: ${command ?? "<empty>"}`, 2);
1233
2082
  }
@@ -1247,6 +2096,8 @@ async function dispatchMerge(context, command, parsed, progress) {
1247
2096
  }
1248
2097
  if (command === "apply")
1249
2098
  return applyVnextMerge(context, { projectRoot: requiredOption(parsed, "project-root"), requestId: requiredPosition(parsed, 0, "merge-request-id"), workId: requiredOption(parsed, "work"), ...(progress ? { progress } : {}) });
2099
+ if (command === "repair")
2100
+ return await repairVnextMerge(context, { projectRoot: requiredOption(parsed, "project-root"), requestId: requiredPosition(parsed, 0, "merge-request-id") });
1250
2101
  if (command === "request") {
1251
2102
  const action = requiredPosition(parsed, 0, "request action");
1252
2103
  const requestId = requiredPosition(parsed, 1, "merge-request-id");
@@ -1343,7 +2194,7 @@ function completedCommandExitCode(payload) {
1343
2194
  const exitCode = payload.exit_code;
1344
2195
  return typeof exitCode === "number" && Number.isInteger(exitCode) ? exitCode : 0;
1345
2196
  }
1346
- function dispatchCleanup(context, command, parsed) {
2197
+ function dispatchCleanup(context, command, parsed, prepared) {
1347
2198
  if (command === "scan") {
1348
2199
  return cleanupScan(context, { projectRoot: requiredOption(parsed, "project-root") });
1349
2200
  }
@@ -1351,6 +2202,7 @@ function dispatchCleanup(context, command, parsed) {
1351
2202
  return cleanupApply(context, {
1352
2203
  projectRoot: requiredOption(parsed, "project-root"),
1353
2204
  planFile: requiredOption(parsed, "plan-file"),
2205
+ prepared,
1354
2206
  reason: requiredOption(parsed, "reason"),
1355
2207
  force: hasOption(parsed, "force")
1356
2208
  });
@@ -1371,12 +2223,14 @@ function dispatchProjectConfig(context, parsed) {
1371
2223
  }
1372
2224
  throw new AppError("usage", `Unknown project config action: ${action}`, 2);
1373
2225
  }
1374
- function dispatchSession(context, command, parsed) {
2226
+ function dispatchSession(context, command, parsed, preparedPayload) {
1375
2227
  if (command === "register") {
1376
2228
  return registerFlowSession(context, {
2229
+ ...(preparedPayload ? { preparedPayload } : {}),
1377
2230
  payloadBase64: optionalOption(parsed, "payload-base64"),
1378
2231
  payloadJson: optionalOption(parsed, "payload-json"),
1379
2232
  payloadFile: optionalOption(parsed, "payload-file"),
2233
+ hookEventId: optionalOption(parsed, "hook-event-id"),
1380
2234
  sessionId: optionalOption(parsed, "session-id")
1381
2235
  });
1382
2236
  }
@@ -1409,7 +2263,45 @@ function dispatchSession(context, command, parsed) {
1409
2263
  }
1410
2264
  throw new AppError("usage", `Unknown session command: ${command ?? "<empty>"}`, 2);
1411
2265
  }
1412
- function dispatchRun(context, command, parsed) {
2266
+ function snapshotCreateInput(parsed) {
2267
+ const recoveryId = optionalOption(parsed, "recovery-id"), stageEntry = optionalOption(parsed, "stage-entry");
2268
+ 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 } : {}) };
2269
+ }
2270
+ function snapshotRestoreInput(parsed) {
2271
+ 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") } : {}) };
2272
+ }
2273
+ function runStartInput(parsed) {
2274
+ const protocolOverrides = readOptionalJsonFile(optionalOption(parsed, "protocol-override-file"));
2275
+ 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")) };
2276
+ }
2277
+ function runForkInput(parsed) {
2278
+ 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") } : {}) };
2279
+ }
2280
+ function recoveryCaptureInput(parsed) {
2281
+ return { projectRoot: requiredOption(parsed, "project-root"), runId: requiredPosition(parsed, 1, "run-id"), recoveryId: requiredOption(parsed, "recovery-id"), capturePath: requiredOption(parsed, "capture-path") };
2282
+ }
2283
+ function recoveryResumeInput(parsed) {
2284
+ 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") };
2285
+ }
2286
+ function dispatchRun(context, command, parsed, prepared = {}) {
2287
+ if (command === "recovery") {
2288
+ const action = requiredPosition(parsed, 0, "recovery action");
2289
+ const projectRoot = requiredOption(parsed, "project-root");
2290
+ const runId = requiredPosition(parsed, 1, "run-id");
2291
+ if (action === "inspect")
2292
+ return inspectRunRecovery(context, { projectRoot, runId });
2293
+ if (action === "begin")
2294
+ return beginRunRecovery(context, { projectRoot, runId, interruption: requiredOption(parsed, "interruption-json") }, prepared.recoveryPayload);
2295
+ if (action === "seal")
2296
+ return sealRunRecovery(context, { projectRoot, runId, recoveryId: requiredOption(parsed, "recovery-id"), settlement: requiredOption(parsed, "settlement-json") }, prepared.recoveryPayload);
2297
+ if (action === "capture")
2298
+ return recordRecoveryCapture(context, recoveryCaptureInput(parsed), prepared.recoveryCapture);
2299
+ if (action === "resume")
2300
+ return resumeRunRecovery(context, recoveryResumeInput(parsed), prepared.recoveryResume);
2301
+ if (action === "accept")
2302
+ return acceptRunRecovery(context, { projectRoot, runId, recoveryId: requiredOption(parsed, "recovery-id"), ...(optionalOption(parsed, "hook-event-id") ? { hookEventId: optionalOption(parsed, "hook-event-id") } : {}) });
2303
+ throw new AppError("usage", "Use: dd-flow run recovery inspect|begin|seal|capture|resume|accept", 2);
2304
+ }
1413
2305
  if (command === "snapshot") {
1414
2306
  const action = requiredPosition(parsed, 0, "snapshot action");
1415
2307
  if (action === "bootstrap") {
@@ -1420,56 +2312,27 @@ function dispatchRun(context, command, parsed) {
1420
2312
  output: requiredOption(parsed, "output")
1421
2313
  });
1422
2314
  if (bootstrapAction === "restore")
1423
- return restoreEvalBootstrapSnapshot(context, {
1424
- snapshot: requiredOption(parsed, "snapshot"),
1425
- projectRoot: requiredOption(parsed, "project-root")
1426
- });
2315
+ return restoreEvalBootstrapSnapshot(context, snapshotRestoreInput(parsed), prepared.bootstrapRestore);
1427
2316
  throw new AppError("usage", "Use: dd-flow run snapshot bootstrap create|restore", 2);
1428
2317
  }
1429
2318
  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 });
2319
+ return createEvalRunSnapshot(context, snapshotCreateInput(parsed));
1444
2320
  }
1445
2321
  if (action === "restore")
1446
- return restoreEvalRunSnapshot(context, {
1447
- snapshot: requiredOption(parsed, "snapshot"),
1448
- projectRoot: requiredOption(parsed, "project-root")
1449
- });
2322
+ return restoreEvalRunSnapshot(context, snapshotRestoreInput(parsed), prepared.snapshotRestore);
1450
2323
  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
2324
  }
2325
+ if (command === "fork") {
2326
+ return forkRunFromSnapshot(context, runForkInput(parsed), prepared.runFork);
2327
+ }
1452
2328
  if (command === "prepare-vnext-specify") {
1453
- return prepareVnextSpecifyRun(context, { projectRoot: requiredOption(parsed, "project-root"), slug: requiredOption(parsed, "slug") });
2329
+ return prepareVnextSpecifyRun(context, { projectRoot: requiredOption(parsed, "project-root"), slug: requiredOption(parsed, "slug"), executionRoutingFile: optionalOption(parsed, "execution-routing-file") });
1454
2330
  }
1455
2331
  if (command === "start") {
1456
2332
  if (optionalOption(parsed, "flow-kind") === "mb-upgrade") {
1457
2333
  assertUpgradeRunStorageReady(context, requiredOption(parsed, "project-root"));
1458
2334
  }
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
- });
2335
+ return startFlowRun(context, prepared.runStart?.input ?? runStartInput(parsed), prepared.runStart?.value);
1473
2336
  }
1474
2337
  if (command === "status") {
1475
2338
  return getFlowRunStatus(context, {
@@ -1539,83 +2402,163 @@ function dispatchRun(context, command, parsed) {
1539
2402
  throw new AppError("usage", `Unknown run flags command: ${action}`, 2);
1540
2403
  }
1541
2404
  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
- });
2405
+ return attachFlowRunStage(context, stageAttachmentInput(parsed));
1550
2406
  }
1551
2407
  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
- });
2408
+ return completeFlowRunStage(context, stageCompletionInput(parsed));
1564
2409
  }
1565
2410
  if (command === "complete") {
1566
2411
  throw new AppError("usage", "run complete is retired; only an operator may use run override", 2);
1567
2412
  }
1568
2413
  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
- });
2414
+ return completeFlowRun(context, runOverrideInput(parsed));
1581
2415
  }
1582
2416
  throw new AppError("usage", `Unknown run command: ${command ?? "<empty>"}`, 2);
1583
2417
  }
1584
- async function dispatchRuntime(context, command, parsed) {
2418
+ function stageAttachmentInput(parsed) {
2419
+ 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") };
2420
+ }
2421
+ function runOverrideInput(parsed) {
2422
+ 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") };
2423
+ }
2424
+ function stageCompletionInput(parsed) {
2425
+ 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") };
2426
+ }
2427
+ function runtimeServiceInput(parsed) {
2428
+ 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 };
2429
+ }
2430
+ function runtimeProcessStopInput(parsed) {
2431
+ const graceMs = optionalNumber(parsed, "grace-ms");
2432
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(graceMs !== undefined ? { graceMs } : {}) };
2433
+ }
2434
+ function runtimeScopeResumeInput(parsed) {
2435
+ return { scopeId: requiredOption(parsed, "scope-id"), requestId: requiredOption(parsed, "request-id"), generation: Number(requiredOption(parsed, "generation")), captureKey: requiredOption(parsed, "capture-key") };
2436
+ }
2437
+ function runtimeProcessRegistrationInput(context, parsed) {
2438
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
2439
+ const budget = parseRuntimeBudget(optionalOption(parsed, "budget-json"));
2440
+ const kind = requiredOption(parsed, "kind");
2441
+ const projectId = optionalOption(parsed, "project-id") ?? null, runId = optionalOption(parsed, "run") ?? null;
2442
+ const guard = projectId && runId ? recoveryGuard(context, projectId, runId) : null;
2443
+ const run = projectId && runId ? context.db.get("SELECT id FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]) : null;
2444
+ return {
2445
+ kind, ownerId: requiredOption(parsed, "owner"), uniqueActiveOperation: kind === "eval-observer",
2446
+ ...(kind === "eval-observer" ? { pid: optionalPositiveNumber(parsed, "pid", true) ?? 0, ...(optionalPositiveNumber(parsed, "process-group-id", true) ? { processGroupId: optionalPositiveNumber(parsed, "process-group-id", true) } : {}) } : {}),
2447
+ ownerPid: optionalPositiveNumber(parsed, "owner-pid", true), projectId, runId,
2448
+ workId: optionalOption(parsed, "work") ?? null, checkId: optionalOption(parsed, "check") ?? null,
2449
+ operationId: optionalOption(parsed, "operation") ?? null, stdoutPath: optionalOption(parsed, "stdout") ?? null,
2450
+ stderrPath: optionalOption(parsed, "stderr") ?? null, ...(leaseMs !== undefined ? { leaseMs } : {}),
2451
+ 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") } : {}) }
2452
+ };
2453
+ }
2454
+ function runtimeProcessConfirmationInput(parsed) {
2455
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true), processGroupId = optionalPositiveNumber(parsed, "process-group-id", true);
2456
+ 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 } : {}) };
2457
+ }
2458
+ function runtimeProcessHeartbeatInput(parsed) {
2459
+ const leaseMs = optionalPositiveNumber(parsed, "lease-ms", true);
2460
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), ...(leaseMs !== undefined ? { leaseMs } : {}) };
2461
+ }
2462
+ function runtimeProcessFinishInput(parsed) {
2463
+ const state = requiredOption(parsed, "state");
2464
+ if (state !== "stopped" && state !== "failed")
2465
+ throw new AppError("validation", "--state must be stopped or failed", 2);
2466
+ return { id: requiredOption(parsed, "id"), leaseToken: requiredOption(parsed, "lease-token"), state, reason: optionalOption(parsed, "reason") ?? null };
2467
+ }
2468
+ async function dispatchRuntime(context, command, parsed, progress, prepared = {}) {
2469
+ if (command === "scope") {
2470
+ if (parsed.positional.length === 1 && parsed.positional[0] === "reconcile") {
2471
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "generation"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2472
+ throw new AppError("usage", "Use runtime scope reconcile --scope-id ID --generation N --request-id ID", 2);
2473
+ return { ok: true, ...await reconcileRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation")), requiredOption(parsed, "request-id")) };
2474
+ }
2475
+ if (parsed.positional.length === 1 && parsed.positional[0] === "resume") {
2476
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "generation", "capture-key"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2477
+ throw new AppError("usage", "Use runtime scope resume --scope-id ID --request-id ID --generation N --capture-key SHA256", 2);
2478
+ return { ok: true, ...await launchRuntimeScopeResume(context, runtimeScopeResumeInput(parsed)) };
2479
+ }
2480
+ if (parsed.positional.length === 1 && parsed.positional[0] === "control") {
2481
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id", "mode", "manifest-json"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2482
+ throw new AppError("usage", "Use runtime scope control --scope-id ID --request-id ID --mode pause|stop [--manifest-json JSON]", 2);
2483
+ const mode = requiredOption(parsed, "mode");
2484
+ if (mode !== "pause" && mode !== "stop")
2485
+ throw new AppError("usage", "Scope control mode must be pause or stop", 2);
2486
+ return { ok: true, ...await launchRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id"), mode, undefined, undefined, undefined, prepared.runtimeManifest) };
2487
+ }
2488
+ if (parsed.positional.length === 1 && parsed.positional[0] === "serve") {
2489
+ if ([...parsed.options.keys()].some(key => !["scope-id", "generation"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2490
+ throw new AppError("usage", "Invalid internal scope worker arguments", 2);
2491
+ return { ok: true, ...await serveRuntimeScopeControl(context, requiredOption(parsed, "scope-id"), Number(requiredOption(parsed, "generation"))) };
2492
+ }
2493
+ if (parsed.positional.length === 1 && parsed.positional[0] === "stop") {
2494
+ if ([...parsed.options.keys()].some(key => !["scope-id", "request-id"].includes(key)) || [...parsed.options.values()].some(values => values.length !== 1))
2495
+ throw new AppError("usage", "Usage: dd-flow runtime scope stop --scope-id EVAL_ID --request-id ID", 2);
2496
+ return { ok: true, ...await stopRuntimeScope(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id")) };
2497
+ }
2498
+ if (parsed.positional.length === 1 && parsed.positional[0] === "status") {
2499
+ if ([...parsed.options.keys()].some(key => key !== "scope-id") || [...parsed.options.values()].some(values => values.length !== 1))
2500
+ throw new AppError("usage", "Usage: dd-flow runtime scope status --scope-id EVAL_ID", 2);
2501
+ return { ok: true, ...runtimeBudgetStatus(context, requiredOption(parsed, "scope-id")) };
2502
+ }
2503
+ 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))
2504
+ throw new AppError("usage", "Usage: dd-flow runtime scope fence --scope-id EVAL_ID --request-id ID", 2);
2505
+ return { ok: true, ...fenceRuntimeBudget(context, requiredOption(parsed, "scope-id"), requiredOption(parsed, "request-id")) };
2506
+ }
1585
2507
  if (command !== "process")
1586
- throw new AppError("usage", "Usage: dd-flow runtime process <register|confirm|heartbeat|finish|status|reconcile>", 2);
2508
+ throw new AppError("usage", "Usage: dd-flow runtime <scope|process>; see dd-flow runtime scope --help", 2);
1587
2509
  const action = requiredPosition(parsed, 0, "runtime process action");
2510
+ if (action === "check-admission")
2511
+ return { ok: true, ...admitRuntimeCheck(context, requiredOption(parsed, "id"), requiredOption(parsed, "lease-token")) };
2512
+ if (action === "start")
2513
+ return await startRuntimeService(context, { ...runtimeServiceInput(parsed), progress });
2514
+ if (action === "stop")
2515
+ return { ok: true, process: await stopManagedProcess(context, runtimeProcessStopInput(parsed)) };
1588
2516
  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
- });
2517
+ const process = registerManagedProcess(context, runtimeProcessRegistrationInput(context, parsed));
1597
2518
  return { ok: true, process };
1598
2519
  }
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 } : {}) }) };
2520
+ if (action === "confirm")
2521
+ return { ok: true, process: confirmManagedProcess(context, runtimeProcessConfirmationInput(parsed)) };
2522
+ if (action === "heartbeat")
2523
+ return { ok: heartbeatManagedProcess(context, runtimeProcessHeartbeatInput(parsed)) };
2524
+ if (action === "admission") {
2525
+ const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
2526
+ 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))
2527
+ throw new AppError("process_ownership_unknown", "Productive dispatch requires its current confirmed runtime owner", 1);
2528
+ const metadata = JSON.parse(record.metadata_json);
2529
+ if (metadata.state_dir !== requiredOption(parsed, "state-dir"))
2530
+ throw new AppError("process_ownership_unknown", "Runtime admission belongs to another state directory", 1);
2531
+ if (record.project_id && record.run_id) {
2532
+ if (managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
2533
+ throw new AppError("process_runtime_scope_mismatch", "Runtime admission belongs to another or unproven flow home", 1);
2534
+ 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") });
2535
+ if (!recovering) {
2536
+ if (metadata.run_admitted !== true || !Number.isSafeInteger(metadata.run_generation))
2537
+ throw new AppError("run_recovery_guarded", "Runtime was not admitted before the RUN fence; reconcile its launch", 1);
2538
+ assertRunMutationAllowed(context, record.project_id, record.run_id, metadata.run_generation);
2539
+ }
2540
+ const run = context.db.get("SELECT status FROM runs WHERE project_id = ? AND id = ?", [record.project_id, record.run_id]);
2541
+ 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")]);
2542
+ 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") });
2543
+ if (!run || run.status !== "running" && !retainedHitlPrompt && !acceptedHitlPrompt && !["judge", "probe"].includes(metadata.role ?? ""))
2544
+ throw new AppError("invalid_run_state", "Subject dispatch requires a running RUN or its retained recovery/HITL prompt", 1);
2545
+ }
2546
+ 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") });
2547
+ return { ok: true, ...budget, process_id: record.id, generation: metadata.run_generation ?? null };
1607
2548
  }
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 }) };
2549
+ if (action === "release-turn") {
2550
+ const record = managedProcessStatus(context).find(process => process.id === requiredOption(parsed, "id"));
2551
+ if (!record || record.lease_token !== requiredOption(parsed, "lease-token") || record.owner_id !== requiredOption(parsed, "owner") || managedProcessRuntimeHome(record, context) !== context.ddFlowHome)
2552
+ throw new AppError("process_ownership_unknown", "Budget release requires its retained physical owner", 1);
2553
+ return releaseProviderTurns(context, record, { daemonId: requiredOption(parsed, "daemon-id"), operationId: optionalOption(parsed, "operation-id"), observationFile: optionalOption(parsed, "observation-file") }, prepared.providerTurnRelease);
1613
2554
  }
2555
+ if (action === "finish")
2556
+ return { ok: finishManagedProcess(context, runtimeProcessFinishInput(parsed)) };
1614
2557
  if (action === "status")
1615
2558
  return { ok: true, processes: managedProcessStatus(context) };
1616
2559
  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);
2560
+ return { ok: true, processes: await reconcileExpiredManagedProcesses(context, requiredOption(parsed, "owner"), optionalNumber(parsed, "grace-ms")) };
2561
+ throw new AppError("usage", "Usage: dd-flow runtime process <start|stop|register|confirm|heartbeat|admission|finish|status|reconcile>", 2);
1619
2562
  }
1620
2563
  function dispatchStat(context, command, parsed) {
1621
2564
  if (command === "usage") {
@@ -1802,7 +2745,9 @@ function dispatchSchema(context, command, parsed) {
1802
2745
  // searching project directories: run_id is a structural field in the
1803
2746
  // submitted artifact and the database owns its materialized run_root.
1804
2747
  const explicitRunId = optionalOption(parsed, "run");
1805
- const declaredRunId = explicitRunId ?? readRunId(file);
2748
+ const data = prepareJsonFile(file, "schema input").value;
2749
+ const declared = data && typeof data === "object" && "run_id" in data ? data.run_id : undefined;
2750
+ const declaredRunId = explicitRunId ?? (typeof declared === "string" && declared.trim() ? declared : undefined);
1806
2751
  const fileRunRoot = path.basename(file) === "run.json" ? path.dirname(path.resolve(file)) : undefined;
1807
2752
  const bound = projectRoot
1808
2753
  ? 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 +2755,7 @@ function dispatchSchema(context, command, parsed) {
1810
2755
  return validateSchema({
1811
2756
  schemaName: requiredOption(parsed, "schema"),
1812
2757
  file,
2758
+ data,
1813
2759
  ...(schemaDir ? { schemaDir } : {}),
1814
2760
  ...(projectRoot ? { projectRoot } : {}),
1815
2761
  ...(declaredRunId || bound?.id ? { runId: declaredRunId ?? bound.id } : {}),
@@ -1819,14 +2765,11 @@ function dispatchSchema(context, command, parsed) {
1819
2765
  }
1820
2766
  throw new AppError("usage", `Unknown schema command: ${command ?? "<empty>"}`, 2);
1821
2767
  }
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
- }
2768
+ function laneWorkspaceInput(parsed) {
2769
+ return { projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workspacePath: requiredOption(parsed, "path"), branch: optionalOption(parsed, "branch") };
2770
+ }
2771
+ function laneWaiterCancelInput(parsed) {
2772
+ return { projectRoot: requiredOption(parsed, "project-root"), lane: requiredOption(parsed, "lane"), workerId: requiredOption(parsed, "worker-id"), reason: requiredOption(parsed, "reason") };
1830
2773
  }
1831
2774
  async function dispatchLane(context, command, parsed) {
1832
2775
  if (command === "status") {
@@ -1838,24 +2781,14 @@ async function dispatchLane(context, command, parsed) {
1838
2781
  if (command === "waiter") {
1839
2782
  const action = requiredPosition(parsed, 0, "lane waiter action");
1840
2783
  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
- });
2784
+ return cancelLaneWaiter(context, laneWaiterCancelInput(parsed));
1847
2785
  }
1848
2786
  throw new AppError("usage", `Unknown lane waiter action: ${action}`, 2);
1849
2787
  }
1850
2788
  if (command === "workspace") {
1851
2789
  const action = requiredPosition(parsed, 0, "lane workspace action");
1852
2790
  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
- });
2791
+ return setLaneWorkspace(context, laneWorkspaceInput(parsed));
1859
2792
  }
1860
2793
  if (action === "check") {
1861
2794
  return checkLaneWorkspace(context, {
@@ -1927,7 +2860,7 @@ async function dispatchLane(context, command, parsed) {
1927
2860
  }
1928
2861
  throw new AppError("usage", `Unknown lane command: ${command ?? "<empty>"}`, 2);
1929
2862
  }
1930
- function dispatchCodexHooks(context, parsed) {
2863
+ function dispatchCodexHooks(context, parsed, prepared) {
1931
2864
  const action = requiredPosition(parsed, 0, "codex hooks action");
1932
2865
  if (action === "print") {
1933
2866
  return printCodexHooks(context, {
@@ -1949,7 +2882,7 @@ function dispatchCodexHooks(context, parsed) {
1949
2882
  target: optionalOption(parsed, "target"),
1950
2883
  profile: optionalOption(parsed, "profile"),
1951
2884
  yes: hasOption(parsed, "yes")
1952
- });
2885
+ }, prepared.codexHooks);
1953
2886
  }
1954
2887
  if (action === "remove") {
1955
2888
  return removeCodexHooks(context, {
@@ -1957,11 +2890,14 @@ function dispatchCodexHooks(context, parsed) {
1957
2890
  target: optionalOption(parsed, "target"),
1958
2891
  profile: optionalOption(parsed, "profile"),
1959
2892
  yes: hasOption(parsed, "yes")
1960
- });
2893
+ }, prepared.codexHooks);
1961
2894
  }
1962
2895
  throw new AppError("usage", `Unknown codex hooks action: ${action}`, 2);
1963
2896
  }
1964
- function dispatchCodexHome(context, parsed) {
2897
+ function codexHomeInput(parsed) {
2898
+ return { projectRoot: requiredOption(parsed, "project-root"), profile: optionalOption(parsed, "profile"), sourceHome: optionalOption(parsed, "source-home"), targetHome: optionalOption(parsed, "target-home") };
2899
+ }
2900
+ function dispatchCodexHome(context, parsed, prepared) {
1965
2901
  const action = requiredPosition(parsed, 0, "codex home action");
1966
2902
  if (action === "plan") {
1967
2903
  return planCodexHome(context, {
@@ -1972,12 +2908,7 @@ function dispatchCodexHome(context, parsed) {
1972
2908
  });
1973
2909
  }
1974
2910
  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
- });
2911
+ return initCodexHome(context, codexHomeInput(parsed), prepared.codexHome);
1981
2912
  }
1982
2913
  if (action === "status") {
1983
2914
  return getCodexHomeStatus(context, {
@@ -2000,11 +2931,14 @@ function dispatchCodexHome(context, parsed) {
2000
2931
  }
2001
2932
  throw new AppError("usage", `Unknown codex home action: ${action}`, 2);
2002
2933
  }
2003
- function dispatchCodexHook(context, parsed, stdin) {
2934
+ async function dispatchCodexHook(context, parsed, stdin) {
2004
2935
  const action = requiredPosition(parsed, 0, "codex hook action");
2005
2936
  if (action === "handle") {
2006
2937
  const isolatedHome = isolatedDdFlowHomeFromHookStdin(stdin);
2007
- const hookContext = isolatedHome ? createContext({ ...context.env, DD_FLOW_HOME: isolatedHome }) : context;
2938
+ const hookContext = isolatedHome ? createContext({ ...context.env, DD_FLOW_HOME: isolatedHome }, "hook") : context;
2939
+ const proof = await verifyCodexHookDelivery(hookContext.env, JSON.parse(stdin || "{}"));
2940
+ if (proof)
2941
+ hookContext.codexHookProof = proof;
2008
2942
  const result = handleCodexHook(hookContext, {
2009
2943
  event: requiredOption(parsed, "event"),
2010
2944
  projectRoot: optionalOption(parsed, "project-root"),
@@ -2027,6 +2961,15 @@ function dispatchZcodeEvent(context, parsed, stdin) {
2027
2961
  }
2028
2962
  throw new AppError("usage", `Unknown zcode event action: ${action}`, 2);
2029
2963
  }
2964
+ function dispatchZcodeHook(context, parsed, stdin) {
2965
+ if (requiredPosition(parsed, 0, "zcode hook action") !== "handle")
2966
+ throw new AppError("usage", "Unknown zcode hook action", 2);
2967
+ const result = handleZcodeHook(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
2968
+ if (result && typeof result === "object" && !Array.isArray(result) && "hookSpecificOutput" in result) {
2969
+ return { hookSpecificOutput: result.hookSpecificOutput };
2970
+ }
2971
+ return {};
2972
+ }
2030
2973
  function dispatchGrokEvent(context, parsed, stdin) {
2031
2974
  const action = requiredPosition(parsed, 0, "grok event action");
2032
2975
  if (action === "handle") {
@@ -2050,7 +2993,7 @@ function dispatchAgyEvent(context, parsed, stdin) {
2050
2993
  return handleAgyEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
2051
2994
  throw new AppError("usage", `Unknown agy event action: ${action}`, 2);
2052
2995
  }
2053
- function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
2996
+ function dispatchWorktree(context, command, parsed, scopeProjectRoot, prepared) {
2054
2997
  if (command === "plan") {
2055
2998
  return planWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
2056
2999
  }
@@ -2061,13 +3004,13 @@ function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
2061
3004
  branch: requiredOption(parsed, "branch"),
2062
3005
  base: requiredOption(parsed, "base"),
2063
3006
  path: requiredOption(parsed, "path")
2064
- });
3007
+ }, prepared.worktreeCreate);
2065
3008
  }
2066
3009
  if (command === "status") {
2067
3010
  return getWorktreeStatus(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
2068
3011
  }
2069
3012
  if (command === "bootstrap") {
2070
- return bootstrapWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
3013
+ return bootstrapWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot }, prepared.worktreeBootstrap);
2071
3014
  }
2072
3015
  if (command === "close") {
2073
3016
  return closeWorktree(context, {
@@ -2079,52 +3022,50 @@ function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
2079
3022
  throw new AppError("usage", `Unknown worktree command: ${command ?? "<empty>"}`, 2);
2080
3023
  }
2081
3024
  function dispatchPlanItem(context, parsed, projectRoot) {
3025
+ return updatePlanItem(context, planItemInput(parsed, projectRoot));
3026
+ }
3027
+ function planItemInput(parsed, projectRoot) {
2082
3028
  const action = requiredPosition(parsed, 0, "plan item action");
2083
3029
  const protocolId = requiredPosition(parsed, 1, "protocol-id");
2084
3030
  const itemId = requiredPosition(parsed, 2, "item-id");
2085
3031
  if (action === "start") {
2086
- return startPlanItem(context, { protocolId, projectRoot, itemId });
3032
+ return { protocolId, projectRoot, itemId, action };
2087
3033
  }
2088
3034
  if (action === "done") {
2089
- return completePlanItem(context, {
3035
+ return {
3036
+ action,
2090
3037
  protocolId,
2091
3038
  projectRoot,
2092
3039
  itemId,
2093
3040
  summary: requiredOption(parsed, "summary"),
2094
3041
  evidence: parsed.options.get("evidence") ?? []
2095
- });
3042
+ };
2096
3043
  }
2097
3044
  if (action === "block") {
2098
- return blockPlanItem(context, {
3045
+ return {
3046
+ action,
2099
3047
  protocolId,
2100
3048
  projectRoot,
2101
3049
  itemId,
2102
3050
  reason: requiredOption(parsed, "reason"),
2103
3051
  userRequired: parseBoolean(requiredOption(parsed, "user-required"), "user-required")
2104
- });
3052
+ };
2105
3053
  }
2106
3054
  if (action === "skip") {
2107
- return skipPlanItem(context, {
3055
+ return {
3056
+ action,
2108
3057
  protocolId,
2109
3058
  projectRoot,
2110
3059
  itemId,
2111
3060
  reason: requiredOption(parsed, "reason")
2112
- });
3061
+ };
2113
3062
  }
2114
3063
  throw new AppError("usage", `Unknown plan item action: ${action}`, 2);
2115
3064
  }
2116
3065
  function readOptionalJsonFile(file) {
2117
3066
  if (!file)
2118
3067
  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
- }
3068
+ return prepareJsonFile(file, "JSON input").value;
2128
3069
  }
2129
3070
  function parseFlowFlagOverrides(values) {
2130
3071
  const result = {};
@@ -2159,7 +3100,11 @@ function requiredPosition(parsed, index, label) {
2159
3100
  function optionalOption(parsed, key) {
2160
3101
  const values = parsed.options.get(key);
2161
3102
  const value = values?.[values.length - 1];
2162
- return value === flagValue ? undefined : value;
3103
+ if (value === flagValue)
3104
+ throw new AppError("usage", `--${key} requires a value`, 2);
3105
+ if (value !== undefined && !value.trim())
3106
+ throw new AppError("usage", `--${key} requires a non-empty value`, 2);
3107
+ return value;
2163
3108
  }
2164
3109
  function allOptions(parsed, key) {
2165
3110
  return (parsed.options.get(key) ?? []).filter((value) => value !== flagValue);
@@ -2324,7 +3269,7 @@ function projectRootForMutation(context, args, result, resolvedScope) {
2324
3269
  if (family === "merge-queue") {
2325
3270
  return projectRootForMergeQueueMutation(context, command, parsed);
2326
3271
  }
2327
- if (family === "merge" && ["one-shot", "apply", "request"].includes(command ?? "")) {
3272
+ if (family === "merge" && ["one-shot", "apply", "repair", "request"].includes(command ?? "")) {
2328
3273
  return requiredOption(parsed, "project-root");
2329
3274
  }
2330
3275
  if (family === "merge-worker" && ["start", "stop"].includes(command ?? "")) {
@@ -2357,7 +3302,7 @@ function projectRootForMutation(context, args, result, resolvedScope) {
2357
3302
  if (family === "opencode" && ((command === "event" && requiredPosition(parsed, 0, "opencode event action") === "handle") || command === "usage")) {
2358
3303
  return requiredOption(parsed, "project-root");
2359
3304
  }
2360
- if (family === "agy" && ((command === "event" && requiredPosition(parsed, 0, "agy event action") === "handle") || command === "usage"))
3305
+ if (["agy", "droid"].includes(family ?? "") && ((command === "event" && requiredPosition(parsed, 0, `${family} event action`) === "handle") || command === "usage"))
2361
3306
  return requiredOption(parsed, "project-root");
2362
3307
  if (family === "codex" && command === "hooks") {
2363
3308
  const action = requiredPosition(parsed, 0, "codex hooks action");
@@ -2394,14 +3339,36 @@ function projectRootForMergeQueueMutation(context, command, parsed) {
2394
3339
  function protocolProjectRoot(context, protocolId) {
2395
3340
  return requireProtocol(context, protocolId).project_root;
2396
3341
  }
3342
+ function prepareCliWorkRepair(context, parsed, objective, scopeProjectRoot) {
3343
+ 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") ?? [];
3344
+ if ([findings.length > 0, unresolved.length > 0, receipts.length > 0].filter(Boolean).length !== 1)
3345
+ throw new AppError("usage", "Repair requires exactly one source: --from-check, --from-finding or --from-unresolved", 2);
3346
+ const scope = { projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"), runId: requiredOption(parsed, "run"), objective };
3347
+ if (findings.length) {
3348
+ if (origins.length || hasOption(parsed, "verification-file"))
3349
+ throw new AppError("usage", "Finding repair derives its origins and cannot accept --origin-work or --verification-file", 2);
3350
+ return prepareVnextCodeReviewRepair(context, { ...scope, findingIds: findings, checkRefsByFinding: Object.fromEntries(findings.map(finding => [finding, parsed.options.get("check-ref") ?? []])) });
3351
+ }
3352
+ if (!origins.length)
3353
+ throw new AppError("usage", "Repair requires at least one --origin-work", 2);
3354
+ if (hasOption(parsed, "check-ref"))
3355
+ throw new AppError("usage", "--check-ref is only supported with --from-finding", 2);
3356
+ if (receipts.length > 1)
3357
+ throw new AppError("usage", "Create one repair Work per --from-check receipt", 2);
3358
+ if (!unresolved.length && hasOption(parsed, "verification-file"))
3359
+ throw new AppError("usage", "--verification-file is only supported with --from-unresolved", 2);
3360
+ const input = { ...scope, originWorkIds: origins, ...(unresolved.length ? { semanticUnresolved: unresolved, verificationPath: requiredOption(parsed, "verification-file") } : { checkReceiptId: receipts[0] }) };
3361
+ return { input, value: prepareVnextCodeRepair(context, input) };
3362
+ }
3363
+ function workerPromptInput(parsed) {
3364
+ const workspaceRoot = optionalOption(parsed, "workspace-root"), taskFile = optionalOption(parsed, "task-file");
3365
+ 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 } : {}) };
3366
+ }
2397
3367
  function runnerIntake(context) {
2398
3368
  const input = context.value.task_input?.[0];
2399
3369
  if (!input?.path)
2400
3370
  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");
3371
+ return prepareTextFile(input.path, "Runner SPECIFY task input").text;
2405
3372
  }
2406
3373
  /** Stage services install context before their lifecycle transition. Keeping
2407
3374
  * this check here makes an incomplete service migration fail closed instead of