@indigoai-us/hq-cli 5.312.2-beta.0 → 5.314.0

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 (1144) hide show
  1. package/CHANGELOG.md +1 -4293
  2. package/assets/scaffold/core/scripts/checkpoint-stop-gate.sh +43 -281
  3. package/assets/scaffold/core/scripts/hook-lib.sh +50 -345
  4. package/assets/scaffold/core/scripts/hq-session.sh +23 -184
  5. package/assets/scaffold/core/scripts/lib/session-id.sh +2 -3
  6. package/assets/scaffold/core/scripts/lib/session-scope-capability.sh +1 -1
  7. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +1 -2
  8. package/assets/scaffold/core/scripts/qmd-reindex-after-sync.sh +87 -10
  9. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +3 -36
  10. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +12 -99
  11. package/assets/scaffold/core/scripts/token-usage-report.sh +20 -81
  12. package/dist/bin/hq-auth-refresh.d.ts +0 -2
  13. package/dist/bin/hq-auth-refresh.js +6 -12
  14. package/dist/commands/__fixtures__/access-vault.d.ts +0 -2
  15. package/dist/commands/__fixtures__/access-vault.js +1 -1
  16. package/dist/commands/_patterns.d.ts +0 -16
  17. package/dist/commands/_patterns.js +3 -20
  18. package/dist/commands/access.d.ts +1 -2
  19. package/dist/commands/access.js +49 -58
  20. package/dist/commands/agents.d.ts +4 -106
  21. package/dist/commands/agents.js +45 -924
  22. package/dist/commands/auth.d.ts +0 -1
  23. package/dist/commands/auth.js +19 -189
  24. package/dist/commands/billing.d.ts +0 -3
  25. package/dist/commands/billing.js +1 -6
  26. package/dist/commands/channels.js +1 -56
  27. package/dist/commands/cloud-demote.js +2 -3
  28. package/dist/commands/cloud-provision.d.ts +0 -14
  29. package/dist/commands/cloud-provision.js +58 -232
  30. package/dist/commands/cloud.d.ts +15 -49
  31. package/dist/commands/cloud.js +122 -358
  32. package/dist/commands/company-transfer.d.ts +28 -4
  33. package/dist/commands/company-transfer.js +49 -5
  34. package/dist/commands/company.js +3 -66
  35. package/dist/commands/core-checkpoint.d.ts +9 -19
  36. package/dist/commands/core-checkpoint.js +37 -301
  37. package/dist/commands/core.d.ts +0 -4
  38. package/dist/commands/core.js +80 -270
  39. package/dist/commands/crm.js +3 -52
  40. package/dist/commands/db-provision.js +4 -4
  41. package/dist/commands/db-sql.js +21 -7
  42. package/dist/commands/dm.d.ts +12 -119
  43. package/dist/commands/dm.js +38 -388
  44. package/dist/commands/doctor.d.ts +0 -12
  45. package/dist/commands/doctor.js +12 -158
  46. package/dist/commands/feedback.d.ts +0 -6
  47. package/dist/commands/feedback.js +37 -86
  48. package/dist/commands/files-browse.d.ts +12 -32
  49. package/dist/commands/files-browse.js +60 -176
  50. package/dist/commands/files.d.ts +0 -17
  51. package/dist/commands/files.js +47 -300
  52. package/dist/commands/group-grants.js +2 -3
  53. package/dist/commands/groups.js +5 -6
  54. package/dist/commands/index-cmd.d.ts +1 -19
  55. package/dist/commands/index-cmd.js +7 -74
  56. package/dist/commands/integrations-api.d.ts +10 -15
  57. package/dist/commands/integrations-api.js +22 -27
  58. package/dist/commands/integrations-connect.d.ts +13 -51
  59. package/dist/commands/integrations-connect.js +71 -86
  60. package/dist/commands/integrations-core.d.ts +6 -6
  61. package/dist/commands/integrations-core.js +11 -25
  62. package/dist/commands/integrations-import.d.ts +1 -1
  63. package/dist/commands/integrations-import.js +24 -43
  64. package/dist/commands/integrations-manage.js +13 -20
  65. package/dist/commands/integrations.d.ts +0 -8
  66. package/dist/commands/integrations.js +7 -94
  67. package/dist/commands/login.js +6 -49
  68. package/dist/commands/mcp-registration.d.ts +25 -32
  69. package/dist/commands/mcp-registration.js +23 -256
  70. package/dist/commands/mcp-status.js +0 -1
  71. package/dist/commands/meetings.js +34 -55
  72. package/dist/commands/members.js +1 -5
  73. package/dist/commands/mesh.d.ts +0 -11
  74. package/dist/commands/mesh.js +76 -1086
  75. package/dist/commands/onboard-identity-guard.d.ts +1 -1
  76. package/dist/commands/onboard.js +5 -24
  77. package/dist/commands/pack-install.js +1 -3
  78. package/dist/commands/packs.js +1 -11
  79. package/dist/commands/people.d.ts +0 -4
  80. package/dist/commands/people.js +3 -37
  81. package/dist/commands/publish.d.ts +1 -8
  82. package/dist/commands/publish.js +4 -17
  83. package/dist/commands/reindex.js +6 -56
  84. package/dist/commands/rescue.d.ts +0 -4
  85. package/dist/commands/rescue.js +17 -27
  86. package/dist/commands/run.js +4 -18
  87. package/dist/commands/safe-extract.d.ts +2 -11
  88. package/dist/commands/safe-extract.js +8 -36
  89. package/dist/commands/scaffold-fast.d.ts +41 -0
  90. package/dist/commands/scaffold-fast.js +57 -0
  91. package/dist/commands/secrets.d.ts +2 -20
  92. package/dist/commands/secrets.js +71 -175
  93. package/dist/commands/skill.d.ts +4 -35
  94. package/dist/commands/skill.js +18 -357
  95. package/dist/commands/sync-mode.d.ts +0 -11
  96. package/dist/commands/sync-mode.js +0 -30
  97. package/dist/commands/sync-narrow.js +5 -36
  98. package/dist/commands/team-sync.js +10 -71
  99. package/dist/commands/update.js +0 -6
  100. package/dist/commands/whoami.d.ts +0 -22
  101. package/dist/commands/whoami.js +4 -137
  102. package/dist/commands/workers.d.ts +14 -2
  103. package/dist/commands/workers.js +10 -7
  104. package/dist/fast-core.d.ts +7 -6
  105. package/dist/fast-core.js +24 -80
  106. package/dist/index.d.ts +4 -3
  107. package/dist/index.js +9 -59
  108. package/dist/lazy-commands.d.ts +44 -20
  109. package/dist/lazy-commands.js +58 -60
  110. package/dist/lib/company-skill-wrapper.d.ts +0 -1
  111. package/dist/lib/company-skill-wrapper.js +29 -121
  112. package/dist/lib/core-utils/codex-skill-bridge.d.ts +1 -2
  113. package/dist/lib/core-utils/qmd-reindex-after-sync.d.ts +1 -14
  114. package/dist/lib/core-utils/qmd-reindex-after-sync.js +17 -101
  115. package/dist/lib/core-utils/soft-timeout.js +1 -1
  116. package/dist/lib/core-utils/timeout-guard.d.ts +3 -3
  117. package/dist/lib/core-utils/timeout-guard.js +13 -28
  118. package/dist/lib/core-utils/token-usage-report.js +3 -17
  119. package/dist/lib/db/control-plane.js +0 -6
  120. package/dist/lib/db/local.d.ts +5 -0
  121. package/dist/lib/db/local.js +1 -1
  122. package/dist/lib/db/migrate.d.ts +12 -0
  123. package/dist/lib/db/migrate.js +5 -5
  124. package/dist/lib/db/remote-sql.d.ts +2 -2
  125. package/dist/lib/db/remote-sql.js +3 -3
  126. package/dist/lib/db/sql.d.ts +10 -0
  127. package/dist/lib/db/sql.js +8 -4
  128. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +1 -1
  129. package/dist/lib/doctor/__testing__/fake-hq-tree.js +1 -1
  130. package/dist/lib/doctor/checks/claude-wiring.js +1 -70
  131. package/dist/lib/doctor/checks/codex-wiring.d.ts +4 -0
  132. package/dist/lib/doctor/checks/codex-wiring.js +35 -3
  133. package/dist/lib/doctor/checks/grok-wiring.js +34 -1
  134. package/dist/lib/doctor/checks/integrations.js +0 -11
  135. package/dist/lib/doctor/checks/runtime-health.d.ts +17 -4
  136. package/dist/lib/doctor/checks/runtime-health.js +7 -20
  137. package/dist/lib/doctor/checks/sync-health.d.ts +0 -21
  138. package/dist/lib/doctor/checks/sync-health.js +2 -72
  139. package/dist/lib/doctor/checks/work-context.js +6 -12
  140. package/dist/lib/doctor/compat.d.ts +16 -0
  141. package/dist/lib/doctor/compat.js +3 -4
  142. package/dist/lib/doctor/deep/effects.js +3 -1
  143. package/dist/lib/doctor/deep/executor.d.ts +10 -4
  144. package/dist/lib/doctor/deep/executor.js +1 -1
  145. package/dist/lib/doctor/deep/parity.d.ts +29 -2
  146. package/dist/lib/doctor/deep/parity.js +7 -7
  147. package/dist/lib/doctor/deep/sandbox.d.ts +25 -7
  148. package/dist/lib/doctor/deep/sandbox.js +7 -5
  149. package/dist/lib/doctor/fix/apply.d.ts +8 -79
  150. package/dist/lib/doctor/fix/apply.js +80 -292
  151. package/dist/lib/doctor/fix/remediation.d.ts +6 -14
  152. package/dist/lib/doctor/fix/remediation.js +9 -49
  153. package/dist/lib/doctor/fixtures/schema.js +3 -1
  154. package/dist/lib/doctor/json-output.d.ts +1 -17
  155. package/dist/lib/doctor/json-output.js +2 -7
  156. package/dist/lib/doctor/platform.d.ts +26 -0
  157. package/dist/lib/doctor/platform.js +5 -5
  158. package/dist/lib/doctor/registry.d.ts +0 -14
  159. package/dist/lib/doctor/registry.js +0 -71
  160. package/dist/lib/doctor/report.js +1 -1
  161. package/dist/lib/doctor/types.d.ts +0 -5
  162. package/dist/lib/doctor/types.js +0 -20
  163. package/dist/lib/flag-registry-worker.js +1 -12
  164. package/dist/lib/flag-registry.d.ts +6 -26
  165. package/dist/lib/flag-registry.js +16 -133
  166. package/dist/lib/index-render/companies.d.ts +1 -4
  167. package/dist/lib/index-render/companies.js +3 -66
  168. package/dist/lib/index-render/company-knowledge.js +17 -80
  169. package/dist/lib/index-render/index.d.ts +0 -1
  170. package/dist/lib/index-render/index.js +1 -2
  171. package/dist/lib/index-render/projects.js +5 -82
  172. package/dist/lib/index-render/shared.d.ts +1 -13
  173. package/dist/lib/index-render/shared.js +2 -41
  174. package/dist/lib/mesh/api.d.ts +10 -103
  175. package/dist/lib/mesh/api.js +64 -334
  176. package/dist/lib/mesh/client.d.ts +2 -3
  177. package/dist/lib/mesh/client.js +2 -3
  178. package/dist/lib/mesh/live/backfill-held.d.ts +16 -67
  179. package/dist/lib/mesh/live/backfill-held.js +61 -415
  180. package/dist/lib/mesh/live/backoff.d.ts +2 -2
  181. package/dist/lib/mesh/live/backoff.js +3 -16
  182. package/dist/lib/mesh/live/daemon/board-refresh.d.ts +1 -7
  183. package/dist/lib/mesh/live/daemon/board-refresh.js +30 -78
  184. package/dist/lib/mesh/live/daemon/credentials.d.ts +10 -64
  185. package/dist/lib/mesh/live/daemon/credentials.js +20 -270
  186. package/dist/lib/mesh/live/daemon/doctor.d.ts +0 -51
  187. package/dist/lib/mesh/live/daemon/doctor.js +6 -180
  188. package/dist/lib/mesh/live/daemon/index.d.ts +10 -13
  189. package/dist/lib/mesh/live/daemon/index.js +6 -7
  190. package/dist/lib/mesh/live/daemon/install.d.ts +1 -255
  191. package/dist/lib/mesh/live/daemon/install.js +13 -811
  192. package/dist/lib/mesh/live/daemon/paths.d.ts +0 -2
  193. package/dist/lib/mesh/live/daemon/paths.js +0 -2
  194. package/dist/lib/mesh/live/daemon/presence.d.ts +5 -24
  195. package/dist/lib/mesh/live/daemon/presence.js +10 -79
  196. package/dist/lib/mesh/live/daemon/run.d.ts +2 -48
  197. package/dist/lib/mesh/live/daemon/run.js +33 -485
  198. package/dist/lib/mesh/live/daemon/state.d.ts +2 -19
  199. package/dist/lib/mesh/live/daemon/state.js +2 -34
  200. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +9 -45
  201. package/dist/lib/mesh/live/daemon/transcript-watch.js +31 -227
  202. package/dist/lib/mesh/live/emit-client.d.ts +0 -8
  203. package/dist/lib/mesh/live/emit-client.js +8 -23
  204. package/dist/lib/mesh/live/emit-evidence.d.ts +0 -19
  205. package/dist/lib/mesh/live/emit-evidence.js +2 -20
  206. package/dist/lib/mesh/live/emit.d.ts +0 -9
  207. package/dist/lib/mesh/live/emit.js +2 -28
  208. package/dist/lib/mesh/live/enqueue.d.ts +0 -5
  209. package/dist/lib/mesh/live/enqueue.js +0 -19
  210. package/dist/lib/mesh/live/flush.d.ts +5 -17
  211. package/dist/lib/mesh/live/flush.js +38 -391
  212. package/dist/lib/mesh/live/format-spool-line.d.ts +2 -5
  213. package/dist/lib/mesh/live/format-spool-line.js +0 -10
  214. package/dist/lib/mesh/live/paths.d.ts +0 -2
  215. package/dist/lib/mesh/live/paths.js +0 -4
  216. package/dist/lib/mesh/live/session-event.schema.json +1 -24
  217. package/dist/lib/mesh/live/session-events-client.d.ts +0 -2
  218. package/dist/lib/mesh/live/session-events-client.js +0 -26
  219. package/dist/lib/mesh/live/spool.d.ts +0 -19
  220. package/dist/lib/mesh/live/spool.js +3 -269
  221. package/dist/lib/mesh/live/validate-session-event.d.ts +1 -1
  222. package/dist/lib/mesh/live/validate-session-event.js +1 -1
  223. package/dist/lib/plan-limit-nag.d.ts +6 -102
  224. package/dist/lib/plan-limit-nag.js +43 -348
  225. package/dist/lib/scan-packages/index.d.ts +0 -2
  226. package/dist/lib/scan-packages/index.js +6 -168
  227. package/dist/lib/search-index/background.d.ts +1 -8
  228. package/dist/lib/search-index/background.js +200 -55
  229. package/dist/lib/search-index/index.d.ts +0 -12
  230. package/dist/lib/search-index/index.js +7 -153
  231. package/dist/lib/work-context/company.d.ts +20 -22
  232. package/dist/lib/work-context/company.js +40 -124
  233. package/dist/lib/work-context/config.d.ts +11 -58
  234. package/dist/lib/work-context/config.js +83 -334
  235. package/dist/lib/work-context/contract.d.ts +0 -10
  236. package/dist/lib/work-context/index.d.ts +25 -0
  237. package/dist/lib/work-context/index.js +21 -0
  238. package/dist/lib/work-context/outbox.d.ts +1 -14
  239. package/dist/lib/work-context/outbox.js +1 -87
  240. package/dist/lib/work-context/reconcile.d.ts +0 -15
  241. package/dist/lib/work-context/reconcile.js +25 -380
  242. package/dist/lib/work-context/state.d.ts +10 -93
  243. package/dist/lib/work-context/state.js +29 -342
  244. package/dist/lib/workers-registry/index.js +8 -62
  245. package/dist/main.d.ts +0 -12
  246. package/dist/main.js +73 -266
  247. package/dist/node-network-compat.d.ts +30 -2
  248. package/dist/node-network-compat.js +51 -4
  249. package/dist/node-preflight.d.ts +1 -7
  250. package/dist/node-preflight.js +5 -5
  251. package/dist/register-all.d.ts +29 -4
  252. package/dist/register-all.js +233 -4
  253. package/dist/run/discover-schemas.d.ts +1 -2
  254. package/dist/run/env-graph-guard.d.ts +2 -2
  255. package/dist/run/env-graph-guard.js +2 -5
  256. package/dist/run/hq-plugin.d.ts +0 -4
  257. package/dist/run/hq-plugin.js +8 -36
  258. package/dist/sentry-before-send.js +0 -80
  259. package/dist/sentry.d.ts +2 -8
  260. package/dist/sentry.js +13 -117
  261. package/dist/startup-registration.d.ts +2 -26
  262. package/dist/startup-registration.js +15 -116
  263. package/dist/utils/cli-telemetry.d.ts +1 -74
  264. package/dist/utils/cli-telemetry.js +7 -434
  265. package/dist/utils/client-health.d.ts +4 -0
  266. package/dist/utils/client-health.js +2 -2
  267. package/dist/utils/cognito-session.d.ts +0 -71
  268. package/dist/utils/cognito-session.js +27 -481
  269. package/dist/utils/contribution-table.d.ts +1 -1
  270. package/dist/utils/environmental-error.d.ts +0 -18
  271. package/dist/utils/environmental-error.js +7 -240
  272. package/dist/utils/expected-cli-error.d.ts +0 -2
  273. package/dist/utils/expected-cli-error.js +0 -4
  274. package/dist/utils/feedback-diagnostics.d.ts +1 -2
  275. package/dist/utils/feedback-log-bundle.d.ts +26 -51
  276. package/dist/utils/feedback-log-bundle.js +31 -211
  277. package/dist/utils/feedback-logs.d.ts +47 -18
  278. package/dist/utils/feedback-logs.js +21 -50
  279. package/dist/utils/feedback-screenshots.d.ts +1 -0
  280. package/dist/utils/feedback-screenshots.js +1 -1
  281. package/dist/utils/hq-roots.d.ts +2 -25
  282. package/dist/utils/hq-roots.js +7 -67
  283. package/dist/utils/incomplete-install-error.d.ts +19 -87
  284. package/dist/utils/incomplete-install-error.js +68 -319
  285. package/dist/utils/install-tree-torn.d.ts +24 -260
  286. package/dist/utils/install-tree-torn.js +51 -998
  287. package/dist/utils/large-file-guard.d.ts +10 -0
  288. package/dist/utils/large-file-guard.js +1 -1
  289. package/dist/utils/local-files-overview.d.ts +8 -4
  290. package/dist/utils/local-files-overview.js +7 -48
  291. package/dist/utils/login-provider.d.ts +0 -7
  292. package/dist/utils/login-provider.js +0 -34
  293. package/dist/utils/pack-contributions.d.ts +9 -2
  294. package/dist/utils/pack-contributions.js +43 -6
  295. package/dist/utils/package-root-diagnostics.d.ts +1 -1
  296. package/dist/utils/people.d.ts +11 -7
  297. package/dist/utils/people.js +20 -5
  298. package/dist/utils/plan-gate-error.d.ts +10 -52
  299. package/dist/utils/plan-gate-error.js +41 -364
  300. package/dist/utils/qmd-model-download-error.d.ts +8 -0
  301. package/dist/utils/qmd-model-download-error.js +1 -1
  302. package/dist/utils/qmd-query-document-error.d.ts +6 -0
  303. package/dist/utils/qmd-query-document-error.js +1 -1
  304. package/dist/utils/redact-error-text.js +1 -2
  305. package/dist/utils/run-bundled-script.d.ts +0 -6
  306. package/dist/utils/run-bundled-script.js +4 -117
  307. package/dist/utils/secrets-cache.d.ts +3 -7
  308. package/dist/utils/secrets-cache.js +14 -162
  309. package/dist/utils/self-update.d.ts +1 -34
  310. package/dist/utils/self-update.js +42 -660
  311. package/dist/utils/sentry-fingerprint.d.ts +1 -23
  312. package/dist/utils/sentry-fingerprint.js +31 -223
  313. package/dist/utils/team-upgrade.d.ts +1 -1
  314. package/dist/utils/team-upgrade.js +3 -4
  315. package/dist/utils/vault-api.d.ts +1 -21
  316. package/dist/utils/vault-api.js +84 -251
  317. package/dist/utils/version-check.d.ts +1 -11
  318. package/dist/utils/version-check.js +3 -32
  319. package/dist/utils/version-gate.d.ts +17 -101
  320. package/dist/utils/version-gate.js +70 -645
  321. package/dist/utils/windows-spawn.d.ts +0 -6
  322. package/dist/utils/windows-spawn.js +0 -37
  323. package/package.json +8 -20
  324. package/README.md +0 -113
  325. package/assets/bot-workers/setup/context/USER-GUIDE.md +0 -404
  326. package/assets/bot-workers/setup/context/quick-reference.md +0 -199
  327. package/assets/bot-workers/setup/skills/agents-and-team.md +0 -167
  328. package/assets/bot-workers/setup/skills/explain-hq.md +0 -35
  329. package/assets/bot-workers/setup/skills/first-company.md +0 -74
  330. package/assets/bot-workers/setup/skills/joining-a-team.md +0 -125
  331. package/assets/bot-workers/setup/skills/pricing.md +0 -92
  332. package/assets/bot-workers/setup/skills/standing-help.md +0 -81
  333. package/assets/bot-workers/setup/skills/your-business.md +0 -281
  334. package/assets/bot-workers/setup/worker.yaml +0 -791
  335. package/assets/lanes-hooks/hq-lanes-drain.json +0 -15
  336. package/assets/lanes-hooks/hq-lanes-drain.mjs +0 -275
  337. package/assets/lanes-hooks/hq-lanes-drain.sh +0 -21
  338. package/assets/lanes-reconcile/hq-lanes-reconcile.service +0 -11
  339. package/assets/lanes-reconcile/hq-lanes-reconcile.timer +0 -12
  340. package/assets/scaffold/.claude/hooks/validate-policy-frontmatter.sh +0 -485
  341. package/assets/scaffold/core/scripts/audit-log.sh +0 -384
  342. package/assets/scaffold/core/scripts/clean-worktree-reconcile-handoff.sh +0 -171
  343. package/assets/scaffold/core/scripts/eval-trigger.sh +0 -193
  344. package/assets/scaffold/core/scripts/git-pack-extension-check.sh +0 -164
  345. package/assets/scaffold/core/scripts/handoff-finalize.sh +0 -688
  346. package/assets/scaffold/core/scripts/handoff-open-steps.sh +0 -81
  347. package/assets/scaffold/core/scripts/handoff-post.sh +0 -252
  348. package/assets/scaffold/core/scripts/hq-delegate-bundle.sh +0 -307
  349. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +0 -252
  350. package/assets/scaffold/core/scripts/hq-delegate-pickup.sh +0 -99
  351. package/assets/scaffold/core/scripts/hq-delegate-publish.sh +0 -91
  352. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +0 -158
  353. package/assets/scaffold/core/scripts/hq-delegate-resolve.sh +0 -145
  354. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +0 -129
  355. package/assets/scaffold/core/scripts/hq-delegate-send.sh +0 -259
  356. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +0 -175
  357. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +0 -238
  358. package/assets/scaffold/core/scripts/hq-dm-bind.sh +0 -585
  359. package/assets/scaffold/core/scripts/hq-job-notify.sh +0 -389
  360. package/assets/scaffold/core/scripts/hq-job-probe.sh +0 -835
  361. package/assets/scaffold/core/scripts/hq-job-remediate.sh +0 -359
  362. package/assets/scaffold/core/scripts/hq-job-run.sh +0 -1025
  363. package/assets/scaffold/core/scripts/hq-pin.sh +0 -118
  364. package/assets/scaffold/core/scripts/jobs-schedule-parse.sh +0 -310
  365. package/assets/scaffold/core/scripts/jobs-validate.sh +0 -451
  366. package/assets/scaffold/core/scripts/knowledge-prefs.sh +0 -55
  367. package/assets/scaffold/core/scripts/lib/portable.sh +0 -211
  368. package/assets/scaffold/core/scripts/lib/secret-patterns.sh +0 -58
  369. package/assets/scaffold/core/scripts/ontology-audience-grant.sh +0 -81
  370. package/assets/scaffold/core/scripts/ontology-brief.mjs +0 -93
  371. package/assets/scaffold/core/scripts/ontology-candidate.sh +0 -100
  372. package/assets/scaffold/core/scripts/ontology-garden.mjs +0 -238
  373. package/assets/scaffold/core/scripts/ontology-source-worklist.sh +0 -79
  374. package/assets/scaffold/core/scripts/outpost-jobs-reconcile.sh +0 -834
  375. package/assets/scaffold/core/scripts/policy-age-report.sh +0 -156
  376. package/assets/scaffold/core/scripts/policy-retire.sh +0 -199
  377. package/assets/scaffold/core/scripts/qmd-reindex-bg.sh +0 -40
  378. package/assets/scaffold/core/scripts/read-policy-frontmatter.sh +0 -32
  379. package/assets/scaffold/core/scripts/refresh-vault-access.sh +0 -188
  380. package/assets/scaffold/core/scripts/resolve-company.sh +0 -199
  381. package/assets/scaffold/core/scripts/resume-thread-lock.sh +0 -285
  382. package/assets/scaffold/core/scripts/source-yaml-validate.sh +0 -36
  383. package/assets/scaffold/core/scripts/verify-story-deliverables.sh +0 -148
  384. package/assets/scaffold/core/scripts/work-mesh-live-bind-trusted.sh +0 -152
  385. package/assets/scaffold/core/scripts/worktree-gc.sh +0 -362
  386. package/contracts/preflight/v1/fixtures.json +0 -87
  387. package/contracts/preflight/v1/schema.json +0 -58
  388. package/dist/command-catalog.generated.d.ts +0 -10655
  389. package/dist/command-catalog.generated.js +0 -13737
  390. package/dist/command-registration-plan.d.ts +0 -474
  391. package/dist/command-registration-plan.js +0 -136
  392. package/dist/commands/agent-enroll.d.ts +0 -146
  393. package/dist/commands/agent-enroll.js +0 -401
  394. package/dist/commands/agent-inbox.d.ts +0 -9
  395. package/dist/commands/agent-inbox.js +0 -102
  396. package/dist/commands/agent-kit.d.ts +0 -87
  397. package/dist/commands/agent-kit.js +0 -480
  398. package/dist/commands/agent-mcp.d.ts +0 -24
  399. package/dist/commands/agent-mcp.js +0 -127
  400. package/dist/commands/agent-probe.d.ts +0 -77
  401. package/dist/commands/agent-probe.js +0 -335
  402. package/dist/commands/agent.d.ts +0 -13
  403. package/dist/commands/agent.js +0 -40
  404. package/dist/commands/billing-sponsor.d.ts +0 -83
  405. package/dist/commands/billing-sponsor.js +0 -344
  406. package/dist/commands/bot-companies.d.ts +0 -40
  407. package/dist/commands/bot-companies.js +0 -64
  408. package/dist/commands/bot-continuity.d.ts +0 -28
  409. package/dist/commands/bot-continuity.js +0 -68
  410. package/dist/commands/bot-jobs.d.ts +0 -127
  411. package/dist/commands/bot-jobs.js +0 -454
  412. package/dist/commands/bot.d.ts +0 -278
  413. package/dist/commands/bot.js +0 -1982
  414. package/dist/commands/cloud-retire.d.ts +0 -51
  415. package/dist/commands/cloud-retire.js +0 -154
  416. package/dist/commands/core-audit-log-native.d.ts +0 -9
  417. package/dist/commands/core-audit-log-native.js +0 -257
  418. package/dist/commands/core-checkpoint-gate-setting.d.ts +0 -59
  419. package/dist/commands/core-checkpoint-gate-setting.js +0 -163
  420. package/dist/commands/core-checkpoint-stop-gate-native.d.ts +0 -34
  421. package/dist/commands/core-checkpoint-stop-gate-native.js +0 -725
  422. package/dist/commands/core-command-catalog.d.ts +0 -34
  423. package/dist/commands/core-command-catalog.js +0 -62
  424. package/dist/commands/core-company-index-scope-flag.d.ts +0 -3
  425. package/dist/commands/core-company-index-scope-flag.js +0 -6
  426. package/dist/commands/core-delegate-w1b.d.ts +0 -10
  427. package/dist/commands/core-delegate-w1b.js +0 -1219
  428. package/dist/commands/core-delegate.d.ts +0 -46
  429. package/dist/commands/core-delegate.js +0 -1040
  430. package/dist/commands/core-dm-bind-native.d.ts +0 -32
  431. package/dist/commands/core-dm-bind-native.js +0 -668
  432. package/dist/commands/core-git-pack-extension-check-native.d.ts +0 -22
  433. package/dist/commands/core-git-pack-extension-check-native.js +0 -190
  434. package/dist/commands/core-handoff-fast.d.ts +0 -18
  435. package/dist/commands/core-handoff-fast.js +0 -104
  436. package/dist/commands/core-handoff-open-steps.d.ts +0 -21
  437. package/dist/commands/core-handoff-open-steps.js +0 -264
  438. package/dist/commands/core-handoff.d.ts +0 -24
  439. package/dist/commands/core-handoff.js +0 -1144
  440. package/dist/commands/core-hq-session-native.d.ts +0 -39
  441. package/dist/commands/core-hq-session-native.js +0 -579
  442. package/dist/commands/core-job-native-utils.d.ts +0 -6
  443. package/dist/commands/core-job-native-utils.js +0 -80
  444. package/dist/commands/core-job-native.d.ts +0 -5
  445. package/dist/commands/core-job-native.js +0 -16
  446. package/dist/commands/core-job-notify-native.d.ts +0 -36
  447. package/dist/commands/core-job-notify-native.js +0 -359
  448. package/dist/commands/core-job-probe-native.d.ts +0 -45
  449. package/dist/commands/core-job-probe-native.js +0 -564
  450. package/dist/commands/core-job-remediate-native.d.ts +0 -26
  451. package/dist/commands/core-job-remediate-native.js +0 -374
  452. package/dist/commands/core-job-remote-launcher.d.ts +0 -7
  453. package/dist/commands/core-job-remote-launcher.js +0 -51
  454. package/dist/commands/core-job-run-native.d.ts +0 -47
  455. package/dist/commands/core-job-run-native.js +0 -1215
  456. package/dist/commands/core-jobs-native.d.ts +0 -25
  457. package/dist/commands/core-jobs-native.js +0 -1339
  458. package/dist/commands/core-knowledge-prefs.d.ts +0 -12
  459. package/dist/commands/core-knowledge-prefs.js +0 -137
  460. package/dist/commands/core-native-handoff-flag.d.ts +0 -4
  461. package/dist/commands/core-native-handoff-flag.js +0 -7
  462. package/dist/commands/core-native-jobs-flag.d.ts +0 -4
  463. package/dist/commands/core-native-jobs-flag.js +0 -7
  464. package/dist/commands/core-native-policy-flag.d.ts +0 -9
  465. package/dist/commands/core-native-policy-flag.js +0 -12
  466. package/dist/commands/core-native-session-flag.d.ts +0 -4
  467. package/dist/commands/core-native-session-flag.js +0 -7
  468. package/dist/commands/core-native-utilities-flag.d.ts +0 -4
  469. package/dist/commands/core-native-utilities-flag.js +0 -7
  470. package/dist/commands/core-native-utilities.d.ts +0 -29
  471. package/dist/commands/core-native-utilities.js +0 -54
  472. package/dist/commands/core-native-worker-skills-flag.d.ts +0 -4
  473. package/dist/commands/core-native-worker-skills-flag.js +0 -7
  474. package/dist/commands/core-ontology-native.d.ts +0 -17
  475. package/dist/commands/core-ontology-native.js +0 -916
  476. package/dist/commands/core-ontology.d.ts +0 -66
  477. package/dist/commands/core-ontology.js +0 -430
  478. package/dist/commands/core-pin-native.d.ts +0 -14
  479. package/dist/commands/core-pin-native.js +0 -236
  480. package/dist/commands/core-policy-frontmatter.d.ts +0 -8
  481. package/dist/commands/core-policy-frontmatter.js +0 -52
  482. package/dist/commands/core-policy.d.ts +0 -14
  483. package/dist/commands/core-policy.js +0 -1018
  484. package/dist/commands/core-refresh-vault-access-native.d.ts +0 -20
  485. package/dist/commands/core-refresh-vault-access-native.js +0 -229
  486. package/dist/commands/core-resolve-company-command.d.ts +0 -4
  487. package/dist/commands/core-resolve-company-command.js +0 -42
  488. package/dist/commands/core-resolve-company-native.d.ts +0 -28
  489. package/dist/commands/core-resolve-company-native.js +0 -408
  490. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +0 -32
  491. package/dist/commands/core-work-mesh-bind-trusted-native.js +0 -190
  492. package/dist/commands/core-worker-lint-native.d.ts +0 -4
  493. package/dist/commands/core-worker-lint-native.js +0 -160
  494. package/dist/commands/core-worker-share-native.d.ts +0 -5
  495. package/dist/commands/core-worker-share-native.js +0 -260
  496. package/dist/commands/core-worker-skills-command.d.ts +0 -8
  497. package/dist/commands/core-worker-skills-command.js +0 -33
  498. package/dist/commands/core-worker-skills-runtime.d.ts +0 -33
  499. package/dist/commands/core-worker-skills-runtime.js +0 -86
  500. package/dist/commands/daemon.d.ts +0 -63
  501. package/dist/commands/daemon.js +0 -877
  502. package/dist/commands/deploy-comments.d.ts +0 -3
  503. package/dist/commands/deploy-comments.js +0 -162
  504. package/dist/commands/lanes-accounts.d.ts +0 -28
  505. package/dist/commands/lanes-accounts.js +0 -595
  506. package/dist/commands/lanes-autopilot.d.ts +0 -11
  507. package/dist/commands/lanes-autopilot.js +0 -336
  508. package/dist/commands/lanes-checks.d.ts +0 -51
  509. package/dist/commands/lanes-checks.js +0 -941
  510. package/dist/commands/lanes-hold.d.ts +0 -43
  511. package/dist/commands/lanes-hold.js +0 -655
  512. package/dist/commands/lanes-kpis.d.ts +0 -11
  513. package/dist/commands/lanes-kpis.js +0 -34
  514. package/dist/commands/lanes-message.d.ts +0 -9
  515. package/dist/commands/lanes-message.js +0 -934
  516. package/dist/commands/lanes-move.d.ts +0 -12
  517. package/dist/commands/lanes-move.js +0 -397
  518. package/dist/commands/lanes-questions.d.ts +0 -36
  519. package/dist/commands/lanes-questions.js +0 -1004
  520. package/dist/commands/lanes-report.d.ts +0 -11
  521. package/dist/commands/lanes-report.js +0 -333
  522. package/dist/commands/lanes-resume.d.ts +0 -6
  523. package/dist/commands/lanes-resume.js +0 -561
  524. package/dist/commands/lanes-review.d.ts +0 -10
  525. package/dist/commands/lanes-review.js +0 -56
  526. package/dist/commands/lanes-shared.d.ts +0 -448
  527. package/dist/commands/lanes-shared.js +0 -170
  528. package/dist/commands/lanes-stories.d.ts +0 -15
  529. package/dist/commands/lanes-stories.js +0 -347
  530. package/dist/commands/lanes-watch.d.ts +0 -7
  531. package/dist/commands/lanes-watch.js +0 -216
  532. package/dist/commands/lanes.d.ts +0 -149
  533. package/dist/commands/lanes.js +0 -8843
  534. package/dist/commands/monitor.d.ts +0 -58
  535. package/dist/commands/monitor.js +0 -980
  536. package/dist/commands/onboard-bot-membership.d.ts +0 -32
  537. package/dist/commands/onboard-bot-membership.js +0 -40
  538. package/dist/commands/onboard-create-identity.d.ts +0 -26
  539. package/dist/commands/onboard-create-identity.js +0 -23
  540. package/dist/commands/outpost-pruner.d.ts +0 -3
  541. package/dist/commands/outpost-pruner.js +0 -125
  542. package/dist/commands/personal-connector-settings-flag.d.ts +0 -4
  543. package/dist/commands/personal-connector-settings-flag.js +0 -7
  544. package/dist/commands/personal-targeted-push-flag.d.ts +0 -4
  545. package/dist/commands/personal-targeted-push-flag.js +0 -7
  546. package/dist/commands/personal-targeted-push-paths.d.ts +0 -3
  547. package/dist/commands/personal-targeted-push-paths.js +0 -67
  548. package/dist/commands/report.d.ts +0 -19
  549. package/dist/commands/report.js +0 -537
  550. package/dist/commands/run-feature-telemetry.d.ts +0 -3
  551. package/dist/commands/run-feature-telemetry.js +0 -6
  552. package/dist/commands/staff/reset-test-account.d.ts +0 -110
  553. package/dist/commands/staff/reset-test-account.js +0 -268
  554. package/dist/commands/staff/test-account.d.ts +0 -51
  555. package/dist/commands/staff/test-account.js +0 -196
  556. package/dist/commands/vault-retention-flag.d.ts +0 -3
  557. package/dist/commands/vault-retention-flag.js +0 -9
  558. package/dist/commands/vault-retention.d.ts +0 -11
  559. package/dist/commands/vault-retention.js +0 -69
  560. package/dist/commands/version.d.ts +0 -10
  561. package/dist/commands/version.js +0 -11
  562. package/dist/fast-scaffold.d.ts +0 -84
  563. package/dist/fast-scaffold.js +0 -353
  564. package/dist/lanes-drain-hook.d.ts +0 -14
  565. package/dist/lanes-drain-hook.js +0 -203
  566. package/dist/lib/agent-kit/adopt-identity.d.ts +0 -27
  567. package/dist/lib/agent-kit/adopt-identity.js +0 -60
  568. package/dist/lib/agent-kit/attachment-download.d.ts +0 -24
  569. package/dist/lib/agent-kit/attachment-download.js +0 -47
  570. package/dist/lib/agent-kit/creds.d.ts +0 -106
  571. package/dist/lib/agent-kit/creds.js +0 -163
  572. package/dist/lib/agent-kit/fallback.d.ts +0 -78
  573. package/dist/lib/agent-kit/fallback.js +0 -210
  574. package/dist/lib/agent-kit/inbox-state.d.ts +0 -83
  575. package/dist/lib/agent-kit/inbox-state.js +0 -159
  576. package/dist/lib/agent-kit/kit-config.d.ts +0 -56
  577. package/dist/lib/agent-kit/kit-config.js +0 -65
  578. package/dist/lib/agent-kit/log.d.ts +0 -16
  579. package/dist/lib/agent-kit/log.js +0 -46
  580. package/dist/lib/agent-kit/mcp/attachments.d.ts +0 -126
  581. package/dist/lib/agent-kit/mcp/attachments.js +0 -222
  582. package/dist/lib/agent-kit/mcp/jsonrpc.d.ts +0 -75
  583. package/dist/lib/agent-kit/mcp/jsonrpc.js +0 -164
  584. package/dist/lib/agent-kit/mcp/tools.d.ts +0 -64
  585. package/dist/lib/agent-kit/mcp/tools.js +0 -397
  586. package/dist/lib/agent-kit/paths.d.ts +0 -65
  587. package/dist/lib/agent-kit/paths.js +0 -118
  588. package/dist/lib/agent-kit/private-file.d.ts +0 -29
  589. package/dist/lib/agent-kit/private-file.js +0 -91
  590. package/dist/lib/agent-kit/run/heartbeat.d.ts +0 -72
  591. package/dist/lib/agent-kit/run/heartbeat.js +0 -128
  592. package/dist/lib/agent-kit/run/inbox.d.ts +0 -76
  593. package/dist/lib/agent-kit/run/inbox.js +0 -205
  594. package/dist/lib/agent-kit/run/supervisor.d.ts +0 -35
  595. package/dist/lib/agent-kit/run/supervisor.js +0 -85
  596. package/dist/lib/agent-kit/run/sync.d.ts +0 -33
  597. package/dist/lib/agent-kit/run/sync.js +0 -58
  598. package/dist/lib/agent-kit/services.d.ts +0 -31
  599. package/dist/lib/agent-kit/services.js +0 -55
  600. package/dist/lib/agent-kit/skills.d.ts +0 -18
  601. package/dist/lib/agent-kit/skills.js +0 -151
  602. package/dist/lib/agent-kit/wake.d.ts +0 -83
  603. package/dist/lib/agent-kit/wake.js +0 -243
  604. package/dist/lib/agents/model-catalog.d.ts +0 -62
  605. package/dist/lib/agents/model-catalog.js +0 -275
  606. package/dist/lib/auth-login-provider-state.d.ts +0 -8
  607. package/dist/lib/auth-login-provider-state.js +0 -63
  608. package/dist/lib/aws-sdk-node-warning-output.d.ts +0 -12
  609. package/dist/lib/aws-sdk-node-warning-output.js +0 -22
  610. package/dist/lib/billing/free-month.d.ts +0 -18
  611. package/dist/lib/billing/free-month.js +0 -31
  612. package/dist/lib/billing/plan-limit-refusals.d.ts +0 -69
  613. package/dist/lib/billing/plan-limit-refusals.js +0 -187
  614. package/dist/lib/billing/plan-limit-upgrade-url.d.ts +0 -11
  615. package/dist/lib/billing/plan-limit-upgrade-url.js +0 -66
  616. package/dist/lib/billing/plan-lock.d.ts +0 -143
  617. package/dist/lib/billing/plan-lock.js +0 -439
  618. package/dist/lib/bot/api.d.ts +0 -349
  619. package/dist/lib/bot/api.js +0 -316
  620. package/dist/lib/bot/attachments.d.ts +0 -45
  621. package/dist/lib/bot/attachments.js +0 -89
  622. package/dist/lib/bot/cli-update.d.ts +0 -138
  623. package/dist/lib/bot/cli-update.js +0 -278
  624. package/dist/lib/bot/company-bind.d.ts +0 -27
  625. package/dist/lib/bot/company-bind.js +0 -62
  626. package/dist/lib/bot/config.d.ts +0 -153
  627. package/dist/lib/bot/config.js +0 -233
  628. package/dist/lib/bot/continuity-download.d.ts +0 -28
  629. package/dist/lib/bot/continuity-download.js +0 -75
  630. package/dist/lib/bot/continuity-install.d.ts +0 -14
  631. package/dist/lib/bot/continuity-install.js +0 -101
  632. package/dist/lib/bot/continuity.d.ts +0 -67
  633. package/dist/lib/bot/continuity.js +0 -301
  634. package/dist/lib/bot/creds.d.ts +0 -24
  635. package/dist/lib/bot/creds.js +0 -51
  636. package/dist/lib/bot/daemon.d.ts +0 -173
  637. package/dist/lib/bot/daemon.js +0 -552
  638. package/dist/lib/bot/inbox-poll-backoff-flag.d.ts +0 -24
  639. package/dist/lib/bot/inbox-poll-backoff-flag.js +0 -135
  640. package/dist/lib/bot/inbox-state.d.ts +0 -18
  641. package/dist/lib/bot/inbox-state.js +0 -51
  642. package/dist/lib/bot/index.d.ts +0 -23
  643. package/dist/lib/bot/index.js +0 -23
  644. package/dist/lib/bot/inflight.d.ts +0 -119
  645. package/dist/lib/bot/inflight.js +0 -83
  646. package/dist/lib/bot/job-completions.d.ts +0 -89
  647. package/dist/lib/bot/job-completions.js +0 -132
  648. package/dist/lib/bot/job-run.d.ts +0 -109
  649. package/dist/lib/bot/job-run.js +0 -246
  650. package/dist/lib/bot/local-config.d.ts +0 -61
  651. package/dist/lib/bot/local-config.js +0 -145
  652. package/dist/lib/bot/local-jobs.d.ts +0 -89
  653. package/dist/lib/bot/local-jobs.js +0 -459
  654. package/dist/lib/bot/local-name.d.ts +0 -54
  655. package/dist/lib/bot/local-name.js +0 -114
  656. package/dist/lib/bot/log.d.ts +0 -13
  657. package/dist/lib/bot/log.js +0 -59
  658. package/dist/lib/bot/owner-context.d.ts +0 -79
  659. package/dist/lib/bot/owner-context.js +0 -175
  660. package/dist/lib/bot/paths.d.ts +0 -76
  661. package/dist/lib/bot/paths.js +0 -131
  662. package/dist/lib/bot/progress.d.ts +0 -132
  663. package/dist/lib/bot/progress.js +0 -289
  664. package/dist/lib/bot/promote.d.ts +0 -16
  665. package/dist/lib/bot/promote.js +0 -106
  666. package/dist/lib/bot/promotion-hold.d.ts +0 -24
  667. package/dist/lib/bot/promotion-hold.js +0 -103
  668. package/dist/lib/bot/promotion-receipt.d.ts +0 -9
  669. package/dist/lib/bot/promotion-receipt.js +0 -56
  670. package/dist/lib/bot/promotion-upload.d.ts +0 -16
  671. package/dist/lib/bot/promotion-upload.js +0 -80
  672. package/dist/lib/bot/prompt.d.ts +0 -136
  673. package/dist/lib/bot/prompt.js +0 -433
  674. package/dist/lib/bot/room-policy.d.ts +0 -63
  675. package/dist/lib/bot/room-policy.js +0 -91
  676. package/dist/lib/bot/run.d.ts +0 -217
  677. package/dist/lib/bot/run.js +0 -1869
  678. package/dist/lib/bot/runnable.d.ts +0 -51
  679. package/dist/lib/bot/runnable.js +0 -65
  680. package/dist/lib/bot/runtime/claude.d.ts +0 -50
  681. package/dist/lib/bot/runtime/claude.js +0 -170
  682. package/dist/lib/bot/runtime/codex.d.ts +0 -28
  683. package/dist/lib/bot/runtime/codex.js +0 -153
  684. package/dist/lib/bot/runtime/grok-acp.d.ts +0 -40
  685. package/dist/lib/bot/runtime/grok-acp.js +0 -265
  686. package/dist/lib/bot/runtime/grok.d.ts +0 -41
  687. package/dist/lib/bot/runtime/grok.js +0 -169
  688. package/dist/lib/bot/runtime/index.d.ts +0 -36
  689. package/dist/lib/bot/runtime/index.js +0 -417
  690. package/dist/lib/bot/runtime/messages-stream.d.ts +0 -56
  691. package/dist/lib/bot/runtime/messages-stream.js +0 -194
  692. package/dist/lib/bot/runtime/sanitize.d.ts +0 -18
  693. package/dist/lib/bot/runtime/sanitize.js +0 -28
  694. package/dist/lib/bot/runtime/types.d.ts +0 -159
  695. package/dist/lib/bot/runtime/types.js +0 -51
  696. package/dist/lib/bot/runtime/windows.d.ts +0 -10
  697. package/dist/lib/bot/runtime/windows.js +0 -53
  698. package/dist/lib/bot/runtime-sign-in.d.ts +0 -24
  699. package/dist/lib/bot/runtime-sign-in.js +0 -31
  700. package/dist/lib/bot/scaffold.d.ts +0 -38
  701. package/dist/lib/bot/scaffold.js +0 -94
  702. package/dist/lib/bot/self-heal.d.ts +0 -52
  703. package/dist/lib/bot/self-heal.js +0 -79
  704. package/dist/lib/bot/self-process.d.ts +0 -19
  705. package/dist/lib/bot/self-process.js +0 -35
  706. package/dist/lib/bot/session.d.ts +0 -19
  707. package/dist/lib/bot/session.js +0 -39
  708. package/dist/lib/bot/setup-explain.d.ts +0 -64
  709. package/dist/lib/bot/setup-explain.js +0 -141
  710. package/dist/lib/bot/split.d.ts +0 -32
  711. package/dist/lib/bot/split.js +0 -241
  712. package/dist/lib/bot/status.d.ts +0 -57
  713. package/dist/lib/bot/status.js +0 -66
  714. package/dist/lib/bot/worker-source.d.ts +0 -66
  715. package/dist/lib/bot/worker-source.js +0 -283
  716. package/dist/lib/checkpoint-ontology/aliases.d.ts +0 -17
  717. package/dist/lib/checkpoint-ontology/aliases.js +0 -44
  718. package/dist/lib/checkpoint-ontology/apply.d.ts +0 -110
  719. package/dist/lib/checkpoint-ontology/apply.js +0 -777
  720. package/dist/lib/checkpoint-ontology/company-brief.d.ts +0 -18
  721. package/dist/lib/checkpoint-ontology/company-brief.js +0 -337
  722. package/dist/lib/checkpoint-ontology/company.d.ts +0 -44
  723. package/dist/lib/checkpoint-ontology/company.js +0 -118
  724. package/dist/lib/checkpoint-ontology/drop-aliases.d.ts +0 -41
  725. package/dist/lib/checkpoint-ontology/drop-aliases.js +0 -76
  726. package/dist/lib/checkpoint-ontology/entity-file.d.ts +0 -109
  727. package/dist/lib/checkpoint-ontology/entity-file.js +0 -371
  728. package/dist/lib/checkpoint-ontology/identity.d.ts +0 -38
  729. package/dist/lib/checkpoint-ontology/identity.js +0 -95
  730. package/dist/lib/checkpoint-ontology/merge-copies.d.ts +0 -199
  731. package/dist/lib/checkpoint-ontology/merge-copies.js +0 -1086
  732. package/dist/lib/checkpoint-ontology/multi-writer.d.ts +0 -101
  733. package/dist/lib/checkpoint-ontology/multi-writer.js +0 -394
  734. package/dist/lib/checkpoint-ontology/plan.d.ts +0 -193
  735. package/dist/lib/checkpoint-ontology/plan.js +0 -504
  736. package/dist/lib/checkpoint-ontology/queued-touches.d.ts +0 -29
  737. package/dist/lib/checkpoint-ontology/queued-touches.js +0 -193
  738. package/dist/lib/checkpoint-ontology/sync-client.d.ts +0 -38
  739. package/dist/lib/checkpoint-ontology/sync-client.js +0 -84
  740. package/dist/lib/checkpoint-ontology/tree.d.ts +0 -55
  741. package/dist/lib/checkpoint-ontology/tree.js +0 -198
  742. package/dist/lib/company-errors-sdk-warning-flag.d.ts +0 -5
  743. package/dist/lib/company-errors-sdk-warning-flag.js +0 -8
  744. package/dist/lib/core-utils/hook-timeout-debug-context-flag.d.ts +0 -20
  745. package/dist/lib/core-utils/hook-timeout-debug-context-flag.js +0 -81
  746. package/dist/lib/core-utils/jq-json-serializer.d.ts +0 -5
  747. package/dist/lib/core-utils/jq-json-serializer.js +0 -10
  748. package/dist/lib/core-utils/secret-patterns.d.ts +0 -43
  749. package/dist/lib/core-utils/secret-patterns.js +0 -34
  750. package/dist/lib/core-utils/sentry-report.d.ts +0 -114
  751. package/dist/lib/core-utils/sentry-report.js +0 -1034
  752. package/dist/lib/core-utils/timeout-guard-native.d.ts +0 -7
  753. package/dist/lib/core-utils/timeout-guard-native.js +0 -40
  754. package/dist/lib/core-utils/worktree-resume.d.ts +0 -20
  755. package/dist/lib/core-utils/worktree-resume.js +0 -1198
  756. package/dist/lib/daemon/catalog.d.ts +0 -134
  757. package/dist/lib/daemon/catalog.js +0 -358
  758. package/dist/lib/daemon/config.d.ts +0 -35
  759. package/dist/lib/daemon/config.js +0 -108
  760. package/dist/lib/daemon/flag.d.ts +0 -25
  761. package/dist/lib/daemon/flag.js +0 -59
  762. package/dist/lib/daemon/handoff.d.ts +0 -56
  763. package/dist/lib/daemon/handoff.js +0 -161
  764. package/dist/lib/daemon/hq-cloud.d.ts +0 -79
  765. package/dist/lib/daemon/hq-cloud.js +0 -183
  766. package/dist/lib/daemon/install.d.ts +0 -85
  767. package/dist/lib/daemon/install.js +0 -320
  768. package/dist/lib/daemon/legacy-sync-env.d.ts +0 -10
  769. package/dist/lib/daemon/legacy-sync-env.js +0 -58
  770. package/dist/lib/daemon/legacy.d.ts +0 -45
  771. package/dist/lib/daemon/legacy.js +0 -133
  772. package/dist/lib/daemon/lock.d.ts +0 -47
  773. package/dist/lib/daemon/lock.js +0 -138
  774. package/dist/lib/daemon/machine-type.d.ts +0 -50
  775. package/dist/lib/daemon/machine-type.js +0 -159
  776. package/dist/lib/daemon/migrate.d.ts +0 -77
  777. package/dist/lib/daemon/migrate.js +0 -265
  778. package/dist/lib/daemon/paths.d.ts +0 -24
  779. package/dist/lib/daemon/paths.js +0 -43
  780. package/dist/lib/daemon/protocol-tail.d.ts +0 -33
  781. package/dist/lib/daemon/protocol-tail.js +0 -131
  782. package/dist/lib/daemon/remote-control.d.ts +0 -74
  783. package/dist/lib/daemon/remote-control.js +0 -153
  784. package/dist/lib/daemon/requests.d.ts +0 -28
  785. package/dist/lib/daemon/requests.js +0 -65
  786. package/dist/lib/daemon/run.d.ts +0 -79
  787. package/dist/lib/daemon/run.js +0 -755
  788. package/dist/lib/daemon/succession.d.ts +0 -118
  789. package/dist/lib/daemon/succession.js +0 -263
  790. package/dist/lib/daemon/supervisor.d.ts +0 -132
  791. package/dist/lib/daemon/supervisor.js +0 -836
  792. package/dist/lib/daemon/sync-runner.d.ts +0 -58
  793. package/dist/lib/daemon/sync-runner.js +0 -277
  794. package/dist/lib/daemon/tools.d.ts +0 -52
  795. package/dist/lib/daemon/tools.js +0 -95
  796. package/dist/lib/daemon/updater.d.ts +0 -57
  797. package/dist/lib/daemon/updater.js +0 -163
  798. package/dist/lib/deploy-api.d.ts +0 -5
  799. package/dist/lib/deploy-api.js +0 -21
  800. package/dist/lib/deploy-apps.d.ts +0 -13
  801. package/dist/lib/deploy-apps.js +0 -29
  802. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  803. package/dist/lib/doctor/__testing__/run-doctor.js +0 -52
  804. package/dist/lib/doctor/checks/bots.d.ts +0 -13
  805. package/dist/lib/doctor/checks/bots.js +0 -189
  806. package/dist/lib/doctor/checks/scaffold-cli-floor.d.ts +0 -6
  807. package/dist/lib/doctor/checks/scaffold-cli-floor.js +0 -73
  808. package/dist/lib/doctor/checks/sync-runtime.d.ts +0 -11
  809. package/dist/lib/doctor/checks/sync-runtime.js +0 -216
  810. package/dist/lib/doctor/client-health-flag-token.d.ts +0 -15
  811. package/dist/lib/doctor/client-health-flag-token.js +0 -66
  812. package/dist/lib/doctor/client-health-reason-codes-flag.d.ts +0 -27
  813. package/dist/lib/doctor/client-health-reason-codes-flag.js +0 -106
  814. package/dist/lib/doctor/fix/json-output.d.ts +0 -28
  815. package/dist/lib/doctor/fix/json-output.js +0 -33
  816. package/dist/lib/doctor/fix/refresh-sync-outcome.d.ts +0 -12
  817. package/dist/lib/doctor/fix/refresh-sync-outcome.js +0 -25
  818. package/dist/lib/doctor/shared.d.ts +0 -8
  819. package/dist/lib/doctor/shared.js +0 -38
  820. package/dist/lib/doctor/stray-gate-entries.d.ts +0 -35
  821. package/dist/lib/doctor/stray-gate-entries.js +0 -83
  822. package/dist/lib/first-sync-next-step.d.ts +0 -37
  823. package/dist/lib/first-sync-next-step.js +0 -189
  824. package/dist/lib/flag-registry-endpoint.d.ts +0 -5
  825. package/dist/lib/flag-registry-endpoint.js +0 -9
  826. package/dist/lib/flag-registry-worker-source.generated.d.ts +0 -2
  827. package/dist/lib/flag-registry-worker-source.generated.js +0 -3
  828. package/dist/lib/flag-snapshot-file.d.ts +0 -20
  829. package/dist/lib/flag-snapshot-file.js +0 -91
  830. package/dist/lib/heartbeat-identity.d.ts +0 -30
  831. package/dist/lib/heartbeat-identity.js +0 -76
  832. package/dist/lib/lanes/account-home.d.ts +0 -8
  833. package/dist/lib/lanes/account-home.js +0 -10
  834. package/dist/lib/lanes/accounts.d.ts +0 -117
  835. package/dist/lib/lanes/accounts.js +0 -366
  836. package/dist/lib/lanes/admission-host.d.ts +0 -22
  837. package/dist/lib/lanes/admission-host.js +0 -37
  838. package/dist/lib/lanes/admission.d.ts +0 -26
  839. package/dist/lib/lanes/admission.js +0 -210
  840. package/dist/lib/lanes/approval-gate.d.ts +0 -8
  841. package/dist/lib/lanes/approval-gate.js +0 -90
  842. package/dist/lib/lanes/autopilot-metrics.d.ts +0 -99
  843. package/dist/lib/lanes/autopilot-metrics.js +0 -301
  844. package/dist/lib/lanes/autopilot-registry.d.ts +0 -62
  845. package/dist/lib/lanes/autopilot-registry.js +0 -192
  846. package/dist/lib/lanes/autopilot.d.ts +0 -120
  847. package/dist/lib/lanes/autopilot.js +0 -1061
  848. package/dist/lib/lanes/blocker-freshness.d.ts +0 -31
  849. package/dist/lib/lanes/blocker-freshness.js +0 -168
  850. package/dist/lib/lanes/checked-company-path.d.ts +0 -3
  851. package/dist/lib/lanes/checked-company-path.js +0 -39
  852. package/dist/lib/lanes/claude-balance.d.ts +0 -97
  853. package/dist/lib/lanes/claude-balance.js +0 -319
  854. package/dist/lib/lanes/compaction.d.ts +0 -110
  855. package/dist/lib/lanes/compaction.js +0 -293
  856. package/dist/lib/lanes/config.d.ts +0 -91
  857. package/dist/lib/lanes/config.js +0 -592
  858. package/dist/lib/lanes/constants.d.ts +0 -3
  859. package/dist/lib/lanes/constants.js +0 -3
  860. package/dist/lib/lanes/delivery-core.d.ts +0 -15
  861. package/dist/lib/lanes/delivery-core.js +0 -21
  862. package/dist/lib/lanes/delivery.d.ts +0 -180
  863. package/dist/lib/lanes/delivery.js +0 -443
  864. package/dist/lib/lanes/dropbox.d.ts +0 -129
  865. package/dist/lib/lanes/dropbox.js +0 -601
  866. package/dist/lib/lanes/effort.d.ts +0 -51
  867. package/dist/lib/lanes/effort.js +0 -113
  868. package/dist/lib/lanes/envelope-repair-dispatch.d.ts +0 -26
  869. package/dist/lib/lanes/envelope-repair-dispatch.js +0 -74
  870. package/dist/lib/lanes/errors.d.ts +0 -39
  871. package/dist/lib/lanes/errors.js +0 -72
  872. package/dist/lib/lanes/flag-keys.d.ts +0 -13
  873. package/dist/lib/lanes/flag-keys.js +0 -13
  874. package/dist/lib/lanes/grants.d.ts +0 -29
  875. package/dist/lib/lanes/grants.js +0 -166
  876. package/dist/lib/lanes/hire-grant-dispatch.d.ts +0 -29
  877. package/dist/lib/lanes/hire-grant-dispatch.js +0 -316
  878. package/dist/lib/lanes/hooks-install.d.ts +0 -82
  879. package/dist/lib/lanes/hooks-install.js +0 -479
  880. package/dist/lib/lanes/host-capacity.d.ts +0 -69
  881. package/dist/lib/lanes/host-capacity.js +0 -254
  882. package/dist/lib/lanes/hq-root.d.ts +0 -19
  883. package/dist/lib/lanes/hq-root.js +0 -28
  884. package/dist/lib/lanes/index.d.ts +0 -76
  885. package/dist/lib/lanes/index.js +0 -42
  886. package/dist/lib/lanes/keep-alive.d.ts +0 -68
  887. package/dist/lib/lanes/keep-alive.js +0 -343
  888. package/dist/lib/lanes/kr-freshness.d.ts +0 -76
  889. package/dist/lib/lanes/kr-freshness.js +0 -413
  890. package/dist/lib/lanes/lane-company.d.ts +0 -10
  891. package/dist/lib/lanes/lane-company.js +0 -41
  892. package/dist/lib/lanes/liveness.d.ts +0 -108
  893. package/dist/lib/lanes/liveness.js +0 -396
  894. package/dist/lib/lanes/machine-identity.d.ts +0 -34
  895. package/dist/lib/lanes/machine-identity.js +0 -92
  896. package/dist/lib/lanes/manager-status-gate.d.ts +0 -17
  897. package/dist/lib/lanes/manager-status-gate.js +0 -133
  898. package/dist/lib/lanes/merge-command.d.ts +0 -15
  899. package/dist/lib/lanes/merge-command.js +0 -629
  900. package/dist/lib/lanes/mesh-events.d.ts +0 -127
  901. package/dist/lib/lanes/mesh-events.js +0 -564
  902. package/dist/lib/lanes/message-replay.d.ts +0 -21
  903. package/dist/lib/lanes/message-replay.js +0 -122
  904. package/dist/lib/lanes/models.d.ts +0 -86
  905. package/dist/lib/lanes/models.js +0 -234
  906. package/dist/lib/lanes/monitor.d.ts +0 -48
  907. package/dist/lib/lanes/monitor.js +0 -428
  908. package/dist/lib/lanes/move-account.d.ts +0 -56
  909. package/dist/lib/lanes/move-account.js +0 -193
  910. package/dist/lib/lanes/orphans.d.ts +0 -25
  911. package/dist/lib/lanes/orphans.js +0 -102
  912. package/dist/lib/lanes/outpost-dispatch.d.ts +0 -147
  913. package/dist/lib/lanes/outpost-dispatch.js +0 -271
  914. package/dist/lib/lanes/outpost-hire-cache.d.ts +0 -22
  915. package/dist/lib/lanes/outpost-hire-cache.js +0 -153
  916. package/dist/lib/lanes/outpost-identity.d.ts +0 -33
  917. package/dist/lib/lanes/outpost-identity.js +0 -59
  918. package/dist/lib/lanes/outpost-profile-repin.d.ts +0 -17
  919. package/dist/lib/lanes/outpost-profile-repin.js +0 -84
  920. package/dist/lib/lanes/outpost-pruner-install.d.ts +0 -37
  921. package/dist/lib/lanes/outpost-pruner-install.js +0 -238
  922. package/dist/lib/lanes/outpost-registry-worker-approval.d.ts +0 -18
  923. package/dist/lib/lanes/outpost-registry-worker-approval.js +0 -109
  924. package/dist/lib/lanes/outpost-snapshot-memo.d.ts +0 -6
  925. package/dist/lib/lanes/outpost-snapshot-memo.js +0 -14
  926. package/dist/lib/lanes/outpost-worktree-pruner-flag.d.ts +0 -19
  927. package/dist/lib/lanes/outpost-worktree-pruner-flag.js +0 -86
  928. package/dist/lib/lanes/outpost-worktree-pruner.d.ts +0 -62
  929. package/dist/lib/lanes/outpost-worktree-pruner.js +0 -1201
  930. package/dist/lib/lanes/profile.d.ts +0 -69
  931. package/dist/lib/lanes/profile.js +0 -552
  932. package/dist/lib/lanes/provider-rejection.d.ts +0 -86
  933. package/dist/lib/lanes/provider-rejection.js +0 -286
  934. package/dist/lib/lanes/questions.d.ts +0 -90
  935. package/dist/lib/lanes/questions.js +0 -384
  936. package/dist/lib/lanes/quota.d.ts +0 -134
  937. package/dist/lib/lanes/quota.js +0 -471
  938. package/dist/lib/lanes/reconcile-install.d.ts +0 -90
  939. package/dist/lib/lanes/reconcile-install.js +0 -257
  940. package/dist/lib/lanes/reconcile.d.ts +0 -155
  941. package/dist/lib/lanes/reconcile.js +0 -3193
  942. package/dist/lib/lanes/registry-flag.d.ts +0 -29
  943. package/dist/lib/lanes/registry-flag.js +0 -139
  944. package/dist/lib/lanes/registry-persona.d.ts +0 -20
  945. package/dist/lib/lanes/registry-persona.js +0 -329
  946. package/dist/lib/lanes/registry.d.ts +0 -122
  947. package/dist/lib/lanes/registry.js +0 -570
  948. package/dist/lib/lanes/reviews.d.ts +0 -38
  949. package/dist/lib/lanes/reviews.js +0 -395
  950. package/dist/lib/lanes/runaway-tool-guard.d.ts +0 -38
  951. package/dist/lib/lanes/runaway-tool-guard.js +0 -284
  952. package/dist/lib/lanes/session-relink.d.ts +0 -25
  953. package/dist/lib/lanes/session-relink.js +0 -216
  954. package/dist/lib/lanes/spawn.d.ts +0 -350
  955. package/dist/lib/lanes/spawn.js +0 -2643
  956. package/dist/lib/lanes/ssm-command-context.d.ts +0 -12
  957. package/dist/lib/lanes/ssm-command-context.js +0 -52
  958. package/dist/lib/lanes/store.d.ts +0 -91
  959. package/dist/lib/lanes/store.js +0 -1811
  960. package/dist/lib/lanes/stories.d.ts +0 -23
  961. package/dist/lib/lanes/stories.js +0 -92
  962. package/dist/lib/lanes/story-ledger.d.ts +0 -80
  963. package/dist/lib/lanes/story-ledger.js +0 -815
  964. package/dist/lib/lanes/story-switch.d.ts +0 -21
  965. package/dist/lib/lanes/story-switch.js +0 -75
  966. package/dist/lib/lanes/text-scan.d.ts +0 -11
  967. package/dist/lib/lanes/text-scan.js +0 -103
  968. package/dist/lib/lanes/throttle.d.ts +0 -116
  969. package/dist/lib/lanes/throttle.js +0 -437
  970. package/dist/lib/lanes/timestamp.d.ts +0 -3
  971. package/dist/lib/lanes/timestamp.js +0 -26
  972. package/dist/lib/lanes/tracker-checks.d.ts +0 -77
  973. package/dist/lib/lanes/tracker-checks.js +0 -134
  974. package/dist/lib/lanes/tracker-report-state.d.ts +0 -10
  975. package/dist/lib/lanes/tracker-report-state.js +0 -124
  976. package/dist/lib/lanes/tracker-report.d.ts +0 -203
  977. package/dist/lib/lanes/tracker-report.js +0 -522
  978. package/dist/lib/lanes/tracker-store.d.ts +0 -18
  979. package/dist/lib/lanes/tracker-store.js +0 -106
  980. package/dist/lib/lanes/types.d.ts +0 -1020
  981. package/dist/lib/lanes/types.js +0 -417
  982. package/dist/lib/lanes/wait.d.ts +0 -39
  983. package/dist/lib/lanes/wait.js +0 -159
  984. package/dist/lib/lanes/watch.d.ts +0 -39
  985. package/dist/lib/lanes/watch.js +0 -249
  986. package/dist/lib/lanes/watcher-main.d.ts +0 -11
  987. package/dist/lib/lanes/watcher-main.js +0 -108
  988. package/dist/lib/lanes/watcher.d.ts +0 -287
  989. package/dist/lib/lanes/watcher.js +0 -1972
  990. package/dist/lib/mesh/live/daemon/config.d.ts +0 -36
  991. package/dist/lib/mesh/live/daemon/config.js +0 -120
  992. package/dist/lib/mesh/live/daemon/legacy-listen.d.ts +0 -43
  993. package/dist/lib/mesh/live/daemon/legacy-listen.js +0 -89
  994. package/dist/lib/mesh/live/daemon/live-cache.d.ts +0 -26
  995. package/dist/lib/mesh/live/daemon/live-cache.js +0 -116
  996. package/dist/lib/mesh/live/daemon/mqtt-events.d.ts +0 -7
  997. package/dist/lib/mesh/live/daemon/mqtt-events.js +0 -2
  998. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  999. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  1000. package/dist/lib/mesh/live/daemon/version-drift.d.ts +0 -5
  1001. package/dist/lib/mesh/live/daemon/version-drift.js +0 -47
  1002. package/dist/lib/mesh/live/daemon/work-subscribe.d.ts +0 -32
  1003. package/dist/lib/mesh/live/daemon/work-subscribe.js +0 -262
  1004. package/dist/lib/mesh/live/report-summary.d.ts +0 -45
  1005. package/dist/lib/mesh/live/report-summary.js +0 -234
  1006. package/dist/lib/mesh/live/session-seq.d.ts +0 -4
  1007. package/dist/lib/mesh/live/session-seq.js +0 -33
  1008. package/dist/lib/mesh/project-board.d.ts +0 -65
  1009. package/dist/lib/mesh/project-board.js +0 -181
  1010. package/dist/lib/mesh/story-status.d.ts +0 -22
  1011. package/dist/lib/mesh/story-status.js +0 -49
  1012. package/dist/lib/monitor.d.ts +0 -149
  1013. package/dist/lib/monitor.js +0 -519
  1014. package/dist/lib/node-binary.d.ts +0 -50
  1015. package/dist/lib/node-binary.js +0 -133
  1016. package/dist/lib/notify-recipient.d.ts +0 -7
  1017. package/dist/lib/notify-recipient.js +0 -11
  1018. package/dist/lib/onboarding/checkpoint.d.ts +0 -13
  1019. package/dist/lib/onboarding/checkpoint.js +0 -44
  1020. package/dist/lib/onboarding/cli/onboard.d.ts +0 -53
  1021. package/dist/lib/onboarding/cli/onboard.js +0 -135
  1022. package/dist/lib/onboarding/cli/prompts.d.ts +0 -28
  1023. package/dist/lib/onboarding/cli/prompts.js +0 -83
  1024. package/dist/lib/onboarding/errors.d.ts +0 -34
  1025. package/dist/lib/onboarding/errors.js +0 -59
  1026. package/dist/lib/onboarding/index.d.ts +0 -13
  1027. package/dist/lib/onboarding/index.js +0 -13
  1028. package/dist/lib/onboarding/orchestrator.d.ts +0 -47
  1029. package/dist/lib/onboarding/orchestrator.js +0 -569
  1030. package/dist/lib/onboarding/types.d.ts +0 -79
  1031. package/dist/lib/onboarding/types.js +0 -8
  1032. package/dist/lib/policy-validator.d.ts +0 -7
  1033. package/dist/lib/policy-validator.js +0 -187
  1034. package/dist/lib/process-flag-company-context.d.ts +0 -8
  1035. package/dist/lib/process-flag-company-context.js +0 -67
  1036. package/dist/lib/report-publish.d.ts +0 -175
  1037. package/dist/lib/report-publish.js +0 -421
  1038. package/dist/lib/report-run.d.ts +0 -62
  1039. package/dist/lib/report-run.js +0 -123
  1040. package/dist/lib/report-snapshot.d.ts +0 -12
  1041. package/dist/lib/report-snapshot.js +0 -135
  1042. package/dist/lib/report-templates.d.ts +0 -9
  1043. package/dist/lib/report-templates.js +0 -21
  1044. package/dist/lib/scaffold-cli-floor.d.ts +0 -8
  1045. package/dist/lib/scaffold-cli-floor.js +0 -50
  1046. package/dist/lib/search-index/collection-path-repair-flag.d.ts +0 -4
  1047. package/dist/lib/search-index/collection-path-repair-flag.js +0 -7
  1048. package/dist/lib/search-index/embed-lock.d.ts +0 -32
  1049. package/dist/lib/search-index/embed-lock.js +0 -286
  1050. package/dist/lib/search-index/load-gate.d.ts +0 -57
  1051. package/dist/lib/search-index/load-gate.js +0 -270
  1052. package/dist/lib/search-index/max-doc-bytes.d.ts +0 -219
  1053. package/dist/lib/search-index/max-doc-bytes.js +0 -463
  1054. package/dist/lib/search-index/qmd-exit-diagnostics.d.ts +0 -5
  1055. package/dist/lib/search-index/qmd-exit-diagnostics.js +0 -40
  1056. package/dist/lib/search-index/reindex-single-flight-flag.d.ts +0 -5
  1057. package/dist/lib/search-index/reindex-single-flight-flag.js +0 -8
  1058. package/dist/lib/service-manager/index.d.ts +0 -42
  1059. package/dist/lib/service-manager/index.js +0 -105
  1060. package/dist/lib/service-manager/launchd.d.ts +0 -81
  1061. package/dist/lib/service-manager/launchd.js +0 -212
  1062. package/dist/lib/service-manager/systemd.d.ts +0 -19
  1063. package/dist/lib/service-manager/systemd.js +0 -72
  1064. package/dist/lib/service-manager/types.d.ts +0 -34
  1065. package/dist/lib/service-manager/types.js +0 -26
  1066. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  1067. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  1068. package/dist/lib/work-context/bind-best.d.ts +0 -66
  1069. package/dist/lib/work-context/bind-best.js +0 -344
  1070. package/dist/lib/work-context/bind-calling-session.d.ts +0 -26
  1071. package/dist/lib/work-context/bind-calling-session.js +0 -63
  1072. package/dist/lib/work-context/company-rebind.d.ts +0 -23
  1073. package/dist/lib/work-context/company-rebind.js +0 -59
  1074. package/dist/lib/work-context/default-company.d.ts +0 -43
  1075. package/dist/lib/work-context/default-company.js +0 -83
  1076. package/dist/lib/work-context/outbox-quarantine-status-flag.d.ts +0 -4
  1077. package/dist/lib/work-context/outbox-quarantine-status-flag.js +0 -7
  1078. package/dist/lib/work-context/prd-sync.d.ts +0 -56
  1079. package/dist/lib/work-context/prd-sync.js +0 -197
  1080. package/dist/lib/work-context/preflight-contract.d.ts +0 -28
  1081. package/dist/lib/work-context/preflight-contract.js +0 -85
  1082. package/dist/lib/work-context/prompt-rebind.d.ts +0 -25
  1083. package/dist/lib/work-context/prompt-rebind.js +0 -85
  1084. package/dist/lib/work-context/windows-acl.d.ts +0 -123
  1085. package/dist/lib/work-context/windows-acl.js +0 -425
  1086. package/dist/lib/workers-registry/read.d.ts +0 -15
  1087. package/dist/lib/workers-registry/read.js +0 -17
  1088. package/dist/native-fast-route.d.ts +0 -7
  1089. package/dist/native-fast-route.js +0 -45
  1090. package/dist/node-network-compat-core.d.ts +0 -12
  1091. package/dist/node-network-compat-core.js +0 -41
  1092. package/dist/node-network-compat-fast.d.ts +0 -7
  1093. package/dist/node-network-compat-fast.js +0 -23
  1094. package/dist/secrets-env-fast-path.d.ts +0 -5
  1095. package/dist/secrets-env-fast-path.js +0 -16
  1096. package/dist/secrets-env-fast-route.d.ts +0 -18
  1097. package/dist/secrets-env-fast-route.js +0 -54
  1098. package/dist/utils/checkpoint-stamp-write-error.d.ts +0 -28
  1099. package/dist/utils/checkpoint-stamp-write-error.js +0 -99
  1100. package/dist/utils/cli-network-lifecycle.d.ts +0 -4
  1101. package/dist/utils/cli-network-lifecycle.js +0 -11
  1102. package/dist/utils/cognito-refresh-sentry.d.ts +0 -3
  1103. package/dist/utils/cognito-refresh-sentry.js +0 -49
  1104. package/dist/utils/console-origin.d.ts +0 -9
  1105. package/dist/utils/console-origin.js +0 -28
  1106. package/dist/utils/exclusive-lock.d.ts +0 -32
  1107. package/dist/utils/exclusive-lock.js +0 -75
  1108. package/dist/utils/fast-stream-errors.d.ts +0 -12
  1109. package/dist/utils/fast-stream-errors.js +0 -18
  1110. package/dist/utils/files-browse-acl.d.ts +0 -5
  1111. package/dist/utils/files-browse-acl.js +0 -11
  1112. package/dist/utils/hq-core-yaml.d.ts +0 -10
  1113. package/dist/utils/hq-core-yaml.js +0 -40
  1114. package/dist/utils/hq-root-resolver.d.ts +0 -13
  1115. package/dist/utils/hq-root-resolver.js +0 -103
  1116. package/dist/utils/redact-url.d.ts +0 -14
  1117. package/dist/utils/redact-url.js +0 -218
  1118. package/dist/utils/scaffold-fast-import-guard.d.ts +0 -2
  1119. package/dist/utils/scaffold-fast-import-guard.js +0 -40
  1120. package/dist/utils/scaffold-packlist-guard.d.ts +0 -7
  1121. package/dist/utils/scaffold-packlist-guard.js +0 -23
  1122. package/dist/utils/scaffold-sibling-references.d.ts +0 -22
  1123. package/dist/utils/scaffold-sibling-references.js +0 -156
  1124. package/dist/utils/secret-load-availability.d.ts +0 -8
  1125. package/dist/utils/secret-load-availability.js +0 -54
  1126. package/dist/utils/staged-install.d.ts +0 -34
  1127. package/dist/utils/staged-install.js +0 -346
  1128. package/dist/utils/staged-npm-install.d.ts +0 -16
  1129. package/dist/utils/staged-npm-install.js +0 -264
  1130. package/dist/utils/sync-log-sources.d.ts +0 -15
  1131. package/dist/utils/sync-log-sources.js +0 -36
  1132. package/dist/utils/table-width.d.ts +0 -7
  1133. package/dist/utils/table-width.js +0 -15
  1134. package/dist/utils/update-command-supervisor.cjs +0 -247
  1135. package/dist/utils/upload-author.d.ts +0 -15
  1136. package/dist/utils/upload-author.js +0 -39
  1137. package/dist/utils/version-report.d.ts +0 -27
  1138. package/dist/utils/version-report.js +0 -105
  1139. package/dist/version-request.d.ts +0 -14
  1140. package/dist/version-request.js +0 -36
  1141. package/scripts/mesh-daemon-if-stale.mjs +0 -20
  1142. package/templates/reports/blank.md +0 -3
  1143. package/templates/reports/daily-digest.md +0 -11
  1144. package/templates/runbooks/update-report.md +0 -21
@@ -1,2643 +0,0 @@
1
- /**
2
- * Detached lane-worker spawn (spec §5, §5.1, §5.4, §5.5).
3
- *
4
- * The worker must leave the caller's process tree (`detached: true` / setsid)
5
- * with stdio pointed at files in the run directory. Account selection is the
6
- * provider home environment variable only. Provider credential files are
7
- * probed for existence and never read. Identity in the child is `HQ_LANE_ID`;
8
- * mutable fields are re-read from the lane record (spec §5.4).
9
- */
10
- import { spawn, spawnSync } from "node:child_process";
11
- import { randomUUID } from "node:crypto";
12
- import * as fs from "node:fs";
13
- import * as path from "node:path";
14
- import { fileURLToPath } from "node:url";
15
- import { PROVIDER_HOME_ENV, accountStatus, isLoggedOut, resolveAccount, selectBalancedAccount, } from "./accounts.js";
16
- import { effectiveAccountHome } from "./account-home.js";
17
- import { buildHostCapacitySnapshot } from "./host-capacity.js";
18
- import { selectClaudeAccount } from "./claude-balance.js";
19
- import { loadQuotaState } from "./quota.js";
20
- import { COMPACTION_PROMPT, compactionAfterUsage, compactionDue, compactLaneSession, } from "./compaction.js";
21
- import { installDrainHook } from "./hooks-install.js";
22
- import { loadLanesConfig, providerAutoCompactTokens, providerCompactAfterMs, } from "./config.js";
23
- import { appendEffortFlag, resolveLaneEffort, } from "./effort.js";
24
- import { defaultProbe, validateLaneModel, validateProfileLaneModel, } from "./models.js";
25
- import { claimableStatesFor, planLaneLaunch, providerSupportsSessionResume, } from "./delivery.js";
26
- import { AccountResolutionError, LanesError } from "./errors.js";
27
- import { ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, materializeWorkerProfile, workerProfilePrompt, } from "./profile.js";
28
- import { registryWorkerRecord } from "./registry-persona.js";
29
- import { resolveMachineIdentity, } from "./machine-identity.js";
30
- import { appendCappedHistory, listLaneIds, readLane, retryUpdateLane } from "./store.js";
31
- import { managerStatusGateHeartbeat } from "./manager-status-gate.js";
32
- import { LEAD_LANE_KEEP_ALIVE_BLOCKED_RESUME_TEXT } from "./keep-alive.js";
33
- import { copySessionFiles, planSessionCopy } from "./move-account.js";
34
- import { ensureSessionHome } from "./session-relink.js";
35
- import { MESSAGE_REPLAY_STATE_NAME } from "./message-replay.js";
36
- import { markAnsweredQuestionsDelivered } from "./questions.js";
37
- import { hasEarlierEligibleQueuedLane, laneAdmissionCapReason, withLaneAdmissionLock, } from "./admission.js";
38
- import { resolveAdmissionHost } from "./admission-host.js";
39
- import { LANE_ENVELOPE_JSON_SCHEMA, ENVELOPE_INVALID_REASON, parseLaneProvider, } from "./types.js";
40
- export const LANES_RUNS_REL = path.join("workspace", "lanes-runs");
41
- /** Written by reconcile before a resume spawn; the worker prompt names this path. */
42
- export const ANSWERED_QUESTIONS_FILE = "answered-questions.json";
43
- export const SPAWN_TERMINAL_REASONS = [
44
- "account_not_logged_in",
45
- "unknown_account",
46
- "account_disabled",
47
- "no_enabled_account",
48
- "spawn_failed",
49
- "not_detached",
50
- "watcher_not_armed",
51
- "model_unsupported",
52
- ];
53
- const PROVIDER_COMMAND = {
54
- claude: "claude",
55
- codex: "codex",
56
- grok: "grok",
57
- };
58
- export function providerCommandOnPath(command, pathEnv) {
59
- // Test and embedded callers can intentionally omit PATH and delegate lookup
60
- // to their spawn implementation. A present PATH is authoritative.
61
- if (pathEnv === undefined)
62
- return true;
63
- if (!pathEnv)
64
- return false;
65
- return pathEnv.split(path.delimiter).some((dir) => {
66
- if (!dir)
67
- return false;
68
- const candidate = path.join(dir, command);
69
- try {
70
- fs.accessSync(candidate, fs.constants.X_OK);
71
- return true;
72
- }
73
- catch {
74
- return false;
75
- }
76
- });
77
- }
78
- /** Per-provider model flag. A missing entry means --model is refused. */
79
- export const PROVIDER_MODEL_FLAG = {
80
- claude: "--model",
81
- codex: "-m",
82
- grok: "-m",
83
- };
84
- export const CLAUDE_AUTO_COMPACT_ENV = "CLAUDE_CODE_AUTO_COMPACT_WINDOW";
85
- /** Codex CLI overrides required for its ChatGPT fast service tier. */
86
- export const CODEX_FAST_MODE_FLAGS = [
87
- "-c",
88
- 'service_tier="fast"',
89
- "--enable",
90
- "fast_mode",
91
- ];
92
- export function parseCliModel(raw) {
93
- if (raw === undefined)
94
- return undefined;
95
- const trimmed = raw.trim();
96
- if (trimmed.length === 0) {
97
- throw new LanesError("empty_model", "--model is empty or whitespace-only", {
98
- value: raw,
99
- });
100
- }
101
- return trimmed;
102
- }
103
- export function resolveLaneModel(input) {
104
- if (input.cliModel !== undefined)
105
- return input.cliModel;
106
- if (input.profileModel !== undefined && input.profileModel.trim().length > 0) {
107
- return input.profileModel.trim();
108
- }
109
- if (input.accountModel !== undefined && input.accountModel.trim().length > 0) {
110
- return input.accountModel.trim();
111
- }
112
- if (input.providerModel !== undefined && input.providerModel.trim().length > 0) {
113
- return input.providerModel.trim();
114
- }
115
- return undefined;
116
- }
117
- function accountModelForSpawn(provider, accountId, config, pinnedModel, profileModel) {
118
- return resolveLaneModel({
119
- cliModel: pinnedModel,
120
- profileModel,
121
- accountModel: config.providers[provider].accounts[accountId]?.model,
122
- providerModel: config.providers[provider].model,
123
- });
124
- }
125
- function supportsSpawnModel(provider, accountId, config, pinnedModel, profileModel, modelDeps, hostname) {
126
- const account = config.providers[provider].accounts[accountId];
127
- if (account === undefined)
128
- return false;
129
- const model = accountModelForSpawn(provider, accountId, config, pinnedModel, profileModel);
130
- if (model === undefined)
131
- return true;
132
- try {
133
- validateLaneModel(provider, model, effectiveAccountHome(account, hostname).home, modelDeps);
134
- return true;
135
- }
136
- catch (err) {
137
- if (err instanceof LanesError && err.error === "model_unsupported")
138
- return false;
139
- throw err;
140
- }
141
- }
142
- function spawnModelFailure(provider, accountId, config, pinnedModel, profileModel, profileId, modelDeps, hostname) {
143
- const account = config.providers[provider].accounts[accountId];
144
- if (account === undefined)
145
- return new LanesError("unknown_account", `Unknown account ${accountId} for ${provider}`, { provider, account: accountId });
146
- const model = accountModelForSpawn(provider, accountId, config, pinnedModel, profileModel);
147
- if (model === undefined)
148
- return null;
149
- try {
150
- validateLaneModel(provider, model, effectiveAccountHome(account, hostname).home, modelDeps);
151
- return null;
152
- }
153
- catch (err) {
154
- if (!(err instanceof LanesError) || err.error !== "model_unsupported")
155
- throw err;
156
- if (profileModel !== undefined && pinnedModel === undefined && profileId !== undefined) {
157
- return new LanesError(err.error, err.message, {
158
- ...err.details,
159
- profile_id: profileId,
160
- worker_profile: profileId,
161
- model_source: "profile",
162
- });
163
- }
164
- return err;
165
- }
166
- }
167
- function selectSpawnAccount(input) {
168
- const { hqRoot, lane, config, existsSync, accountDeps, modelDeps, pinnedModel, profileModel, currentModelValidated, hostname, repairRecordedAccount, recordedModel, now } = input;
169
- const context = {
170
- hqRoot,
171
- existsSync,
172
- accountDeps,
173
- hostname,
174
- ...(pinnedModel ?? profileModel ? { model: pinnedModel ?? profileModel } : {}),
175
- };
176
- if (lane.account === undefined) {
177
- const modelSpecified = pinnedModel !== undefined || profileModel !== undefined;
178
- const allowedAccounts = modelSpecified
179
- ? Object.keys(config.providers[lane.provider].accounts).filter((id) => supportsSpawnModel(lane.provider, id, config, pinnedModel, profileModel, modelDeps, hostname))
180
- : undefined;
181
- return {
182
- account: selectBalancedAccount(lane.provider, config, {
183
- ...context,
184
- ...(allowedAccounts !== undefined ? { allowedAccounts } : {}),
185
- preferredAccounts: config.providers[lane.provider].preferred_accounts ?? [],
186
- }),
187
- changeReason: "first_assignment",
188
- };
189
- }
190
- const current = config.providers[lane.provider].accounts[lane.account];
191
- let reason;
192
- let refusal;
193
- const operatorMovePending = lane.pending_resume !== undefined &&
194
- lane.account_history?.at(-1)?.reason === "operator_move";
195
- if (current === undefined || !current.enabled) {
196
- reason = "account_unavailable";
197
- refusal = new AccountResolutionError(current === undefined ? "unknown_account" : "account_disabled", `Account ${JSON.stringify(lane.account)} is unavailable for ${lane.provider}`, { provider: lane.provider, account: lane.account });
198
- }
199
- else {
200
- const status = accountStatus(lane.provider, lane.account, config, {
201
- existsSync,
202
- hostname,
203
- ...(accountDeps?.probe ? { probe: accountDeps.probe } : {}),
204
- ...(accountDeps?.env ? { env: accountDeps.env } : {}),
205
- });
206
- if (isLoggedOut(status)) {
207
- reason = repairRecordedAccount ? "recorded_account_logged_out" : "account_unavailable";
208
- refusal = new LanesError("account_not_logged_in", `Account ${lane.account} for ${lane.provider} is not logged in`, { provider: lane.provider, account: lane.account });
209
- }
210
- else {
211
- try {
212
- resolveAccount(lane.provider, lane.account, config, context);
213
- const modelFailure = currentModelValidated
214
- ? null
215
- : spawnModelFailure(lane.provider, lane.account, config, pinnedModel, profileModel, lane.worker_profile, modelDeps, hostname);
216
- if (modelFailure !== null) {
217
- reason = "model_change";
218
- refusal = modelFailure;
219
- }
220
- else {
221
- return { account: resolveAccount(lane.provider, lane.account, config, context) };
222
- }
223
- }
224
- catch (err) {
225
- if (err instanceof AccountResolutionError && err.error === "account_quota_exhausted") {
226
- reason = "usage_limit";
227
- refusal = err;
228
- }
229
- else if (err instanceof AccountResolutionError && err.error === "account_model_unavailable") {
230
- reason = "usage_limit";
231
- refusal = err;
232
- }
233
- else if (err instanceof LanesError && err.error === "model_unsupported") {
234
- reason = "model_change";
235
- refusal = err;
236
- }
237
- else {
238
- throw err;
239
- }
240
- }
241
- }
242
- }
243
- if (operatorMovePending) {
244
- if (refusal instanceof Error)
245
- throw refusal;
246
- throw new LanesError("account_unavailable", `Explicit account move target ${lane.account} is unavailable`, {
247
- provider: lane.provider,
248
- account: lane.account,
249
- });
250
- }
251
- const recoverRecordedClaudeModel = lane.provider === "claude" &&
252
- reason !== undefined &&
253
- (reason === "recorded_account_logged_out" ||
254
- (reason === "account_unavailable" && repairRecordedAccount && recordedModel !== undefined));
255
- if (recoverRecordedClaudeModel) {
256
- const lanes = listLaneIds(hqRoot)
257
- .map((laneId) => readLane(hqRoot, laneId))
258
- .filter((record) => record.host.kind === lane.host.kind && record.host.id === lane.host.id);
259
- const capacity = buildHostCapacitySnapshot({
260
- host: lane.host,
261
- lanes,
262
- config,
263
- existsSync,
264
- probe: accountDeps?.probe,
265
- env: accountDeps?.env,
266
- hostname,
267
- now,
268
- });
269
- const selection = selectClaudeAccount({
270
- hosts: [{ capacity, lanes, laneListAvailable: true }],
271
- targetHost: lane.host,
272
- config,
273
- quotaState: loadQuotaState(hqRoot),
274
- ...((recordedModel ?? pinnedModel ?? profileModel) !== undefined
275
- ? { model: recordedModel ?? pinnedModel ?? profileModel }
276
- : {}),
277
- });
278
- return {
279
- account: resolveAccount(lane.provider, selection.account, config, context),
280
- changeReason: reason,
281
- ...(recordedModel !== undefined ? { preservedModel: recordedModel } : {}),
282
- };
283
- }
284
- const allowedAccounts = Object.entries(config.providers[lane.provider].accounts)
285
- .filter(([id, account]) => id !== lane.account && account.enabled)
286
- .filter(([id]) => accountStatus(lane.provider, id, config, {
287
- existsSync,
288
- hostname,
289
- ...(accountDeps?.probe ? { probe: accountDeps.probe } : {}),
290
- ...(accountDeps?.env ? { env: accountDeps.env } : {}),
291
- }).logged_in === true)
292
- .filter(([id]) => supportsSpawnModel(lane.provider, id, config, pinnedModel, profileModel, modelDeps, hostname))
293
- .map(([id]) => id);
294
- try {
295
- return {
296
- account: selectBalancedAccount(lane.provider, config, {
297
- ...context,
298
- allowedAccounts,
299
- }),
300
- changeReason: reason,
301
- };
302
- }
303
- catch (err) {
304
- if (reason === "account_unavailable" || reason === "recorded_account_logged_out") {
305
- if (refusal instanceof Error)
306
- throw refusal;
307
- throw new LanesError("account_not_logged_in", `Account ${lane.account} for ${lane.provider} is not logged in or available, and no other logged-in account can serve this lane`, { provider: lane.provider, account: lane.account });
308
- }
309
- if (refusal instanceof Error)
310
- throw refusal;
311
- throw err;
312
- }
313
- }
314
- function previouslyUnavailableAccounts(lane) {
315
- const excluded = new Set();
316
- for (const entry of [...(lane.account_history ?? [])].reverse()) {
317
- if (entry.reason === "first_assignment" || entry.reason === "operator_move")
318
- break;
319
- if ((entry.reason === "account_unavailable" || entry.reason === "recorded_account_logged_out") &&
320
- entry.from !== null)
321
- excluded.add(entry.from);
322
- }
323
- return excluded;
324
- }
325
- function archivedResumeMessageText(hqRoot, laneId, messageId) {
326
- if (!messageId || /[\\/\0]/.test(messageId))
327
- return undefined;
328
- const file = path.join(laneRunDir(hqRoot, laneId), "dropbox", "delivered", `${messageId}.resume.jsonl`);
329
- let raw;
330
- try {
331
- raw = fs.readFileSync(file, "utf8");
332
- }
333
- catch (err) {
334
- if (err.code === "ENOENT")
335
- return undefined;
336
- throw new LanesError("account_retry_context_unreadable", `Could not read the archived message needed to resume lane ${laneId}`, { lane_id: laneId, message_id: messageId });
337
- }
338
- const records = [];
339
- for (const line of raw.split(/\r?\n/)) {
340
- if (line.trim().length === 0)
341
- continue;
342
- let parsed;
343
- try {
344
- parsed = JSON.parse(line);
345
- }
346
- catch {
347
- continue;
348
- }
349
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
350
- continue;
351
- records.push(parsed);
352
- }
353
- if (records.length !== 1) {
354
- throw new LanesError("account_retry_context_invalid", `The archived message needed to resume lane ${laneId} is malformed`, { lane_id: laneId, message_id: messageId });
355
- }
356
- const value = records[0];
357
- if (value === null ||
358
- typeof value !== "object" ||
359
- value.message_id !== messageId ||
360
- typeof value.text !== "string") {
361
- throw new LanesError("account_retry_context_invalid", `The archived message needed to resume lane ${laneId} is malformed`, { lane_id: laneId, message_id: messageId });
362
- }
363
- return value.text;
364
- }
365
- function pendingResumeForRetry(hqRoot, lane, sessionId, at) {
366
- const last = lane.last_resume;
367
- const keepAlive = last?.keep_alive === true ? { keep_alive: true } : {};
368
- if (last === undefined || last.session_id !== sessionId) {
369
- return { session_id: sessionId, trigger: "resume", resumed_from: "interrupted", at, ...keepAlive };
370
- }
371
- const compact = last.compact === undefined ? {} : { compact: last.compact };
372
- if (last.trigger === "answered_questions") {
373
- return { session_id: sessionId, trigger: "answered_questions", at, ...compact, ...keepAlive };
374
- }
375
- if (last.trigger === "watcher") {
376
- return {
377
- session_id: sessionId,
378
- trigger: "watcher",
379
- resumed_from: last.resumed_from ?? "interrupted",
380
- ...(last.text !== undefined ? { text: last.text } : {}),
381
- at,
382
- ...compact,
383
- ...keepAlive,
384
- };
385
- }
386
- if (last.trigger === "message" || last.trigger === "monitor_event" || last.trigger === "system_notice") {
387
- if (last.message_id === undefined) {
388
- throw new LanesError("account_retry_context_missing", `The message id needed to resume lane ${lane.lane_id} is missing`, { lane_id: lane.lane_id, trigger: last.trigger });
389
- }
390
- const text = last.text ?? archivedResumeMessageText(hqRoot, lane.lane_id, last.message_id);
391
- if (text === undefined) {
392
- throw new LanesError("account_retry_context_missing", `The operator message needed to resume lane ${lane.lane_id} is unavailable`, { lane_id: lane.lane_id, message_id: last.message_id });
393
- }
394
- return {
395
- session_id: sessionId,
396
- trigger: last.trigger === "message" && last.monitor_event === true ? "monitor_event" : last.trigger,
397
- text,
398
- message_id: last.message_id,
399
- ...(last.monitor_event === true || last.trigger === "monitor_event" ? { monitor_event: true } : {}),
400
- at,
401
- ...compact,
402
- ...keepAlive,
403
- };
404
- }
405
- return {
406
- session_id: sessionId,
407
- trigger: "resume",
408
- resumed_from: last.resumed_from ?? "interrupted",
409
- ...(last.text !== undefined ? { text: last.text } : {}),
410
- ...(last.message_id !== undefined ? { message_id: last.message_id } : {}),
411
- at,
412
- ...compact,
413
- ...keepAlive,
414
- };
415
- }
416
- /** Change account only after a provider/runtime account failure, then re-admit. */
417
- export async function retryLaneOnAlternateAccount(hqRoot, lane, reason, writer = "watcher", deps = {}) {
418
- const config = loadLanesConfig(hqRoot);
419
- const existsSync = deps.existsSync ?? ((p) => fs.existsSync(p));
420
- const env = deps.env ?? process.env;
421
- const admissionHost = deps.admissionHost ?? resolveAdmissionHost();
422
- const hostname = deps.hostname?.trim() || admissionHost.hostname.trim() || resolveAdmissionHost().hostname;
423
- const modelDeps = {
424
- ...deps.modelDeps,
425
- env: deps.modelDeps?.env ?? env,
426
- };
427
- const accountDeps = {
428
- probe: modelDeps.probe ?? defaultProbe,
429
- env,
430
- };
431
- const profile = lane.worker_profile ? loadWorkerProfile(hqRoot, lane.worker_profile) : undefined;
432
- const profileModel = profile?.meta.provider === lane.provider ? profile.meta.model : undefined;
433
- const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
434
- ? lane.model
435
- : undefined;
436
- const unavailableAccounts = previouslyUnavailableAccounts(lane);
437
- const allowedAccounts = Object.entries(config.providers[lane.provider].accounts)
438
- .filter(([id, account]) => id !== lane.account && !unavailableAccounts.has(id) && account.enabled)
439
- .filter(([id]) => accountStatus(lane.provider, id, config, {
440
- existsSync,
441
- hostname,
442
- ...(accountDeps?.probe ? { probe: accountDeps.probe } : {}),
443
- ...(accountDeps?.env ? { env: accountDeps.env } : {}),
444
- }).logged_in === true)
445
- .filter(([id]) => supportsSpawnModel(lane.provider, id, config, pinnedModel, profileModel, modelDeps, hostname))
446
- .map(([id]) => id);
447
- const modelContext = {
448
- hqRoot,
449
- existsSync,
450
- accountDeps,
451
- hostname,
452
- ...(pinnedModel ?? profileModel ? { model: pinnedModel ?? profileModel } : {}),
453
- allowedAccounts,
454
- };
455
- let target;
456
- try {
457
- target = selectBalancedAccount(lane.provider, config, modelContext);
458
- }
459
- catch (err) {
460
- if (reason === "account_unavailable" || unavailableAccounts.size > 0) {
461
- throw new LanesError("account_not_logged_in", `Account ${lane.account ?? "(none)"} for ${lane.provider} is unavailable and no other logged-in account can serve this lane`, { provider: lane.provider, account: lane.account ?? null });
462
- }
463
- throw err;
464
- }
465
- const source = lane.account ? config.providers[lane.provider].accounts[lane.account] : undefined;
466
- const sessionId = providerSupportsSessionResume(lane.provider) &&
467
- typeof lane.provider_session_id === "string" &&
468
- lane.provider_session_id.trim().length > 0
469
- ? lane.provider_session_id
470
- : undefined;
471
- if (source && sessionId) {
472
- copySessionFiles(planSessionCopy(lane.provider, {
473
- sourceHome: lane.provider_home_at_spawn ?? effectiveAccountHome(source, hostname).home,
474
- targetHome: target.home,
475
- cwd: hqRoot,
476
- sessionId,
477
- }));
478
- }
479
- const now = (deps.now ?? (() => new Date()))();
480
- const at = now.toISOString();
481
- const nowMs = now.getTime();
482
- return withLaneAdmissionLock(hqRoot, lane.provider, async () => {
483
- const current = readLane(hqRoot, lane.lane_id);
484
- if (current.state !== "running" ||
485
- current.account !== lane.account ||
486
- current.provider_session_id !== lane.provider_session_id) {
487
- throw new LanesError("account_retry_conflict", `Lane ${lane.lane_id} changed while account recovery was prepared`, {
488
- lane_id: lane.lane_id,
489
- state: current.state,
490
- account: current.account ?? null,
491
- provider_session_id_changed: current.provider_session_id !== lane.provider_session_id,
492
- });
493
- }
494
- const moveToRetryQueue = (row) => {
495
- const entry = {
496
- from: row.account ?? null,
497
- to: target.id,
498
- at,
499
- reason,
500
- };
501
- return {
502
- ...row,
503
- state: "queued",
504
- queued_reason: "account_retry",
505
- queued_details: undefined,
506
- queued_at: at,
507
- admission_reserved_at: undefined,
508
- terminal_reason: undefined,
509
- terminal_details: undefined,
510
- account: target.id,
511
- account_history: appendCappedHistory(row.account_history ?? [], entry),
512
- pending_resume: sessionId
513
- ? pendingResumeForRetry(hqRoot, row, sessionId, at)
514
- : undefined,
515
- };
516
- };
517
- const candidate = moveToRetryQueue(current);
518
- const admissionLanes = listLaneIds(hqRoot)
519
- .filter((id) => id !== current.lane_id)
520
- .map((id) => readLane(hqRoot, id));
521
- admissionLanes.push(candidate);
522
- const profileMaxFor = (row) => row.worker_profile === undefined
523
- ? undefined
524
- : loadWorkerProfile(hqRoot, row.worker_profile).meta.max_concurrent;
525
- const capacityReason = laneAdmissionCapReason(admissionLanes, candidate, config, admissionHost, profile?.meta.max_concurrent, nowMs);
526
- const earlierEligibleLane = hasEarlierEligibleQueuedLane(admissionLanes, candidate, config, admissionHost, profileMaxFor, nowMs);
527
- const moved = retryUpdateLane(hqRoot, lane.lane_id, writer, (row) => {
528
- if (row.state !== "running" ||
529
- row.account !== lane.account ||
530
- row.provider_session_id !== lane.provider_session_id) {
531
- throw new LanesError("account_retry_conflict", `Lane ${lane.lane_id} changed while account recovery was prepared`, {
532
- lane_id: lane.lane_id,
533
- state: row.state,
534
- account: row.account ?? null,
535
- provider_session_id_changed: row.provider_session_id !== lane.provider_session_id,
536
- });
537
- }
538
- return moveToRetryQueue(row);
539
- });
540
- if (capacityReason !== undefined || earlierEligibleLane)
541
- return moved;
542
- return spawnLaneWorker(hqRoot, moved, deps);
543
- });
544
- }
545
- export function appendModelFlag(provider, args, model) {
546
- if (model === undefined)
547
- return args;
548
- const flag = PROVIDER_MODEL_FLAG[provider];
549
- if (flag === undefined) {
550
- throw new LanesError("model_unsupported", `Provider ${provider} does not accept --model`, { provider, model });
551
- }
552
- if (provider === "codex") {
553
- // `codex exec -- <prompt>`: an option after `--` is read as a positional.
554
- const end = args.indexOf("--");
555
- if (end !== -1)
556
- return [...args.slice(0, end), flag, model, ...args.slice(end)];
557
- }
558
- return [...args, flag, model];
559
- }
560
- /** Add Codex fast-mode flags before the prompt/positional separator. */
561
- export function appendFastModeFlags(provider, args, enabled) {
562
- if (provider !== "codex" || enabled !== true)
563
- return args;
564
- const flags = [...CODEX_FAST_MODE_FLAGS];
565
- const end = args.indexOf("--");
566
- if (end === -1)
567
- return [...args, ...flags];
568
- return [...args.slice(0, end), ...flags, ...args.slice(end)];
569
- }
570
- function appendProviderProfileFlags(provider, args, profile) {
571
- if (profile === undefined)
572
- return args;
573
- const ignored = new Set(profile.ignoredFields ?? []);
574
- switch (provider) {
575
- case "claude": {
576
- const flags = [
577
- "--append-system-prompt",
578
- profile.systemPrompt,
579
- // A profile is a per-spawn input. Do not let Claude's session resume
580
- // snapshot hide a changed profile from the next launch.
581
- "--system-prompt-snapshot",
582
- "off",
583
- ...(profile.settingsPath !== undefined && !ignored.has("settings")
584
- ? ["--settings", profile.settingsPath]
585
- : []),
586
- ];
587
- return [...args, ...flags];
588
- }
589
- case "codex": {
590
- const flags = ["-c", `developer_instructions=${JSON.stringify(profile.systemPrompt)}`];
591
- const end = args.indexOf("--");
592
- if (end === -1)
593
- return [...args, ...flags];
594
- return [...args.slice(0, end), ...flags, ...args.slice(end)];
595
- }
596
- case "grok":
597
- return [...args, "--rules", profile.systemPrompt];
598
- default: {
599
- const _exhaustive = provider;
600
- return _exhaustive;
601
- }
602
- }
603
- }
604
- /** Make the worker policy directory available to Codex hook subprocesses. */
605
- function appendCodexWorkerPolicyDirFlag(provider, args, workerPolicyDir) {
606
- if (provider !== "codex" || workerPolicyDir === undefined)
607
- return args;
608
- if (!workerPolicyDir.trim()) {
609
- throw new LanesError("invalid_worker_policy_dir", "Worker policy directory must not be empty");
610
- }
611
- const setting = `shell_environment_policy.set.HQ_POLICY_WORKER_DIR=${JSON.stringify(workerPolicyDir)}`;
612
- const separator = args.indexOf("--");
613
- if (separator === -1)
614
- return [...args, "-c", setting];
615
- return [...args.slice(0, separator), "-c", setting, ...args.slice(separator)];
616
- }
617
- function accountHomeHostname(deps) {
618
- return (deps.hostname?.trim() ||
619
- deps.admissionHost?.hostname.trim() ||
620
- resolveAdmissionHost().hostname);
621
- }
622
- export const PID_LIVENESS_DECISIONS = [
623
- "esrch",
624
- "starttime_mismatch",
625
- "eperm",
626
- "starttime_match",
627
- "no_recorded_starttime",
628
- "starttime_unreadable",
629
- "missing_pid_file",
630
- ];
631
- export function missingPidProbe() {
632
- return {
633
- pid: null,
634
- recorded_starttime: null,
635
- live_starttime: null,
636
- starttime_error: "ENOENT",
637
- alive: false,
638
- decided_by: "missing_pid_file",
639
- };
640
- }
641
- export function defaultPidIsAlive(pid) {
642
- try {
643
- process.kill(pid, 0);
644
- return true;
645
- }
646
- catch (err) {
647
- const code = err.code;
648
- if (code === "ESRCH")
649
- return false;
650
- if (code === "EPERM")
651
- return true;
652
- throw err;
653
- }
654
- }
655
- export const STOP_TERM_WAIT_MS = 500;
656
- export const STOP_KILL_WAIT_MS = 200;
657
- const defaultSpawnProcess = (command, args, options) => spawn(command, args, options);
658
- function defaultKillProcess(pid, signal = "SIGTERM") {
659
- process.kill(pid, signal);
660
- }
661
- export function parseSpawnTerminalReason(value) {
662
- if (SPAWN_TERMINAL_REASONS.includes(value)) {
663
- return value;
664
- }
665
- throw new LanesError("unknown_spawn_reason", `Unknown spawn terminal reason ${JSON.stringify(value)}. Accepted: ${SPAWN_TERMINAL_REASONS.join(", ")}`, { accepted: [...SPAWN_TERMINAL_REASONS], value });
666
- }
667
- export function laneRunDir(hqRoot, laneId) {
668
- return path.join(hqRoot, LANES_RUNS_REL, laneId);
669
- }
670
- export function watcherMainPath() {
671
- return fileURLToPath(new URL("./watcher-main.js", import.meta.url));
672
- }
673
- export function parseProcStat(text) {
674
- const open = text.indexOf("(");
675
- const close = text.lastIndexOf(")");
676
- if (open <= 0 || close <= open) {
677
- throw new LanesError("proc_stat_unreadable", "Could not parse /proc/<pid>/stat", { text: text.slice(0, 120) });
678
- }
679
- const pid = Number(text.slice(0, open).trim());
680
- const rest = text.slice(close + 1).trim().split(/\s+/);
681
- const ppid = Number(rest[1]);
682
- const pgrp = Number(rest[2]);
683
- const session = Number(rest[3]);
684
- if (![pid, ppid, pgrp, session].every((n) => Number.isInteger(n))) {
685
- throw new LanesError("proc_stat_unreadable", "Could not parse pid/ppid/pgrp/session from /proc/<pid>/stat", { text: text.slice(0, 120) });
686
- }
687
- // /proc/<pid>/stat fields are 1-indexed and `rest` begins at field 3 (state),
688
- // so field N lives at rest[N - 3]. starttime is field 22 -> rest[19].
689
- // rest[21] is field 24 (rss), which at spawn is a page count like 1 and grows
690
- // as the process runs — recording it made every fresh lane look dead within
691
- // seconds of starting.
692
- const startRaw = rest[19];
693
- const starttime = startRaw !== undefined ? Number(startRaw) : undefined;
694
- return {
695
- pid,
696
- ppid,
697
- pgrp,
698
- session,
699
- starttime: Number.isInteger(starttime) ? starttime : undefined,
700
- };
701
- }
702
- export function readProcStarttimeDetailed(pid) {
703
- const proc = path.join("/proc", String(pid), "stat");
704
- try {
705
- const starttime = parseProcStat(fs.readFileSync(proc, "utf8")).starttime;
706
- if (starttime === undefined)
707
- return { starttime: null, error: "missing_field" };
708
- return { starttime, error: null };
709
- }
710
- catch (err) {
711
- const code = err.code;
712
- if (code === "ENOENT")
713
- return { starttime: null, error: "ENOENT" };
714
- process.stderr.write(`hq lanes: failed to read starttime for pid ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
715
- return {
716
- starttime: null,
717
- error: typeof code === "string" ? code : "unreadable",
718
- };
719
- }
720
- }
721
- export function readProcStarttime(pid) {
722
- return readProcStarttimeDetailed(pid).starttime;
723
- }
724
- export function formatPidRecord(rec) {
725
- return rec.starttime !== undefined ? `${rec.pid} ${rec.starttime}\n` : `${rec.pid}\n`;
726
- }
727
- export function parsePidRecord(text) {
728
- const tokens = text.trim().split(/\s+/);
729
- const pid = Number(tokens[0]);
730
- if (!Number.isInteger(pid) || pid <= 0)
731
- return null;
732
- const starttime = tokens[1] !== undefined ? Number(tokens[1]) : undefined;
733
- return {
734
- pid,
735
- starttime: Number.isInteger(starttime) ? starttime : undefined,
736
- };
737
- }
738
- export function readPidRecord(filePath) {
739
- try {
740
- return parsePidRecord(fs.readFileSync(filePath, "utf8"));
741
- }
742
- catch (err) {
743
- const code = err.code;
744
- if (code === "ENOENT")
745
- return null;
746
- process.stderr.write(`hq lanes: failed to read pid file ${filePath}: ${err instanceof Error ? err.message : String(err)}\n`);
747
- throw err;
748
- }
749
- }
750
- export function writePidRecord(filePath, rec) {
751
- writeText(filePath, formatPidRecord(rec));
752
- }
753
- export function probePidRecord(rec, isAlive = defaultPidIsAlive, readStarttime = readProcStarttime) {
754
- const recorded = rec.starttime ?? null;
755
- const base = { pid: rec.pid, recorded_starttime: recorded };
756
- let killAlive;
757
- let killDecision = "starttime_match";
758
- try {
759
- killAlive = isAlive(rec.pid);
760
- }
761
- catch (err) {
762
- const code = err.code;
763
- if (code === "ESRCH") {
764
- return {
765
- ...base,
766
- live_starttime: null,
767
- starttime_error: null,
768
- alive: false,
769
- decided_by: "esrch",
770
- };
771
- }
772
- if (code === "EPERM") {
773
- killAlive = true;
774
- killDecision = "eperm";
775
- }
776
- else {
777
- throw err;
778
- }
779
- }
780
- if (!killAlive) {
781
- return {
782
- ...base,
783
- live_starttime: null,
784
- starttime_error: null,
785
- alive: false,
786
- decided_by: "esrch",
787
- };
788
- }
789
- if (recorded === null) {
790
- return {
791
- ...base,
792
- live_starttime: null,
793
- starttime_error: null,
794
- alive: true,
795
- decided_by: killDecision === "eperm" ? "eperm" : "no_recorded_starttime",
796
- };
797
- }
798
- let live;
799
- let starttime_error = null;
800
- try {
801
- live = readStarttime(rec.pid);
802
- if (live === null)
803
- starttime_error = "unreadable";
804
- }
805
- catch (err) {
806
- const code = err.code;
807
- live = null;
808
- starttime_error = typeof code === "string" ? code : "unreadable";
809
- }
810
- if (live === null) {
811
- return {
812
- ...base,
813
- live_starttime: null,
814
- starttime_error,
815
- alive: true,
816
- decided_by: "starttime_unreadable",
817
- };
818
- }
819
- if (live !== recorded) {
820
- return {
821
- ...base,
822
- live_starttime: live,
823
- starttime_error: null,
824
- alive: false,
825
- decided_by: "starttime_mismatch",
826
- };
827
- }
828
- return {
829
- ...base,
830
- live_starttime: live,
831
- starttime_error: null,
832
- alive: true,
833
- decided_by: killDecision === "eperm" ? "eperm" : "starttime_match",
834
- };
835
- }
836
- export function isPidRecordAlive(rec, isAlive = defaultPidIsAlive, readStarttime = readProcStarttime) {
837
- return probePidRecord(rec, isAlive, readStarttime).alive;
838
- }
839
- function blockingSleep(ms) {
840
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
841
- }
842
- export function signalProcessGroup(pid, signal, killProcess) {
843
- try {
844
- killProcess(-pid, signal);
845
- return;
846
- }
847
- catch (err) {
848
- const code = err.code;
849
- if (code === "ESRCH")
850
- return;
851
- if (code !== "EINVAL" && code !== "EPERM") {
852
- process.stderr.write(`hq lanes: process-group ${signal} for pid ${pid} failed: ${err instanceof Error ? err.message : String(err)}\n`);
853
- }
854
- }
855
- try {
856
- killProcess(pid, signal);
857
- }
858
- catch (err) {
859
- const code = err.code;
860
- if (code === "ESRCH")
861
- return;
862
- process.stderr.write(`hq lanes: ${signal} for pid ${pid} failed: ${err instanceof Error ? err.message : String(err)}\n`);
863
- throw err;
864
- }
865
- }
866
- export function stopLaneProcesses(hqRoot, laneId, deps = {}) {
867
- const killProcess = deps.killProcess ?? defaultKillProcess;
868
- const isAlive = deps.isAlive ??
869
- ((pid) => {
870
- try {
871
- process.kill(pid, 0);
872
- return true;
873
- }
874
- catch (err) {
875
- const code = err.code;
876
- if (code === "ESRCH")
877
- return false;
878
- if (code === "EPERM")
879
- return true;
880
- throw err;
881
- }
882
- });
883
- const sleepMs = deps.sleepMs ?? blockingSleep;
884
- const readStarttime = deps.readStarttime ?? readProcStarttime;
885
- const runDir = laneRunDir(hqRoot, laneId);
886
- const worker = readPidRecord(path.join(runDir, "worker.pid"));
887
- const watcher = readPidRecord(path.join(runDir, "watcher.pid"));
888
- const signals = [];
889
- const targets = [worker, watcher].filter((rec) => rec !== null);
890
- const fire = (rec, signal) => {
891
- if (!isPidRecordAlive(rec, isAlive, readStarttime))
892
- return;
893
- signals.push({ pid: rec.pid, signal, group: true });
894
- signalProcessGroup(rec.pid, signal, killProcess);
895
- };
896
- for (const rec of targets)
897
- fire(rec, "SIGTERM");
898
- if (targets.some((rec) => isPidRecordAlive(rec, isAlive, readStarttime))) {
899
- sleepMs(STOP_TERM_WAIT_MS);
900
- }
901
- for (const rec of targets) {
902
- if (isPidRecordAlive(rec, isAlive, readStarttime))
903
- fire(rec, "SIGKILL");
904
- }
905
- return { worker, watcher, signals };
906
- }
907
- export function defaultProveDetached(pid, deps = {}) {
908
- const proc = path.join("/proc", String(pid), "stat");
909
- try {
910
- const text = deps.readProcStatText
911
- ? deps.readProcStatText(pid)
912
- : fs.readFileSync(proc, "utf8");
913
- const parsed = parseProcStat(text);
914
- const leader = parsed.pid === pid && parsed.pgrp === parsed.pid && parsed.session === parsed.pgrp;
915
- return {
916
- detached: leader,
917
- pid,
918
- pgid: parsed.pgrp,
919
- sid: parsed.session,
920
- method: "proc_stat_session_leader",
921
- reason: leader ? undefined : "not_session_leader",
922
- };
923
- }
924
- catch (err) {
925
- const code = err.code;
926
- if (code !== "ENOENT") {
927
- process.stderr.write(`hq lanes: failed to read ${proc}: ${err instanceof Error ? err.message : String(err)}\n`);
928
- throw err;
929
- }
930
- }
931
- try {
932
- process.kill(pid, 0);
933
- }
934
- catch (err) {
935
- const code = err.code;
936
- if (code === "ESRCH") {
937
- return { detached: false, pid, method: "pid_alive", reason: "pid_not_alive" };
938
- }
939
- if (code !== "EPERM") {
940
- process.stderr.write(`hq lanes: liveness probe for pid ${pid} failed: ${err instanceof Error ? err.message : String(err)}\n`);
941
- throw err;
942
- }
943
- }
944
- const psProof = proveDetachedViaPs(pid);
945
- if (psProof)
946
- return psProof;
947
- return {
948
- detached: false,
949
- pid,
950
- method: "pid_alive_without_proc",
951
- reason: "not_session_leader",
952
- };
953
- }
954
- function proveDetachedViaPs(pid) {
955
- try {
956
- const result = spawnSync("ps", ["-p", String(pid), "-o", "pid=,pgid="], {
957
- encoding: "utf8",
958
- timeout: 500,
959
- });
960
- if (result.error || result.status !== 0)
961
- return null;
962
- const parts = (result.stdout ?? "").trim().split(/\s+/).map(Number);
963
- if (parts.length < 2 || parts.some((n) => !Number.isInteger(n)))
964
- return null;
965
- const psPid = parts[0];
966
- const pgid = parts[1];
967
- const leader = psPid === pid && pgid === pid;
968
- return {
969
- detached: leader,
970
- pid,
971
- pgid,
972
- method: "ps_session_leader",
973
- reason: leader ? undefined : "not_session_leader",
974
- };
975
- }
976
- catch (err) {
977
- process.stderr.write(`hq lanes: ps detach proof failed for pid ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
978
- return null;
979
- }
980
- }
981
- export function nextEnvelopePath(runDir) {
982
- const dir = path.join(runDir, "envelopes");
983
- let n = 1;
984
- while (true) {
985
- const name = `${String(n).padStart(3, "0")}.json`;
986
- const filePath = path.join(dir, name);
987
- if (!fs.existsSync(filePath))
988
- return filePath;
989
- n += 1;
990
- if (n > 999) {
991
- throw new LanesError("envelope_sequence_exhausted", `No free envelope slot under ${dir}`, { dir });
992
- }
993
- }
994
- }
995
- export function envelopeInstruction(envelopePath) {
996
- return (`When finished, write a JSON object to ${envelopePath} using these key names exactly: ` +
997
- `schema_version, decision, summary, story_status, artifacts, story_complete, story_complete_reason, questions, blocked_reason, next_check_at. ` +
998
- `schema_version must be the exact string "hq-lane-envelope.v1". ` +
999
- `decision must be one of "done", "ask", "blocked". ` +
1000
- `summary is a string. ` +
1001
- `story_status must be one of "queued", "in_progress", "review", "done". ` +
1002
- `artifacts is an array. ` +
1003
- `story_complete is a boolean and story_complete_reason is a non-empty string. ` +
1004
- `story_complete true requires story_status done and a reason stating what was delivered and how it was verified. ` +
1005
- `story_complete false requires story_status other than done and a reason stating what is still missing. ` +
1006
- `questions is present and non-empty exactly when decision is "ask". ` +
1007
- `blocked_reason is present exactly when decision is "blocked". ` +
1008
- `next_check_at is optional; when present, use an ISO date-time for the next time-based keep-alive check.`);
1009
- }
1010
- /**
1011
- * Standing authorization carried by every brief and every resume turn. A
1012
- * lane that ends each turn asking "continue or stop" has asked the operator
1013
- * to re-grant what the brief already granted; the paragraph names that as
1014
- * out of bounds and says what a `decision: ask` envelope is for.
1015
- */
1016
- export const STANDING_AUTHORIZATION = "STANDING AUTHORIZATION. This brief authorises completing every item it lists; " +
1017
- "you do not need to ask before finishing any of them. " +
1018
- 'A "decision": "ask" envelope is only for a decision this brief does not settle, ' +
1019
- "and it must name that decision and its options. " +
1020
- 'Do not raise a question whose options amount to "continue" or "stop" the work this brief describes; ' +
1021
- "continue that work until it is complete or you are blocked on something only the operator can supply.";
1022
- /**
1023
- * Foreground-only rule carried next to the standing authorization. Two lanes
1024
- * ended `interrupted` after backgrounding a slow test suite and ending the
1025
- * turn while it was still running; nothing in the brief said not to.
1026
- */
1027
- export const FOREGROUND_ONLY_RULE = "FOREGROUND ONLY. Run every command, test suite and check in the foreground and wait for it to finish. " +
1028
- "Never background a process and end the turn while it is still running. " +
1029
- "A turn that ends before the envelope is written is classified interrupted, " +
1030
- "and whatever the background process produces afterwards is not read.";
1031
- /**
1032
- * The answers as written by the reconcile pass (`answered-questions.json`),
1033
- * reduced to id + choice. A malformed file reads as no inline answers; the
1034
- * path is still named so the worker can read it.
1035
- */
1036
- export function readAnsweredQuestionLines(answersPath) {
1037
- let text;
1038
- try {
1039
- text = fs.readFileSync(answersPath, "utf8");
1040
- }
1041
- catch (err) {
1042
- const code = err.code;
1043
- if (code === "ENOENT")
1044
- return [];
1045
- process.stderr.write(`hq lanes: failed to read ${answersPath}: ${err instanceof Error ? err.message : String(err)}\n`);
1046
- throw err;
1047
- }
1048
- let parsed;
1049
- try {
1050
- parsed = JSON.parse(text);
1051
- }
1052
- catch (err) {
1053
- throw new LanesError("answered_questions_invalid", `Answered questions at ${answersPath} are not valid JSON`, { path: answersPath });
1054
- }
1055
- if (!Array.isArray(parsed)) {
1056
- throw new LanesError("answered_questions_invalid", `Answered questions at ${answersPath} must be a JSON array`, { path: answersPath });
1057
- }
1058
- const out = [];
1059
- for (const [index, item] of parsed.entries()) {
1060
- if (!item || typeof item !== "object" || Array.isArray(item)) {
1061
- throw new LanesError("answered_questions_invalid", `Answered question ${index} at ${answersPath} must be an object`, { path: answersPath, index });
1062
- }
1063
- const rec = item;
1064
- if (typeof rec.question_id !== "string" || !rec.question_id.trim()) {
1065
- throw new LanesError("answered_questions_invalid", `Answered question ${index} at ${answersPath} must have a question_id`, { path: answersPath, index });
1066
- }
1067
- if (typeof rec.choice !== "string") {
1068
- throw new LanesError("answered_questions_invalid", `Answered question ${rec.question_id} at ${answersPath} must have a choice`, { path: answersPath, question_id: rec.question_id });
1069
- }
1070
- const line = {
1071
- question_id: rec.question_id,
1072
- choice: rec.choice,
1073
- };
1074
- if (rec.notes !== undefined && typeof rec.notes !== "string") {
1075
- throw new LanesError("answered_questions_invalid", `Answered question ${rec.question_id} at ${answersPath} has invalid notes`, { path: answersPath, question_id: rec.question_id });
1076
- }
1077
- if (typeof rec.notes === "string" && rec.notes.length > 0)
1078
- line.notes = rec.notes;
1079
- out.push(line);
1080
- }
1081
- return out;
1082
- }
1083
- export function resumePrompt(input) {
1084
- const parts = [];
1085
- if (input.resumedFrom !== undefined) {
1086
- parts.push(`${input.resumeSource === "watcher" ? "The lane watcher" : "The operator"} resumed this lane from state ${input.resumedFrom}. ` +
1087
- (input.resumedFrom === "interrupted"
1088
- ? "The previous run ended without writing its envelope; continue the work from where it stopped."
1089
- : "Continue the work from where the previous run stopped."));
1090
- }
1091
- if (input.monitorEvent !== undefined) {
1092
- parts.push(input.monitorEvent);
1093
- }
1094
- else if (input.operatorMessage !== undefined) {
1095
- parts.push("OPERATOR INSTRUCTION (outranks the lane brief). " +
1096
- "The following message was sent to this lane by the operator. Treat it as an operator instruction that outranks the brief.\n\n" +
1097
- input.operatorMessage);
1098
- }
1099
- if (input.answersPath !== undefined) {
1100
- const lines = (input.answers ?? []).map((item) => item.notes !== undefined
1101
- ? `- ${item.question_id}: ${item.choice}\n Operator notes: ${item.notes}`
1102
- : `- ${item.question_id}: ${item.choice}`);
1103
- parts.push([
1104
- `Previously answered questions are at ${input.answersPath}; treat those choices and the operator notes under them as operator decisions that outrank the brief. Continue the work.`,
1105
- ...(lines.length > 0 ? ["Answers:", ...lines] : []),
1106
- ].join("\n"));
1107
- }
1108
- if (input.envelopeRepairErrors !== undefined) {
1109
- const errors = [input.envelopeRepairErrors.first_error, input.envelopeRepairErrors.second_error]
1110
- .filter((error) => typeof error === "string" && error.length > 0);
1111
- parts.push([
1112
- `The previous envelope repair failed validation. The next envelope slot is ${input.envelopePath}; write a new valid envelope there.`,
1113
- "Exact validation errors recorded in envelope_repair:",
1114
- ...errors.map((error, index) => `- envelope_repair.${index === 0 ? "first_error" : "second_error"}: ${JSON.stringify(error)}`),
1115
- "For an ask question, include non-empty id, question, and context fields.",
1116
- ].join("\n"));
1117
- }
1118
- // Every resume turn carries the authorization, including a textless
1119
- // `hq lanes resume`: a pre-upgrade session's brief never had the paragraph.
1120
- if (input.operatorMessage !== undefined ||
1121
- input.monitorEvent !== undefined ||
1122
- input.answersPath !== undefined ||
1123
- input.resumedFrom !== undefined) {
1124
- parts.push(STANDING_AUTHORIZATION);
1125
- parts.push(FOREGROUND_ONLY_RULE);
1126
- }
1127
- parts.push(envelopeInstruction(input.envelopePath));
1128
- return parts.join("\n\n");
1129
- }
1130
- /** Spec §4: the one repair turn. Schema, parser error, raw text, JSON only. */
1131
- export function envelopeRepairPrompt(input) {
1132
- const maxRawTextChars = 24_000;
1133
- const rawText = input.rawText.length <= maxRawTextChars
1134
- ? input.rawText
1135
- : `${input.rawText.slice(0, 12_000)}\n\n[... raw envelope truncated; inspect ${input.envelopePath} for the complete file ...]\n\n${input.rawText.slice(-12_000)}`;
1136
- if (input.missing) {
1137
- return [
1138
- `Missing expected envelope file: ${input.envelopePath}`,
1139
- "The previous envelope is stale and must not be reused or copied into this run's result.",
1140
- "Printing an envelope in the conversation or writing it to last-message.txt is not enough; write the JSON object directly to the expected file.",
1141
- "If the task is unfinished, write decision: done, story_complete: false, and set story_status and story_complete_reason to describe the work that remains. The repair turn itself is never a reason for blocked.",
1142
- "This repair turn only writes the missing envelope; do not resume the task.",
1143
- "Schema:",
1144
- JSON.stringify(LANE_ENVELOPE_JSON_SCHEMA, null, 2),
1145
- `Write the corrected JSON object to ${input.envelopePath}, overwriting it. ` +
1146
- `Output only that JSON. Do not add keys the schema does not name, and do not resume the task.`,
1147
- ].join("\n\n");
1148
- }
1149
- return [
1150
- `The file you wrote at ${input.envelopePath} is not a valid hq-lane-envelope.v1. ` +
1151
- `This is the single repair turn: rewrite that file so it validates, and do nothing else.`,
1152
- `Parser error: ${input.error}`,
1153
- "For an ask question, include non-empty id, question, and context fields.",
1154
- "Schema:",
1155
- JSON.stringify(LANE_ENVELOPE_JSON_SCHEMA, null, 2),
1156
- "Your previous output was:",
1157
- rawText,
1158
- `Write the corrected JSON object to ${input.envelopePath}, overwriting it. ` +
1159
- `Output only that JSON. Do not add keys the schema does not name, and do not resume the task.`,
1160
- ].join("\n\n");
1161
- }
1162
- export function buildProviderCommand(provider, input) {
1163
- const parsed = parseLaneProvider(provider);
1164
- const command = PROVIDER_COMMAND[parsed];
1165
- if (input.resume && !providerSupportsSessionResume(parsed)) {
1166
- throw new LanesError("resume_unsupported", `Provider ${parsed} cannot resume an exited worker from a session id`, { provider: parsed });
1167
- }
1168
- if (input.resume && input.freshTurnPrompt !== undefined) {
1169
- throw new LanesError("invalid_launch", "resume and freshTurnPrompt cannot both be set on one launch", { provider: parsed });
1170
- }
1171
- let prompt;
1172
- if (input.freshTurnPrompt !== undefined) {
1173
- prompt = input.freshTurnPrompt;
1174
- }
1175
- else {
1176
- prompt = `Execute the lane brief at ${input.briefPath}. ${envelopeInstruction(input.envelopePath)}`;
1177
- if (input.extraPrompt)
1178
- prompt += ` ${input.extraPrompt}`;
1179
- }
1180
- let args;
1181
- if (input.resume && parsed === "codex") {
1182
- // `codex exec resume` (0.155.1) takes `[SESSION_ID] [PROMPT]` and has
1183
- // neither `-C` nor `--color`; the session keeps its recorded cwd. `--json`
1184
- // makes the resumed run re-emit `thread.started` with the same id.
1185
- args = [
1186
- "exec",
1187
- "resume",
1188
- "--dangerously-bypass-hook-trust",
1189
- "--skip-git-repo-check",
1190
- "--dangerously-bypass-approvals-and-sandbox",
1191
- "--json",
1192
- "--output-last-message",
1193
- input.lastMessagePath,
1194
- "--",
1195
- input.resume.session_id,
1196
- input.resume.prompt,
1197
- ];
1198
- }
1199
- else if (input.resume && parsed === "grok") {
1200
- // `grok --single <prompt> --resume <id>` (1.0.34) continues the recorded
1201
- // session and prints the same `sessionId` in its JSON result.
1202
- args = [
1203
- "--single",
1204
- input.resume.prompt,
1205
- "--resume",
1206
- input.resume.session_id,
1207
- "--permission-mode",
1208
- "bypassPermissions",
1209
- "--always-approve",
1210
- "--output-format",
1211
- "json",
1212
- ];
1213
- }
1214
- else if (input.resume) {
1215
- args = [
1216
- "-p",
1217
- "--resume",
1218
- input.resume.session_id,
1219
- input.resume.prompt,
1220
- "--permission-mode",
1221
- "bypassPermissions",
1222
- "--output-format",
1223
- "json",
1224
- ];
1225
- }
1226
- else if (parsed === "codex") {
1227
- // `--json` puts the thread id on stdout (`thread.started`); that is the
1228
- // only place `codex exec` exposes the id a later resume needs.
1229
- args = [
1230
- "exec",
1231
- "--dangerously-bypass-hook-trust",
1232
- "--skip-git-repo-check",
1233
- "--dangerously-bypass-approvals-and-sandbox",
1234
- "--color",
1235
- "never",
1236
- "--json",
1237
- "-C",
1238
- input.hqRoot,
1239
- "--output-last-message",
1240
- input.lastMessagePath,
1241
- "--",
1242
- prompt,
1243
- ];
1244
- }
1245
- else if (parsed === "grok") {
1246
- args = [
1247
- "--single",
1248
- prompt,
1249
- "--permission-mode",
1250
- "bypassPermissions",
1251
- "--always-approve",
1252
- "--output-format",
1253
- "json",
1254
- ];
1255
- }
1256
- else {
1257
- args = [
1258
- "-p",
1259
- prompt,
1260
- "--permission-mode",
1261
- "bypassPermissions",
1262
- "--output-format",
1263
- "json",
1264
- ];
1265
- }
1266
- return {
1267
- command,
1268
- args: appendFastModeFlags(parsed, appendEffortFlag(parsed, appendModelFlag(parsed, appendCodexWorkerPolicyDirFlag(parsed, appendProviderProfileFlags(parsed, args, input.profile), input.workerPolicyDir), input.model), input.effort), input.fastMode),
1269
- };
1270
- }
1271
- export function workerEnv(base, resolved, laneId, hqRoot, autoCompactTokens, meshCompany, workerPolicyDir, registryWorker) {
1272
- const accepted = Object.values(PROVIDER_HOME_ENV);
1273
- if (!accepted.includes(resolved.envVar)) {
1274
- throw new LanesError("unknown_provider_home_env", `Unknown provider home variable ${JSON.stringify(resolved.envVar)}. Accepted: ${accepted.join(", ")}`, { accepted, value: resolved.envVar });
1275
- }
1276
- const env = { ...base };
1277
- delete env.HQ_PROJECT_ID;
1278
- delete env.HQ_STORY_ID;
1279
- delete env.HQ_POLICY_WORKER_DIR;
1280
- delete env.HQ_LANE_APPROVAL_REQUIRED;
1281
- delete env.HQ_LANE_HUMAN_CHECKPOINTS;
1282
- env[resolved.envVar] = resolved.home;
1283
- delete env[CLAUDE_AUTO_COMPACT_ENV];
1284
- if (resolved.envVar === PROVIDER_HOME_ENV.claude && autoCompactTokens !== undefined) {
1285
- env[CLAUDE_AUTO_COMPACT_ENV] = String(autoCompactTokens);
1286
- }
1287
- env.HQ_LANE_ID = laneId;
1288
- env.HQ_ROOT = hqRoot;
1289
- if (registryWorker && (registryWorker.approval_required || registryWorker.human_checkpoints.length > 0)) {
1290
- env.HQ_LANE_APPROVAL_REQUIRED = "1";
1291
- env.HQ_LANE_HUMAN_CHECKPOINTS = registryWorker.human_checkpoints.length > 0
1292
- ? registryWorker.human_checkpoints.join(",")
1293
- : "external_publish";
1294
- }
1295
- if (workerPolicyDir !== undefined &&
1296
- (resolved.envVar === PROVIDER_HOME_ENV.claude || resolved.envVar === PROVIDER_HOME_ENV.codex)) {
1297
- env.HQ_POLICY_WORKER_DIR = workerPolicyDir;
1298
- }
1299
- if (meshCompany) {
1300
- env.HQ_SPAWN_COMPANY = meshCompany.slug || meshCompany.uid;
1301
- }
1302
- else {
1303
- delete env.HQ_SPAWN_COMPANY;
1304
- }
1305
- return env;
1306
- }
1307
- export const WORKER_POLICY_HOOK_CAPABILITY = "# hq-capability: worker-policy-dir v1";
1308
- function installedWorkerPolicyHookSupportsDirectory(hqRoot) {
1309
- const hookPath = path.join(hqRoot, ".claude", "hooks", "inject-policy-on-trigger.sh");
1310
- try {
1311
- return fs.readFileSync(hookPath, "utf8")
1312
- .split(/\r?\n/)
1313
- .some((line) => line === WORKER_POLICY_HOOK_CAPABILITY);
1314
- }
1315
- catch (err) {
1316
- const code = err.code;
1317
- if (code === "ENOENT")
1318
- return false;
1319
- process.stderr.write(`hq lanes: cannot inspect worker-policy hook capability at ${hookPath}: ${err instanceof Error ? err.message : String(err)}; keeping policy prompt delivery\n`);
1320
- return false;
1321
- }
1322
- }
1323
- /** Grok does not run HQ hooks; Claude and Codex use the installed capability marker. */
1324
- export function workerPolicyDeliveryMode(hqRoot, provider) {
1325
- return provider !== "grok" && installedWorkerPolicyHookSupportsDirectory(hqRoot)
1326
- ? "hook"
1327
- : "prompt";
1328
- }
1329
- function ensureDir(dir) {
1330
- fs.mkdirSync(dir, { recursive: true });
1331
- }
1332
- function fileSizeOrZero(filePath) {
1333
- try {
1334
- return fs.statSync(filePath).size;
1335
- }
1336
- catch (err) {
1337
- const code = err.code;
1338
- if (code === "ENOENT")
1339
- return 0;
1340
- process.stderr.write(`hq lanes: failed to stat ${filePath}: ${err instanceof Error ? err.message : String(err)}\n`);
1341
- throw err;
1342
- }
1343
- }
1344
- function writeText(filePath, text) {
1345
- ensureDir(path.dirname(filePath));
1346
- fs.writeFileSync(filePath, text, "utf8");
1347
- }
1348
- function appendWorkerProfileEvent(runDir, event) {
1349
- const eventsPath = path.join(runDir, "watcher", "profile-events.jsonl");
1350
- ensureDir(path.dirname(eventsPath));
1351
- fs.appendFileSync(eventsPath, `${JSON.stringify({
1352
- event: "profile_applied",
1353
- ...event,
1354
- at: new Date().toISOString(),
1355
- })}\n`);
1356
- }
1357
- function openLog(filePath) {
1358
- ensureDir(path.dirname(filePath));
1359
- return fs.openSync(filePath, "a");
1360
- }
1361
- function closeFd(fd, label) {
1362
- try {
1363
- fs.closeSync(fd);
1364
- }
1365
- catch (err) {
1366
- process.stderr.write(`hq lanes: failed to close ${label} fd ${fd}: ${err instanceof Error ? err.message : String(err)}\n`);
1367
- throw err;
1368
- }
1369
- }
1370
- function killQuietly(kill, pid, label) {
1371
- try {
1372
- signalProcessGroup(pid, "SIGTERM", kill);
1373
- }
1374
- catch (err) {
1375
- const code = err.code;
1376
- if (code === "ESRCH")
1377
- return;
1378
- process.stderr.write(`hq lanes: failed to stop ${label} pid ${pid}: ${err instanceof Error ? err.message : String(err)}\n`);
1379
- throw err;
1380
- }
1381
- }
1382
- export function markSpawnFailure(hqRoot, laneId, reasonRaw, details) {
1383
- const reason = parseSpawnTerminalReason(reasonRaw);
1384
- return retryUpdateLane(hqRoot, laneId, "spawn", (current) => {
1385
- const existing = current
1386
- .terminal_reason;
1387
- if (current.state === "failed" && existing === reason)
1388
- return current;
1389
- return {
1390
- ...current,
1391
- state: "failed",
1392
- queued_reason: undefined,
1393
- queued_details: undefined,
1394
- queued_at: undefined,
1395
- admission_reserved_at: undefined,
1396
- terminal_reason: reason,
1397
- terminal_details: details,
1398
- };
1399
- });
1400
- }
1401
- function spawnDetached(spawnProcess, command, args, env, cwd, stdoutPath, stderrPath) {
1402
- const outFd = openLog(stdoutPath);
1403
- let errFd;
1404
- try {
1405
- errFd = openLog(stderrPath);
1406
- const child = spawnProcess(command, args, {
1407
- detached: true,
1408
- windowsHide: true,
1409
- stdio: ["ignore", outFd, errFd],
1410
- env,
1411
- cwd,
1412
- });
1413
- child.unref();
1414
- if (typeof child.pid !== "number" || child.pid <= 0) {
1415
- throw new LanesError("spawn_failed", `Failed to start ${command} (no pid)`, { command, args });
1416
- }
1417
- return child.pid;
1418
- }
1419
- catch (err) {
1420
- if (err instanceof LanesError)
1421
- throw err;
1422
- throw new LanesError("spawn_failed", `Failed to start ${command}: ${err instanceof Error ? err.message : String(err)}`, {
1423
- command,
1424
- args,
1425
- message: err instanceof Error ? err.message : String(err),
1426
- });
1427
- }
1428
- finally {
1429
- closeFd(outFd, stdoutPath);
1430
- if (errFd !== undefined)
1431
- closeFd(errFd, stderrPath);
1432
- }
1433
- }
1434
- function requireDetached(proveDetached, pid, kind) {
1435
- const proof = proveDetached(pid);
1436
- if (proof.detached)
1437
- return proof;
1438
- const error = kind === "watcher" ? "watcher_not_armed" : "not_detached";
1439
- throw new LanesError(error, `${kind} pid ${pid} was not proven detached`, { pid, kind, reason: proof.reason ?? error, method: proof.method });
1440
- }
1441
- function originHostOf(lane) {
1442
- const value = lane.origin_host;
1443
- return typeof value === "string" ? value : "";
1444
- }
1445
- function originHostSourceOf(lane) {
1446
- const value = lane.origin_host_source;
1447
- return value === "imds" || value === "hostname" ? value : "";
1448
- }
1449
- function markOutpostSelfTarget(hqRoot, laneId, details) {
1450
- return retryUpdateLane(hqRoot, laneId, "spawn", (current) => {
1451
- const existing = current
1452
- .terminal_reason;
1453
- if (current.state === "cancelled" && existing === "outpost_self_target") {
1454
- return current;
1455
- }
1456
- return {
1457
- ...current,
1458
- state: "cancelled",
1459
- queued_reason: undefined,
1460
- queued_details: undefined,
1461
- terminal_reason: "outpost_self_target",
1462
- terminal_details: details,
1463
- };
1464
- });
1465
- }
1466
- /**
1467
- * Spec §5.2 executing-side check. Compares this machine's identity to
1468
- * `origin_host` (never to `host.id`). Unresolvable identity is a cancel.
1469
- * Must run before the worker is spawned.
1470
- */
1471
- export function refuseOutpostSelfTarget(hqRoot, lane, deps) {
1472
- const identity = (deps.resolveMachineIdentity ?? resolveMachineIdentity)();
1473
- const origin = originHostOf(lane);
1474
- const originSource = originHostSourceOf(lane);
1475
- let selfTargeted = origin === "" || identity.status !== "ok";
1476
- if (!selfTargeted && identity.status === "ok") {
1477
- if (originSource === "imds") {
1478
- const execImds = identity.imds ?? (identity.source === "imds" ? identity.id : null);
1479
- selfTargeted = execImds === null || execImds === origin;
1480
- }
1481
- else if (originSource === "hostname") {
1482
- const execHost = identity.hostname ??
1483
- (identity.source === "hostname" ? identity.id : null);
1484
- selfTargeted = execHost === null ? identity.id === origin : execHost === origin;
1485
- }
1486
- else {
1487
- selfTargeted = identity.id === origin;
1488
- }
1489
- }
1490
- if (!selfTargeted)
1491
- return;
1492
- const cancelled = markOutpostSelfTarget(hqRoot, lane.lane_id, {
1493
- origin_host: origin,
1494
- identity,
1495
- });
1496
- throw new LanesError("outpost_self_target", "Outpost exec came back to the caller; lane cancelled before work", {
1497
- origin_host: origin,
1498
- identity,
1499
- lane_id: lane.lane_id,
1500
- lane: cancelled,
1501
- });
1502
- }
1503
- function writeSpawnManifest(runDir, input) {
1504
- writeText(path.join(runDir, "spawn.json"), `${JSON.stringify({
1505
- command: input.command,
1506
- args: input.args,
1507
- env_var: input.envVar,
1508
- account: input.account,
1509
- worker_pid: input.workerPid,
1510
- watcher_pid: input.watcherPid,
1511
- detached: true,
1512
- envelope_path: input.envelopePath,
1513
- ...(input.turnId !== undefined ? { turn_id: input.turnId } : {}),
1514
- resume: input.resume,
1515
- worker_out_offset: input.workerOutOffset,
1516
- ...(input.fastMode ? { fast_mode: true } : {}),
1517
- ...(input.profile
1518
- ? {
1519
- worker_profile: input.profile.id,
1520
- worker_profile_hash: input.profile.hash,
1521
- worker_profile_ignored: [...input.profile.ignoredFields],
1522
- worker_policy_delivery: input.profile.policyDelivery,
1523
- ...(input.profile.policyDir !== undefined
1524
- ? {
1525
- worker_policy_dir: input.profile.policyDir,
1526
- worker_policy_env: { HQ_POLICY_WORKER_DIR: input.profile.policyDir },
1527
- }
1528
- : {}),
1529
- ...(input.profile.settingsPath
1530
- ? { worker_profile_settings: input.profile.settingsPath }
1531
- : {}),
1532
- }
1533
- : {}),
1534
- }, null, 2)}\n`);
1535
- }
1536
- /** Arm (or re-arm) the detached per-lane watcher. */
1537
- export function armLaneWatcher(hqRoot, laneId, deps = {}) {
1538
- const env = deps.env ?? process.env;
1539
- const spawnProcess = deps.spawnProcess ?? defaultSpawnProcess;
1540
- const proveDetached = deps.proveDetached ?? defaultProveDetached;
1541
- const runDir = laneRunDir(hqRoot, laneId);
1542
- const logsDir = path.join(runDir, "logs");
1543
- ensureDir(logsDir);
1544
- const cliEntry = deps.hqCliEntry?.trim() || process.argv[1]?.trim();
1545
- if (!cliEntry) {
1546
- throw new LanesError("watcher_cli_entry_unavailable", "Cannot arm the lane watcher without the current hq CLI entrypoint", { lane_id: laneId });
1547
- }
1548
- const watcherPid = spawnDetached(spawnProcess, process.execPath, [watcherMainPath(), laneId], {
1549
- ...env,
1550
- HQ_ROOT: hqRoot,
1551
- HQ_LANE_ID: laneId,
1552
- HQ_LANE_CLI_ENTRY: path.resolve(cliEntry),
1553
- }, hqRoot, path.join(logsDir, "watcher.out"), path.join(logsDir, "watcher.err"));
1554
- writePidRecord(path.join(runDir, "watcher.pid"), {
1555
- pid: watcherPid,
1556
- starttime: readProcStarttime(watcherPid) ?? undefined,
1557
- });
1558
- try {
1559
- requireDetached(proveDetached, watcherPid, "watcher");
1560
- }
1561
- catch (err) {
1562
- killQuietly(deps.killProcess ?? defaultKillProcess, watcherPid, "watcher");
1563
- throw err;
1564
- }
1565
- return watcherPid;
1566
- }
1567
- /** Read the per-run manifest. Missing file or field reads as absent. */
1568
- export function readSpawnManifest(runDir) {
1569
- const filePath = path.join(runDir, "spawn.json");
1570
- let text;
1571
- try {
1572
- text = fs.readFileSync(filePath, "utf8");
1573
- }
1574
- catch (err) {
1575
- const code = err.code;
1576
- if (code === "ENOENT")
1577
- return {};
1578
- process.stderr.write(`hq lanes: failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}\n`);
1579
- throw err;
1580
- }
1581
- let parsed;
1582
- try {
1583
- parsed = JSON.parse(text);
1584
- }
1585
- catch (err) {
1586
- process.stderr.write(`hq lanes: ${filePath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}\n`);
1587
- return {};
1588
- }
1589
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1590
- return {};
1591
- const rec = parsed;
1592
- const out = {};
1593
- if (typeof rec.envelope_path === "string")
1594
- out.envelope_path = rec.envelope_path;
1595
- if (typeof rec.turn_id === "string")
1596
- out.turn_id = rec.turn_id;
1597
- if (typeof rec.provider_home_at_spawn === "string") {
1598
- out.provider_home_at_spawn = rec.provider_home_at_spawn;
1599
- }
1600
- if (typeof rec.worker_out_offset === "number" &&
1601
- Number.isInteger(rec.worker_out_offset) &&
1602
- rec.worker_out_offset >= 0) {
1603
- out.worker_out_offset = rec.worker_out_offset;
1604
- }
1605
- if (typeof rec.fast_mode === "boolean")
1606
- out.fast_mode = rec.fast_mode;
1607
- if (typeof rec.worker_profile === "string")
1608
- out.worker_profile = rec.worker_profile;
1609
- if (typeof rec.worker_profile_hash === "string")
1610
- out.worker_profile_hash = rec.worker_profile_hash;
1611
- if (Array.isArray(rec.worker_profile_ignored) && rec.worker_profile_ignored.every((item) => typeof item === "string")) {
1612
- out.worker_profile_ignored = rec.worker_profile_ignored;
1613
- }
1614
- if (typeof rec.worker_profile_settings === "string")
1615
- out.worker_profile_settings = rec.worker_profile_settings;
1616
- if (rec.resume &&
1617
- typeof rec.resume === "object" &&
1618
- typeof rec.resume.session_id === "string") {
1619
- out.resume = { session_id: rec.resume.session_id };
1620
- }
1621
- else if (rec.resume === null) {
1622
- out.resume = null;
1623
- }
1624
- return out;
1625
- }
1626
- function laneLaunchResult(lane) {
1627
- const { provider_home_at_spawn: _providerHomeAtSpawn, ...safe } = lane;
1628
- return safe;
1629
- }
1630
- function sameSeniorRef(a, b) {
1631
- return a.kind === b.kind && a.id === b.id;
1632
- }
1633
- function inferTrigger(lane) {
1634
- if (lane.state === "awaiting_input")
1635
- return { kind: "answered_questions" };
1636
- return { kind: "admit" };
1637
- }
1638
- /**
1639
- * Bind the account, spawn the worker and its watcher outside the caller's
1640
- * tree, then CAS the record to `running`. A spawn that cannot be proven
1641
- * started and detached is a named terminal reason, never a bare `failed`.
1642
- *
1643
- * Fresh-vs-resume is decided by `planLaneLaunch` (delivery.ts), never here.
1644
- */
1645
- export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
1646
- const env = deps.env ?? process.env;
1647
- const hostname = accountHomeHostname(deps);
1648
- const modelDeps = {
1649
- ...deps.modelDeps,
1650
- env: deps.modelDeps?.env ?? env,
1651
- };
1652
- const existsSync = deps.existsSync ?? ((p) => fs.existsSync(p));
1653
- const spawnProcess = deps.spawnProcess ?? defaultSpawnProcess;
1654
- const proveDetached = deps.proveDetached ?? defaultProveDetached;
1655
- const killProcess = deps.killProcess ?? defaultKillProcess;
1656
- const runDir = laneRunDir(hqRoot, lane.lane_id);
1657
- const previousSpawn = readSpawnManifest(runDir);
1658
- const stored = readLane(hqRoot, lane.lane_id);
1659
- const recoveredSessionId = (typeof stored.provider_session_id === "string" && stored.provider_session_id.trim()
1660
- ? stored.provider_session_id
1661
- : undefined) ??
1662
- (typeof stored.last_resume?.session_id === "string" && stored.last_resume.session_id.trim()
1663
- ? stored.last_resume.session_id
1664
- : undefined) ??
1665
- (typeof previousSpawn.resume?.session_id === "string" && previousSpawn.resume.session_id.trim()
1666
- ? previousSpawn.resume.session_id
1667
- : undefined);
1668
- const existing = {
1669
- ...stored,
1670
- ...(stored.provider_session_id === undefined && recoveredSessionId !== undefined
1671
- ? { provider_session_id: recoveredSessionId }
1672
- : {}),
1673
- ...(stored.provider_home_at_spawn === undefined && previousSpawn.provider_home_at_spawn !== undefined
1674
- ? { provider_home_at_spawn: previousSpawn.provider_home_at_spawn }
1675
- : {}),
1676
- };
1677
- if (existing.state === "running") {
1678
- if (launch.trigger?.kind === "resume") {
1679
- throw new LanesError("lane_not_resumable", `Lane ${lane.lane_id} is already running`, { lane_id: lane.lane_id, state: existing.state });
1680
- }
1681
- return laneLaunchResult(existing);
1682
- }
1683
- // A queued lane that a move parked at the target's cap carries the turn
1684
- // it was resumed with: the admit spawn continues that session instead of
1685
- // starting fresh from the brief.
1686
- const pendingResume = launch.trigger === undefined && existing.state === "queued" ? existing.pending_resume : undefined;
1687
- const trigger = launch.trigger ?? inferTrigger(existing);
1688
- const failedResumeClaim = (trigger.kind === "resume" && trigger.fromFailed === true) || pendingResume?.from_failed === true;
1689
- const failedResumeExpectedSenior = trigger.kind === "resume" && trigger.fromFailed === true
1690
- ? trigger.expectedSenior
1691
- : pendingResume?.from_failed === true
1692
- ? pendingResume.expected_senior
1693
- : undefined;
1694
- // A message into a finished lane must not turn that lane `failed` when the
1695
- // account cannot be bound: nothing has started yet, so the record keeps its
1696
- // state and the caller sees the error. Admission and question resume keep
1697
- // today's behaviour of naming the terminal reason on the record.
1698
- const markPreSpawnFailure = trigger.kind !== "message" && trigger.kind !== "resume";
1699
- const plan = pendingResume?.trigger === "answered_questions"
1700
- ? pendingResume.session_id !== undefined && providerSupportsSessionResume(existing.provider)
1701
- ? { mode: "resume", session_id: pendingResume.session_id }
1702
- : planLaneLaunch(existing, { kind: "answered_questions" })
1703
- : pendingResume?.session_id !== undefined && providerSupportsSessionResume(existing.provider)
1704
- ? { mode: "resume", session_id: pendingResume.session_id }
1705
- : planLaneLaunch(existing, trigger);
1706
- if (existing.host.kind === "outpost") {
1707
- refuseOutpostSelfTarget(hqRoot, existing, deps);
1708
- }
1709
- const logsDir = path.join(runDir, "logs");
1710
- ensureDir(logsDir);
1711
- ensureDir(path.join(runDir, "envelopes"));
1712
- const profile = existing.worker_profile
1713
- ? loadWorkerProfileWithRegistry(hqRoot, existing.worker_profile, {
1714
- laneCompany: existing.company?.slug ?? existing.mesh_company?.slug,
1715
- ...(existing.registry_worker !== undefined
1716
- ? { registryWorkerRecord: existing.registry_worker }
1717
- : {}),
1718
- })
1719
- : undefined;
1720
- if (existing.host.kind === "outpost" &&
1721
- profile !== undefined &&
1722
- existing.worker_profile_hash !== profile.contentHash) {
1723
- throw new LanesError("worker_profile_hash_mismatch", `Worker profile ${JSON.stringify(existing.worker_profile)} on Outpost ${existing.host.id} changed after pickup validation`, {
1724
- lane_id: existing.lane_id,
1725
- worker: existing.worker_profile,
1726
- outpost: existing.host.id,
1727
- expected_hash: existing.worker_profile_hash ?? null,
1728
- actual_hash: profile.contentHash,
1729
- });
1730
- }
1731
- const profileDefaultsApply = profile !== undefined && profile.meta.provider === existing.provider;
1732
- const profileModel = profileDefaultsApply ? profile.meta.model : undefined;
1733
- const profileEffort = profileDefaultsApply ? profile.meta.effort : undefined;
1734
- const ignoredProfileFields = profile
1735
- ? ignoredWorkerProfileFields(existing.provider)
1736
- : [];
1737
- const policyDelivery = profile
1738
- ? workerPolicyDeliveryMode(hqRoot, existing.provider)
1739
- : undefined;
1740
- const workerPolicyDir = profile !== undefined && existing.provider !== "grok"
1741
- ? path.relative(hqRoot, profile.dir).split(path.sep).join("/")
1742
- : undefined;
1743
- const profileRuntime = profile
1744
- ? materializeWorkerProfile(profile, runDir)
1745
- : undefined;
1746
- const profileLaunch = profile
1747
- ? {
1748
- systemPrompt: workerProfilePrompt(profile, policyDelivery ?? "prompt"),
1749
- ...(profileRuntime?.settingsPath !== undefined
1750
- ? { settingsPath: profileRuntime.settingsPath }
1751
- : {}),
1752
- ignoredFields: ignoredProfileFields,
1753
- }
1754
- : undefined;
1755
- const profileChanged = profile !== undefined && existing.worker_profile_hash !== profile.contentHash;
1756
- const config = loadLanesConfig(hqRoot);
1757
- const repairRecordedAccount = plan.mode === "resume" &&
1758
- (trigger.kind === "resume" || pendingResume?.trigger === "resume" || pendingResume?.trigger === "watcher");
1759
- const recordedModel = repairRecordedAccount && existing.model_source === "account"
1760
- ? existing.model
1761
- : undefined;
1762
- // `hq lanes set` on a running lane leaves the change pending until this spawn.
1763
- const pendingSettings = existing.pending_settings;
1764
- let pinnedModel = pendingSettings?.model ?? (existing.model_source === undefined || existing.model_source === "cli" || existing.model_source === "preserved"
1765
- ? existing.model
1766
- : undefined);
1767
- const accountDeps = {
1768
- probe: modelDeps.probe ?? defaultProbe,
1769
- env,
1770
- };
1771
- let selection;
1772
- try {
1773
- selection = selectSpawnAccount({
1774
- hqRoot,
1775
- lane: existing,
1776
- config,
1777
- existsSync,
1778
- accountDeps,
1779
- modelDeps,
1780
- pinnedModel,
1781
- profileModel,
1782
- currentModelValidated: deps.currentModelValidated === true,
1783
- hostname,
1784
- repairRecordedAccount,
1785
- ...(recordedModel !== undefined ? { recordedModel } : {}),
1786
- now: (deps.now ?? (() => new Date()))(),
1787
- });
1788
- }
1789
- catch (err) {
1790
- if (err instanceof AccountResolutionError ||
1791
- (err instanceof LanesError &&
1792
- (err.error === "account_not_logged_in" || err.error === "model_unsupported"))) {
1793
- if (markPreSpawnFailure) {
1794
- markSpawnFailure(hqRoot, lane.lane_id, err.error, err.details);
1795
- }
1796
- throw err;
1797
- }
1798
- process.stderr.write(`hq lanes: account bind failed for ${lane.lane_id}: ${err instanceof Error ? err.message : String(err)}\n`);
1799
- throw err;
1800
- }
1801
- const preservedAccountModel = selection.preservedModel;
1802
- if (preservedAccountModel !== undefined)
1803
- pinnedModel = preservedAccountModel;
1804
- const resolved = selection.account;
1805
- const status = accountStatus(lane.provider, resolved.id, config, { existsSync, hostname });
1806
- if (isLoggedOut(status)) {
1807
- const failed = markPreSpawnFailure
1808
- ? markSpawnFailure(hqRoot, lane.lane_id, "account_not_logged_in", {
1809
- provider: lane.provider,
1810
- account: resolved.id,
1811
- })
1812
- : existing;
1813
- throw new LanesError("account_not_logged_in", `Account ${resolved.id} for ${lane.provider} is not logged in (no credential file)`, { provider: lane.provider, account: resolved.id, lane_id: lane.lane_id, lane: failed });
1814
- }
1815
- if (existing.account !== resolved.id) {
1816
- const source = existing.account
1817
- ? config.providers[existing.provider].accounts[existing.account]
1818
- : undefined;
1819
- if (source &&
1820
- existing.provider_session_id &&
1821
- providerSupportsSessionResume(existing.provider)) {
1822
- copySessionFiles(planSessionCopy(existing.provider, {
1823
- sourceHome: existing.provider_home_at_spawn ?? effectiveAccountHome(source, hostname).home,
1824
- targetHome: resolved.home,
1825
- cwd: hqRoot,
1826
- sessionId: existing.provider_session_id,
1827
- }));
1828
- }
1829
- }
1830
- if (plan.mode === "resume" && existing.provider !== "grok") {
1831
- ensureSessionHome({
1832
- provider: existing.provider,
1833
- sessionId: plan.session_id,
1834
- cwd: hqRoot,
1835
- targetHome: resolved.home,
1836
- registeredHomes: Object.values(config.providers[existing.provider].accounts)
1837
- .map((account) => effectiveAccountHome(account, hostname).home),
1838
- providerHomeAtSpawn: existing.provider_home_at_spawn,
1839
- });
1840
- }
1841
- if (existing.account !== resolved.id) {
1842
- const at = (deps.now ?? (() => new Date()))().toISOString();
1843
- const reason = selection.changeReason ?? "first_assignment";
1844
- retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => {
1845
- if (current.account === resolved.id)
1846
- return current;
1847
- if (current.account !== existing.account) {
1848
- throw new LanesError("account_bind_conflict", `Lane ${lane.lane_id} changed accounts while its worker spawn was prepared`, { lane_id: lane.lane_id, expected_account: existing.account ?? null, account: current.account ?? null });
1849
- }
1850
- const entry = {
1851
- from: current.account ?? null,
1852
- to: resolved.id,
1853
- at,
1854
- reason,
1855
- };
1856
- return {
1857
- ...current,
1858
- account: resolved.id,
1859
- ...(preservedAccountModel !== undefined
1860
- ? { model: preservedAccountModel, model_source: "preserved" }
1861
- : {}),
1862
- account_history: appendCappedHistory(current.account_history ?? [], entry),
1863
- };
1864
- });
1865
- }
1866
- try {
1867
- installDrainHook(lane.provider, resolved.home);
1868
- }
1869
- catch (err) {
1870
- process.stderr.write(`hq lanes: drain hook install failed for ${resolved.home}: ${err instanceof Error ? err.message : String(err)}\n`);
1871
- throw err;
1872
- }
1873
- const briefPath = path.join(runDir, "brief.md");
1874
- const envelopePath = nextEnvelopePath(runDir);
1875
- const lastMessagePath = path.join(logsDir, "last-message.txt");
1876
- const answersPath = path.join(runDir, ANSWERED_QUESTIONS_FILE);
1877
- const carriesAnsweredQuestions = trigger.kind === "answered_questions" || pendingResume?.trigger === "answered_questions";
1878
- const answeredLines = carriesAnsweredQuestions && existsSync(answersPath)
1879
- ? readAnsweredQuestionLines(answersPath)
1880
- : undefined;
1881
- const extraPrompt = existsSync(answersPath)
1882
- ? `Previously answered questions are at ${answersPath}; treat those choices as operator decisions that outrank the brief.`
1883
- : undefined;
1884
- const accountCfg = config.providers[lane.provider].accounts[resolved.id];
1885
- const autoCompactTokens = lane.provider === "claude"
1886
- ? providerAutoCompactTokens(config.providers.claude)
1887
- : undefined;
1888
- const childEnv = workerEnv(env, { envVar: resolved.envVar, home: resolved.home }, lane.lane_id, hqRoot, autoCompactTokens, lane.mesh_company ?? lane.company ?? undefined, workerPolicyDir, lane.registry_worker);
1889
- const laneTurnId = randomUUID();
1890
- childEnv.HQ_LANE_TURN_ID = laneTurnId;
1891
- const model = resolveLaneModel({
1892
- cliModel: pinnedModel,
1893
- profileModel,
1894
- accountModel: accountCfg?.model,
1895
- providerModel: config.providers[lane.provider].model,
1896
- });
1897
- const pendingResumeEffort = pendingResume !== undefined
1898
- ? pendingSettings?.effort !== undefined
1899
- ? { effort: pendingSettings.effort, source: "cli" }
1900
- : {
1901
- ...(existing.effort !== undefined ? { effort: existing.effort } : {}),
1902
- source: existing.effort_source ?? "none",
1903
- }
1904
- : undefined;
1905
- const effort = launch.effort ?? pendingResumeEffort ?? resolveLaneEffort({
1906
- cliEffort: pendingSettings?.effort ?? (existing.effort_source === "cli" ? existing.effort : undefined),
1907
- profileEffort,
1908
- accountEffort: accountCfg?.effort,
1909
- providerEffort: config.providers[lane.provider].effort,
1910
- model,
1911
- });
1912
- const fastMode = lane.provider === "codex"
1913
- ? (profileDefaultsApply ? profile?.meta.fast_mode : undefined) ??
1914
- (model !== undefined && (config.providers.codex.fast_mode_models ?? []).includes(model))
1915
- : false;
1916
- const resume = plan.mode === "resume"
1917
- ? {
1918
- session_id: plan.session_id,
1919
- prompt: resumePrompt({
1920
- envelopePath,
1921
- operatorMessage: trigger.kind === "message" && trigger.monitor_event !== true
1922
- ? trigger.text
1923
- : trigger.kind === "resume"
1924
- ? trigger.text
1925
- : pendingResume?.monitor_event === true
1926
- ? undefined
1927
- : pendingResume?.text,
1928
- monitorEvent: trigger.kind === "message" && trigger.monitor_event === true
1929
- ? trigger.text
1930
- : pendingResume?.monitor_event === true
1931
- ? pendingResume.text
1932
- : undefined,
1933
- resumedFrom: trigger.kind === "resume" ? trigger.from : pendingResume?.resumed_from,
1934
- resumeSource: pendingResume?.trigger === "watcher" ? "watcher" : undefined,
1935
- answersPath: answeredLines !== undefined ? answersPath : undefined,
1936
- answers: answeredLines,
1937
- envelopeRepairErrors: lane.terminal_reason === ENVELOPE_INVALID_REASON &&
1938
- lane.envelope_repair?.attempted === true &&
1939
- lane.envelope_repair.succeeded === false
1940
- ? {
1941
- first_error: lane.envelope_repair.first_error,
1942
- ...(lane.envelope_repair.second_error !== undefined
1943
- ? { second_error: lane.envelope_repair.second_error }
1944
- : {}),
1945
- }
1946
- : undefined,
1947
- }),
1948
- }
1949
- : undefined;
1950
- const command = buildProviderCommand(lane.provider, {
1951
- hqRoot,
1952
- briefPath,
1953
- envelopePath,
1954
- lastMessagePath,
1955
- extraPrompt,
1956
- model,
1957
- effort: effort.effort,
1958
- fastMode,
1959
- profile: profileLaunch,
1960
- workerPolicyDir,
1961
- resume,
1962
- });
1963
- // A systemd PATH mismatch is an environment defect, not a lane failure.
1964
- // Keep the lane eligible for a later reconcile after the installer repairs it.
1965
- if (!providerCommandOnPath(command.command, childEnv.PATH)) {
1966
- const searchedPath = childEnv.PATH ?? "";
1967
- // Only admission may re-queue. A resume (answered questions, operator
1968
- // message) must keep the recorded state so the next reconcile does not
1969
- // infer `admit` and start a fresh run in place of the recorded session;
1970
- // the caller keeps the message text and sees the named error.
1971
- if (trigger.kind !== "admit") {
1972
- throw new LanesError("provider_binary_missing", `Provider binary ${command.command} for ${lane.provider} is not executable on PATH ${JSON.stringify(searchedPath)}; lane ${lane.lane_id} keeps state ${existing.state}`, {
1973
- provider: lane.provider,
1974
- command: command.command,
1975
- searched_path: searchedPath,
1976
- lane_id: lane.lane_id,
1977
- state: existing.state,
1978
- trigger: trigger.kind,
1979
- });
1980
- }
1981
- return retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => ({
1982
- ...current,
1983
- state: "queued",
1984
- queued_reason: "provider_binary_missing",
1985
- queued_details: undefined,
1986
- terminal_reason: undefined,
1987
- terminal_details: {
1988
- provider: lane.provider,
1989
- command: command.command,
1990
- searched_path: searchedPath,
1991
- },
1992
- }));
1993
- }
1994
- // Resume-time compaction (compaction.ts). Runs before the claim so the
1995
- // lane is never `running` without a worker while `/compact` works.
1996
- let compaction;
1997
- const compactWanted = pendingResume?.compact ?? launch.compact;
1998
- if (resume && compactWanted !== false) {
1999
- const nowFn = deps.now ?? (() => new Date());
2000
- const decision = compactionDue(existing, nowFn().getTime(), providerCompactAfterMs(config.providers[lane.provider]));
2001
- if (decision.due) {
2002
- const compactCommand = buildProviderCommand(lane.provider, {
2003
- hqRoot,
2004
- briefPath,
2005
- envelopePath,
2006
- lastMessagePath,
2007
- model,
2008
- effort: effort.effort,
2009
- fastMode,
2010
- profile: profileLaunch,
2011
- workerPolicyDir,
2012
- resume: { session_id: resume.session_id, prompt: COMPACTION_PROMPT },
2013
- });
2014
- compaction = compactLaneSession({
2015
- command: compactCommand.command,
2016
- args: compactCommand.args,
2017
- sessionId: resume.session_id,
2018
- accountHome: resolved.home,
2019
- env: childEnv,
2020
- cwd: hqRoot,
2021
- logsDir,
2022
- decision,
2023
- before: existing.last_run_usage ?? null,
2024
- now: nowFn,
2025
- run: deps.runCompaction,
2026
- locateTranscript: deps.locateTranscript,
2027
- });
2028
- }
2029
- }
2030
- // Claim running before spawning. Two callers that both observe queued must
2031
- // not both start processes; the CAS loser returns without spawn.
2032
- const nowIso = (deps.now ?? (() => new Date()))().toISOString();
2033
- const resumeHistoryTrigger = pendingResume?.keep_alive === true
2034
- ? "keep_alive"
2035
- : pendingResume?.trigger === "monitor_event" || pendingResume?.monitor_event === true ||
2036
- (trigger.kind === "message" && trigger.monitor_event === true)
2037
- ? "monitor_event"
2038
- : pendingResume?.trigger === "system_notice" ||
2039
- (trigger.kind === "message" && trigger.system_notice === true)
2040
- ? "system_notice"
2041
- : pendingResume?.trigger === "watcher"
2042
- ? "watcher"
2043
- : pendingResume?.trigger === "message" || trigger.kind === "message"
2044
- ? "message"
2045
- : pendingResume?.trigger === "resume" || trigger.kind === "resume"
2046
- ? "resume_cli"
2047
- : "reconcile";
2048
- const resumeHistoryCaller = pendingResume?.caller ||
2049
- (pendingResume?.trigger !== "watcher" && typeof env.HQ_LANE_ID === "string" ? env.HQ_LANE_ID.trim() : "") ||
2050
- (pendingResume?.trigger === "message" || pendingResume?.trigger === "monitor_event" ||
2051
- pendingResume?.trigger === "system_notice" || trigger.kind === "answered_questions" ||
2052
- trigger.kind === "resume" || trigger.kind === "message"
2053
- ? "user"
2054
- : undefined);
2055
- let statusGateHeartbeat;
2056
- try {
2057
- statusGateHeartbeat = managerStatusGateHeartbeat(hqRoot, existing, laneTurnId, nowIso);
2058
- }
2059
- catch (err) {
2060
- const code = err instanceof LanesError ? err.error : "manager_status_gate_unavailable";
2061
- const message = err instanceof Error ? err.message : String(err);
2062
- process.stderr.write(`hq lanes: manager status gate disabled for ${lane.lane_id}: ${code}: ${message}\n`);
2063
- statusGateHeartbeat = undefined;
2064
- }
2065
- let claimed = false;
2066
- let priorStartRecorded = false;
2067
- const claimedRecord = retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => {
2068
- claimed = false;
2069
- if (current.state === "running" && current.account === resolved.id) {
2070
- if (trigger.kind === "resume") {
2071
- throw new LanesError("lane_not_resumable", `Lane ${current.lane_id} is already running`, { lane_id: current.lane_id, state: current.state });
2072
- }
2073
- return current;
2074
- }
2075
- if (!claimableStatesFor(trigger, current).includes(current.state)) {
2076
- throw new LanesError("spawn_state_mismatch", `Cannot mark ${current.lane_id} running from ${current.state}`, { lane_id: current.lane_id, state: current.state, trigger: trigger.kind });
2077
- }
2078
- // The host report is written in the claim CAS before exec proves that a
2079
- // worker started. Use the prior spawn manifest's turn id (written only
2080
- // after detachment is proven), with last_resume for legacy manifests.
2081
- priorStartRecorded = previousSpawn.turn_id !== undefined ||
2082
- current.last_resume !== undefined ||
2083
- (current.resume_history?.length ?? 0) > 0;
2084
- if (failedResumeClaim &&
2085
- (failedResumeExpectedSenior === undefined ||
2086
- !sameSeniorRef(current.senior, failedResumeExpectedSenior))) {
2087
- throw new LanesError("failed_resume_senior_changed", `Lane ${current.lane_id}'s senior changed after its failed-resume request was authorized`, {
2088
- lane_id: current.lane_id,
2089
- expected_senior: failedResumeExpectedSenior ?? null,
2090
- current_senior: current.senior,
2091
- });
2092
- }
2093
- claimed = true;
2094
- const next = {
2095
- ...current,
2096
- state: "running",
2097
- queued_reason: undefined,
2098
- queued_details: undefined,
2099
- queued_at: undefined,
2100
- admission_reserved_at: undefined,
2101
- terminal_reason: undefined,
2102
- terminal_details: undefined,
2103
- // An account move's reservation ends with the claim.
2104
- pending_resume: undefined,
2105
- pending_settings: undefined,
2106
- account: resolved.id,
2107
- provider_home_at_spawn: resolved.home,
2108
- ...(model !== undefined ? { model } : {}),
2109
- ...(model !== undefined
2110
- ? {
2111
- model_source: pinnedModel !== undefined
2112
- ? preservedAccountModel === undefined && pendingSettings?.model !== undefined
2113
- ? "cli"
2114
- : preservedAccountModel !== undefined || existing.model_source === "preserved"
2115
- ? "preserved"
2116
- : "cli"
2117
- : profileModel !== undefined
2118
- ? "profile"
2119
- : accountCfg?.model !== undefined
2120
- ? "account"
2121
- : config.providers[lane.provider].model !== undefined
2122
- ? "provider"
2123
- : "none",
2124
- }
2125
- : { model_source: "none" }),
2126
- effort_source: effort.source,
2127
- status_gate: statusGateHeartbeat,
2128
- last_host_report_at: nowIso,
2129
- ...(profile
2130
- ? {
2131
- worker_profile_hash: profile.contentHash,
2132
- registry_worker: profile.registryWorker !== undefined
2133
- ? registryWorkerRecord(profile.registryWorker)
2134
- : undefined,
2135
- worker_profile_ignored: [...ignoredProfileFields],
2136
- worker_policy_delivery: policyDelivery,
2137
- }
2138
- : { registry_worker: undefined, worker_policy_delivery: undefined }),
2139
- };
2140
- if (resume !== undefined) {
2141
- next.provider_session_id = resume.session_id;
2142
- next.provider_session_id_absent = undefined;
2143
- }
2144
- if (effort.effort !== undefined)
2145
- next.effort = effort.effort;
2146
- else
2147
- delete next.effort;
2148
- // `undefined` deliberately overlays the CAS merge's current record so a
2149
- // dynamic default disappearing removes the stale persisted model.
2150
- if (model === undefined)
2151
- next.model = undefined;
2152
- if (fastMode)
2153
- next.fast_mode = true;
2154
- else
2155
- delete next.fast_mode;
2156
- // Freeze the counters of the run that followed the previous compaction
2157
- // before this launch replaces last_resume.
2158
- if (current.last_compaction && current.last_compaction.after === null) {
2159
- const after = compactionAfterUsage(current);
2160
- if (after !== null)
2161
- next.last_compaction = { ...current.last_compaction, after };
2162
- }
2163
- if (compaction)
2164
- next.last_compaction = { ...compaction, resume_at: nowIso };
2165
- if (resume && pendingResume !== undefined) {
2166
- next.last_resume = {
2167
- session_id: resume.session_id,
2168
- at: nowIso,
2169
- account: resolved.id,
2170
- trigger: pendingResume.trigger,
2171
- ...(pendingResume.keep_alive === true ? { keep_alive: true } : {}),
2172
- ...(pendingResume.message_id !== undefined ? { message_id: pendingResume.message_id } : {}),
2173
- ...(pendingResume.monitor_event === true ? { monitor_event: true } : {}),
2174
- ...(pendingResume.resumed_from !== undefined ? { resumed_from: pendingResume.resumed_from } : {}),
2175
- ...(pendingResume.from_failed === true ? { from_failed: true } : {}),
2176
- ...(pendingResume.text !== undefined ? { text: pendingResume.text } : {}),
2177
- ...(pendingResume.compact !== undefined ? { compact: pendingResume.compact } : {}),
2178
- };
2179
- }
2180
- else if (resume && trigger.kind !== "admit") {
2181
- next.last_resume = {
2182
- session_id: resume.session_id,
2183
- at: nowIso,
2184
- account: resolved.id,
2185
- trigger: trigger.kind === "message" && trigger.system_notice === true ? "system_notice" : trigger.kind,
2186
- ...(trigger.kind === "message"
2187
- ? {
2188
- message_id: trigger.message_id,
2189
- text: trigger.text,
2190
- ...(trigger.monitor_event === true ? { monitor_event: true } : {}),
2191
- }
2192
- : {}),
2193
- ...(launch.compact !== undefined ? { compact: launch.compact } : {}),
2194
- ...(trigger.kind === "resume"
2195
- ? {
2196
- resumed_from: trigger.from,
2197
- ...(trigger.fromFailed === true ? { from_failed: true } : {}),
2198
- ...(trigger.text !== undefined ? { text: trigger.text } : {}),
2199
- ...(trigger.message_id !== undefined ? { message_id: trigger.message_id } : {}),
2200
- }
2201
- : {}),
2202
- };
2203
- }
2204
- if (resume && pendingResume?.text !== LEAD_LANE_KEEP_ALIVE_BLOCKED_RESUME_TEXT) {
2205
- next.keep_alive_blocked_resume_streak = 0;
2206
- }
2207
- return next;
2208
- });
2209
- if (!claimed) {
2210
- if (compaction) {
2211
- const record = compaction;
2212
- return retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => ({
2213
- ...current,
2214
- last_compaction: record,
2215
- }));
2216
- }
2217
- return laneLaunchResult(claimedRecord);
2218
- }
2219
- // Each normal spawn/resume starts a fresh provider turn. The resume prompt
2220
- // carries the prior message text, so only messages delivered after this
2221
- // reset may be replayed if the new turn compacts.
2222
- const replayStatePath = path.join(runDir, "dropbox", MESSAGE_REPLAY_STATE_NAME);
2223
- const replayStateTempPath = `${replayStatePath}.${process.pid}.${laneTurnId}.tmp`;
2224
- try {
2225
- fs.mkdirSync(path.dirname(replayStatePath), { recursive: true });
2226
- fs.writeFileSync(replayStateTempPath, `${JSON.stringify({
2227
- schema_version: 1,
2228
- turn_id: laneTurnId,
2229
- last_compaction_marker: null,
2230
- })}\n`, { mode: 0o600 });
2231
- fs.renameSync(replayStateTempPath, replayStatePath);
2232
- }
2233
- catch (err) {
2234
- try {
2235
- fs.rmSync(replayStateTempPath, { force: true });
2236
- }
2237
- catch (cleanupErr) {
2238
- process.stderr.write(`hq lanes: compaction replay state temp cleanup failed for ${lane.lane_id}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}\n`);
2239
- }
2240
- delete childEnv.HQ_LANE_TURN_ID;
2241
- process.stderr.write(`hq lanes: compaction replay disabled for ${lane.lane_id}; failed to reset turn state: ${err instanceof Error ? err.message : String(err)}\n`);
2242
- }
2243
- const workerOutPath = path.join(logsDir, "worker.out");
2244
- const workerOutOffset = fileSizeOrZero(workerOutPath);
2245
- let workerPid;
2246
- let watcherPid;
2247
- try {
2248
- workerPid = spawnDetached(spawnProcess, command.command, command.args, childEnv, hqRoot, path.join(logsDir, "worker.out"), path.join(logsDir, "worker.err"));
2249
- writePidRecord(path.join(runDir, "worker.pid"), {
2250
- pid: workerPid,
2251
- starttime: readProcStarttime(workerPid) ?? undefined,
2252
- });
2253
- requireDetached(proveDetached, workerPid, "worker");
2254
- if (answeredLines && answeredLines.length > 0) {
2255
- markAnsweredQuestionsDelivered(hqRoot, lane.lane_id, answeredLines.map(({ question_id }) => question_id), (deps.now ?? (() => new Date()))().toISOString());
2256
- }
2257
- watcherPid = armLaneWatcher(hqRoot, lane.lane_id, deps);
2258
- writeSpawnManifest(runDir, {
2259
- command: command.command,
2260
- args: command.args,
2261
- envVar: resolved.envVar,
2262
- account: resolved.id,
2263
- workerPid,
2264
- watcherPid,
2265
- envelopePath,
2266
- turnId: laneTurnId,
2267
- resume: resume ? { session_id: resume.session_id } : null,
2268
- workerOutOffset,
2269
- fastMode,
2270
- ...(profile
2271
- ? {
2272
- profile: {
2273
- id: profile.id,
2274
- hash: profile.contentHash,
2275
- ignoredFields: ignoredProfileFields,
2276
- policyDelivery: policyDelivery ?? "prompt",
2277
- ...(workerPolicyDir !== undefined ? { policyDir: workerPolicyDir } : {}),
2278
- ...(profileRuntime?.settingsPath !== undefined
2279
- ? { settingsPath: profileRuntime.settingsPath }
2280
- : {}),
2281
- },
2282
- }
2283
- : {}),
2284
- });
2285
- if (profile !== undefined) {
2286
- appendWorkerProfileEvent(runDir, {
2287
- profile_id: profile.id,
2288
- profile_hash: profile.contentHash,
2289
- changed: profileChanged,
2290
- provider: lane.provider,
2291
- ignored_fields: ignoredProfileFields,
2292
- });
2293
- }
2294
- }
2295
- catch (err) {
2296
- if (workerPid !== undefined)
2297
- killQuietly(killProcess, workerPid, "worker");
2298
- if (watcherPid !== undefined)
2299
- killQuietly(killProcess, watcherPid, "watcher");
2300
- const reason = err instanceof LanesError &&
2301
- SPAWN_TERMINAL_REASONS.includes(err.error)
2302
- ? err.error
2303
- : "spawn_failed";
2304
- const failed = markSpawnFailure(hqRoot, lane.lane_id, reason, {
2305
- message: err instanceof Error ? err.message : String(err),
2306
- ...(err instanceof LanesError ? err.details : {}),
2307
- });
2308
- if (err instanceof LanesError) {
2309
- throw new LanesError(err.error, err.message, {
2310
- ...err.details,
2311
- lane_id: lane.lane_id,
2312
- lane: failed,
2313
- });
2314
- }
2315
- throw err;
2316
- }
2317
- if (priorStartRecorded) {
2318
- retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => ({
2319
- ...current,
2320
- resume_history: appendCappedHistory(current.resume_history ?? [], {
2321
- at: nowIso,
2322
- trigger: resumeHistoryTrigger,
2323
- ...(resumeHistoryCaller ? { caller: resumeHistoryCaller } : {}),
2324
- }),
2325
- }));
2326
- }
2327
- return laneLaunchResult(readLane(hqRoot, lane.lane_id));
2328
- }
2329
- /**
2330
- * Handle the private request sent by an older, long-running watcher to the
2331
- * currently installed `hq` executable. The persisted repair attempt is the
2332
- * authorization for this one-shot spawn; the request cannot select an
2333
- * arbitrary lane or write outside that lane's envelope directory.
2334
- */
2335
- export function spawnEnvelopeRepairRequest(hqRoot, rawRequest, deps = {}) {
2336
- const invalid = (message) => {
2337
- throw new LanesError("repair_request_invalid", message, {});
2338
- };
2339
- if (!rawRequest || typeof rawRequest !== "object" || Array.isArray(rawRequest)) {
2340
- return invalid("Envelope repair request must be an object");
2341
- }
2342
- const request = rawRequest;
2343
- if (Object.keys(request).some((key) => key !== "lane_id" && key !== "input")) {
2344
- return invalid("Envelope repair request has unknown fields");
2345
- }
2346
- if (typeof request.lane_id !== "string" ||
2347
- !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(request.lane_id)) {
2348
- return invalid("Envelope repair request must include a lane_id");
2349
- }
2350
- if (!request.input || typeof request.input !== "object" || Array.isArray(request.input)) {
2351
- return invalid("Envelope repair request input must be an object");
2352
- }
2353
- const rawInput = request.input;
2354
- const allowedInputFields = new Set([
2355
- "session_id",
2356
- "envelopePath",
2357
- "error",
2358
- "rawText",
2359
- "missing",
2360
- ]);
2361
- if (Object.keys(rawInput).some((key) => !allowedInputFields.has(key))) {
2362
- return invalid("Envelope repair request input has unknown fields");
2363
- }
2364
- if (typeof rawInput.envelopePath !== "string" ||
2365
- !path.isAbsolute(rawInput.envelopePath) ||
2366
- path.resolve(rawInput.envelopePath) !== rawInput.envelopePath ||
2367
- typeof rawInput.error !== "string" ||
2368
- !rawInput.error.trim() ||
2369
- typeof rawInput.rawText !== "string" ||
2370
- (rawInput.session_id !== undefined &&
2371
- rawInput.session_id !== null &&
2372
- (typeof rawInput.session_id !== "string" || !rawInput.session_id.trim())) ||
2373
- (rawInput.missing !== undefined && typeof rawInput.missing !== "boolean")) {
2374
- return invalid("Envelope repair request input has invalid fields");
2375
- }
2376
- const lane = readLane(hqRoot, request.lane_id);
2377
- const repair = lane.envelope_repair;
2378
- if (lane.state !== "running" || !repair?.attempted || repair.succeeded) {
2379
- throw new LanesError("repair_request_not_authorized", `Lane ${lane.lane_id} has no pending envelope repair attempt`, { lane_id: lane.lane_id });
2380
- }
2381
- if (repair.first_error !== rawInput.error) {
2382
- throw new LanesError("repair_request_stale", `Lane ${lane.lane_id} envelope repair request no longer matches its recorded error`, { lane_id: lane.lane_id });
2383
- }
2384
- const envelopeDir = path.resolve(laneRunDir(hqRoot, lane.lane_id), "envelopes");
2385
- const envelopePath = path.resolve(rawInput.envelopePath);
2386
- if (path.dirname(envelopePath) !== envelopeDir ||
2387
- !path.basename(envelopePath).endsWith(".json") ||
2388
- typeof repair.envelope_ref !== "string" ||
2389
- path.posix.dirname(repair.envelope_ref) !== "envelopes" ||
2390
- !path.posix.basename(repair.envelope_ref).endsWith(".json")) {
2391
- throw new LanesError("repair_request_path_invalid", `Lane ${lane.lane_id} envelope repair request does not name a lane envelope`, { lane_id: lane.lane_id });
2392
- }
2393
- const recordedEnvelopePath = path.resolve(laneRunDir(hqRoot, lane.lane_id), repair.envelope_ref);
2394
- if (envelopePath !== recordedEnvelopePath) {
2395
- throw new LanesError("repair_request_envelope_mismatch", `Lane ${lane.lane_id} envelope repair request does not match the recorded repair slot`, { lane_id: lane.lane_id, envelope_ref: repair.envelope_ref });
2396
- }
2397
- const warnings = [];
2398
- const input = {
2399
- envelopePath,
2400
- error: rawInput.error,
2401
- rawText: rawInput.rawText,
2402
- ...(typeof rawInput.session_id === "string" || rawInput.session_id === null
2403
- ? { session_id: rawInput.session_id }
2404
- : {}),
2405
- ...(typeof rawInput.missing === "boolean" ? { missing: rawInput.missing } : {}),
2406
- onProfileWarning: (fields) => warnings.push([...fields]),
2407
- };
2408
- const pid = spawnEnvelopeRepair(hqRoot, lane, input, deps);
2409
- return { pid, profile_warnings: warnings };
2410
- }
2411
- /**
2412
- * `resume`: claude and codex continue the recorded session with the repair
2413
- * prompt. `fresh_turn`: grok gets a new single-turn invocation on the same
2414
- * account, whose prompt carries the schema, the parser error and the raw
2415
- * failed output. Grok can resume a session (operator messages and
2416
- * `hq lanes resume` use it), but its repair turn stays a fresh turn: that
2417
- * path was built and proven that way, and a repair by resume has not been.
2418
- */
2419
- export function envelopeRepairMode(provider) {
2420
- return providerSupportsSessionResume(provider) && provider !== "grok" ? "resume" : "fresh_turn";
2421
- }
2422
- /**
2423
- * Spec §4 repair turn. The lane is still `running` (the watcher has not
2424
- * written a terminal state), so this does not claim or transition the
2425
- * record. It resumes the recorded provider session with the repair prompt
2426
- * (`resume` mode), or for a provider with no session resume runs the repair
2427
- * prompt as a fresh single turn on the same account (`fresh_turn` mode). It
2428
- * replaces `worker.pid` and rewrites `spawn.json` so the watcher's next tick
2429
- * follows the new process. The account is the one already bound on the record.
2430
- * Fast-mode evidence is updated after the replacement is proven detached.
2431
- */
2432
- export function spawnEnvelopeRepair(hqRoot, lane, input, deps = {}) {
2433
- const env = deps.env ?? process.env;
2434
- const hostname = accountHomeHostname(deps);
2435
- const existsSync = deps.existsSync ?? ((p) => fs.existsSync(p));
2436
- const spawnProcess = deps.spawnProcess ?? defaultSpawnProcess;
2437
- const proveDetached = deps.proveDetached ?? defaultProveDetached;
2438
- const killProcess = deps.killProcess ?? defaultKillProcess;
2439
- const mode = envelopeRepairMode(lane.provider);
2440
- const sessionId = input.session_id ?? null;
2441
- if (mode === "resume" && sessionId === null) {
2442
- throw new LanesError("repair_session_missing", `Provider ${lane.provider} repairs by resuming its session, but no session id was given`, { provider: lane.provider });
2443
- }
2444
- const runDir = laneRunDir(hqRoot, lane.lane_id);
2445
- const logsDir = path.join(runDir, "logs");
2446
- ensureDir(logsDir);
2447
- const config = loadLanesConfig(hqRoot);
2448
- const profile = lane.worker_profile
2449
- ? loadWorkerProfileWithRegistry(hqRoot, lane.worker_profile, {
2450
- laneCompany: lane.company?.slug ?? lane.mesh_company?.slug,
2451
- ...(lane.registry_worker !== undefined
2452
- ? { registryWorkerRecord: lane.registry_worker }
2453
- : {}),
2454
- onUnknownMetaFields: (fields) => {
2455
- process.stderr.write(`hq lanes watcher: envelope repair ignored unknown worker profile meta field(s) for ${lane.worker_profile}: ${fields.join(", ")}\n`);
2456
- input.onProfileWarning?.(fields);
2457
- },
2458
- })
2459
- : undefined;
2460
- const profileDefaultsApply = profile !== undefined && profile.meta.provider === lane.provider;
2461
- const profileModel = profileDefaultsApply ? profile.meta.model : undefined;
2462
- const profileEffort = profileDefaultsApply ? profile.meta.effort : undefined;
2463
- const ignoredProfileFields = profile
2464
- ? ignoredWorkerProfileFields(lane.provider)
2465
- : [];
2466
- const policyDelivery = profile
2467
- ? workerPolicyDeliveryMode(hqRoot, lane.provider)
2468
- : undefined;
2469
- const workerPolicyDir = profile !== undefined && lane.provider !== "grok"
2470
- ? path.relative(hqRoot, profile.dir).split(path.sep).join("/")
2471
- : undefined;
2472
- const profileRuntime = profile
2473
- ? materializeWorkerProfile(profile, runDir)
2474
- : undefined;
2475
- const profileLaunch = profile
2476
- ? {
2477
- systemPrompt: workerProfilePrompt(profile, policyDelivery ?? "prompt"),
2478
- ...(profileRuntime?.settingsPath !== undefined
2479
- ? { settingsPath: profileRuntime.settingsPath }
2480
- : {}),
2481
- ignoredFields: ignoredProfileFields,
2482
- }
2483
- : undefined;
2484
- const pinnedModel = lane.model_source === undefined || lane.model_source === "cli" || lane.model_source === "preserved"
2485
- ? lane.model
2486
- : undefined;
2487
- const resolved = resolveAccount(lane.provider, lane.account, config, {
2488
- hqRoot,
2489
- existsSync,
2490
- hostname,
2491
- model: pinnedModel ?? profileModel,
2492
- });
2493
- if (profileDefaultsApply && profileModel !== undefined && pinnedModel === undefined) {
2494
- validateProfileLaneModel(lane.provider, profileModel, resolved.home, profile.id, {
2495
- ...deps.modelDeps,
2496
- env: deps.modelDeps?.env ?? env,
2497
- });
2498
- }
2499
- const autoCompactTokens = lane.provider === "claude"
2500
- ? providerAutoCompactTokens(config.providers.claude)
2501
- : undefined;
2502
- const childEnv = workerEnv(env, { envVar: resolved.envVar, home: resolved.home }, lane.lane_id, hqRoot, autoCompactTokens, lane.mesh_company ?? lane.company ?? undefined, workerPolicyDir, lane.registry_worker);
2503
- const accountCfg = config.providers[lane.provider].accounts[resolved.id];
2504
- const model = resolveLaneModel({
2505
- cliModel: pinnedModel,
2506
- profileModel,
2507
- accountModel: accountCfg?.model,
2508
- providerModel: config.providers[lane.provider].model,
2509
- });
2510
- const effort = resolveLaneEffort({
2511
- cliEffort: lane.effort_source === "cli" ? lane.effort : undefined,
2512
- profileEffort,
2513
- accountEffort: accountCfg?.effort,
2514
- providerEffort: config.providers[lane.provider].effort,
2515
- model,
2516
- });
2517
- const fastMode = lane.provider === "codex"
2518
- ? (profileDefaultsApply ? profile?.meta.fast_mode : undefined) ??
2519
- (model !== undefined && (config.providers.codex.fast_mode_models ?? []).includes(model))
2520
- : false;
2521
- const repairPrompt = envelopeRepairPrompt({
2522
- envelopePath: input.envelopePath,
2523
- error: input.error,
2524
- rawText: input.rawText,
2525
- missing: input.missing,
2526
- });
2527
- const command = buildProviderCommand(lane.provider, {
2528
- hqRoot,
2529
- briefPath: path.join(runDir, "brief.md"),
2530
- envelopePath: input.envelopePath,
2531
- lastMessagePath: path.join(logsDir, "last-message.txt"),
2532
- model,
2533
- effort: effort.effort,
2534
- fastMode,
2535
- profile: profileLaunch,
2536
- workerPolicyDir,
2537
- ...(mode === "resume" && sessionId !== null
2538
- ? { resume: { session_id: sessionId, prompt: repairPrompt } }
2539
- : { freshTurnPrompt: repairPrompt }),
2540
- });
2541
- const workerOutOffset = fileSizeOrZero(path.join(logsDir, "worker.out"));
2542
- const previous = readSpawnManifest(runDir);
2543
- let workerPid;
2544
- try {
2545
- workerPid = spawnDetached(spawnProcess, command.command, command.args, childEnv, hqRoot, path.join(logsDir, "worker.out"), path.join(logsDir, "worker.err"));
2546
- writePidRecord(path.join(runDir, "worker.pid"), {
2547
- pid: workerPid,
2548
- starttime: readProcStarttime(workerPid) ?? undefined,
2549
- });
2550
- requireDetached(proveDetached, workerPid, "worker");
2551
- const watcherPid = readPidRecord(path.join(runDir, "watcher.pid"))?.pid ?? 0;
2552
- writeSpawnManifest(runDir, {
2553
- command: command.command,
2554
- args: command.args,
2555
- envVar: resolved.envVar,
2556
- account: resolved.id,
2557
- workerPid,
2558
- watcherPid,
2559
- envelopePath: previous.envelope_path ?? input.envelopePath,
2560
- resume: mode === "resume" && sessionId !== null ? { session_id: sessionId } : null,
2561
- workerOutOffset,
2562
- fastMode,
2563
- ...(profile
2564
- ? {
2565
- profile: {
2566
- id: profile.id,
2567
- hash: profile.contentHash,
2568
- ignoredFields: ignoredProfileFields,
2569
- policyDelivery: policyDelivery ?? "prompt",
2570
- ...(workerPolicyDir !== undefined ? { policyDir: workerPolicyDir } : {}),
2571
- ...(profileRuntime?.settingsPath !== undefined
2572
- ? { settingsPath: profileRuntime.settingsPath }
2573
- : {}),
2574
- },
2575
- }
2576
- : {}),
2577
- });
2578
- if (profile !== undefined) {
2579
- appendWorkerProfileEvent(runDir, {
2580
- profile_id: profile.id,
2581
- profile_hash: profile.contentHash,
2582
- changed: lane.worker_profile_hash !== profile.contentHash,
2583
- provider: lane.provider,
2584
- ignored_fields: ignoredProfileFields,
2585
- });
2586
- }
2587
- retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => {
2588
- const next = { ...current };
2589
- if (profile !== undefined) {
2590
- next.worker_profile_hash = profile.contentHash;
2591
- next.worker_profile_ignored = [...ignoredProfileFields];
2592
- next.worker_policy_delivery = policyDelivery;
2593
- if (model !== undefined) {
2594
- next.model = model;
2595
- next.model_source = pinnedModel !== undefined
2596
- ? lane.model_source === "preserved" ? "preserved" : "cli"
2597
- : profileModel !== undefined
2598
- ? "profile"
2599
- : accountCfg?.model !== undefined
2600
- ? "account"
2601
- : config.providers[lane.provider].model !== undefined
2602
- ? "provider"
2603
- : "none";
2604
- }
2605
- else {
2606
- next.model = undefined;
2607
- next.model_source = "none";
2608
- }
2609
- next.effort_source = effort.source;
2610
- if (effort.effort !== undefined)
2611
- next.effort = effort.effort;
2612
- else
2613
- delete next.effort;
2614
- }
2615
- else {
2616
- next.worker_policy_delivery = undefined;
2617
- }
2618
- if (fastMode)
2619
- next.fast_mode = true;
2620
- else
2621
- delete next.fast_mode;
2622
- return next;
2623
- });
2624
- }
2625
- catch (err) {
2626
- if (workerPid !== undefined)
2627
- killQuietly(killProcess, workerPid, "worker");
2628
- throw err;
2629
- }
2630
- const startedAt = (deps.now ?? (() => new Date()))().toISOString();
2631
- const callerLaneId = typeof env.HQ_LANE_ID === "string" ? env.HQ_LANE_ID.trim() : "";
2632
- retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => ({
2633
- ...current,
2634
- resume_history: appendCappedHistory(current.resume_history ?? [], {
2635
- at: startedAt,
2636
- trigger: "envelope_repair",
2637
- ...(callerLaneId ? { caller: callerLaneId } : {}),
2638
- }),
2639
- }));
2640
- return workerPid;
2641
- }
2642
- export { PROVIDER_HOME_ENV, PROVIDER_COMMAND };
2643
- //# sourceMappingURL=spawn.js.map