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

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 (138) hide show
  1. package/CHANGELOG.md +402 -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 +1344 -376
  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 +575 -293
  72. package/dist/services/lanes.js +61 -53
  73. package/dist/services/lifecycle-command.js +87 -7
  74. package/dist/services/lifecycle-invocations.js +835 -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 +343 -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 +69 -28
  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 +701 -164
  128. package/dist/services/workspace-bootstrap.js +76 -0
  129. package/dist/services/worktrees.js +85 -35
  130. package/dist/shared/entity-references.js +8 -0
  131. package/dist/shared/errors.js +12 -0
  132. package/dist/storage/database.js +444 -32
  133. package/dist/storage/paths.js +17 -4
  134. package/dist/storage/work-references.js +23 -0
  135. package/dist/storage/writer-contract.js +77 -0
  136. package/dist/storage/writer-migration.js +102 -0
  137. package/package.json +11 -4
  138. package/tools/repair-paused-run-status.mjs +59 -0
@@ -1,6 +1,4 @@
1
1
  import crypto from "node:crypto";
2
- import fs from "node:fs";
3
- import path from "node:path";
4
2
  import { spawnSync } from "node:child_process";
5
3
  import { AppError } from "../shared/errors.js";
6
4
  import { appendAudit } from "./audit.js";
@@ -8,6 +6,32 @@ import { requireProjectByRoot } from "./projects.js";
8
6
  import { resolveProjectRoot } from "../storage/paths.js";
9
7
  const defaultTtlSeconds = 300;
10
8
  const defaultPollIntervalSeconds = 10;
9
+ export function prepareLaneWaitTiming(input) {
10
+ return {
11
+ timeoutSeconds: normalizeNonNegativeNumber(input.timeoutSeconds, 0, "timeout"),
12
+ pollIntervalSeconds: normalizePositiveNumber(input.pollIntervalSeconds, defaultPollIntervalSeconds, "poll-interval")
13
+ };
14
+ }
15
+ export function prepareLaneLock(context, input, action) {
16
+ if (typeof input.workerId !== "string" || !input.workerId.trim())
17
+ throw new AppError("validation", "Lane lock requires a nonempty worker ID", 2);
18
+ if (["acquire", "release", "wait-acquire"].includes(action) && (typeof input.reason !== "string" || !input.reason.trim()))
19
+ throw new AppError("validation", "Lane lock requires a nonempty reason", 2);
20
+ if (input.leaseToken !== undefined && (typeof input.leaseToken !== "string" || !input.leaseToken.trim()))
21
+ throw new AppError("validation", "Lease token must be nonempty text", 2);
22
+ const ttlSeconds = normalizePositiveNumber(input.ttlSeconds, defaultTtlSeconds, "ttl");
23
+ const { timeoutSeconds, pollIntervalSeconds } = prepareLaneWaitTiming(input);
24
+ const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
25
+ const lane = normalizeLane(input.lane);
26
+ if (input.workspacePath !== undefined)
27
+ requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
28
+ else if (["acquire", "wait", "wait-acquire"].includes(action))
29
+ throw new AppError("validation", "Lane lock requires a workspace path", 2);
30
+ if (action === "acquire" || action === "wait-acquire")
31
+ assertWorkerMayAcquireLaneLock(context, project.id, lane, input.workerId);
32
+ const lock = action === "heartbeat" || action === "release" ? requireOwnedActiveLock(context, project.id, lane, input.workerId, input.leaseToken) : undefined;
33
+ return { project, lane, ttlSeconds, timeoutSeconds, pollIntervalSeconds, lock };
34
+ }
11
35
  export function getLaneStatus(context, input) {
12
36
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
13
37
  return {
@@ -23,10 +47,16 @@ export function expireProjectLaneLocks(context, projectId) {
23
47
  export function expireProjectLaneWaiters(context, projectId) {
24
48
  expireStaleWaiters(context, projectId);
25
49
  }
26
- export function setLaneWorkspace(context, input) {
50
+ export function prepareLaneWorkspace(context, input) {
51
+ if (input.branch !== undefined && (typeof input.branch !== "string" || !input.branch.trim()))
52
+ throw new AppError("validation", "Expected branch must be nonempty text", 2);
27
53
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
28
54
  const lane = normalizeLane(input.lane);
29
55
  const workspacePath = resolveExistingPath(input.workspacePath);
56
+ return { project, lane, workspacePath };
57
+ }
58
+ export function setLaneWorkspace(context, input) {
59
+ const { project, lane, workspacePath } = prepareLaneWorkspace(context, input);
30
60
  const now = context.now();
31
61
  const existing = laneRecord(context, project.id, lane);
32
62
  context.db.run(`INSERT INTO lanes
@@ -69,11 +99,7 @@ export function checkLaneWorkspace(context, input) {
69
99
  };
70
100
  }
71
101
  export function acquireLaneLock(context, input) {
72
- const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
73
- const lane = normalizeLane(input.lane);
74
- requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
75
- assertWorkerMayAcquireLaneLock(context, project.id, lane, input.workerId);
76
- const ttlSeconds = normalizePositiveNumber(input.ttlSeconds, defaultTtlSeconds, "ttl");
102
+ const { project, lane, ttlSeconds } = prepareLaneLock(context, input, "acquire");
77
103
  expireStaleLocks(context, project.id);
78
104
  const active = activeLaneLock(context, project.id, lane);
79
105
  if (active) {
@@ -116,13 +142,8 @@ export function acquireLaneLock(context, input) {
116
142
  };
117
143
  }
118
144
  export function heartbeatLaneLock(context, input) {
119
- const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
120
- const lane = normalizeLane(input.lane);
121
- if (input.workspacePath) {
122
- requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
123
- }
124
- const lock = requireOwnedActiveLock(context, project.id, lane, input.workerId, input.leaseToken);
125
- const ttlSeconds = normalizePositiveNumber(input.ttlSeconds, defaultTtlSeconds, "ttl");
145
+ const { project, lock: preparedLock, ttlSeconds } = prepareLaneLock(context, input, "heartbeat");
146
+ const lock = preparedLock;
126
147
  const now = context.now();
127
148
  context.db.run(`UPDATE lane_locks SET heartbeat_at = ?, expires_at = ?, updated_at = ? WHERE id = ?`, [now, expiresAt(now, ttlSeconds), now, lock.id]);
128
149
  appendAudit(context, {
@@ -133,12 +154,8 @@ export function heartbeatLaneLock(context, input) {
133
154
  return { ok: true, lock: activeLaneLock(context, project.id, lock.lane) };
134
155
  }
135
156
  export function releaseLaneLock(context, input) {
136
- const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
137
- const lane = normalizeLane(input.lane);
138
- if (input.workspacePath) {
139
- requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
140
- }
141
- const lock = requireOwnedActiveLock(context, project.id, lane, input.workerId, input.leaseToken);
157
+ const { project, lock: preparedLock } = prepareLaneLock(context, input, "release");
158
+ const lock = preparedLock;
142
159
  const now = context.now();
143
160
  context.db.run(`UPDATE lane_locks
144
161
  SET status = 'released', released_at = ?, reason = ?, updated_at = ?
@@ -152,11 +169,7 @@ export function releaseLaneLock(context, input) {
152
169
  return { ok: true, lock: laneLockById(context, lock.id) };
153
170
  }
154
171
  export async function waitForLaneLock(context, input) {
155
- const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
156
- const lane = normalizeLane(input.lane);
157
- requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
158
- const timeoutSeconds = normalizeNonNegativeNumber(input.timeoutSeconds, 0, "timeout");
159
- const pollIntervalSeconds = normalizePositiveNumber(input.pollIntervalSeconds, defaultPollIntervalSeconds, "poll-interval");
172
+ const { project, lane, timeoutSeconds, pollIntervalSeconds } = prepareLaneLock(context, input, "wait");
160
173
  const start = Date.now();
161
174
  while (true) {
162
175
  expireStaleLocks(context, project.id);
@@ -186,13 +199,18 @@ export function getLaneWaiters(context, input) {
186
199
  }))
187
200
  };
188
201
  }
189
- export function cancelLaneWaiter(context, input) {
202
+ export function prepareLaneWaiterCancellation(context, input) {
203
+ if (typeof input.workerId !== "string" || !input.workerId.trim())
204
+ throw new AppError("validation", "Lane waiter requires a nonempty worker ID", 2);
205
+ if (typeof input.reason !== "string" || !input.reason.trim())
206
+ throw new AppError("validation", "lane waiter cancel requires --reason", 2);
190
207
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
191
208
  const lane = normalizeLane(input.lane);
192
209
  const reason = input.reason.trim();
193
- if (!reason) {
194
- throw new AppError("validation", "lane waiter cancel requires --reason", 2);
195
- }
210
+ return { project, lane, reason };
211
+ }
212
+ export function cancelLaneWaiter(context, input) {
213
+ const { project, lane, reason } = prepareLaneWaiterCancellation(context, input);
196
214
  expireStaleWaiters(context, project.id);
197
215
  const now = context.now();
198
216
  const waiter = activeLaneWaiterForWorker(context, project.id, lane, input.workerId);
@@ -245,13 +263,7 @@ export function expireLaneWaiterById(context, input) {
245
263
  return { ok: true, expired: result.changes === 1, waiter_id: input.waiterId };
246
264
  }
247
265
  export async function waitAcquireLaneLock(context, input) {
248
- const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
249
- const lane = normalizeLane(input.lane);
250
- requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath);
251
- assertWorkerMayAcquireLaneLock(context, project.id, lane, input.workerId);
252
- const timeoutSeconds = normalizeNonNegativeNumber(input.timeoutSeconds, 0, "timeout");
253
- const pollIntervalSeconds = normalizePositiveNumber(input.pollIntervalSeconds, defaultPollIntervalSeconds, "poll-interval");
254
- const ttlSeconds = normalizePositiveNumber(input.ttlSeconds, defaultTtlSeconds, "ttl");
266
+ const { project, lane, timeoutSeconds, pollIntervalSeconds, ttlSeconds } = prepareLaneLock(context, input, "wait-acquire");
255
267
  const startedAt = Date.now();
256
268
  const waiterDeadline = timeoutSeconds > 0 ? new Date(startedAt + timeoutSeconds * 1000).toISOString() : null;
257
269
  while (true) {
@@ -375,10 +387,9 @@ function laneWaitersForProject(context, projectId, lane) {
375
387
  LIMIT 100`, [projectId]);
376
388
  }
377
389
  function activeLaneLock(context, projectId, lane) {
378
- expireStaleLocks(context, projectId);
379
390
  return context.db.get(`SELECT * FROM lane_locks
380
- WHERE project_id = ? AND lane = ? AND status = 'active'
381
- ORDER BY updated_at DESC, id DESC LIMIT 1`, [projectId, lane]);
391
+ WHERE project_id = ? AND lane = ? AND status = 'active' AND expires_at > ?
392
+ ORDER BY updated_at DESC, id DESC LIMIT 1`, [projectId, lane, context.now()]);
382
393
  }
383
394
  function activeLaneWaiterForWorker(context, projectId, lane, workerId) {
384
395
  return context.db.get(`SELECT * FROM lane_waiters
@@ -513,10 +524,10 @@ function ensureQueuedLaneWaiter(context, input) {
513
524
  return waiter;
514
525
  }
515
526
  function tryAcquireQueuedLaneLock(context, input) {
516
- expireStaleLocks(context, input.projectId);
517
- expireStaleWaiters(context, input.projectId);
518
- context.db.exec("BEGIN IMMEDIATE");
527
+ context.db.beginWriteTransaction();
519
528
  try {
529
+ expireStaleLocks(context, input.projectId);
530
+ expireStaleWaiters(context, input.projectId);
520
531
  const existingLock = activeLaneLock(context, input.projectId, input.lane);
521
532
  if (existingLock?.worker_id === input.workerId) {
522
533
  context.db.exec("COMMIT");
@@ -618,11 +629,7 @@ function tryAcquireQueuedLaneLock(context, input) {
618
629
  }
619
630
  }
620
631
  function resolveExistingPath(value) {
621
- const absolute = path.resolve(value);
622
- if (!fs.existsSync(absolute)) {
623
- throw new AppError("not_found", `Workspace path does not exist: ${absolute}`, 1);
624
- }
625
- return fs.realpathSync(absolute);
632
+ return resolveProjectRoot(value);
626
633
  }
627
634
  function detectBranch(workspacePath) {
628
635
  const result = spawnSync("git", ["-C", workspacePath, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8" });
@@ -635,7 +642,7 @@ function expiresAt(now, ttlSeconds) {
635
642
  return new Date(new Date(now).getTime() + ttlSeconds * 1000).toISOString();
636
643
  }
637
644
  function normalizeLane(value) {
638
- const normalized = value.trim().toLowerCase();
645
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
639
646
  if (!normalized || !/^[a-z0-9._-]+$/.test(normalized)) {
640
647
  throw new AppError("validation", "Lane name must contain only lowercase letters, numbers, dot, underscore, or hyphen", 2);
641
648
  }
@@ -643,15 +650,16 @@ function normalizeLane(value) {
643
650
  }
644
651
  function normalizePositiveNumber(value, fallback, label) {
645
652
  const normalized = value ?? fallback;
646
- if (!Number.isFinite(normalized) || normalized <= 0) {
647
- throw new AppError("validation", `--${label} must be a positive number`, 2);
653
+ if (!Number.isFinite(normalized) || normalized <= 0 ||
654
+ (label === "poll-interval" ? normalized * 1000 > 2 ** 31 - 1 : !Number.isFinite(new Date(Date.now() + normalized * 1000).getTime()))) {
655
+ throw new AppError("validation", `--${label} must be a positive number within the supported timer/date range`, 2);
648
656
  }
649
657
  return normalized;
650
658
  }
651
659
  function normalizeNonNegativeNumber(value, fallback, label) {
652
660
  const normalized = value ?? fallback;
653
- if (!Number.isFinite(normalized) || normalized < 0) {
654
- throw new AppError("validation", `--${label} must be zero or a positive number`, 2);
661
+ if (!Number.isFinite(normalized) || normalized < 0 || !Number.isFinite(new Date(Date.now() + normalized * 1000).getTime())) {
662
+ throw new AppError("validation", `--${label} must be zero or a positive number within the supported date range`, 2);
655
663
  }
656
664
  return normalized;
657
665
  }
@@ -1,5 +1,11 @@
1
1
  import path from "node:path";
2
2
  import { parse, quote } from "shell-quote";
3
+ /** Native hooks and the lightweight ingress must recognize the same shell. */
4
+ export function lifecycleCommandFromPayload(payload) {
5
+ const input = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
6
+ const command = [payload.command, input.command, input.cmd].find(value => typeof value === "string" && value.length > 0);
7
+ return typeof command === "string" ? unwrapShellCommand(command) : undefined;
8
+ }
3
9
  const controlOperators = new Set(["&&", "||", ";", "|", "|&", "&", "(", ")", "<(", ">("]);
4
10
  const redirectionOperators = new Set(["<", ">", ">>", ">|", "<&", ">&", "<<<"]);
5
11
  /** Parse the deliberately small direct-command surface accepted by lifecycle hooks. */
@@ -32,7 +38,7 @@ function parseLifecycleCommandInner(command, wrapped) {
32
38
  const heredoc = stripHeredocBodies(command);
33
39
  let entries;
34
40
  try {
35
- entries = parse(heredoc.command, (name) => `$${name}`);
41
+ entries = parse(withoutFileDescriptors(heredoc.command), (name) => `$${name}`);
36
42
  }
37
43
  catch {
38
44
  // A command that cannot be tokenized cannot create a trusted claim. The
@@ -56,11 +62,11 @@ function parseLifecycleCommandInner(command, wrapped) {
56
62
  if (!found.length)
57
63
  return { kind: "none" };
58
64
  const first = found[0];
59
- if (found.length !== 1 || composed || first.nestedCompound) {
65
+ if (found.length !== 1 || composed || first.nestedCompound || (heredoc.present && !heredoc.safe)) {
60
66
  return {
61
67
  kind: "compound",
62
68
  invocation: { ...first.invocation, rewriteSafe: false },
63
- reason: found.length !== 1 ? "multiple_lifecycle_invocations" : first.nestedCompound ? "nested_compound_invocation" : "shell_composition"
69
+ reason: found.length !== 1 ? "multiple_lifecycle_invocations" : first.nestedCompound ? "nested_compound_invocation" : heredoc.present && !heredoc.safe ? "unsafe_heredoc" : "shell_composition"
64
70
  };
65
71
  }
66
72
  return { kind: "standalone", invocation: first.invocation };
@@ -127,7 +133,7 @@ function invocationFromSegment(segment, heredoc, wrapped, inheritedEnv) {
127
133
  }
128
134
  }
129
135
  const executable = segment.words[index];
130
- if (!executable || path.basename(executable) !== "dd-flow")
136
+ if (!executable || path.basename(executable) !== "dd-flow" && executable !== "$DD_FLOW_BIN")
131
137
  return null;
132
138
  const argv = segment.words.slice(index + 1);
133
139
  const operation = lifecycleOperation(argv);
@@ -138,7 +144,7 @@ function invocationFromSegment(segment, heredoc, wrapped, inheritedEnv) {
138
144
  executable,
139
145
  argv,
140
146
  env,
141
- args: parseCommandArgs(argv.slice(2)),
147
+ args: parseCommandArgs(argv.slice(operation === "recovery_accept" ? 3 : 2)),
142
148
  command: quote(segment.words),
143
149
  rewriteSafe: !heredoc && !wrapped && !segment.dynamic,
144
150
  wrapped,
@@ -170,15 +176,28 @@ function wrappedInvocationFromSegment(segment) {
170
176
  return parseLifecycleCommandInner(payload, true);
171
177
  }
172
178
  function lifecycleOperation(argv) {
179
+ // The CLI handles help before dispatch, wherever the flag occurs.
180
+ if (argv.some(arg => arg === "--help" || arg === "-h"))
181
+ return null;
182
+ if (argv[0] === "run" && argv[1] === "recovery" && argv[2] === "accept")
183
+ return "recovery_accept";
173
184
  const key = `${argv[0] ?? ""} ${argv[1] ?? ""}`;
174
185
  if (key === "session register")
175
186
  return "session_register";
176
187
  if (key === "stage start")
177
188
  return "stage_start";
189
+ if (key === "stage finish")
190
+ return "stage_finish";
191
+ if (key === "stage pause")
192
+ return "stage_pause";
178
193
  if (key === "stage resume")
179
194
  return "stage_resume";
180
195
  if (key === "work start")
181
196
  return "work_start";
197
+ if (key === "work finish")
198
+ return "work_finish";
199
+ if (key === "work fail")
200
+ return "work_fail";
182
201
  return null;
183
202
  }
184
203
  export function parseCommandArgs(argv) {
@@ -187,6 +206,12 @@ export function parseCommandArgs(argv) {
187
206
  for (let index = 0; index < argv.length; index += 1) {
188
207
  const value = argv[index];
189
208
  if (value?.startsWith("--")) {
209
+ const equals = value.indexOf("=");
210
+ if (equals > 2) {
211
+ const key = value.slice(2, equals);
212
+ options.set(key, [...(options.get(key) ?? []), value.slice(equals + 1)]);
213
+ continue;
214
+ }
190
215
  const key = value.slice(2);
191
216
  const next = argv[index + 1];
192
217
  const optionValue = !next || next.startsWith("--") ? "__dd_flow_flag__" : next;
@@ -213,6 +238,58 @@ export function commandPosition(invocation, index) {
213
238
  function assignment(word) {
214
239
  return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
215
240
  }
241
+ /** Source offsets matter: shell-quote loses the difference between `2>&1`
242
+ * and the literal argument `2 >&1`. Only inspect unquoted shell syntax. */
243
+ function shellSyntaxOffsets(command) {
244
+ const offsets = [];
245
+ let quoted = null, escaped = false;
246
+ for (let i = 0; i < command.length; i++) {
247
+ const char = command[i];
248
+ if (escaped) {
249
+ escaped = false;
250
+ continue;
251
+ }
252
+ if (char === "\\" && quoted !== "'") {
253
+ escaped = true;
254
+ continue;
255
+ }
256
+ if (quoted) {
257
+ if (char === quoted)
258
+ quoted = null;
259
+ continue;
260
+ }
261
+ if (char === "'" || char === '"') {
262
+ quoted = char;
263
+ continue;
264
+ }
265
+ if (char === "#" && (i === 0 || /\s/.test(command[i - 1]))) {
266
+ offsets.push(i);
267
+ break;
268
+ }
269
+ if (char === "<" || char === ">")
270
+ offsets.push(i);
271
+ }
272
+ return offsets;
273
+ }
274
+ function descriptorStart(command, index) {
275
+ let start = index;
276
+ while (start > 0 && /[0-9]/.test(command[start - 1]))
277
+ start--;
278
+ return start === 0 || /[\s;&|]/.test(command[start - 1]) ? start : index;
279
+ }
280
+ export function shellSuffixOffset(command) {
281
+ const offset = shellSyntaxOffsets(command)[0];
282
+ return offset === undefined ? command.length : descriptorStart(command, offset);
283
+ }
284
+ function withoutFileDescriptors(command) {
285
+ for (const index of shellSyntaxOffsets(command).reverse()) {
286
+ if (command[index] === "#")
287
+ continue;
288
+ const start = descriptorStart(command, index);
289
+ command = command.slice(0, start) + command.slice(index);
290
+ }
291
+ return command;
292
+ }
216
293
  function addAssignment(env, word) {
217
294
  const separator = word.indexOf("=");
218
295
  env[word.slice(0, separator)] = word.slice(separator + 1);
@@ -223,6 +300,7 @@ function stripHeredocBodies(command) {
223
300
  const pending = [];
224
301
  let active;
225
302
  let present = false;
303
+ let count = 0, quoted = true;
226
304
  for (const line of lines) {
227
305
  if (active) {
228
306
  const candidate = active.stripTabs ? line.replace(/^\t+/, "") : line;
@@ -233,13 +311,15 @@ function stripHeredocBodies(command) {
233
311
  if (line.trim())
234
312
  output.push(line);
235
313
  const found = heredocDelimiters(line);
314
+ count += found.length;
315
+ quoted &&= found.every(item => item.quoted);
236
316
  if (found.length) {
237
317
  present = true;
238
318
  active = found[0];
239
319
  pending.push(...found.slice(1));
240
320
  }
241
321
  }
242
- return { command: output.join(" ; "), present };
322
+ return { command: output.join(" ; "), present, safe: count === 1 && quoted && !active && pending.length === 0 };
243
323
  }
244
324
  function heredocDelimiters(line) {
245
325
  const result = [];
@@ -282,7 +362,7 @@ function heredocDelimiters(line) {
282
362
  index += 1;
283
363
  const delimiter = line.slice(start, index);
284
364
  if (delimiter)
285
- result.push({ delimiter, stripTabs });
365
+ result.push({ delimiter, stripTabs, quoted: delimiterQuote !== null });
286
366
  }
287
367
  return result;
288
368
  }