@deksden-com/dd-flow-cli 0.7.0 → 0.8.0-beta.135

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 (65) hide show
  1. package/CHANGELOG.md +630 -0
  2. package/README.md +6 -1
  3. package/dist/build-info.json +10 -10
  4. package/dist/cli/help.js +88 -10
  5. package/dist/cli/run-cli.js +525 -28
  6. package/dist/domain/stage-catalog.js +22 -0
  7. package/dist/schemas/code-review-decision.schema.json +26 -0
  8. package/dist/schemas/code-review-result.schema.json +14 -0
  9. package/dist/schemas/code-verification.schema.json +14 -0
  10. package/dist/schemas/code-work-batch.schema.json +24 -0
  11. package/dist/schemas/code-work-result.schema.json +16 -0
  12. package/dist/schemas/flow-contract.schema.json +6 -3
  13. package/dist/schemas/flow-run.schema.json +16 -123
  14. package/dist/schemas/plan-aspect-map.schema.json +22 -0
  15. package/dist/schemas/plan-review-decision.schema.json +14 -0
  16. package/dist/schemas/plan-review-result.schema.json +42 -0
  17. package/dist/schemas/protocol-plan.schema.json +15 -182
  18. package/dist/schemas/stage-finish-input.schema.json +16 -2
  19. package/dist/schemas/stage-report.schema.json +8 -7
  20. package/dist/schemas/vnext-protocol-plan.schema.json +37 -0
  21. package/dist/schemas/vnext-protocolize-result.schema.json +29 -0
  22. package/dist/schemas/vnext-specify.schema.json +45 -0
  23. package/dist/services/branch-context.js +1 -1
  24. package/dist/services/cleanup.js +8 -8
  25. package/dist/services/cli-operation-classifier.js +10 -2
  26. package/dist/services/code-checks.js +244 -0
  27. package/dist/services/config.js +7 -1
  28. package/dist/services/dashboard.js +12 -12
  29. package/dist/services/engines.js +1 -1
  30. package/dist/services/eval-snapshots.js +404 -0
  31. package/dist/services/hooks.js +774 -18
  32. package/dist/services/ids.js +16 -6
  33. package/dist/services/lanes.js +1 -1
  34. package/dist/services/merge-queue.js +5 -5
  35. package/dist/services/merge-worker.js +2 -2
  36. package/dist/services/migrations.js +2 -2
  37. package/dist/services/plan-runtime.js +1 -1
  38. package/dist/services/projects.js +4 -4
  39. package/dist/services/prompts.js +1 -1
  40. package/dist/services/protocols.js +8 -8
  41. package/dist/services/run-projection.js +49 -13
  42. package/dist/services/runs.js +504 -51
  43. package/dist/services/schema-validation.js +21 -3
  44. package/dist/services/sessions.js +51 -12
  45. package/dist/services/stage-blocker.js +57 -0
  46. package/dist/services/stage-context.js +90 -0
  47. package/dist/services/stage-lifecycle.js +198 -75
  48. package/dist/services/stage-pause.js +175 -0
  49. package/dist/services/stage-report-renderer.js +65 -0
  50. package/dist/services/usage.js +526 -18
  51. package/dist/services/vnext-code-review.js +308 -0
  52. package/dist/services/vnext-code.js +616 -0
  53. package/dist/services/vnext-contracts.js +1 -0
  54. package/dist/services/vnext-execution-profile.js +27 -0
  55. package/dist/services/vnext-fanout.js +79 -0
  56. package/dist/services/vnext-plan-review.js +499 -0
  57. package/dist/services/vnext-plan.js +576 -0
  58. package/dist/services/vnext-protocolize.js +542 -0
  59. package/dist/services/vnext-specify.js +595 -0
  60. package/dist/services/vnext-workspace-policy.js +87 -0
  61. package/dist/services/work-registry.js +499 -0
  62. package/dist/services/worktrees.js +58 -37
  63. package/dist/storage/database.js +263 -34
  64. package/dist/storage/paths.js +47 -1
  65. package/package.json +12 -12
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import path from "node:path";
2
3
  import { createContext, createRouterContext } from "../runtime/context.js";
3
4
  import { helpForArgs } from "./help.js";
4
5
  import { AppError, isAppError } from "../shared/errors.js";
@@ -9,7 +10,7 @@ import { blockPlanItem, completePlanItem, getPlanStatus, skipPlanItem, startPlan
9
10
  import { cancelMergeQueueJob, claimNextMergeJob, claimMergeJob, claimMergeBundle, completeMergeBundle, completeMergeJob, failMergeBundle, failMergeJob, getMergeBundleStatus, getMergeQueueStatus, noteMergeJob, waitNextMergeJob } from "../services/merge-queue.js";
10
11
  import { getMergeWorkerStatus, oneShotMergeClaim, startMergeWorker, stopProjectMergeWorker } from "../services/merge-worker.js";
11
12
  import { cleanupApply, cleanupScan } from "../services/cleanup.js";
12
- import { getCodexHomeStatus, getCodexHooksStatus, handleCodexHook, initCodexHome, installCodexHooks, planCodexHome, printCodexHomeEnv, printCodexHooks, removeCodexHome, removeCodexHooks } from "../services/hooks.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";
13
14
  import { bootstrapWorktree, closeWorktree, createWorktreeRecord, getWorktreeStatus, planWorktree } from "../services/worktrees.js";
14
15
  import { acquireLaneLock, cancelLaneWaiter, checkLaneWorkspace, getLaneWaiters, getLaneStatus, heartbeatLaneLock, releaseLaneLock, setLaneWorkspace, waitAcquireLaneLock, waitForLaneLock } from "../services/lanes.js";
15
16
  import { getProjectConfigStatus, setProjectConfigValue } from "../services/config.js";
@@ -20,19 +21,32 @@ import { autoRefreshDashboards, dashboardData, getCmuxStatus, openDashboard, ope
20
21
  import { dashboardTargetSummary, preferredDashboardCommand, relatedDashboardCommands, resolveDashboardTarget } from "../services/dashboard-targets.js";
21
22
  import { getFlowSessionStatus, registerFlowSession, stopFlowSession, stopMergeWorker, syncFlowSessionUsage } from "../services/sessions.js";
22
23
  import { getProtocolBranchContext } from "../services/branch-context.js";
23
- import { attachFlowRunStage, completeFlowRun, completeFlowRunStage, getFlowRunTimeline, getFlowRunUsage, getFlowRunFlagsStatus, getFlowRunStatus, listFlowRuns, reviseFlowRunFlags, startFlowRun } from "../services/runs.js";
24
+ import { attachFlowRunStage, completeFlowRun, completeFlowRunStage, getFlowRunSessions, getFlowRunTimeline, getStoredFlowRunUsage, getFlowRunFlagsStatus, getFlowRunStatus, getFlowRunConfig, getFlowRunVariables, listFlowRuns, reviseFlowRunFlags, setFlowRunConfig, setFlowRunVariable, startFlowRun } from "../services/runs.js";
24
25
  import { previewNextEntityId } from "../services/ids.js";
25
26
  import { validateSchema } from "../services/schema-validation.js";
26
27
  import { preflightMemoryPermissions } from "../services/memory-permissions.js";
28
+ import { ingestAgyUsage, ingestGrokUsage, ingestOpenCodeUsage, ingestZcodeUsage } from "../services/usage.js";
27
29
  import { applyMigration, assessMigrationImpact, assertUpgradeRunStorageReady, planMigration, verifyMigrationReport } from "../services/migrations.js";
28
30
  import { publishProjectSummary } from "../services/project-summary.js";
29
31
  import { requireProjectByRoot } from "../services/projects.js";
30
32
  import { resolveProjectRoot } from "../storage/paths.js";
31
33
  import { doctorEngines, bindRunEngine, engineInfo, installCurrentEngine, listEngines, resolveEngine, resolveExplicitProjectRoot, resolveOperationProjectRoot, routeArgsThroughEngine } from "../services/engines.js";
32
34
  import { preflightCliCompatibility } from "../services/compatibility-preflight.js";
35
+ import { finishVnextSpecifyStage, getVnextWorkStatus, isVnextSpecifyFlow, isVnextSpecifyRun, launchVnextSpecify } from "../services/vnext-specify.js";
36
+ import { finishVnextProtocolize, isVnextProtocolizeRun, startVnextProtocolize } from "../services/vnext-protocolize.js";
37
+ import { finishVnextPlan, isVnextPlanRun, startVnextPlan } from "../services/vnext-plan.js";
38
+ import { dispatchVnextPlanReview, finishVnextPlanReview, isVnextPlanReviewRun, recordVnextPlanReviewCapacity, startVnextPlanReview } from "../services/vnext-plan-review.js";
39
+ import { addVnextCodeRepair, finishVnextCode, startVnextCode } from "../services/vnext-code.js";
40
+ import { addVnextCodeReviewRepair, finishVnextCodeReview, isVnextCodeReviewRun, startVnextCodeReview } from "../services/vnext-code-review.js";
41
+ import { getVnextFanoutStatus } from "../services/vnext-fanout.js";
42
+ import { pauseStageForUser, resumeStageAfterUser } from "../services/stage-pause.js";
43
+ import { blockStageForRuntime, unblockStageAfterRuntimeRepair } from "../services/stage-blocker.js";
33
44
  import { classifyCliOperation, requiresExplicitUpgradeAuthorization } from "../services/cli-operation-classifier.js";
34
45
  import { renderWorkerPrompt } from "../services/prompts.js";
35
46
  import { finishStage, startStage } from "../services/stage-lifecycle.js";
47
+ import { addWorkBatch, cancelWork, deleteWork, failWork, finishWork, listWorks, mutateWorkDeps, retryWork, showWork, startWork } from "../services/work-registry.js";
48
+ import { createEvalBootstrapSnapshot, createEvalRunSnapshot, prepareVnextSpecifyRun, restoreEvalBootstrapSnapshot, restoreEvalRunSnapshot } from "../services/eval-snapshots.js";
49
+ import { loadExternalStageContext } from "../services/stage-context.js";
36
50
  const defaultIo = {
37
51
  stdout: process.stdout,
38
52
  stderr: process.stderr,
@@ -42,10 +56,8 @@ const flagValue = "__dd_flow_flag__";
42
56
  export async function runCli(args, io = defaultIo, env = process.env) {
43
57
  const output = parseOutputOptions(args);
44
58
  const progress = progressForCommand(output.args);
59
+ let heartbeat;
45
60
  try {
46
- if (args.includes("--progress-jsonl")) {
47
- throw new AppError("usage", "--progress-jsonl is not implemented yet; use --json for final structured progress", 2);
48
- }
49
61
  if (output.args.length === 1 && output.args[0] === "--version") {
50
62
  const payload = getCliVersionReport();
51
63
  if (output.json)
@@ -68,9 +80,15 @@ export async function runCli(args, io = defaultIo, env = process.env) {
68
80
  }
69
81
  const routerContext = createRouterContext(env);
70
82
  emitHumanProgress(io, output, progress, "start");
83
+ if (output.progressJsonl) {
84
+ writeProgressJsonl(io, "start", `Starting ${output.args.slice(0, 3).join(" ")}`);
85
+ heartbeat = setInterval(() => writeProgressJsonl(io, "running", "Command is still running"), 15_000);
86
+ }
71
87
  const scopeProjectRoot = resolveProjectRootBeforeRouting(output.args, env);
72
- const routed = await routeArgsThroughEngine(routerContext, output.json ? [...output.args, "--json"] : output.args, io, io.stdin, env, scopeProjectRoot);
88
+ const routed = await routeArgsThroughEngine(routerContext, output.json ? [...output.args, "--json", ...(output.progressJsonl ? ["--progress-jsonl"] : [])] : output.args, io, io.stdin, env, scopeProjectRoot);
73
89
  if (routed?.routed && !routed.inProcess) {
90
+ if (heartbeat)
91
+ clearInterval(heartbeat);
74
92
  emitHumanProgress(io, output, progress, "done");
75
93
  return routed.exitCode;
76
94
  }
@@ -78,9 +96,13 @@ export async function runCli(args, io = defaultIo, env = process.env) {
78
96
  ? createContext({ ...env, DD_FLOW_ENGINE_MODE: "1", DD_FLOW_ENGINE_HOME: "in-process", DD_FLOW_ROUTED_FROM: getCliVersionReport().cli.version }, databaseModeForCommand(output.args, classification))
79
97
  : createContext(env, databaseModeForCommand(output.args, classification));
80
98
  preflightCliCompatibility(dispatchContext, output.args, env, scopeProjectRoot);
81
- const result = await dispatch(output.args, dispatchContext, io, scopeProjectRoot, classification);
99
+ const result = await dispatch(output.args, dispatchContext, io, scopeProjectRoot, classification, output);
82
100
  const refreshWarnings = refreshDashboardsAfterMutation(dispatchContext, output.args, result, scopeProjectRoot);
83
101
  const resultWithWarnings = addWarnings(result, refreshWarnings);
102
+ if (heartbeat)
103
+ clearInterval(heartbeat);
104
+ if (output.progressJsonl)
105
+ writeProgressJsonl(io, "done", "Command finished");
84
106
  emitHumanProgress(io, output, progress, "done");
85
107
  const payload = attachProgress(resultWithWarnings, progress, output);
86
108
  if (output.json)
@@ -90,12 +112,18 @@ export async function runCli(args, io = defaultIo, env = process.env) {
90
112
  return completedCommandExitCode(payload);
91
113
  }
92
114
  catch (error) {
115
+ if (heartbeat)
116
+ clearInterval(heartbeat);
93
117
  const payload = isAppError(error)
94
118
  ? { ok: false, error: { code: error.code, message: error.message, details: error.details } }
95
119
  : { ok: false, error: { code: "unexpected", message: String(error) } };
96
120
  emitHumanProgress(io, output, progress, "failed");
121
+ if (output.progressJsonl)
122
+ writeProgressJsonl(io, "failed", payload.error.message, { code: payload.error.code });
97
123
  const errorPayload = attachProgress(payload, progress, output);
98
- if (output.json)
124
+ if (output.json && output.progressJsonl)
125
+ writeJson(io.stdout, errorPayload);
126
+ else if (output.json)
99
127
  writeJson(io.stderr, errorPayload);
100
128
  else
101
129
  io.stderr.write(renderHumanError(payload));
@@ -157,15 +185,20 @@ function renderHumanError(payload) {
157
185
  function parseOutputOptions(args) {
158
186
  const stripped = [];
159
187
  let json = false;
188
+ let progressJsonl = false;
160
189
  for (const arg of args) {
161
190
  if (arg === "--json") {
162
191
  json = true;
163
192
  continue;
164
193
  }
194
+ if (arg === "--progress-jsonl") {
195
+ progressJsonl = true;
196
+ continue;
197
+ }
165
198
  stripped.push(arg);
166
199
  }
167
200
  const hookJsonOnly = stripped[0] === "codex" && stripped[1] === "hook" && stripped[2] === "handle";
168
- return { json: json || hookJsonOnly, args: stripped, hookJsonOnly };
201
+ return { json: json || hookJsonOnly, progressJsonl, args: stripped, hookJsonOnly };
169
202
  }
170
203
  function progressForCommand(args) {
171
204
  const [family, command, subcommand] = args;
@@ -211,6 +244,12 @@ function emitHumanProgress(io, output, progress, phase) {
211
244
  }
212
245
  }
213
246
  }
247
+ function writeProgressJsonl(io, phase, message, detail) {
248
+ io.stderr.write(`${JSON.stringify({ schema_id: "dd-flow/progress@1", phase, message, at: new Date().toISOString(), ...(detail ? { detail } : {}) })}\n`);
249
+ }
250
+ function commandProgress(io, output) {
251
+ return (message) => output.progressJsonl ? writeProgressJsonl(io, "running", message) : io.stderr.write(`[running] ${message}\n`);
252
+ }
214
253
  function attachProgress(result, progress, output) {
215
254
  if (progress.length === 0 || output.hookJsonOnly)
216
255
  return result;
@@ -416,7 +455,7 @@ function stringValue(value) {
416
455
  function shortSha(value) {
417
456
  return value ? value.slice(0, 12) : "unknown";
418
457
  }
419
- async function dispatch(args, context, io, scopeProjectRoot = null, classification = classifyCliOperation(args, context.env)) {
458
+ async function dispatch(args, context, io, scopeProjectRoot = null, classification = classifyCliOperation(args, context.env), output = parseOutputOptions(args)) {
420
459
  const [family, command, ...rest] = args;
421
460
  const parsed = parseArgs(rest);
422
461
  if (family === "engine") {
@@ -560,6 +599,32 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
560
599
  const protocolId = requiredPosition(parsed, 0, "protocol-id");
561
600
  return getPlanStatus(context, { protocolId, projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "plan status") });
562
601
  }
602
+ if (family === "plan" && command === "reviews") {
603
+ throw new AppError("usage", "PLAN review dispatch moved to: dd-flow plan-review dispatch <RUN>", 2);
604
+ }
605
+ if (family === "plan-review" && command === "dispatch") {
606
+ return dispatchVnextPlanReview(context, { projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "plan-review dispatch"), runId: requiredPosition(parsed, 0, "run-id") });
607
+ }
608
+ if (family === "stage" && command === "fanout") {
609
+ const action = requiredPosition(parsed, 0, "fanout action");
610
+ const runId = requiredPosition(parsed, 1, "run-id");
611
+ const stage = requiredOption(parsed, "stage");
612
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "stage fanout");
613
+ if (action === "status")
614
+ return getVnextFanoutStatus(context, { projectRoot, runId, stage });
615
+ if (action === "dispatch") {
616
+ if (stage === "plan-review")
617
+ return dispatchVnextPlanReview(context, { projectRoot, runId });
618
+ return getVnextFanoutStatus(context, { projectRoot, runId, stage });
619
+ }
620
+ throw new AppError("usage", "Use: dd-flow stage fanout <status|dispatch> <RUN> --stage <stage> --project-root <path>", 2);
621
+ }
622
+ if (family === "run" && command === "capacity") {
623
+ if (requiredPosition(parsed, 0, "capacity action") !== "record")
624
+ throw new AppError("usage", "Use: dd-flow run capacity record <RUN> --available-slots <0..15> --project-root <path>", 2);
625
+ const availableSlots = Number(requiredOption(parsed, "available-slots"));
626
+ return recordVnextPlanReviewCapacity(context, { projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "run capacity record"), runId: requiredPosition(parsed, 1, "run-id"), availableSlots });
627
+ }
563
628
  if (family === "plan" && command === "item") {
564
629
  return dispatchPlanItem(context, parsed, requiredScopeProjectRoot(scopeProjectRoot, "plan item"));
565
630
  }
@@ -575,31 +640,279 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
575
640
  ...(workspaceRoot ? { workspaceRoot } : {})
576
641
  });
577
642
  }
643
+ if (family === "work" && command === "status") {
644
+ return getVnextWorkStatus(context, {
645
+ projectRoot: requiredOption(parsed, "project-root"),
646
+ workId: requiredPosition(parsed, 0, "work-id")
647
+ });
648
+ }
649
+ if (family === "work" && command === "add-batch") {
650
+ return addWorkBatch(context, { parentWorkId: requiredOption(parsed, "parent"), file: requiredOption(parsed, "file") });
651
+ }
652
+ if (family === "work" && command === "ls") {
653
+ 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")) } : {}) });
654
+ }
655
+ if (family === "work" && command === "show")
656
+ return showWork(context, requiredPosition(parsed, 0, "work-id"));
657
+ if (family === "work" && command === "repair" && requiredPosition(parsed, 0, "action") === "add") {
658
+ if (!hasOption(parsed, "task-stdin"))
659
+ throw new AppError("usage", "work repair add requires --task-stdin", 2);
660
+ const origins = parsed.options.get("origin-work") ?? [];
661
+ const findings = parsed.options.get("from-finding") ?? [];
662
+ if (!origins.length && !findings.length)
663
+ throw new AppError("usage", "work repair add requires --from-check with --origin-work or --from-finding", 2);
664
+ if (findings.length)
665
+ return addVnextCodeReviewRepair(context, {
666
+ projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"),
667
+ runId: requiredOption(parsed, "run"),
668
+ findingIds: findings,
669
+ writeScope: parsed.options.get("write-scope") ?? [],
670
+ objective: await readStdin(io.stdin)
671
+ });
672
+ if (!hasOption(parsed, "from-check"))
673
+ throw new AppError("usage", "check repair requires --from-check", 2);
674
+ if (!origins.length)
675
+ throw new AppError("usage", "check repair requires at least one --origin-work", 2);
676
+ return addVnextCodeRepair(context, {
677
+ projectRoot: requiredScopeProjectRoot(scopeProjectRoot, "work repair add"),
678
+ runId: requiredOption(parsed, "run"),
679
+ checkReceiptId: requiredOption(parsed, "from-check"),
680
+ originWorkIds: origins,
681
+ writeScope: parsed.options.get("write-scope") ?? [],
682
+ objective: await readStdin(io.stdin)
683
+ });
684
+ }
685
+ if (family === "work" && command === "deps") {
686
+ const on = parsed.options.get("on") ?? [];
687
+ return mutateWorkDeps(context, { workId: requiredPosition(parsed, 1, "work-id"), action: requiredPosition(parsed, 0, "action"), ...(on.length ? { on } : {}) });
688
+ }
689
+ if (family === "work" && command === "delete")
690
+ return deleteWork(context, requiredPosition(parsed, 0, "work-id"));
691
+ if (family === "work" && command === "start") {
692
+ const hookEventId = optionalOption(parsed, "hook-event-id");
693
+ const projectRoot = requiredScopeProjectRoot(scopeProjectRoot, "work start");
694
+ return startWork(context, requiredPosition(parsed, 0, "work-id"), { ...(hookEventId ? { hookEventId } : {}), projectRoot });
695
+ }
696
+ if (family === "work" && command === "finish") {
697
+ const resultFile = optionalOption(parsed, "result-file");
698
+ const resultStdin = hasOption(parsed, "result-stdin");
699
+ if (Boolean(resultFile) === resultStdin)
700
+ throw new AppError("usage", "work finish requires exactly one of --result-file or --result-stdin", 2);
701
+ const result = resultFile ? fs.readFileSync(path.resolve(resultFile), "utf8") : await readStdin(io.stdin);
702
+ return await finishWork(context, requiredPosition(parsed, 0, "work-id"), result, commandProgress(io, output));
703
+ }
704
+ if (family === "work" && command === "fail")
705
+ return failWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
706
+ if (family === "work" && command === "cancel")
707
+ return cancelWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
708
+ if (family === "work" && command === "retry")
709
+ return retryWork(context, requiredPosition(parsed, 0, "work-id"), requiredOption(parsed, "reason"));
578
710
  if (family === "stage" && command === "start") {
579
711
  const dir = optionalOption(parsed, "dir");
580
712
  const bootstrap = hasOption(parsed, "bootstrap");
581
713
  const subject = optionalOption(parsed, "subject");
582
714
  const intakeFile = optionalOption(parsed, "intake-file");
583
- const sessionId = optionalOption(parsed, "session-id");
715
+ const intakeStdin = hasOption(parsed, "intake-stdin");
716
+ const contextFile = optionalOption(parsed, "context-file");
717
+ const contextSha256 = optionalOption(parsed, "context-sha256");
718
+ if (Boolean(contextFile) !== Boolean(contextSha256))
719
+ throw new AppError("usage", "stage start requires --context-file together with --context-sha256", 2);
720
+ if (hasOption(parsed, "session-id")) {
721
+ throw new AppError("usage", "--session-id is managed by the harness lifecycle adapter and is not accepted", 2);
722
+ }
723
+ let hookEventId = optionalOption(parsed, "hook-event-id");
724
+ const requireSessionBinding = hasOption(parsed, "require-session-binding");
725
+ const projectRoot = requiredOption(parsed, "project-root");
726
+ const stage = requiredOption(parsed, "stage");
727
+ const externalContext = contextFile && contextSha256 ? loadExternalStageContext({ file: contextFile, expectedSha256: contextSha256, stage }) : undefined;
728
+ const claimVnextStageStart = (runId) => {
729
+ registerProject(context, { root: projectRoot });
730
+ return findRecentMatchingHookEvent(context, {
731
+ projectId: requireProjectByRoot(context, resolveProjectRoot(projectRoot)).id,
732
+ matchKey: stageStartMatchKey(runId, stage, projectRoot, contextSha256),
733
+ errorCode: "trusted_session_binding_required",
734
+ operation: `vNext ${stage.toUpperCase()} start`
735
+ }).eventKey;
736
+ };
737
+ if ((bootstrap || (!bootstrap && stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") }))) && stage === "specify" && isVnextSpecifyFlow(projectRoot)) {
738
+ if ((intakeFile && intakeStdin) || (externalContext && (intakeFile || intakeStdin))) {
739
+ throw new AppError("usage", "Use exactly one of --intake-file or --intake-stdin", 2);
740
+ }
741
+ if (!intakeFile && !intakeStdin && !externalContext) {
742
+ throw new AppError("usage", "vNext SPECIFY start requires --intake-file, --intake-stdin or a runner context", 2);
743
+ }
744
+ if (!hookEventId) {
745
+ registerProject(context, { root: projectRoot });
746
+ hookEventId = bootstrap
747
+ ? claimBootstrapHookEvent(context, {
748
+ projectId: requireProjectByRoot(context, resolveProjectRoot(projectRoot)).id,
749
+ projectRoot,
750
+ subject: subject ?? "specify",
751
+ intakeMode: externalContext ? "context" : intakeStdin ? "stdin" : "file",
752
+ ...(contextSha256 ? { contextSha256 } : {})
753
+ })
754
+ : claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
755
+ }
756
+ const result = launchVnextSpecify(context, {
757
+ projectRoot,
758
+ ...(externalContext ? { intakeMarkdown: runnerIntake(externalContext) } : intakeFile ? { intakeFile } : { intakeMarkdown: await readStdin(io.stdin) }),
759
+ hookEventId,
760
+ ...(subject ? { slug: subject } : {}),
761
+ ...(externalContext ? { externalContext } : {}),
762
+ ...(!bootstrap ? { runId: requiredPosition(parsed, 0, "run-id") } : {})
763
+ });
764
+ return attachExternalStageContext(result, externalContext);
765
+ }
766
+ if (!bootstrap && stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
767
+ hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
768
+ return attachExternalStageContext(startVnextProtocolize(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
769
+ }
770
+ if (!bootstrap && stage === "plan" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
771
+ hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
772
+ return attachExternalStageContext(startVnextPlan(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
773
+ }
774
+ if (!bootstrap && stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
775
+ hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
776
+ return attachExternalStageContext(startVnextPlanReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
777
+ }
778
+ if (!bootstrap && stage === "code" && isVnextPlanRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
779
+ hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
780
+ return attachExternalStageContext(await startVnextCode(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, progress: commandProgress(io, output), ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
781
+ }
782
+ if (!bootstrap && stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id") })) {
783
+ hookEventId ??= claimVnextStageStart(requiredPosition(parsed, 0, "run-id"));
784
+ return attachExternalStageContext(startVnextCodeReview(context, { projectRoot, runId: requiredPosition(parsed, 0, "run-id"), hookEventId, ...(contextSha256 ? { contextSha256 } : {}), ...(externalContext ? { externalContext } : {}) }), externalContext);
785
+ }
786
+ if (intakeStdin) {
787
+ throw new AppError("usage", "--intake-stdin is only available for vNext SPECIFY", 2);
788
+ }
789
+ if (externalContext) {
790
+ throw new AppError("usage", "--context-file is currently supported only by vNext flow stages", 2);
791
+ }
584
792
  return startStage(context, {
585
- projectRoot: requiredOption(parsed, "project-root"),
793
+ projectRoot,
586
794
  ...(bootstrap ? { bootstrap: { subject: subject ?? requiredOption(parsed, "subject"), ...(intakeFile ? { intakeFile } : {}) } } : { runId: requiredPosition(parsed, 0, "run-id") }),
587
- stage: requiredOption(parsed, "stage"),
588
- ...(sessionId ? { sessionId } : {}),
795
+ stage,
796
+ ...(hookEventId ? { hookEventId } : {}),
797
+ ...(requireSessionBinding ? { requireSessionBinding: true } : {}),
589
798
  ...(dir ? { dir } : {})
590
799
  });
591
800
  }
592
801
  if (family === "stage" && command === "finish") {
593
802
  const dir = optionalOption(parsed, "dir");
594
- const outcome = optionalOption(parsed, "outcome") ?? optionalOption(parsed, "status");
803
+ if (hasOption(parsed, "status")) {
804
+ throw new AppError("usage", "Stage status belongs in the semantic input file", 2);
805
+ }
806
+ const projectRoot = requiredOption(parsed, "project-root");
807
+ const runId = requiredPosition(parsed, 0, "run-id");
808
+ const stage = requiredOption(parsed, "stage");
595
809
  const semanticFile = optionalOption(parsed, "semantic-file") ?? optionalOption(parsed, "data");
810
+ const resultFile = optionalOption(parsed, "result-file") ?? semanticFile;
811
+ const resultStdin = hasOption(parsed, "result-stdin");
812
+ if (stage === "specify" && isVnextSpecifyRun(context, { projectRoot, runId })) {
813
+ const outcome = optionalOption(parsed, "outcome");
814
+ if (!outcome || !["specified", "failed", "cancelled"].includes(outcome)) {
815
+ throw new AppError("usage", "vNext SPECIFY requires --outcome specified|failed|cancelled; use stage pause for a user question", 2);
816
+ }
817
+ if (resultFile && resultStdin) {
818
+ throw new AppError("usage", "Use exactly one of --result-file or --result-stdin", 2);
819
+ }
820
+ if (!resultFile && !resultStdin) {
821
+ throw new AppError("usage", "vNext SPECIFY finish requires --result-file or --result-stdin", 2);
822
+ }
823
+ return finishVnextSpecifyStage(context, {
824
+ projectRoot,
825
+ runId,
826
+ ...(resultFile ? { resultFile } : { resultJson: await readStdin(io.stdin) }),
827
+ outcome: outcome
828
+ });
829
+ }
830
+ if (stage === "protocolize" && isVnextProtocolizeRun(context, { projectRoot, runId })) {
831
+ if (!resultFile || resultStdin || hasOption(parsed, "outcome")) {
832
+ throw new AppError("usage", "vNext PROTOCOLIZE requires exactly --result-file", 2);
833
+ }
834
+ return finishVnextProtocolize(context, { projectRoot, runId, resultFile });
835
+ }
836
+ if (stage === "plan" && isVnextPlanRun(context, { projectRoot, runId })) {
837
+ if (optionalOption(parsed, "code-work-batch-file"))
838
+ throw new AppError("usage", "vNext PLAN derives its CODE batch from accepted semantic plans; do not supply a batch file", 2);
839
+ return finishVnextPlan(context, { projectRoot, runId });
840
+ }
841
+ if (stage === "plan-review" && isVnextPlanReviewRun(context, { projectRoot, runId })) {
842
+ if (resultStdin || hasOption(parsed, "outcome"))
843
+ throw new AppError("usage", "vNext PLAN-REVIEW uses --decision-file", 2);
844
+ const decisionFile = optionalOption(parsed, "decision-file");
845
+ return finishVnextPlanReview(context, { projectRoot, runId, ...(decisionFile ? { decisionFile } : {}) });
846
+ }
847
+ if (stage === "code" && isVnextPlanRun(context, { projectRoot, runId })) {
848
+ if (semanticFile || resultFile || resultStdin || hasOption(parsed, "outcome")) {
849
+ throw new AppError("usage", "vNext CODE finish accepts only --verification-file", 2);
850
+ }
851
+ return await finishVnextCode(context, { projectRoot, runId, verificationFile: optionalOption(parsed, "verification-file") ?? path.join("<missing>", "code-verification.json"), progress: commandProgress(io, output) });
852
+ }
853
+ if (stage === "code-review" && isVnextCodeReviewRun(context, { projectRoot, runId })) {
854
+ if (resultStdin || semanticFile || resultFile || hasOption(parsed, "outcome"))
855
+ throw new AppError("usage", "vNext CODE-REVIEW uses --decision-file", 2);
856
+ return await finishVnextCodeReview(context, { projectRoot, runId, ...(optionalOption(parsed, "decision-file") ? { decisionFile: optionalOption(parsed, "decision-file") } : {}), progress: commandProgress(io, output) });
857
+ }
858
+ if (hasOption(parsed, "outcome") || hasOption(parsed, "result-file") || resultStdin) {
859
+ throw new AppError("usage", "--outcome, --result-file and --result-stdin are only available for vNext SPECIFY", 2);
860
+ }
596
861
  return finishStage(context, {
862
+ projectRoot,
863
+ runId,
864
+ stage,
865
+ ...(dir ? { dir } : {}),
866
+ ...(semanticFile ? { semanticFile } : {})
867
+ });
868
+ }
869
+ if (family === "stage" && command === "pause") {
870
+ if (!hasOption(parsed, "question-stdin"))
871
+ throw new AppError("usage", "stage pause requires --question-stdin", 2);
872
+ return pauseStageForUser(context, {
597
873
  projectRoot: requiredOption(parsed, "project-root"),
598
874
  runId: requiredPosition(parsed, 0, "run-id"),
599
875
  stage: requiredOption(parsed, "stage"),
600
- ...(dir ? { dir } : {}),
601
- ...(outcome ? { outcome } : {}),
602
- ...(semanticFile ? { semanticFile } : {})
876
+ workId: requiredOption(parsed, "work"),
877
+ question: await readStdin(io.stdin)
878
+ });
879
+ }
880
+ if (family === "stage" && command === "resume") {
881
+ if (!hasOption(parsed, "answer-stdin"))
882
+ throw new AppError("usage", "stage resume requires --answer-stdin", 2);
883
+ const hookEventId = optionalOption(parsed, "hook-event-id");
884
+ return resumeStageAfterUser(context, {
885
+ projectRoot: requiredOption(parsed, "project-root"),
886
+ runId: requiredPosition(parsed, 0, "run-id"),
887
+ stage: requiredOption(parsed, "stage"),
888
+ workId: requiredOption(parsed, "work"),
889
+ answer: await readStdin(io.stdin),
890
+ ...(hookEventId ? { hookEventId } : {})
891
+ });
892
+ }
893
+ if (family === "stage" && command === "block") {
894
+ if (!hasOption(parsed, "summary-stdin"))
895
+ throw new AppError("usage", "stage block requires --summary-stdin", 2);
896
+ const kind = requiredOption(parsed, "kind");
897
+ if (kind !== "engine" && kind !== "harness" && kind !== "environment")
898
+ throw new AppError("usage", "--kind must be engine, harness or environment", 2);
899
+ return blockStageForRuntime(context, {
900
+ projectRoot: requiredOption(parsed, "project-root"),
901
+ runId: requiredPosition(parsed, 0, "run-id"),
902
+ stage: requiredOption(parsed, "stage"),
903
+ workId: requiredOption(parsed, "work"),
904
+ kind,
905
+ code: requiredOption(parsed, "code"),
906
+ summary: await readStdin(io.stdin),
907
+ retryable: hasOption(parsed, "retryable")
908
+ });
909
+ }
910
+ if (family === "stage" && command === "unblock") {
911
+ return unblockStageAfterRuntimeRepair(context, {
912
+ projectRoot: requiredOption(parsed, "project-root"),
913
+ runId: requiredPosition(parsed, 0, "run-id"),
914
+ stage: requiredOption(parsed, "stage"),
915
+ workId: requiredOption(parsed, "work")
603
916
  });
604
917
  }
605
918
  if (family === "lane") {
@@ -623,6 +936,9 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
623
936
  if (family === "run") {
624
937
  return dispatchRun(context, command, parsed);
625
938
  }
939
+ if (family === "stat") {
940
+ return dispatchStat(context, command, parsed);
941
+ }
626
942
  if (family === "id") {
627
943
  return dispatchId(context, command, parsed);
628
944
  }
@@ -650,6 +966,37 @@ async function dispatch(args, context, io, scopeProjectRoot = null, classificati
650
966
  if (family === "codex" && command === "hook") {
651
967
  return dispatchCodexHook(context, parsed, await readStdin(io.stdin));
652
968
  }
969
+ if (family === "zcode" && command === "event") {
970
+ return dispatchZcodeEvent(context, parsed, await readStdin(io.stdin));
971
+ }
972
+ if (family === "zcode" && command === "usage") {
973
+ if (requiredPosition(parsed, 0, "zcode usage action") !== "ingest")
974
+ throw new AppError("usage", "Unknown zcode usage action", 2);
975
+ return ingestZcodeUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
976
+ }
977
+ if (family === "grok" && command === "event") {
978
+ return dispatchGrokEvent(context, parsed, await readStdin(io.stdin));
979
+ }
980
+ if (family === "grok" && command === "usage") {
981
+ if (requiredPosition(parsed, 0, "grok usage action") !== "ingest")
982
+ throw new AppError("usage", "Unknown grok usage action", 2);
983
+ return ingestGrokUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
984
+ }
985
+ if (family === "opencode" && command === "event") {
986
+ return dispatchOpenCodeEvent(context, parsed, await readStdin(io.stdin));
987
+ }
988
+ if (family === "opencode" && command === "usage") {
989
+ if (requiredPosition(parsed, 0, "opencode usage action") !== "ingest")
990
+ throw new AppError("usage", "Unknown opencode usage action", 2);
991
+ return ingestOpenCodeUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
992
+ }
993
+ if (family === "agy" && command === "event")
994
+ return dispatchAgyEvent(context, parsed, await readStdin(io.stdin));
995
+ if (family === "agy" && command === "usage") {
996
+ if (requiredPosition(parsed, 0, "agy usage action") !== "ingest")
997
+ throw new AppError("usage", "Unknown agy usage action", 2);
998
+ return ingestAgyUsage(context, { projectRoot: requiredOption(parsed, "project-root"), stdin: await readStdin(io.stdin) });
999
+ }
653
1000
  if (family === "worktree") {
654
1001
  return dispatchWorktree(context, command, parsed, requiredScopeProjectRoot(scopeProjectRoot, `worktree ${command ?? ""}`));
655
1002
  }
@@ -962,6 +1309,48 @@ function dispatchSession(context, command, parsed) {
962
1309
  throw new AppError("usage", `Unknown session command: ${command ?? "<empty>"}`, 2);
963
1310
  }
964
1311
  function dispatchRun(context, command, parsed) {
1312
+ if (command === "snapshot") {
1313
+ const action = requiredPosition(parsed, 0, "snapshot action");
1314
+ if (action === "bootstrap") {
1315
+ const bootstrapAction = requiredPosition(parsed, 1, "bootstrap snapshot action");
1316
+ if (bootstrapAction === "create")
1317
+ return createEvalBootstrapSnapshot(context, {
1318
+ projectRoot: requiredOption(parsed, "project-root"),
1319
+ output: requiredOption(parsed, "output")
1320
+ });
1321
+ if (bootstrapAction === "restore")
1322
+ return restoreEvalBootstrapSnapshot(context, {
1323
+ snapshot: requiredOption(parsed, "snapshot"),
1324
+ projectRoot: requiredOption(parsed, "project-root")
1325
+ });
1326
+ throw new AppError("usage", "Use: dd-flow run snapshot bootstrap create|restore", 2);
1327
+ }
1328
+ if (action === "create") {
1329
+ const candidate = parsed.options.has("candidate");
1330
+ const stageEntry = optionalOption(parsed, "stage-entry");
1331
+ if (candidate && stageEntry !== undefined)
1332
+ throw new AppError("usage", "Use either --candidate or --stage-entry, not both", 2);
1333
+ if (!candidate && stageEntry === undefined)
1334
+ throw new AppError("usage", "Snapshot create requires --candidate or --stage-entry", 2);
1335
+ const input = {
1336
+ projectRoot: requiredOption(parsed, "project-root"),
1337
+ runId: requiredPosition(parsed, 1, "run-id"),
1338
+ output: requiredOption(parsed, "output")
1339
+ };
1340
+ return candidate
1341
+ ? createEvalRunSnapshot(context, { ...input, candidate: true })
1342
+ : createEvalRunSnapshot(context, { ...input, stageEntry: stageEntry });
1343
+ }
1344
+ if (action === "restore")
1345
+ return restoreEvalRunSnapshot(context, {
1346
+ snapshot: requiredOption(parsed, "snapshot"),
1347
+ projectRoot: requiredOption(parsed, "project-root")
1348
+ });
1349
+ 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);
1350
+ }
1351
+ if (command === "prepare-vnext-specify") {
1352
+ return prepareVnextSpecifyRun(context, { projectRoot: requiredOption(parsed, "project-root"), slug: requiredOption(parsed, "slug") });
1353
+ }
965
1354
  if (command === "start") {
966
1355
  if (optionalOption(parsed, "flow-kind") === "mb-upgrade") {
967
1356
  assertUpgradeRunStorageReady(context, requiredOption(parsed, "project-root"));
@@ -997,12 +1386,33 @@ function dispatchRun(context, command, parsed) {
997
1386
  hiddenSections: allOptions(parsed, "hide")
998
1387
  });
999
1388
  }
1000
- if (command === "usage") {
1001
- return getFlowRunUsage(context, {
1002
- projectRoot: requiredOption(parsed, "project-root"),
1003
- runId: requiredPosition(parsed, 0, "run-id"),
1004
- groupBy: optionalOption(parsed, "group-by")
1005
- });
1389
+ if (command === "config") {
1390
+ const action = requiredPosition(parsed, 0, "run config action");
1391
+ const runId = requiredPosition(parsed, 1, "run-id");
1392
+ if (action === "status") {
1393
+ return getFlowRunConfig(context, { projectRoot: requiredOption(parsed, "project-root"), runId });
1394
+ }
1395
+ if (action === "set") {
1396
+ return setFlowRunConfig(context, {
1397
+ projectRoot: requiredOption(parsed, "project-root"),
1398
+ runId,
1399
+ key: requiredOption(parsed, "key"),
1400
+ value: requiredOption(parsed, "value"),
1401
+ reason: requiredOption(parsed, "reason")
1402
+ });
1403
+ }
1404
+ throw new AppError("usage", `Unknown run config action: ${action}`, 2);
1405
+ }
1406
+ if (command === "vars") {
1407
+ const action = requiredPosition(parsed, 0, "run vars action");
1408
+ const runId = requiredPosition(parsed, 1, "run-id");
1409
+ if (action === "ls")
1410
+ return getFlowRunVariables(context, { projectRoot: requiredOption(parsed, "project-root"), runId });
1411
+ if (action === "get")
1412
+ return getFlowRunVariables(context, { projectRoot: requiredOption(parsed, "project-root"), runId, key: requiredOption(parsed, "key") });
1413
+ if (action === "set")
1414
+ return setFlowRunVariable(context, { projectRoot: requiredOption(parsed, "project-root"), runId, key: requiredOption(parsed, "key"), value: requiredOption(parsed, "value") });
1415
+ throw new AppError("usage", `Unknown run vars command: ${action}`, 2);
1006
1416
  }
1007
1417
  if (command === "flags") {
1008
1418
  const action = requiredPosition(parsed, 0, "flow flags action");
@@ -1052,16 +1462,39 @@ function dispatchRun(context, command, parsed) {
1052
1462
  });
1053
1463
  }
1054
1464
  if (command === "complete") {
1465
+ throw new AppError("usage", "run complete is retired; only an operator may use run override", 2);
1466
+ }
1467
+ if (command === "override") {
1468
+ const status = requiredOption(parsed, "status");
1469
+ if (!['cancelled', 'failed'].includes(status)) {
1470
+ throw new AppError("usage", "run override status must be cancelled or failed", 2, { status });
1471
+ }
1055
1472
  return completeFlowRun(context, {
1056
1473
  projectRoot: requiredOption(parsed, "project-root"),
1057
1474
  runId: requiredPosition(parsed, 0, "run-id"),
1058
- status: requiredOption(parsed, "status"),
1475
+ status,
1059
1476
  verdict: optionalOption(parsed, "verdict"),
1060
- nextAction: optionalOption(parsed, "next-action")
1477
+ nextAction: optionalOption(parsed, "next-action"),
1478
+ manualOverrideReason: requiredOption(parsed, "reason")
1061
1479
  });
1062
1480
  }
1063
1481
  throw new AppError("usage", `Unknown run command: ${command ?? "<empty>"}`, 2);
1064
1482
  }
1483
+ function dispatchStat(context, command, parsed) {
1484
+ if (command === "usage") {
1485
+ return getStoredFlowRunUsage(context, {
1486
+ projectRoot: requiredOption(parsed, "project-root"),
1487
+ runId: requiredOption(parsed, "run"),
1488
+ groupBy: optionalOption(parsed, "group-by"),
1489
+ sessionId: optionalOption(parsed, "session"),
1490
+ stage: optionalOption(parsed, "stage")
1491
+ });
1492
+ }
1493
+ if (command === "run" && parsed.positional[0] === "sessions" && parsed.positional[1] === "ls") {
1494
+ return getFlowRunSessions(context, { projectRoot: requiredOption(parsed, "project-root"), runId: requiredOption(parsed, "run") });
1495
+ }
1496
+ throw new AppError("usage", "Usage: dd-flow stat usage --run <RUN-ID> --project-root <root> | dd-flow stat run sessions ls --run <RUN-ID> --project-root <root>", 2);
1497
+ }
1065
1498
  function dispatchId(context, command, parsed) {
1066
1499
  if (command === "next") {
1067
1500
  return previewNextEntityId(context, {
@@ -1412,7 +1845,9 @@ function dispatchCodexHome(context, parsed) {
1412
1845
  function dispatchCodexHook(context, parsed, stdin) {
1413
1846
  const action = requiredPosition(parsed, 0, "codex hook action");
1414
1847
  if (action === "handle") {
1415
- const result = handleCodexHook(context, {
1848
+ const isolatedHome = isolatedDdFlowHomeFromHookStdin(stdin);
1849
+ const hookContext = isolatedHome ? createContext({ ...context.env, DD_FLOW_HOME: isolatedHome }) : context;
1850
+ const result = handleCodexHook(hookContext, {
1416
1851
  event: requiredOption(parsed, "event"),
1417
1852
  projectRoot: optionalOption(parsed, "project-root"),
1418
1853
  stdin
@@ -1424,6 +1859,39 @@ function dispatchCodexHook(context, parsed, stdin) {
1424
1859
  }
1425
1860
  throw new AppError("usage", `Unknown codex hook action: ${action}`, 2);
1426
1861
  }
1862
+ function dispatchZcodeEvent(context, parsed, stdin) {
1863
+ const action = requiredPosition(parsed, 0, "zcode event action");
1864
+ if (action === "handle") {
1865
+ return handleZcodeEvent(context, {
1866
+ projectRoot: requiredOption(parsed, "project-root"),
1867
+ stdin
1868
+ });
1869
+ }
1870
+ throw new AppError("usage", `Unknown zcode event action: ${action}`, 2);
1871
+ }
1872
+ function dispatchGrokEvent(context, parsed, stdin) {
1873
+ const action = requiredPosition(parsed, 0, "grok event action");
1874
+ if (action === "handle") {
1875
+ const result = handleGrokEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
1876
+ if (result && typeof result === "object" && !Array.isArray(result) && "hookSpecificOutput" in result) {
1877
+ return { hookSpecificOutput: result.hookSpecificOutput };
1878
+ }
1879
+ return {};
1880
+ }
1881
+ throw new AppError("usage", `Unknown grok event action: ${action}`, 2);
1882
+ }
1883
+ function dispatchOpenCodeEvent(context, parsed, stdin) {
1884
+ const action = requiredPosition(parsed, 0, "opencode event action");
1885
+ if (action === "handle")
1886
+ return handleOpenCodeEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
1887
+ throw new AppError("usage", `Unknown opencode event action: ${action}`, 2);
1888
+ }
1889
+ function dispatchAgyEvent(context, parsed, stdin) {
1890
+ const action = requiredPosition(parsed, 0, "agy event action");
1891
+ if (action === "handle")
1892
+ return handleAgyEvent(context, { projectRoot: requiredOption(parsed, "project-root"), stdin });
1893
+ throw new AppError("usage", `Unknown agy event action: ${action}`, 2);
1894
+ }
1427
1895
  function dispatchWorktree(context, command, parsed, scopeProjectRoot) {
1428
1896
  if (command === "plan") {
1429
1897
  return planWorktree(context, { protocolId: requiredOption(parsed, "protocol-id"), projectRoot: scopeProjectRoot });
@@ -1726,7 +2194,7 @@ function projectRootForMutation(context, args, result, resolvedScope) {
1726
2194
  if (family === "run" && ["start", "attach-stage", "complete-stage", "complete", "flags"].includes(command ?? "")) {
1727
2195
  return requiredOption(parsed, "project-root");
1728
2196
  }
1729
- if (family === "stage" && ["start", "finish"].includes(command ?? "")) {
2197
+ if (family === "stage" && ["start", "pause", "resume", "finish"].includes(command ?? "")) {
1730
2198
  return requiredOption(parsed, "project-root");
1731
2199
  }
1732
2200
  if (family === "worktree" && ["create", "bootstrap", "close"].includes(command ?? "")) {
@@ -1735,6 +2203,14 @@ function projectRootForMutation(context, args, result, resolvedScope) {
1735
2203
  if (family === "codex" && command === "hook" && requiredPosition(parsed, 0, "codex hook action") === "handle") {
1736
2204
  return optionalOption(parsed, "project-root");
1737
2205
  }
2206
+ if (family === "zcode" && ((command === "event" && requiredPosition(parsed, 0, "zcode event action") === "handle") || command === "usage")) {
2207
+ return requiredOption(parsed, "project-root");
2208
+ }
2209
+ if (family === "opencode" && ((command === "event" && requiredPosition(parsed, 0, "opencode event action") === "handle") || command === "usage")) {
2210
+ return requiredOption(parsed, "project-root");
2211
+ }
2212
+ if (family === "agy" && ((command === "event" && requiredPosition(parsed, 0, "agy event action") === "handle") || command === "usage"))
2213
+ return requiredOption(parsed, "project-root");
1738
2214
  if (family === "codex" && command === "hooks") {
1739
2215
  const action = requiredPosition(parsed, 0, "codex hooks action");
1740
2216
  return ["install", "remove"].includes(action) ? requiredOption(parsed, "project-root") : undefined;
@@ -1770,6 +2246,27 @@ function projectRootForMergeQueueMutation(context, command, parsed) {
1770
2246
  function protocolProjectRoot(context, protocolId) {
1771
2247
  return requireProtocol(context, protocolId).project_root;
1772
2248
  }
2249
+ function runnerIntake(context) {
2250
+ const input = context.value.task_input?.[0];
2251
+ if (!input?.path)
2252
+ throw new AppError("validation", "Runner SPECIFY context requires one ordered task_input file", 2);
2253
+ const file = path.resolve(input.path);
2254
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile())
2255
+ throw new AppError("not_found", "Runner SPECIFY task input is missing", 2, { task_input: file });
2256
+ return fs.readFileSync(file, "utf8");
2257
+ }
2258
+ /** Stage services install context before their lifecycle transition. Keeping
2259
+ * this check here makes an incomplete service migration fail closed instead of
2260
+ * silently materialising evidence after a Stage has become running. */
2261
+ function attachExternalStageContext(result, loaded) {
2262
+ if (!loaded)
2263
+ return result;
2264
+ const promptPath = typeof result.prompt_path === "string" ? result.prompt_path : null;
2265
+ if (!promptPath || !result.external_context || typeof result.external_context !== "object") {
2266
+ throw new AppError("stage_context_not_installed", "vNext stage service did not atomically install the supplied runner context", 1);
2267
+ }
2268
+ return { ...result, worker_prompt_markdown: fs.readFileSync(promptPath, "utf8") };
2269
+ }
1773
2270
  function isScopedProtocolMutation(family, command) {
1774
2271
  if (family === "transition")
1775
2272
  return true;