@deksden-com/dd-flow-cli 0.9.0-beta.13 → 0.9.0-beta.133

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 (204) hide show
  1. package/CHANGELOG.md +666 -0
  2. package/README.md +101 -1
  3. package/dist/build-info.json +10 -10
  4. package/dist/cli/argument-values.js +38 -0
  5. package/dist/cli/command-inputs.js +306 -0
  6. package/dist/cli/help.js +88 -12
  7. package/dist/cli/hook-ingress.js +78 -0
  8. package/dist/cli/input-preparation.js +116 -0
  9. package/dist/cli/native-hook-ingress.js +80 -0
  10. package/dist/cli/run-cli.js +1465 -450
  11. package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
  12. package/dist/cli/runtime-maintenance-ingress.js +52 -0
  13. package/dist/cli/runtime-process.js +153 -0
  14. package/dist/cli.js +17 -2
  15. package/dist/domain/stage-catalog.js +1 -1
  16. package/dist/harness-runtime/DD-ZCODE.md +99 -0
  17. package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
  18. package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
  19. package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
  20. package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
  21. package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
  22. package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
  23. package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
  24. package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
  25. package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
  26. package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
  27. package/dist/harness-runtime/lib/codex-capacity-policy.d.mts +10 -0
  28. package/dist/harness-runtime/lib/codex-capacity-policy.mjs +89 -0
  29. package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
  30. package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
  31. package/dist/harness-runtime/lib/daemon-operations.mjs +370 -0
  32. package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
  33. package/dist/harness-runtime/lib/dd-agy-daemon.mjs +693 -0
  34. package/dist/harness-runtime/lib/dd-agy.mjs +59 -0
  35. package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
  36. package/dist/harness-runtime/lib/dd-codex-daemon.mjs +190 -0
  37. package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
  38. package/dist/harness-runtime/lib/dd-codex.mjs +805 -0
  39. package/dist/harness-runtime/lib/dd-droid-daemon.mjs +128 -0
  40. package/dist/harness-runtime/lib/dd-droid.mjs +561 -0
  41. package/dist/harness-runtime/lib/dd-grok-daemon.mjs +490 -0
  42. package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
  43. package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +255 -0
  44. package/dist/harness-runtime/lib/dd-opencode.mjs +128 -0
  45. package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +703 -0
  46. package/dist/harness-runtime/lib/dd-zcode.mjs +1108 -0
  47. package/dist/harness-runtime/lib/delegation-instructions.d.mts +13 -0
  48. package/dist/harness-runtime/lib/delegation-instructions.mjs +144 -0
  49. package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
  50. package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
  51. package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
  52. package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
  53. package/dist/harness-runtime/lib/lease-renewal.mjs +36 -0
  54. package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
  55. package/dist/harness-runtime/lib/lifecycle-command.mjs +272 -0
  56. package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
  57. package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
  58. package/dist/harness-runtime/lib/managed-daemon.d.mts +12 -0
  59. package/dist/harness-runtime/lib/managed-daemon.mjs +619 -0
  60. package/dist/harness-runtime/lib/model-observations.mjs +101 -0
  61. package/dist/harness-runtime/lib/native-children.d.mts +13 -0
  62. package/dist/harness-runtime/lib/native-children.mjs +78 -0
  63. package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
  64. package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
  65. package/dist/harness-runtime/lib/native-streams.mjs +45 -0
  66. package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
  67. package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
  68. package/dist/harness-runtime/lib/operation-context.mjs +5 -0
  69. package/dist/harness-runtime/lib/operation-errors.d.mts +14 -0
  70. package/dist/harness-runtime/lib/operation-errors.mjs +116 -0
  71. package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
  72. package/dist/harness-runtime/lib/operation-progress.mjs +112 -0
  73. package/dist/harness-runtime/lib/process-json.d.mts +5 -0
  74. package/dist/harness-runtime/lib/process-json.mjs +201 -0
  75. package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
  76. package/dist/harness-runtime/lib/runner-events.mjs +200 -0
  77. package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
  78. package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
  79. package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
  80. package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
  81. package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
  82. package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
  83. package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
  84. package/dist/protocol/local-files.js +18 -9
  85. package/dist/runtime/context.js +8 -4
  86. package/dist/schemas/agent-profile.schema.json +1 -1
  87. package/dist/schemas/code-review-result.schema.json +1 -1
  88. package/dist/schemas/code-verification.schema.json +7 -5
  89. package/dist/schemas/code-work-batch.schema.json +2 -2
  90. package/dist/schemas/flow-run.schema.json +2 -0
  91. package/dist/schemas/plan-review-decision.schema.json +3 -3
  92. package/dist/schemas/plan-review-result.schema.json +2 -2
  93. package/dist/schemas/run-control-receipt.schema.json +118 -0
  94. package/dist/schemas/run-control-request.schema.json +36 -0
  95. package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
  96. package/dist/services/branch-context.js +3 -3
  97. package/dist/services/canon.js +11 -8
  98. package/dist/services/check-runner-evidence.js +121 -0
  99. package/dist/services/cleanup.js +133 -40
  100. package/dist/services/cli-operation-classifier.js +22 -24
  101. package/dist/services/code-checks.js +851 -109
  102. package/dist/services/codex-capacity.js +367 -0
  103. package/dist/services/codex-hook-delivery.js +32 -0
  104. package/dist/services/command-context.js +80 -0
  105. package/dist/services/compatibility-preflight.js +13 -3
  106. package/dist/services/config.js +11 -8
  107. package/dist/services/continuation-outcome.js +20 -0
  108. package/dist/services/controller-fanout.js +119 -0
  109. package/dist/services/dashboard.js +135 -56
  110. package/dist/services/engines.js +245 -119
  111. package/dist/services/eval-snapshots.js +1146 -105
  112. package/dist/services/execution-policy.js +181 -0
  113. package/dist/services/external-work-launch.js +230 -0
  114. package/dist/services/harness-adapter.js +329 -36
  115. package/dist/services/harness-config.js +2 -0
  116. package/dist/services/hooks.js +747 -325
  117. package/dist/services/lanes.js +78 -65
  118. package/dist/services/lifecycle-command.js +1 -288
  119. package/dist/services/lifecycle-contract.js +1 -0
  120. package/dist/services/lifecycle-invocations.js +1774 -0
  121. package/dist/services/managed-daemon-binding.js +38 -0
  122. package/dist/services/managed-lease-monitor.js +133 -0
  123. package/dist/services/managed-processes.js +409 -51
  124. package/dist/services/merge-queue.js +228 -149
  125. package/dist/services/merge-server.js +163 -35
  126. package/dist/services/migrations.js +37 -16
  127. package/dist/services/native-daemon-history.js +49 -0
  128. package/dist/services/native-session-control.js +39 -0
  129. package/dist/services/plan-runtime.js +26 -11
  130. package/dist/services/plans.js +28 -25
  131. package/dist/services/projects.js +20 -15
  132. package/dist/services/prompts.js +28 -17
  133. package/dist/services/protocols.js +163 -87
  134. package/dist/services/recovery-observation-budget.js +121 -0
  135. package/dist/services/recovery-snapshot-database.js +145 -0
  136. package/dist/services/repair-intents.js +42 -0
  137. package/dist/services/review-copy.js +157 -0
  138. package/dist/services/review-deferral.js +23 -0
  139. package/dist/services/run-control-receipt.js +56 -0
  140. package/dist/services/run-control-worker.js +411 -0
  141. package/dist/services/run-control.js +985 -0
  142. package/dist/services/run-controller-adapter.js +399 -0
  143. package/dist/services/run-controller-capture.js +179 -0
  144. package/dist/services/run-controller-process.js +187 -0
  145. package/dist/services/run-controller-recovery.js +289 -0
  146. package/dist/services/run-controller-state.js +97 -0
  147. package/dist/services/run-controller.js +1035 -0
  148. package/dist/services/run-engine-bindings.js +1 -1
  149. package/dist/services/run-fork.js +147 -0
  150. package/dist/services/run-observations.js +152 -0
  151. package/dist/services/run-projection.js +22 -64
  152. package/dist/services/run-recovery-guard.js +75 -0
  153. package/dist/services/run-recovery-runtime.js +112 -0
  154. package/dist/services/run-recovery.js +349 -0
  155. package/dist/services/runs.js +558 -217
  156. package/dist/services/runtime-budget.js +430 -0
  157. package/dist/services/runtime-command.js +43 -0
  158. package/dist/services/runtime-scope-capture.js +52 -0
  159. package/dist/services/runtime-scope-control.js +468 -0
  160. package/dist/services/runtime-scope-resume.js +599 -0
  161. package/dist/services/runtime-scope-stop.js +180 -0
  162. package/dist/services/runtime-scope-worker.js +287 -0
  163. package/dist/services/runtime-service.js +96 -0
  164. package/dist/services/schema-validation.js +10 -8
  165. package/dist/services/scope-writer-cleanup.js +27 -0
  166. package/dist/services/sessions.js +35 -69
  167. package/dist/services/stage-blocker.js +17 -7
  168. package/dist/services/stage-context.js +185 -19
  169. package/dist/services/stage-lifecycle.js +98 -107
  170. package/dist/services/stage-pause.js +89 -75
  171. package/dist/services/stage-report-renderer.js +158 -6
  172. package/dist/services/stage-work-graph.js +35 -0
  173. package/dist/services/tooling.js +32 -23
  174. package/dist/services/usage.js +49 -101
  175. package/dist/services/verification-matrix.js +374 -0
  176. package/dist/services/vnext-code-review.js +222 -87
  177. package/dist/services/vnext-code.js +324 -251
  178. package/dist/services/vnext-contracts.js +10 -1
  179. package/dist/services/vnext-execution-profile.js +79 -4
  180. package/dist/services/vnext-fanout.js +177 -17
  181. package/dist/services/vnext-merge.js +335 -113
  182. package/dist/services/vnext-plan-review.js +276 -126
  183. package/dist/services/vnext-plan.js +227 -102
  184. package/dist/services/vnext-protocolize.js +335 -82
  185. package/dist/services/vnext-specify.js +119 -81
  186. package/dist/services/work-registry.js +1038 -192
  187. package/dist/services/workspace-bootstrap.js +87 -0
  188. package/dist/services/workspace-files.js +85 -0
  189. package/dist/services/worktrees.js +98 -44
  190. package/dist/shared/entity-references.js +8 -0
  191. package/dist/shared/errors.js +17 -0
  192. package/dist/storage/agent-output.js +26 -0
  193. package/dist/storage/database.js +781 -37
  194. package/dist/storage/foreign-key-transaction.js +39 -0
  195. package/dist/storage/immutable-input.js +45 -0
  196. package/dist/storage/import-guard.js +102 -0
  197. package/dist/storage/native-cleanup.js +52 -0
  198. package/dist/storage/paths.js +17 -4
  199. package/dist/storage/projection-lock.js +73 -0
  200. package/dist/storage/work-references.js +23 -0
  201. package/dist/storage/writer-contract.js +77 -0
  202. package/dist/storage/writer-migration.js +85 -0
  203. package/package.json +30 -13
  204. 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,288 +1 @@
1
- import path from "node:path";
2
- import { parse, quote } from "shell-quote";
3
- const controlOperators = new Set(["&&", "||", ";", "|", "|&", "&", "(", ")", "<(", ">("]);
4
- const redirectionOperators = new Set(["<", ">", ">>", ">|", "<&", ">&", "<<<"]);
5
- /** Parse the deliberately small direct-command surface accepted by lifecycle hooks. */
6
- export function parseLifecycleCommand(command) {
7
- return parseLifecycleCommandInner(command, false);
8
- }
9
- /** Preserve the historical Desktop contract: execute the payload, not its one-command shell wrapper. */
10
- export function unwrapShellCommand(command) {
11
- let entries;
12
- try {
13
- entries = parse(command, (name) => `$${name}`);
14
- }
15
- catch {
16
- return command;
17
- }
18
- if (!entries.every((entry) => typeof entry === "string"))
19
- return command;
20
- const words = entries;
21
- let index = 0;
22
- while (index < words.length && assignment(words[index]))
23
- index += 1;
24
- const executable = path.basename(words[index] ?? "");
25
- if (!new Set(["bash", "sh", "zsh"]).has(executable))
26
- return command;
27
- if (!new Set(["-c", "-lc", "-cl"]).has(words[index + 1] ?? "") || words.length !== index + 3)
28
- return command;
29
- return words[index + 2] ?? command;
30
- }
31
- function parseLifecycleCommandInner(command, wrapped) {
32
- const heredoc = stripHeredocBodies(command);
33
- let entries;
34
- try {
35
- entries = parse(heredoc.command, (name) => `$${name}`);
36
- }
37
- catch {
38
- // A command that cannot be tokenized cannot create a trusted claim. The
39
- // real lifecycle CLI will consequently fail its binding requirement.
40
- return { kind: "none" };
41
- }
42
- const { segments, composed } = commandSegments(entries);
43
- const found = [];
44
- const exportedEnv = {};
45
- for (const segment of segments) {
46
- Object.assign(exportedEnv, exportedAssignments(segment));
47
- const direct = invocationFromSegment(segment, heredoc.present, wrapped, exportedEnv);
48
- if (direct) {
49
- found.push({ invocation: direct, nestedCompound: segment.dynamic });
50
- continue;
51
- }
52
- const nested = wrappedInvocationFromSegment(segment);
53
- if (nested && nested.kind !== "none")
54
- found.push({ invocation: { ...nested.invocation, heredoc: nested.invocation.heredoc || heredoc.present, rewriteSafe: false, wrapped: true }, nestedCompound: nested.kind === "compound" });
55
- }
56
- if (!found.length)
57
- return { kind: "none" };
58
- const first = found[0];
59
- if (found.length !== 1 || composed || first.nestedCompound) {
60
- return {
61
- kind: "compound",
62
- invocation: { ...first.invocation, rewriteSafe: false },
63
- reason: found.length !== 1 ? "multiple_lifecycle_invocations" : first.nestedCompound ? "nested_compound_invocation" : "shell_composition"
64
- };
65
- }
66
- return { kind: "standalone", invocation: first.invocation };
67
- }
68
- function commandSegments(entries) {
69
- const segments = [];
70
- let words = [];
71
- let dynamic = false;
72
- let composed = false;
73
- const flush = () => {
74
- if (words.length || dynamic)
75
- segments.push({ words, dynamic });
76
- words = [];
77
- dynamic = false;
78
- };
79
- for (let index = 0; index < entries.length; index += 1) {
80
- const entry = entries[index];
81
- if (typeof entry === "string") {
82
- words.push(entry);
83
- continue;
84
- }
85
- if ("comment" in entry)
86
- break;
87
- if (!("op" in entry) || typeof entry.op !== "string") {
88
- dynamic = true;
89
- continue;
90
- }
91
- const operator = entry.op;
92
- if (operator === "glob") {
93
- dynamic = true;
94
- words.push("pattern" in entry && typeof entry.pattern === "string" ? entry.pattern : "");
95
- continue;
96
- }
97
- if (controlOperators.has(operator)) {
98
- composed = true;
99
- flush();
100
- continue;
101
- }
102
- if (redirectionOperators.has(operator)) {
103
- const target = entries[index + 1];
104
- if (typeof target === "string" || (target && typeof target === "object" && "op" in target && target.op === "glob"))
105
- index += 1;
106
- continue;
107
- }
108
- dynamic = true;
109
- }
110
- flush();
111
- return { segments, composed };
112
- }
113
- function invocationFromSegment(segment, heredoc, wrapped, inheritedEnv) {
114
- let index = 0;
115
- const env = { ...inheritedEnv };
116
- while (index < segment.words.length && assignment(segment.words[index])) {
117
- addAssignment(env, segment.words[index]);
118
- index += 1;
119
- }
120
- if (path.basename(segment.words[index] ?? "") === "env") {
121
- index += 1;
122
- if (segment.words[index]?.startsWith("-"))
123
- return null;
124
- while (index < segment.words.length && assignment(segment.words[index])) {
125
- addAssignment(env, segment.words[index]);
126
- index += 1;
127
- }
128
- }
129
- const executable = segment.words[index];
130
- if (!executable || path.basename(executable) !== "dd-flow")
131
- return null;
132
- const argv = segment.words.slice(index + 1);
133
- const operation = lifecycleOperation(argv);
134
- if (!operation)
135
- return null;
136
- return {
137
- operation,
138
- executable,
139
- argv,
140
- env,
141
- args: parseCommandArgs(argv.slice(2)),
142
- command: quote(segment.words),
143
- rewriteSafe: !heredoc && !wrapped && !segment.dynamic,
144
- wrapped,
145
- heredoc
146
- };
147
- }
148
- function exportedAssignments(segment) {
149
- const result = {};
150
- if (segment.words[0] !== "export")
151
- return result;
152
- for (const word of segment.words.slice(1)) {
153
- if (!assignment(word))
154
- return {};
155
- addAssignment(result, word);
156
- }
157
- return result;
158
- }
159
- function wrappedInvocationFromSegment(segment) {
160
- let index = 0;
161
- while (index < segment.words.length && assignment(segment.words[index]))
162
- index += 1;
163
- const executable = path.basename(segment.words[index] ?? "");
164
- if (!new Set(["bash", "sh", "zsh"]).has(executable))
165
- return null;
166
- const flag = segment.words[index + 1];
167
- const payload = segment.words[index + 2];
168
- if (!payload || !new Set(["-c", "-lc", "-cl"]).has(flag ?? "") || segment.words.length !== index + 3)
169
- return null;
170
- return parseLifecycleCommandInner(payload, true);
171
- }
172
- 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;
183
- }
184
- export function parseCommandArgs(argv) {
185
- const positional = [];
186
- const options = new Map();
187
- for (let index = 0; index < argv.length; index += 1) {
188
- const value = argv[index];
189
- if (value?.startsWith("--")) {
190
- const key = value.slice(2);
191
- const next = argv[index + 1];
192
- const optionValue = !next || next.startsWith("--") ? "__dd_flow_flag__" : next;
193
- options.set(key, [...(options.get(key) ?? []), optionValue]);
194
- if (optionValue !== "__dd_flow_flag__")
195
- index += 1;
196
- }
197
- else if (value)
198
- positional.push(value);
199
- }
200
- return { positional, options };
201
- }
202
- export function commandOption(invocation, name) {
203
- const values = invocation.args.options.get(name);
204
- const value = values?.[values.length - 1];
205
- return value === "__dd_flow_flag__" ? undefined : value;
206
- }
207
- export function commandHasOption(invocation, name) {
208
- return invocation.args.options.has(name);
209
- }
210
- export function commandPosition(invocation, index) {
211
- return invocation.args.positional[index];
212
- }
213
- function assignment(word) {
214
- return /^[A-Za-z_][A-Za-z0-9_]*=/.test(word);
215
- }
216
- function addAssignment(env, word) {
217
- const separator = word.indexOf("=");
218
- env[word.slice(0, separator)] = word.slice(separator + 1);
219
- }
220
- function stripHeredocBodies(command) {
221
- const lines = command.split(/\r?\n/);
222
- const output = [];
223
- const pending = [];
224
- let active;
225
- let present = false;
226
- for (const line of lines) {
227
- if (active) {
228
- const candidate = active.stripTabs ? line.replace(/^\t+/, "") : line;
229
- if (candidate === active.delimiter)
230
- active = pending.shift();
231
- continue;
232
- }
233
- if (line.trim())
234
- output.push(line);
235
- const found = heredocDelimiters(line);
236
- if (found.length) {
237
- present = true;
238
- active = found[0];
239
- pending.push(...found.slice(1));
240
- }
241
- }
242
- return { command: output.join(" ; "), present };
243
- }
244
- function heredocDelimiters(line) {
245
- const result = [];
246
- let quoteState = null;
247
- let escaped = false;
248
- for (let index = 0; index < line.length - 1; index += 1) {
249
- const char = line[index];
250
- if (escaped) {
251
- escaped = false;
252
- continue;
253
- }
254
- if (char === "\\" && quoteState !== "'") {
255
- escaped = true;
256
- continue;
257
- }
258
- if (quoteState) {
259
- if (char === quoteState)
260
- quoteState = null;
261
- continue;
262
- }
263
- if (char === "'" || char === '"') {
264
- quoteState = char;
265
- continue;
266
- }
267
- if (char !== "<" || line[index + 1] !== "<" || line[index + 2] === "<")
268
- continue;
269
- index += 2;
270
- const stripTabs = line[index] === "-";
271
- if (stripTabs)
272
- index += 1;
273
- while (/\s/.test(line[index] ?? ""))
274
- index += 1;
275
- const delimiterQuote = line[index] === "'" || line[index] === '"' ? line[index++] : null;
276
- const start = index;
277
- if (delimiterQuote)
278
- while (index < line.length && line[index] !== delimiterQuote)
279
- index += 1;
280
- else
281
- while (index < line.length && !/[\s;&|<>]/.test(line[index]))
282
- index += 1;
283
- const delimiter = line.slice(start, index);
284
- if (delimiter)
285
- result.push({ delimiter, stripTabs });
286
- }
287
- return result;
288
- }
1
+ export { lifecycleCommandFromPayload, parseLifecycleCommand, continuationCommand, unwrapShellCommand, parseCommandArgs, commandOption, commandHasOption, commandPosition, shellSuffixOffset } from "../harness-runtime/lib/lifecycle-command.mjs";
@@ -0,0 +1 @@
1
+ export { lifecycleRoutes, lifecycleInternalOptions, lifecycleOperationForArgv, lifecycleRouteForOperation } from "../harness-runtime/lib/lifecycle-contract.mjs";