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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/CHANGELOG.md +526 -0
  2. package/README.md +68 -0
  3. package/dist/build-info.json +8 -8
  4. package/dist/cli/command-inputs.js +305 -0
  5. package/dist/cli/help.js +89 -13
  6. package/dist/cli/hook-ingress.js +77 -0
  7. package/dist/cli/input-preparation.js +116 -0
  8. package/dist/cli/native-hook-ingress.js +48 -0
  9. package/dist/cli/run-cli.js +1465 -384
  10. package/dist/cli.js +8 -2
  11. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  12. package/dist/harness-runtime/bin/dd-agy.mjs +52 -0
  13. package/dist/harness-runtime/bin/dd-codex.mjs +26 -0
  14. package/dist/harness-runtime/bin/dd-droid.mjs +33 -0
  15. package/dist/harness-runtime/bin/dd-grok.mjs +30 -0
  16. package/dist/harness-runtime/bin/dd-opencode.mjs +21 -0
  17. package/dist/harness-runtime/bin/dd-zcode.mjs +83 -0
  18. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  19. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  20. package/dist/harness-runtime/lib/daemon-operations.mjs +226 -0
  21. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  22. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +500 -0
  23. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  24. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  25. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +149 -0
  26. package/dist/harness-runtime/lib/dd-codex.mjs +563 -0
  27. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +125 -0
  28. package/dist/harness-runtime/lib/dd-droid.mjs +475 -0
  29. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +394 -0
  30. package/dist/harness-runtime/lib/dd-grok.mjs +174 -0
  31. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +219 -0
  32. package/dist/harness-runtime/lib/dd-opencode.mjs +98 -0
  33. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +645 -0
  34. package/dist/harness-runtime/lib/dd-zcode.mjs +982 -0
  35. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  36. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  37. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  38. package/dist/harness-runtime/lib/driver-recovery.mjs +129 -0
  39. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  40. package/dist/harness-runtime/lib/managed-daemon.mjs +327 -0
  41. package/dist/harness-runtime/lib/model-observations.mjs +77 -0
  42. package/dist/harness-runtime/lib/native-hook-command.d.mts +3 -0
  43. package/dist/harness-runtime/lib/native-hook-command.mjs +108 -0
  44. package/dist/harness-runtime/lib/observation-clock.mjs +36 -0
  45. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  46. package/dist/harness-runtime/lib/operation-errors.mjs +19 -0
  47. package/dist/harness-runtime/lib/process-json.mjs +71 -0
  48. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  49. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  50. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  51. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  52. package/dist/harness-runtime/lib/tool-observations.d.mts +17 -0
  53. package/dist/harness-runtime/lib/tool-observations.mjs +153 -0
  54. package/dist/harness-runtime/lib/zcode-usage.mjs +54 -0
  55. package/dist/protocol/local-files.js +18 -9
  56. package/dist/runtime/context.js +2 -2
  57. package/dist/schemas/agent-profile.schema.json +1 -1
  58. package/dist/schemas/code-review-result.schema.json +1 -1
  59. package/dist/schemas/code-work-batch.schema.json +3 -3
  60. package/dist/schemas/code-work-result.schema.json +3 -3
  61. package/dist/schemas/plan-review-result.schema.json +2 -2
  62. package/dist/schemas/run-control-receipt.schema.json +99 -0
  63. package/dist/schemas/run-control-request.schema.json +36 -0
  64. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  65. package/dist/services/canon.js +11 -8
  66. package/dist/services/cleanup.js +132 -39
  67. package/dist/services/cli-operation-classifier.js +22 -24
  68. package/dist/services/code-checks.js +589 -106
  69. package/dist/services/codex-hook-delivery.js +28 -0
  70. package/dist/services/command-context.js +80 -0
  71. package/dist/services/config.js +11 -8
  72. package/dist/services/continuation-outcome.js +20 -0
  73. package/dist/services/controller-fanout.js +173 -0
  74. package/dist/services/dashboard.js +103 -31
  75. package/dist/services/engines.js +121 -76
  76. package/dist/services/eval-snapshots.js +994 -97
  77. package/dist/services/execution-policy.js +181 -0
  78. package/dist/services/external-work-launch.js +166 -0
  79. package/dist/services/harness-adapter.js +147 -24
  80. package/dist/services/harness-config.js +2 -0
  81. package/dist/services/hooks.js +702 -327
  82. package/dist/services/lanes.js +78 -65
  83. package/dist/services/lifecycle-command.js +113 -18
  84. package/dist/services/lifecycle-contract.js +30 -0
  85. package/dist/services/lifecycle-invocations.js +1379 -0
  86. package/dist/services/managed-daemon-binding.js +38 -0
  87. package/dist/services/managed-processes.js +302 -34
  88. package/dist/services/merge-queue.js +228 -149
  89. package/dist/services/merge-server.js +66 -28
  90. package/dist/services/migrations.js +37 -16
  91. package/dist/services/native-daemon-history.js +49 -0
  92. package/dist/services/native-session-control.js +39 -0
  93. package/dist/services/plan-runtime.js +26 -11
  94. package/dist/services/plans.js +28 -25
  95. package/dist/services/projects.js +20 -15
  96. package/dist/services/prompts.js +25 -16
  97. package/dist/services/protocols.js +160 -86
  98. package/dist/services/recovery-observation-budget.js +61 -0
  99. package/dist/services/recovery-snapshot-database.js +142 -0
  100. package/dist/services/repair-intents.js +40 -0
  101. package/dist/services/review-copy.js +136 -0
  102. package/dist/services/run-control-receipt.js +56 -0
  103. package/dist/services/run-control-worker.js +351 -0
  104. package/dist/services/run-control.js +888 -0
  105. package/dist/services/run-controller-adapter.js +231 -0
  106. package/dist/services/run-controller-capture.js +167 -0
  107. package/dist/services/run-controller-process.js +180 -0
  108. package/dist/services/run-controller-recovery.js +221 -0
  109. package/dist/services/run-controller-state.js +36 -0
  110. package/dist/services/run-controller.js +798 -0
  111. package/dist/services/run-engine-bindings.js +1 -1
  112. package/dist/services/run-fork.js +142 -0
  113. package/dist/services/run-observations.js +112 -0
  114. package/dist/services/run-projection.js +22 -64
  115. package/dist/services/run-recovery-runtime.js +80 -0
  116. package/dist/services/run-recovery.js +345 -0
  117. package/dist/services/runs.js +536 -181
  118. package/dist/services/runtime-budget.js +413 -0
  119. package/dist/services/runtime-command.js +43 -0
  120. package/dist/services/runtime-scope-capture.js +52 -0
  121. package/dist/services/runtime-scope-control.js +460 -0
  122. package/dist/services/runtime-scope-resume.js +577 -0
  123. package/dist/services/runtime-scope-stop.js +159 -0
  124. package/dist/services/runtime-scope-worker.js +242 -0
  125. package/dist/services/runtime-service.js +97 -0
  126. package/dist/services/schema-validation.js +10 -8
  127. package/dist/services/scope-writer-cleanup.js +26 -0
  128. package/dist/services/sessions.js +35 -69
  129. package/dist/services/stage-blocker.js +17 -7
  130. package/dist/services/stage-context.js +50 -19
  131. package/dist/services/stage-lifecycle.js +100 -103
  132. package/dist/services/stage-pause.js +88 -75
  133. package/dist/services/stage-report-renderer.js +116 -6
  134. package/dist/services/stage-work-graph.js +35 -0
  135. package/dist/services/usage.js +35 -98
  136. package/dist/services/vnext-code-review.js +197 -84
  137. package/dist/services/vnext-code.js +278 -251
  138. package/dist/services/vnext-execution-profile.js +5 -3
  139. package/dist/services/vnext-fanout.js +172 -17
  140. package/dist/services/vnext-merge.js +345 -111
  141. package/dist/services/vnext-plan-review.js +171 -111
  142. package/dist/services/vnext-plan.js +180 -87
  143. package/dist/services/vnext-protocolize.js +320 -74
  144. package/dist/services/vnext-specify.js +115 -77
  145. package/dist/services/work-registry.js +1001 -187
  146. package/dist/services/workspace-bootstrap.js +76 -0
  147. package/dist/services/workspace-files.js +83 -0
  148. package/dist/services/worktrees.js +88 -36
  149. package/dist/shared/entity-references.js +8 -0
  150. package/dist/shared/errors.js +12 -0
  151. package/dist/storage/database.js +692 -35
  152. package/dist/storage/foreign-key-transaction.js +39 -0
  153. package/dist/storage/immutable-input.js +45 -0
  154. package/dist/storage/import-guard.js +102 -0
  155. package/dist/storage/native-cleanup.js +52 -0
  156. package/dist/storage/paths.js +17 -4
  157. package/dist/storage/projection-lock.js +73 -0
  158. package/dist/storage/work-references.js +23 -0
  159. package/dist/storage/writer-contract.js +77 -0
  160. package/dist/storage/writer-migration.js +85 -0
  161. package/package.json +24 -13
  162. package/tools/repair-paused-run-status.mjs +84 -0
@@ -1,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,31 @@ 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
+ const workspace = input.workspacePath !== undefined ? requireMatchingLaneWorkspace(context, project.id, lane, input.workspacePath) : undefined;
27
+ if (input.workspacePath === undefined && ["acquire", "wait", "wait-acquire"].includes(action))
28
+ throw new AppError("validation", "Lane lock requires a workspace path", 2);
29
+ if (action === "acquire" || action === "wait-acquire")
30
+ assertWorkerMayAcquireLaneLock(context, project.id, lane, input.workerId);
31
+ const lock = action === "heartbeat" || action === "release" ? requireOwnedActiveLock(context, project.id, lane, input.workerId, input.leaseToken) : undefined;
32
+ return { project, lane, ttlSeconds, timeoutSeconds, pollIntervalSeconds, lock, workspace };
33
+ }
11
34
  export function getLaneStatus(context, input) {
12
35
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
13
36
  return {
@@ -23,10 +46,16 @@ export function expireProjectLaneLocks(context, projectId) {
23
46
  export function expireProjectLaneWaiters(context, projectId) {
24
47
  expireStaleWaiters(context, projectId);
25
48
  }
26
- export function setLaneWorkspace(context, input) {
49
+ export function prepareLaneWorkspace(context, input) {
50
+ if (input.branch !== undefined && (typeof input.branch !== "string" || !input.branch.trim()))
51
+ throw new AppError("validation", "Expected branch must be nonempty text", 2);
27
52
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
28
53
  const lane = normalizeLane(input.lane);
29
54
  const workspacePath = resolveExistingPath(input.workspacePath);
55
+ return { project, lane, workspacePath };
56
+ }
57
+ export function setLaneWorkspace(context, input) {
58
+ const { project, lane, workspacePath } = prepareLaneWorkspace(context, input);
30
59
  const now = context.now();
31
60
  const existing = laneRecord(context, project.id, lane);
32
61
  context.db.run(`INSERT INTO lanes
@@ -69,11 +98,12 @@ export function checkLaneWorkspace(context, input) {
69
98
  };
70
99
  }
71
100
  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");
101
+ const prepared = prepareLaneLock(context, input, "acquire");
102
+ return context.db.writeTransaction(() => acquirePreparedLaneLock(context, input, prepared));
103
+ }
104
+ function acquirePreparedLaneLock(context, input, prepared) {
105
+ const { project, lane, ttlSeconds } = prepared;
106
+ assertPreparedLaneLock(context, prepared, input.workerId);
77
107
  expireStaleLocks(context, project.id);
78
108
  const active = activeLaneLock(context, project.id, lane);
79
109
  if (active) {
@@ -115,14 +145,15 @@ export function acquireLaneLock(context, input) {
115
145
  ...(expired ? { expired_lock_id: expired.id } : {})
116
146
  };
117
147
  }
148
+ function assertPreparedLaneLock(context, prepared, workerId) {
149
+ if (JSON.stringify(laneRecord(context, prepared.project.id, prepared.lane)) !== JSON.stringify(prepared.workspace)
150
+ || context.db.get("SELECT root FROM projects WHERE id = ?", [prepared.project.id])?.root !== prepared.project.root)
151
+ throw new AppError("lane_workspace_changed", "Lane registration changed after workspace preparation", 1);
152
+ assertWorkerMayAcquireLaneLock(context, prepared.project.id, prepared.lane, workerId);
153
+ }
118
154
  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");
155
+ const { project, lock: preparedLock, ttlSeconds } = prepareLaneLock(context, input, "heartbeat");
156
+ const lock = preparedLock;
126
157
  const now = context.now();
127
158
  context.db.run(`UPDATE lane_locks SET heartbeat_at = ?, expires_at = ?, updated_at = ? WHERE id = ?`, [now, expiresAt(now, ttlSeconds), now, lock.id]);
128
159
  appendAudit(context, {
@@ -133,12 +164,8 @@ export function heartbeatLaneLock(context, input) {
133
164
  return { ok: true, lock: activeLaneLock(context, project.id, lock.lane) };
134
165
  }
135
166
  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);
167
+ const { project, lock: preparedLock } = prepareLaneLock(context, input, "release");
168
+ const lock = preparedLock;
142
169
  const now = context.now();
143
170
  context.db.run(`UPDATE lane_locks
144
171
  SET status = 'released', released_at = ?, reason = ?, updated_at = ?
@@ -152,11 +179,7 @@ export function releaseLaneLock(context, input) {
152
179
  return { ok: true, lock: laneLockById(context, lock.id) };
153
180
  }
154
181
  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");
182
+ const { project, lane, timeoutSeconds, pollIntervalSeconds } = prepareLaneLock(context, input, "wait");
160
183
  const start = Date.now();
161
184
  while (true) {
162
185
  expireStaleLocks(context, project.id);
@@ -186,13 +209,18 @@ export function getLaneWaiters(context, input) {
186
209
  }))
187
210
  };
188
211
  }
189
- export function cancelLaneWaiter(context, input) {
212
+ export function prepareLaneWaiterCancellation(context, input) {
213
+ if (typeof input.workerId !== "string" || !input.workerId.trim())
214
+ throw new AppError("validation", "Lane waiter requires a nonempty worker ID", 2);
215
+ if (typeof input.reason !== "string" || !input.reason.trim())
216
+ throw new AppError("validation", "lane waiter cancel requires --reason", 2);
190
217
  const project = requireProjectByRoot(context, resolveProjectRoot(input.projectRoot));
191
218
  const lane = normalizeLane(input.lane);
192
219
  const reason = input.reason.trim();
193
- if (!reason) {
194
- throw new AppError("validation", "lane waiter cancel requires --reason", 2);
195
- }
220
+ return { project, lane, reason };
221
+ }
222
+ export function cancelLaneWaiter(context, input) {
223
+ const { project, lane, reason } = prepareLaneWaiterCancellation(context, input);
196
224
  expireStaleWaiters(context, project.id);
197
225
  const now = context.now();
198
226
  const waiter = activeLaneWaiterForWorker(context, project.id, lane, input.workerId);
@@ -245,13 +273,7 @@ export function expireLaneWaiterById(context, input) {
245
273
  return { ok: true, expired: result.changes === 1, waiter_id: input.waiterId };
246
274
  }
247
275
  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");
276
+ const { project, lane, timeoutSeconds, pollIntervalSeconds, ttlSeconds } = prepareLaneLock(context, input, "wait-acquire");
255
277
  const startedAt = Date.now();
256
278
  const waiterDeadline = timeoutSeconds > 0 ? new Date(startedAt + timeoutSeconds * 1000).toISOString() : null;
257
279
  while (true) {
@@ -375,10 +397,9 @@ function laneWaitersForProject(context, projectId, lane) {
375
397
  LIMIT 100`, [projectId]);
376
398
  }
377
399
  function activeLaneLock(context, projectId, lane) {
378
- expireStaleLocks(context, projectId);
379
400
  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]);
401
+ WHERE project_id = ? AND lane = ? AND status = 'active' AND expires_at > ?
402
+ ORDER BY updated_at DESC, id DESC LIMIT 1`, [projectId, lane, context.now()]);
382
403
  }
383
404
  function activeLaneWaiterForWorker(context, projectId, lane, workerId) {
384
405
  return context.db.get(`SELECT * FROM lane_waiters
@@ -513,13 +534,15 @@ function ensureQueuedLaneWaiter(context, input) {
513
534
  return waiter;
514
535
  }
515
536
  function tryAcquireQueuedLaneLock(context, input) {
516
- expireStaleLocks(context, input.projectId);
517
- expireStaleWaiters(context, input.projectId);
518
- context.db.exec("BEGIN IMMEDIATE");
519
- try {
537
+ const prepared = prepareLaneLock(context, input, "wait-acquire");
538
+ if (prepared.project.id !== input.projectId || prepared.lane !== input.lane)
539
+ throw new AppError("lane_workspace_changed", "Lane identity changed while waiting", 1);
540
+ return context.db.writeTransaction(() => {
541
+ assertPreparedLaneLock(context, prepared, input.workerId);
542
+ expireStaleLocks(context, input.projectId);
543
+ expireStaleWaiters(context, input.projectId);
520
544
  const existingLock = activeLaneLock(context, input.projectId, input.lane);
521
545
  if (existingLock?.worker_id === input.workerId) {
522
- context.db.exec("COMMIT");
523
546
  return {
524
547
  acquired: true,
525
548
  payload: {
@@ -537,7 +560,6 @@ function tryAcquireQueuedLaneLock(context, input) {
537
560
  }
538
561
  const latest = latestLaneWaiterForWorker(context, input.projectId, input.lane, input.workerId);
539
562
  if (latest && ["cancelled", "expired"].includes(latest.status) && latest.updated_at >= input.invocationStartedAt) {
540
- context.db.exec("COMMIT");
541
563
  return {
542
564
  acquired: false,
543
565
  payload: {
@@ -561,14 +583,14 @@ function tryAcquireQueuedLaneLock(context, input) {
561
583
  });
562
584
  const head = firstQueuedLaneWaiter(context, input.projectId, input.lane);
563
585
  if (!existingLock && head?.id === waiter.id) {
564
- const lockResult = acquireLaneLock(context, {
586
+ const lockResult = acquirePreparedLaneLock(context, {
565
587
  projectRoot: input.projectRoot,
566
588
  lane: input.lane,
567
589
  workerId: input.workerId,
568
590
  workspacePath: input.workspacePath,
569
591
  ttlSeconds: input.ttlSeconds,
570
592
  reason: input.reason
571
- });
593
+ }, prepared);
572
594
  const now = context.now();
573
595
  context.db.run(`UPDATE lane_waiters
574
596
  SET status = 'acquired', acquired_at = ?, updated_at = ?
@@ -580,7 +602,6 @@ function tryAcquireQueuedLaneLock(context, input) {
580
602
  reason: input.reason,
581
603
  payload: { project_id: input.projectId, lane: input.lane, worker_id: input.workerId, waiter_id: waiter.id }
582
604
  });
583
- context.db.exec("COMMIT");
584
605
  return {
585
606
  acquired: true,
586
607
  payload: {
@@ -597,7 +618,6 @@ function tryAcquireQueuedLaneLock(context, input) {
597
618
  };
598
619
  }
599
620
  const position = queuedWaiterPosition(context, input.projectId, input.lane, waiter.id);
600
- context.db.exec("COMMIT");
601
621
  return {
602
622
  acquired: false,
603
623
  payload: {
@@ -611,18 +631,10 @@ function tryAcquireQueuedLaneLock(context, input) {
611
631
  position
612
632
  }
613
633
  };
614
- }
615
- catch (error) {
616
- context.db.exec("ROLLBACK");
617
- throw error;
618
- }
634
+ });
619
635
  }
620
636
  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);
637
+ return resolveProjectRoot(value);
626
638
  }
627
639
  function detectBranch(workspacePath) {
628
640
  const result = spawnSync("git", ["-C", workspacePath, "rev-parse", "--abbrev-ref", "HEAD"], { encoding: "utf8" });
@@ -635,7 +647,7 @@ function expiresAt(now, ttlSeconds) {
635
647
  return new Date(new Date(now).getTime() + ttlSeconds * 1000).toISOString();
636
648
  }
637
649
  function normalizeLane(value) {
638
- const normalized = value.trim().toLowerCase();
650
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
639
651
  if (!normalized || !/^[a-z0-9._-]+$/.test(normalized)) {
640
652
  throw new AppError("validation", "Lane name must contain only lowercase letters, numbers, dot, underscore, or hyphen", 2);
641
653
  }
@@ -643,15 +655,16 @@ function normalizeLane(value) {
643
655
  }
644
656
  function normalizePositiveNumber(value, fallback, label) {
645
657
  const normalized = value ?? fallback;
646
- if (!Number.isFinite(normalized) || normalized <= 0) {
647
- throw new AppError("validation", `--${label} must be a positive number`, 2);
658
+ if (!Number.isFinite(normalized) || normalized <= 0 ||
659
+ (label === "poll-interval" ? normalized * 1000 > 2 ** 31 - 1 : !Number.isFinite(new Date(Date.now() + normalized * 1000).getTime()))) {
660
+ throw new AppError("validation", `--${label} must be a positive number within the supported timer/date range`, 2);
648
661
  }
649
662
  return normalized;
650
663
  }
651
664
  function normalizeNonNegativeNumber(value, fallback, label) {
652
665
  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);
666
+ if (!Number.isFinite(normalized) || normalized < 0 || !Number.isFinite(new Date(Date.now() + normalized * 1000).getTime())) {
667
+ throw new AppError("validation", `--${label} must be zero or a positive number within the supported date range`, 2);
655
668
  }
656
669
  return normalized;
657
670
  }
@@ -1,11 +1,45 @@
1
1
  import path from "node:path";
2
2
  import { parse, quote } from "shell-quote";
3
+ import { lifecycleOperationForArgv } from "./lifecycle-contract.js";
4
+ /** Native hooks and the lightweight ingress must recognize the same shell. */
5
+ export function lifecycleCommandFromPayload(payload) {
6
+ const input = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : {};
7
+ const command = [payload.command, input.command, input.cmd].find(value => typeof value === "string" && value.length > 0);
8
+ return typeof command === "string" ? unwrapShellCommand(command) : undefined;
9
+ }
3
10
  const controlOperators = new Set(["&&", "||", ";", "|", "|&", "&", "(", ")", "<(", ">("]);
4
11
  const redirectionOperators = new Set(["<", ">", ">>", ">|", "<&", ">&", "<<<"]);
5
12
  /** Parse the deliberately small direct-command surface accepted by lifecycle hooks. */
6
13
  export function parseLifecycleCommand(command) {
7
14
  return parseLifecycleCommandInner(command, false);
8
15
  }
16
+ /** Exact diagnostic routes; these deliberately confer no lifecycle authority. */
17
+ export function continuationCommand(command) {
18
+ let entries;
19
+ try {
20
+ entries = parse(command, name => `$${name}`);
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ if (!entries.every(entry => typeof entry === "string"))
26
+ return null;
27
+ const words = entries;
28
+ const start = words.findIndex(word => ["stage", "work"].includes(word));
29
+ if (start < 1)
30
+ return null;
31
+ const launcher = words.slice(0, start);
32
+ while (launcher[0] && /^[A-Za-z_][A-Za-z0-9_]*=/.test(launcher[0]))
33
+ launcher.shift();
34
+ const direct = launcher.length === 1 && (path.basename(launcher[0]) === "dd-flow" || launcher[0] === "$DD_FLOW_BIN");
35
+ const node = launcher.length === 2 && path.basename(launcher[0]) === "node" && (path.basename(launcher[1]) === "cli.js" || launcher[1] === "$DD_FLOW_BIN");
36
+ if (!direct && !node)
37
+ return null;
38
+ const args = parseCommandArgs(words.slice(start));
39
+ const route = args.positional.slice(0, 3).join(" ");
40
+ const operation = route === "work repair add" ? "work_repair_add" : args.positional[0] === "stage" && args.positional[1] === "block" ? "stage_block" : null;
41
+ return operation ? { operation, args } : null;
42
+ }
9
43
  /** Preserve the historical Desktop contract: execute the payload, not its one-command shell wrapper. */
10
44
  export function unwrapShellCommand(command) {
11
45
  let entries;
@@ -32,7 +66,7 @@ function parseLifecycleCommandInner(command, wrapped) {
32
66
  const heredoc = stripHeredocBodies(command);
33
67
  let entries;
34
68
  try {
35
- entries = parse(heredoc.command, (name) => `$${name}`);
69
+ entries = parse(withoutFileDescriptors(heredoc.command), (name) => `$${name}`);
36
70
  }
37
71
  catch {
38
72
  // A command that cannot be tokenized cannot create a trusted claim. The
@@ -56,11 +90,11 @@ function parseLifecycleCommandInner(command, wrapped) {
56
90
  if (!found.length)
57
91
  return { kind: "none" };
58
92
  const first = found[0];
59
- if (found.length !== 1 || composed || first.nestedCompound) {
93
+ if (found.length !== 1 || composed || first.nestedCompound || (heredoc.present && !heredoc.safe)) {
60
94
  return {
61
95
  kind: "compound",
62
96
  invocation: { ...first.invocation, rewriteSafe: false },
63
- reason: found.length !== 1 ? "multiple_lifecycle_invocations" : first.nestedCompound ? "nested_compound_invocation" : "shell_composition"
97
+ reason: found.length !== 1 ? "multiple_lifecycle_invocations" : first.nestedCompound ? "nested_compound_invocation" : heredoc.present && !heredoc.safe ? "unsafe_heredoc" : "shell_composition"
64
98
  };
65
99
  }
66
100
  return { kind: "standalone", invocation: first.invocation };
@@ -126,8 +160,16 @@ function invocationFromSegment(segment, heredoc, wrapped, inheritedEnv) {
126
160
  index += 1;
127
161
  }
128
162
  }
129
- const executable = segment.words[index];
130
- if (!executable || path.basename(executable) !== "dd-flow")
163
+ let executable = segment.words[index];
164
+ let nodeLauncher = false;
165
+ let launcher;
166
+ if (executable && path.basename(executable) === "node"
167
+ && (path.basename(segment.words[index + 1] ?? "") === "cli.js" || segment.words[index + 1] === "$DD_FLOW_BIN")) {
168
+ launcher = executable;
169
+ executable = segment.words[++index];
170
+ nodeLauncher = true;
171
+ }
172
+ if (!executable || path.basename(executable) !== "dd-flow" && executable !== "$DD_FLOW_BIN" && !(nodeLauncher && path.basename(executable) === "cli.js"))
131
173
  return null;
132
174
  const argv = segment.words.slice(index + 1);
133
175
  const operation = lifecycleOperation(argv);
@@ -136,9 +178,10 @@ function invocationFromSegment(segment, heredoc, wrapped, inheritedEnv) {
136
178
  return {
137
179
  operation,
138
180
  executable,
181
+ ...(launcher ? { launcher } : {}),
139
182
  argv,
140
183
  env,
141
- args: parseCommandArgs(argv.slice(2)),
184
+ args: parseCommandArgs(argv.slice(operation === "recovery_accept" ? 3 : 2)),
142
185
  command: quote(segment.words),
143
186
  rewriteSafe: !heredoc && !wrapped && !segment.dynamic,
144
187
  wrapped,
@@ -170,16 +213,7 @@ function wrappedInvocationFromSegment(segment) {
170
213
  return parseLifecycleCommandInner(payload, true);
171
214
  }
172
215
  function lifecycleOperation(argv) {
173
- const key = `${argv[0] ?? ""} ${argv[1] ?? ""}`;
174
- if (key === "session register")
175
- return "session_register";
176
- if (key === "stage start")
177
- return "stage_start";
178
- if (key === "stage resume")
179
- return "stage_resume";
180
- if (key === "work start")
181
- return "work_start";
182
- return null;
216
+ return lifecycleOperationForArgv(argv);
183
217
  }
184
218
  export function parseCommandArgs(argv) {
185
219
  const positional = [];
@@ -187,6 +221,12 @@ export function parseCommandArgs(argv) {
187
221
  for (let index = 0; index < argv.length; index += 1) {
188
222
  const value = argv[index];
189
223
  if (value?.startsWith("--")) {
224
+ const equals = value.indexOf("=");
225
+ if (equals > 2) {
226
+ const key = value.slice(2, equals);
227
+ options.set(key, [...(options.get(key) ?? []), value.slice(equals + 1)]);
228
+ continue;
229
+ }
190
230
  const key = value.slice(2);
191
231
  const next = argv[index + 1];
192
232
  const optionValue = !next || next.startsWith("--") ? "__dd_flow_flag__" : next;
@@ -213,6 +253,58 @@ export function commandPosition(invocation, index) {
213
253
  function assignment(word) {
214
254
  return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
215
255
  }
256
+ /** Source offsets matter: shell-quote loses the difference between `2>&1`
257
+ * and the literal argument `2 >&1`. Only inspect unquoted shell syntax. */
258
+ function shellSyntaxOffsets(command) {
259
+ const offsets = [];
260
+ let quoted = null, escaped = false;
261
+ for (let i = 0; i < command.length; i++) {
262
+ const char = command[i];
263
+ if (escaped) {
264
+ escaped = false;
265
+ continue;
266
+ }
267
+ if (char === "\\" && quoted !== "'") {
268
+ escaped = true;
269
+ continue;
270
+ }
271
+ if (quoted) {
272
+ if (char === quoted)
273
+ quoted = null;
274
+ continue;
275
+ }
276
+ if (char === "'" || char === '"') {
277
+ quoted = char;
278
+ continue;
279
+ }
280
+ if (char === "#" && (i === 0 || /\s/.test(command[i - 1]))) {
281
+ offsets.push(i);
282
+ break;
283
+ }
284
+ if (char === "<" || char === ">")
285
+ offsets.push(i);
286
+ }
287
+ return offsets;
288
+ }
289
+ function descriptorStart(command, index) {
290
+ let start = index;
291
+ while (start > 0 && /[0-9]/.test(command[start - 1]))
292
+ start--;
293
+ return start === 0 || /[\s;&|]/.test(command[start - 1]) ? start : index;
294
+ }
295
+ export function shellSuffixOffset(command) {
296
+ const offset = shellSyntaxOffsets(command)[0];
297
+ return offset === undefined ? command.length : descriptorStart(command, offset);
298
+ }
299
+ function withoutFileDescriptors(command) {
300
+ for (const index of shellSyntaxOffsets(command).reverse()) {
301
+ if (command[index] === "#")
302
+ continue;
303
+ const start = descriptorStart(command, index);
304
+ command = command.slice(0, start) + command.slice(index);
305
+ }
306
+ return command;
307
+ }
216
308
  function addAssignment(env, word) {
217
309
  const separator = word.indexOf("=");
218
310
  env[word.slice(0, separator)] = word.slice(separator + 1);
@@ -223,6 +315,7 @@ function stripHeredocBodies(command) {
223
315
  const pending = [];
224
316
  let active;
225
317
  let present = false;
318
+ let count = 0, quoted = true;
226
319
  for (const line of lines) {
227
320
  if (active) {
228
321
  const candidate = active.stripTabs ? line.replace(/^\t+/, "") : line;
@@ -233,13 +326,15 @@ function stripHeredocBodies(command) {
233
326
  if (line.trim())
234
327
  output.push(line);
235
328
  const found = heredocDelimiters(line);
329
+ count += found.length;
330
+ quoted &&= found.every(item => item.quoted);
236
331
  if (found.length) {
237
332
  present = true;
238
333
  active = found[0];
239
334
  pending.push(...found.slice(1));
240
335
  }
241
336
  }
242
- return { command: output.join(" ; "), present };
337
+ return { command: output.join(" ; "), present, safe: count === 1 && quoted && !active && pending.length === 0 };
243
338
  }
244
339
  function heredocDelimiters(line) {
245
340
  const result = [];
@@ -282,7 +377,7 @@ function heredocDelimiters(line) {
282
377
  index += 1;
283
378
  const delimiter = line.slice(start, index);
284
379
  if (delimiter)
285
- result.push({ delimiter, stripTabs });
380
+ result.push({ delimiter, stripTabs, quoted: delimiterQuote !== null });
286
381
  }
287
382
  return result;
288
383
  }
@@ -0,0 +1,30 @@
1
+ export const lifecycleRoutes = {
2
+ "session register": "session_register",
3
+ "stage start": "stage_start",
4
+ "stage finish": "stage_finish",
5
+ "stage pause": "stage_pause",
6
+ "stage resume": "stage_resume",
7
+ "work start": "work_start",
8
+ "work finish": "work_finish",
9
+ "work fail": "work_fail",
10
+ "merge apply": "merge_apply",
11
+ "merge repair": "merge_repair",
12
+ "run recovery accept": "recovery_accept"
13
+ };
14
+ export const lifecycleInternalOptions = ["invocation-id", "hook-event-id"];
15
+ export function lifecycleOperationForArgv(argv) {
16
+ if (argv.some(arg => arg === "--help" || arg === "-h"))
17
+ return null;
18
+ for (const [route, operation] of Object.entries(lifecycleRoutes)) {
19
+ const parts = route.split(" ");
20
+ if (parts.every((part, index) => argv[index] === part))
21
+ return operation;
22
+ }
23
+ return null;
24
+ }
25
+ export function lifecycleRouteForOperation(operation) {
26
+ const entry = Object.entries(lifecycleRoutes).find(([, value]) => value === operation);
27
+ if (!entry)
28
+ throw new Error(`Unknown lifecycle operation: ${operation}`);
29
+ return entry[0];
30
+ }