@cohortapp/agent-sdk 2.17.0 → 2.18.5

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 (531) hide show
  1. package/.claude/settings.json +18 -0
  2. package/.env.example +18 -5
  3. package/README.md +1 -0
  4. package/bin/maestro.mjs +62 -0
  5. package/docs/guides/billing-console-keys.md +60 -0
  6. package/docs/guides/front-door-session.md +54 -9
  7. package/docs/guides/mac-mini.md +20 -25
  8. package/docs/guides/setup-wizard.md +1 -1
  9. package/docs/runbooks/fleet-rollout.md +156 -0
  10. package/docs/runbooks/mac-mini-bootstrap.md +12 -14
  11. package/lib/action-executor.js +19 -3
  12. package/lib/budget-guard.mjs +279 -3
  13. package/lib/channels/base-adapter.mjs +3 -1
  14. package/lib/channels/contract.mjs +2 -1
  15. package/lib/channels/inbox-item.mjs +8 -0
  16. package/lib/claude-bin.mjs +5 -6
  17. package/lib/cli/doctor-checks.mjs +141 -10
  18. package/lib/cli/global-setup-extras.mjs +5 -1
  19. package/lib/cli/inbox.mjs +100 -15
  20. package/lib/cli/seat-auth.mjs +463 -0
  21. package/lib/cli/session.mjs +80 -12
  22. package/lib/collective/capture-slots.mjs +234 -0
  23. package/lib/collective/capture.mjs +8 -6
  24. package/lib/collective/config.mjs +2 -0
  25. package/lib/collective/global-config.mjs +63 -1
  26. package/lib/collective/loop-guard.mjs +155 -0
  27. package/lib/collective/presence.mjs +142 -5
  28. package/lib/comms/send-gate.mjs +559 -1
  29. package/lib/diagnostics/alerts.mjs +49 -0
  30. package/lib/diagnostics/cadence-output-freshness.mjs +288 -0
  31. package/lib/engine/agents/definitions.mjs +343 -0
  32. package/lib/engine/agents/persist.mjs +275 -0
  33. package/lib/engine/agents/runtime.mjs +748 -0
  34. package/lib/engine/agents/usage.mjs +95 -0
  35. package/lib/engine/auth-status.mjs +139 -0
  36. package/lib/engine/budget.mjs +194 -0
  37. package/lib/engine/cli.mjs +1204 -0
  38. package/lib/engine/commands/index.mjs +269 -0
  39. package/lib/engine/context/budget.mjs +219 -0
  40. package/lib/engine/context/cache.mjs +125 -0
  41. package/lib/engine/context/child-env.mjs +215 -0
  42. package/lib/engine/context/compaction.mjs +342 -0
  43. package/lib/engine/context/images.mjs +90 -0
  44. package/lib/engine/context/instructions.mjs +327 -0
  45. package/lib/engine/context/lazy-instructions.mjs +169 -0
  46. package/lib/engine/context/manager.mjs +182 -0
  47. package/lib/engine/context/real-path.mjs +91 -0
  48. package/lib/engine/context/secret-values.mjs +163 -0
  49. package/lib/engine/context/settings.mjs +274 -0
  50. package/lib/engine/context/stream-input.mjs +159 -0
  51. package/lib/engine/guard.mjs +152 -0
  52. package/lib/engine/hooks.mjs +713 -0
  53. package/lib/engine/loop.mjs +560 -0
  54. package/lib/engine/mcp/client.mjs +254 -0
  55. package/lib/engine/mcp/config.mjs +301 -0
  56. package/lib/engine/mcp/http.mjs +201 -0
  57. package/lib/engine/mcp/index.mjs +146 -0
  58. package/lib/engine/mcp/jsonrpc.mjs +147 -0
  59. package/lib/engine/mcp/naming.mjs +66 -0
  60. package/lib/engine/mcp/resources.mjs +89 -0
  61. package/lib/engine/mcp/results.mjs +133 -0
  62. package/lib/engine/mcp/stdio.mjs +137 -0
  63. package/lib/engine/mcp/supervisor.mjs +116 -0
  64. package/lib/engine/messages.mjs +104 -0
  65. package/lib/engine/output/json.mjs +164 -0
  66. package/lib/engine/output/stream-json.mjs +266 -0
  67. package/lib/engine/permissions.mjs +845 -0
  68. package/lib/engine/process-identity.mjs +164 -0
  69. package/lib/engine/process-tree.mjs +551 -0
  70. package/lib/engine/prompt.mjs +60 -0
  71. package/lib/engine/session/store.mjs +299 -0
  72. package/lib/engine/session-runtime/args.mjs +97 -0
  73. package/lib/engine/session-runtime/host.mjs +143 -0
  74. package/lib/engine/session-runtime/inbox.mjs +122 -0
  75. package/lib/engine/session-runtime/notifications.mjs +129 -0
  76. package/lib/engine/session-runtime/registry.mjs +328 -0
  77. package/lib/engine/session-runtime/runner.mjs +344 -0
  78. package/lib/engine/session-runtime/socket.mjs +212 -0
  79. package/lib/engine/session-runtime/wakeup.mjs +115 -0
  80. package/lib/engine/skills/index.mjs +321 -0
  81. package/lib/engine/tools/bash-background.mjs +533 -0
  82. package/lib/engine/tools/bash.mjs +216 -0
  83. package/lib/engine/tools/edit.mjs +97 -0
  84. package/lib/engine/tools/glob.mjs +81 -0
  85. package/lib/engine/tools/grep.mjs +224 -0
  86. package/lib/engine/tools/index.mjs +84 -0
  87. package/lib/engine/tools/list-agents.mjs +32 -0
  88. package/lib/engine/tools/ls.mjs +127 -0
  89. package/lib/engine/tools/monitor.mjs +82 -0
  90. package/lib/engine/tools/notebook-edit.mjs +218 -0
  91. package/lib/engine/tools/read.mjs +103 -0
  92. package/lib/engine/tools/schedule-wakeup.mjs +45 -0
  93. package/lib/engine/tools/schema.mjs +144 -0
  94. package/lib/engine/tools/send-message.mjs +77 -0
  95. package/lib/engine/tools/session.mjs +70 -0
  96. package/lib/engine/tools/todo.mjs +144 -0
  97. package/lib/engine/tools/toolsearch.mjs +217 -0
  98. package/lib/engine/tools/walk.mjs +193 -0
  99. package/lib/engine/tools/web-switch.mjs +31 -0
  100. package/lib/engine/tools/webfetch-html.mjs +387 -0
  101. package/lib/engine/tools/webfetch-net.mjs +340 -0
  102. package/lib/engine/tools/webfetch.mjs +198 -0
  103. package/lib/engine/tools/websearch.mjs +91 -0
  104. package/lib/engine/tools/workflow.mjs +95 -0
  105. package/lib/engine/tools/write.mjs +76 -0
  106. package/lib/engine/tui/line-editor.mjs +137 -0
  107. package/lib/engine/tui/render.mjs +86 -0
  108. package/lib/engine/tui/tui.mjs +274 -0
  109. package/lib/engine/wire/anthropic-messages.mjs +263 -0
  110. package/lib/engine/wire/effort.mjs +36 -0
  111. package/lib/engine/wire/errors.mjs +496 -0
  112. package/lib/engine/wire/http.mjs +441 -0
  113. package/lib/engine/wire/index.mjs +76 -0
  114. package/lib/engine/wire/openai-chat.mjs +332 -0
  115. package/lib/engine/wire/prompt-cache.mjs +79 -0
  116. package/lib/engine/wire/search.mjs +140 -0
  117. package/lib/engine/wire/sse.mjs +114 -0
  118. package/lib/engine/wire/stall.mjs +349 -0
  119. package/lib/engine/wire/token-provider.mjs +175 -0
  120. package/lib/engine/wire/usage.mjs +192 -0
  121. package/lib/engine/workflow/host.mjs +524 -0
  122. package/lib/engine/workflow/journal.mjs +188 -0
  123. package/lib/engine/workflow/json-schema.mjs +171 -0
  124. package/lib/engine/workflow/meta.mjs +329 -0
  125. package/lib/engine/workflow/notifications.mjs +52 -0
  126. package/lib/engine/workflow/runtime.mjs +447 -0
  127. package/lib/engine/workflow/sandbox.mjs +534 -0
  128. package/lib/engine/workflow/worker.mjs +141 -0
  129. package/lib/engine/workflow/worktree.mjs +74 -0
  130. package/lib/execution/disposition.mjs +1 -1
  131. package/lib/execution/intake.mjs +10 -0
  132. package/lib/execution/surface-policy.mjs +15 -0
  133. package/lib/learning/curator.mjs +8 -6
  134. package/lib/learning/reflect.mjs +8 -6
  135. package/lib/model-router/catalog/cohort.yaml +137 -0
  136. package/lib/model-router/catalog.mjs +118 -1
  137. package/lib/model-router/failover.mjs +67 -16
  138. package/lib/model-router/llm-task.mjs +39 -3
  139. package/lib/model-router/resolve.mjs +89 -3
  140. package/lib/model-router/spawn.mjs +46 -47
  141. package/lib/model-router/taxonomy.mjs +126 -4
  142. package/lib/org/cost-sync.mjs +141 -11
  143. package/lib/org/inbound/broadcast.mjs +289 -0
  144. package/lib/org/inbound/collective.mjs +375 -0
  145. package/lib/org/inbound/directedness.mjs +96 -8
  146. package/lib/org/inbound/facts.mjs +78 -2
  147. package/lib/org/inbound/project.mjs +22 -0
  148. package/lib/org/inbound/surfaces.mjs +14 -0
  149. package/lib/org/llm-token.mjs +879 -0
  150. package/lib/org/mesh.mjs +61 -0
  151. package/lib/org/messaging.mjs +3 -1
  152. package/lib/org/protocol.checksum +1 -1
  153. package/lib/org/protocol.mjs +15 -0
  154. package/lib/org/quota.mjs +520 -0
  155. package/lib/org/tool-surface.mjs +104 -16
  156. package/lib/org/ui-parity.mjs +16 -1
  157. package/lib/org/work-ledger.mjs +37 -6
  158. package/lib/rate-guard.mjs +114 -1
  159. package/lib/resource-governor.mjs +41 -6
  160. package/lib/runtime/adapter.mjs +833 -0
  161. package/lib/runtime/child-env.mjs +191 -0
  162. package/lib/runtime/legacy-shell-guard.mjs +97 -0
  163. package/lib/runtime/seat-engine.mjs +162 -0
  164. package/lib/session/ask-ledger.mjs +271 -0
  165. package/lib/session/current-work.mjs +676 -0
  166. package/lib/session/feed-core.mjs +40 -3
  167. package/lib/session/launch-args.mjs +56 -4
  168. package/lib/session/status-summary.mjs +26 -9
  169. package/lib/session/upgrade-notice.mjs +42 -0
  170. package/lib/setup/claude-probe.mjs +117 -13
  171. package/lib/setup/enrich.mjs +13 -10
  172. package/lib/setup/sections/model.mjs +39 -13
  173. package/lib/telemetry/collect.mjs +229 -11
  174. package/lib/upgrade/ignored-drift.mjs +105 -0
  175. package/lib/voice/post-call-brief.mjs +30 -17
  176. package/package.json +13 -3
  177. package/plugins/maestro-skills/skills/board-work.md +5 -0
  178. package/plugins/maestro-skills/skills/inbound-triage.md +56 -15
  179. package/plugins/maestro-skills/skills/main-session.md +18 -7
  180. package/scaffold/config/collective.yaml +7 -0
  181. package/scripts/ci/check-durable-write-seam.mjs +3 -1
  182. package/scripts/ci/check-tarball-fidelity.mjs +126 -2
  183. package/scripts/ci/run-tests.mjs +47 -19
  184. package/scripts/cohort-llm/api-key-helper.mjs +92 -0
  185. package/scripts/collective/hook-runner.mjs +142 -19
  186. package/scripts/continuous-monitor.sh +13 -0
  187. package/scripts/cost/track-claude-usage.mjs +15 -0
  188. package/scripts/daemon/agent-daemon.mjs +408 -20
  189. package/scripts/daemon/assurance.mjs +48 -12
  190. package/scripts/daemon/cadence-consumer.mjs +218 -68
  191. package/scripts/daemon/cadence-handlers.mjs +73 -4
  192. package/scripts/daemon/classifier.mjs +75 -26
  193. package/scripts/daemon/context-compiler.mjs +51 -37
  194. package/scripts/daemon/deliver.mjs +30 -1
  195. package/scripts/daemon/dispatcher.mjs +595 -149
  196. package/scripts/daemon/health.mjs +14 -1
  197. package/scripts/daemon/maestro-daemon.mjs +11 -0
  198. package/scripts/daemon/prompt-builder.mjs +24 -0
  199. package/scripts/daemon/responder.mjs +246 -79
  200. package/scripts/daemon/sdk-version.mjs +98 -16
  201. package/scripts/eval/probe-gateway.mjs +635 -0
  202. package/scripts/eval/replay/extract.mjs +270 -0
  203. package/scripts/eval/replay/grade.mjs +260 -0
  204. package/scripts/eval/replay/lib/config.mjs +50 -0
  205. package/scripts/eval/replay/lib/effects.mjs +65 -0
  206. package/scripts/eval/replay/lib/fixture.mjs +188 -0
  207. package/scripts/eval/replay/lib/judge.mjs +72 -0
  208. package/scripts/eval/replay/lib/redact.mjs +136 -0
  209. package/scripts/eval/replay/lib/sandbox.mjs +170 -0
  210. package/scripts/eval/replay/lib/schema-check.mjs +63 -0
  211. package/scripts/eval/replay/lib/transcript.mjs +76 -0
  212. package/scripts/eval/replay/mcp-replay-stub.mjs +101 -0
  213. package/scripts/eval/replay/report.mjs +185 -0
  214. package/scripts/eval/replay/run.mjs +404 -0
  215. package/scripts/fleet/rollout.mjs +1151 -0
  216. package/scripts/hooks/pre-send-audit.sh +36 -245
  217. package/scripts/hooks/pre-write-yaml-validate.mjs +275 -0
  218. package/scripts/hooks/validate-state-yaml.sh +190 -0
  219. package/scripts/huddle/huddle-llm.mjs +361 -0
  220. package/scripts/huddle/huddle-server.mjs +46 -121
  221. package/scripts/local-triggers/autoupdate.sh +465 -81
  222. package/scripts/local-triggers/run-trigger.sh +13 -0
  223. package/scripts/maintenance/pin-integrity.mjs +364 -0
  224. package/scripts/poll-slack-events.sh +41 -9
  225. package/scripts/poller/slack-socket-mode.mjs +28 -3
  226. package/scripts/session/supervisor.mjs +80 -13
  227. package/scripts/spawn-session.sh +13 -0
  228. package/bin/maestro.test.mjs +0 -1574
  229. package/lib/action-executor.test.mjs +0 -871
  230. package/lib/archetype.test.mjs +0 -132
  231. package/lib/assurance/plan-note.test.mjs +0 -234
  232. package/lib/assurance/room-budget.test.mjs +0 -486
  233. package/lib/assurance/tier.test.mjs +0 -174
  234. package/lib/autonomy.test.mjs +0 -66
  235. package/lib/backlog.test.mjs +0 -302
  236. package/lib/backup/policy.test.mjs +0 -305
  237. package/lib/budget-escalate.test.mjs +0 -232
  238. package/lib/budget-guard.envelope.test.mjs +0 -476
  239. package/lib/budget-guard.test.mjs +0 -427
  240. package/lib/cadence-bus-requeue.test.mjs +0 -83
  241. package/lib/cadence-bus-schedule.test.mjs +0 -194
  242. package/lib/cadence-bus.test.mjs +0 -720
  243. package/lib/cadences.test.mjs +0 -230
  244. package/lib/capability/inventory.test.mjs +0 -232
  245. package/lib/capability.test.mjs +0 -78
  246. package/lib/channels/base-adapter.test.mjs +0 -590
  247. package/lib/channels/channels.test.mjs +0 -371
  248. package/lib/channels/contract.test.mjs +0 -162
  249. package/lib/channels/inbox-item.test.mjs +0 -368
  250. package/lib/channels/orgmail/adapter.test.mjs +0 -448
  251. package/lib/channels/pairing.test.mjs +0 -270
  252. package/lib/channels/repeat-suppressor.test.mjs +0 -134
  253. package/lib/channels/slack-adapter.test.mjs +0 -212
  254. package/lib/channels/telegram-adapter.test.mjs +0 -306
  255. package/lib/channels/voice/adapter.test.mjs +0 -278
  256. package/lib/channels/whatsapp/adapter-baileys.test.mjs +0 -359
  257. package/lib/channels/whatsapp/baileys-typing.test.mjs +0 -154
  258. package/lib/charter.test.mjs +0 -89
  259. package/lib/claude-bin.test.mjs +0 -131
  260. package/lib/cli/board.test.mjs +0 -227
  261. package/lib/cli/design.test.mjs +0 -270
  262. package/lib/cli/doctor-checks.test.mjs +0 -336
  263. package/lib/cli/global-setup-extras.test.mjs +0 -462
  264. package/lib/cli/inbox.test.mjs +0 -230
  265. package/lib/cli/session-ack.test.mjs +0 -63
  266. package/lib/cli/session.test.mjs +0 -613
  267. package/lib/collective/capture.test.mjs +0 -121
  268. package/lib/collective/cards.test.mjs +0 -114
  269. package/lib/collective/config.test.mjs +0 -123
  270. package/lib/collective/global-config.test.mjs +0 -220
  271. package/lib/collective/global-skills.test.mjs +0 -126
  272. package/lib/collective/presence.test.mjs +0 -95
  273. package/lib/collective/recall.test.mjs +0 -116
  274. package/lib/collective/vendor-skills.test.mjs +0 -306
  275. package/lib/comms/send-gate.test.mjs +0 -770
  276. package/lib/comms.test.mjs +0 -41
  277. package/lib/context/budget.test.mjs +0 -252
  278. package/lib/context/history-scope.test.mjs +0 -79
  279. package/lib/cost/ledger-row.test.mjs +0 -183
  280. package/lib/design/design-md.test.mjs +0 -318
  281. package/lib/design/fixtures/DESIGN.golden.md +0 -238
  282. package/lib/design/fixtures/PRODUCT.golden.md +0 -67
  283. package/lib/design/fixtures/foundation.json +0 -133
  284. package/lib/design/refresh-gate.test.mjs +0 -144
  285. package/lib/design/write.test.mjs +0 -241
  286. package/lib/diagnostics/alerts.test.mjs +0 -318
  287. package/lib/diagnostics/backup-freshness.test.mjs +0 -185
  288. package/lib/diagnostics/counters.test.mjs +0 -206
  289. package/lib/diagnostics/events.test.mjs +0 -290
  290. package/lib/diagnostics/otel.test.mjs +0 -196
  291. package/lib/diagnostics/trace.test.mjs +0 -251
  292. package/lib/env-compat.test.mjs +0 -104
  293. package/lib/execution/disposition.test.mjs +0 -553
  294. package/lib/execution/drive.test.mjs +0 -270
  295. package/lib/execution/effects.test.mjs +0 -344
  296. package/lib/execution/intake.test.mjs +0 -389
  297. package/lib/execution/journal.test.mjs +0 -261
  298. package/lib/execution/match.test.mjs +0 -235
  299. package/lib/execution/pipeline.test.mjs +0 -392
  300. package/lib/execution/route.test.mjs +0 -186
  301. package/lib/execution/surface-policy.test.mjs +0 -162
  302. package/lib/fs-atomic.test.mjs +0 -72
  303. package/lib/fs-ownership.test.mjs +0 -158
  304. package/lib/goals/admission.test.mjs +0 -164
  305. package/lib/goals/classify.test.mjs +0 -167
  306. package/lib/goals/collaborate.test.mjs +0 -336
  307. package/lib/goals/gaps.test.mjs +0 -284
  308. package/lib/goals/loop.test.mjs +0 -845
  309. package/lib/hooks/bus.test.mjs +0 -387
  310. package/lib/identity/persona.test.mjs +0 -142
  311. package/lib/kpi-sensors.test.mjs +0 -278
  312. package/lib/kpi.test.mjs +0 -244
  313. package/lib/learning/config.test.mjs +0 -75
  314. package/lib/learning/counters.test.mjs +0 -69
  315. package/lib/learning/curator-consolidate.test.mjs +0 -238
  316. package/lib/learning/curator.test.mjs +0 -106
  317. package/lib/learning/reflect.test.mjs +0 -0
  318. package/lib/learning/session-index.test.mjs +0 -125
  319. package/lib/learning/skill-writer.test.mjs +0 -210
  320. package/lib/mandate/audit.test.mjs +0 -195
  321. package/lib/mandate/contract.test.mjs +0 -185
  322. package/lib/mandate/derive.test.mjs +0 -274
  323. package/lib/mandate/model.test.mjs +0 -164
  324. package/lib/mandate/refresh.test.mjs +0 -389
  325. package/lib/mcp/server.test.mjs +0 -426
  326. package/lib/model-router/auth-profiles.test.mjs +0 -580
  327. package/lib/model-router/catalog.test.mjs +0 -385
  328. package/lib/model-router/economics.test.mjs +0 -438
  329. package/lib/model-router/failover.test.mjs +0 -439
  330. package/lib/model-router/health.test.mjs +0 -338
  331. package/lib/model-router/integration-coverage.test.mjs +0 -831
  332. package/lib/model-router/integration.test.mjs +0 -564
  333. package/lib/model-router/ledger.test.mjs +0 -415
  334. package/lib/model-router/llm-task.test.mjs +0 -392
  335. package/lib/model-router/org-credentials.test.mjs +0 -265
  336. package/lib/model-router/pricing-refresh.test.mjs +0 -286
  337. package/lib/model-router/reconcile.test.mjs +0 -316
  338. package/lib/model-router/repair.test.mjs +0 -180
  339. package/lib/model-router/spawn.test.mjs +0 -446
  340. package/lib/model-router/taxonomy.test.mjs +0 -410
  341. package/lib/model-router.test.mjs +0 -1207
  342. package/lib/org/activity.test.mjs +0 -134
  343. package/lib/org/approvals.test.mjs +0 -216
  344. package/lib/org/awareness.test.mjs +0 -159
  345. package/lib/org/board-mine-cache.test.mjs +0 -53
  346. package/lib/org/board.test.mjs +0 -187
  347. package/lib/org/bootstrap-context.test.mjs +0 -153
  348. package/lib/org/client.test.mjs +0 -1206
  349. package/lib/org/cohort-client.test.mjs +0 -126
  350. package/lib/org/cost-sync.test.mjs +0 -153
  351. package/lib/org/doctor.test.mjs +0 -346
  352. package/lib/org/engagement-ledger.test.mjs +0 -112
  353. package/lib/org/engagement.test.mjs +0 -739
  354. package/lib/org/handoff.test.mjs +0 -269
  355. package/lib/org/inbound/directedness.test.mjs +0 -668
  356. package/lib/org/inbound/facts.test.mjs +0 -471
  357. package/lib/org/inbound/hydrate.test.mjs +0 -908
  358. package/lib/org/inbound/index.test.mjs +0 -429
  359. package/lib/org/inbound/project.test.mjs +0 -287
  360. package/lib/org/integration-tools.test.mjs +0 -160
  361. package/lib/org/keys.test.mjs +0 -92
  362. package/lib/org/knowledge.test.mjs +0 -326
  363. package/lib/org/leases.test.mjs +0 -235
  364. package/lib/org/mesh-directives.test.mjs +0 -110
  365. package/lib/org/mesh-integration.test.mjs +0 -127
  366. package/lib/org/mesh.test.mjs +0 -400
  367. package/lib/org/messaging.test.mjs +0 -471
  368. package/lib/org/param-contract.test.mjs +0 -477
  369. package/lib/org/policy.test.mjs +0 -237
  370. package/lib/org/protocol.checksum.test.mjs +0 -90
  371. package/lib/org/protocol.test.mjs +0 -323
  372. package/lib/org/push.test.mjs +0 -792
  373. package/lib/org/registry.test.mjs +0 -100
  374. package/lib/org/resource-tools.test.mjs +0 -361
  375. package/lib/org/tool-access.test.mjs +0 -144
  376. package/lib/org/tool-surface-integration.test.mjs +0 -120
  377. package/lib/org/tool-surface.test.mjs +0 -1268
  378. package/lib/org/typing.test.mjs +0 -291
  379. package/lib/org/ui-parity.test.mjs +0 -560
  380. package/lib/org/verify.test.mjs +0 -194
  381. package/lib/org/work-ledger.test.mjs +0 -273
  382. package/lib/plan/adoption-e2e.test.mjs +0 -366
  383. package/lib/plan/budget-enforcement.test.mjs +0 -400
  384. package/lib/plan/compile.test.mjs +0 -382
  385. package/lib/plan/emit.test.mjs +0 -269
  386. package/lib/plan/explain.test.mjs +0 -188
  387. package/lib/prompts/parallelism.test.mjs +0 -177
  388. package/lib/rag/rag.test.mjs +0 -505
  389. package/lib/rate-guard.test.mjs +0 -272
  390. package/lib/reactive-gate.test.mjs +0 -57
  391. package/lib/render.test.mjs +0 -68
  392. package/lib/resource-governor.test.mjs +0 -488
  393. package/lib/scheduling/dynamic-jobs.test.mjs +0 -344
  394. package/lib/scheduling/jitter.test.mjs +0 -140
  395. package/lib/secrets/broker.test.mjs +0 -280
  396. package/lib/secrets/providers.test.mjs +0 -274
  397. package/lib/security/audit-engine.test.mjs +0 -424
  398. package/lib/security/coerce-args.test.mjs +0 -281
  399. package/lib/security/dangerous-tools.test.mjs +0 -68
  400. package/lib/security/external-content.test.mjs +0 -84
  401. package/lib/security/redact.test.mjs +0 -441
  402. package/lib/security/secret-equal.test.mjs +0 -55
  403. package/lib/session/config.test.mjs +0 -92
  404. package/lib/session/feed-core.test.mjs +0 -198
  405. package/lib/session/first-run.test.mjs +0 -121
  406. package/lib/session/frontdoor.test.mjs +0 -205
  407. package/lib/session/handoffs.test.mjs +0 -183
  408. package/lib/session/identity.test.mjs +0 -180
  409. package/lib/session/inbox-claims.test.mjs +0 -286
  410. package/lib/session/launch-args.test.mjs +0 -157
  411. package/lib/session/liveness.test.mjs +0 -100
  412. package/lib/session/status-summary.test.mjs +0 -118
  413. package/lib/session-permissions.test.mjs +0 -120
  414. package/lib/setup/claude-probe.test.mjs +0 -187
  415. package/lib/setup/completeness.test.mjs +0 -110
  416. package/lib/setup/context-pack.test.mjs +0 -89
  417. package/lib/setup/enrich.test.mjs +0 -115
  418. package/lib/setup/enroll-from-cohort.test.mjs +0 -300
  419. package/lib/setup/integration.test.mjs +0 -162
  420. package/lib/setup/io.test.mjs +0 -77
  421. package/lib/setup/runner.test.mjs +0 -132
  422. package/lib/setup/sections/identity.test.mjs +0 -234
  423. package/lib/setup/sections/inventory.test.mjs +0 -198
  424. package/lib/setup/sections/learning.test.mjs +0 -81
  425. package/lib/setup/sections/mandate.test.mjs +0 -388
  426. package/lib/setup/sections/messaging.test.mjs +0 -127
  427. package/lib/setup/sections/model.test.mjs +0 -240
  428. package/lib/setup/sections/org.test.mjs +0 -346
  429. package/lib/setup/sections/orgmail.test.mjs +0 -118
  430. package/lib/setup/sections/recovery.test.mjs +0 -98
  431. package/lib/setup/sections/subagents.test.mjs +0 -429
  432. package/lib/setup/sections/verify.test.mjs +0 -175
  433. package/lib/setup/sot.test.mjs +0 -81
  434. package/lib/setup/state.test.mjs +0 -115
  435. package/lib/singleton.test.mjs +0 -151
  436. package/lib/subagents/cli.test.mjs +0 -389
  437. package/lib/subagents/client.test.mjs +0 -309
  438. package/lib/subagents/gap.test.mjs +0 -234
  439. package/lib/subagents/lock.test.mjs +0 -248
  440. package/lib/subagents/manifest.test.mjs +0 -175
  441. package/lib/subagents/refs.test.mjs +0 -204
  442. package/lib/subagents/resolve.test.mjs +0 -422
  443. package/lib/subagents/schema.test.mjs +0 -328
  444. package/lib/telemetry/alerts.test.mjs +0 -109
  445. package/lib/telemetry/collect.test.mjs +0 -1274
  446. package/lib/tool-definitions-integration.test.mjs +0 -83
  447. package/lib/tool-definitions.test.mjs +0 -437
  448. package/lib/upgrade/global-refresh.test.mjs +0 -65
  449. package/lib/upgrade/launchd-reconcile.test.mjs +0 -272
  450. package/lib/upgrade/post-steps.test.mjs +0 -200
  451. package/lib/upgrade/verify.test.mjs +0 -164
  452. package/lib/util/fetch-timeout.test.mjs +0 -202
  453. package/lib/util/reconnect.test.mjs +0 -369
  454. package/lib/util/unhandled.test.mjs +0 -216
  455. package/lib/voice/outbound.test.mjs +0 -69
  456. package/lib/voice/session-rotation.test.mjs +0 -114
  457. package/lib/voice/stt.test.mjs +0 -226
  458. package/lib/voice/voice.test.mjs +0 -990
  459. package/scripts/cadence/enqueue-cadence-tick.test.mjs +0 -187
  460. package/scripts/ci/check-docs-accuracy.test.mjs +0 -409
  461. package/scripts/ci/check-durable-write-seam.test.mjs +0 -90
  462. package/scripts/ci/check-no-build-artifacts.test.mjs +0 -71
  463. package/scripts/ci/check-no-residual-identity.test.mjs +0 -202
  464. package/scripts/ci/check-skill-packs.test.mjs +0 -495
  465. package/scripts/ci/check-subagent-frontmatter.test.mjs +0 -124
  466. package/scripts/ci/check.test.mjs +0 -194
  467. package/scripts/ci/conformance-org-api.test.mjs +0 -425
  468. package/scripts/cloud-relay/voice/relay-identity.test.mjs +0 -96
  469. package/scripts/collective/hook-runner.test.mjs +0 -173
  470. package/scripts/cost/fleet-digest.test.mjs +0 -207
  471. package/scripts/cost/track-claude-usage-pricing.test.mjs +0 -183
  472. package/scripts/cost/track-claude-usage.test.mjs +0 -148
  473. package/scripts/daemon/agent-daemon-board-mine.test.mjs +0 -96
  474. package/scripts/daemon/agent-daemon-design.test.mjs +0 -238
  475. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +0 -60
  476. package/scripts/daemon/agent-daemon.test.mjs +0 -995
  477. package/scripts/daemon/assurance-e2e.test.mjs +0 -613
  478. package/scripts/daemon/assurance.test.mjs +0 -1791
  479. package/scripts/daemon/board-mirror.test.mjs +0 -165
  480. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +0 -393
  481. package/scripts/daemon/cadence-consumer-governance.test.mjs +0 -276
  482. package/scripts/daemon/cadence-consumer.test.mjs +0 -776
  483. package/scripts/daemon/cadence-handlers.test.mjs +0 -837
  484. package/scripts/daemon/classifier-identity.test.mjs +0 -137
  485. package/scripts/daemon/classifier.test.mjs +0 -266
  486. package/scripts/daemon/classify-kind.test.mjs +0 -40
  487. package/scripts/daemon/context-compiler.test.mjs +0 -406
  488. package/scripts/daemon/deliver.test.mjs +0 -564
  489. package/scripts/daemon/dispatcher-cooldown.test.mjs +0 -122
  490. package/scripts/daemon/dispatcher-governance.test.mjs +0 -1013
  491. package/scripts/daemon/dispatcher-resume.test.mjs +0 -166
  492. package/scripts/daemon/dispatcher-session-continuity.test.mjs +0 -365
  493. package/scripts/daemon/execution-ladder.test.mjs +0 -470
  494. package/scripts/daemon/goal-steward-cadence.test.mjs +0 -312
  495. package/scripts/daemon/inbox-deferral-session.test.mjs +0 -49
  496. package/scripts/daemon/inbox-deferral.test.mjs +0 -336
  497. package/scripts/daemon/inbox-wake.test.mjs +0 -199
  498. package/scripts/daemon/integration.test.mjs +0 -149
  499. package/scripts/daemon/lib/self-echo.test.mjs +0 -153
  500. package/scripts/daemon/lib/session-router.test.mjs +0 -554
  501. package/scripts/daemon/prompt-builder-preamble.test.mjs +0 -210
  502. package/scripts/daemon/prompt-builder.test.mjs +0 -556
  503. package/scripts/daemon/responder-cost.test.mjs +0 -68
  504. package/scripts/daemon/responder-history.test.mjs +0 -221
  505. package/scripts/daemon/sdk-version.test.mjs +0 -31
  506. package/scripts/daemon/session-lock.test.mjs +0 -252
  507. package/scripts/daemon/session-outcomes.test.mjs +0 -533
  508. package/scripts/daemon/typing-registry.test.mjs +0 -102
  509. package/scripts/hooks/pre-send-audit.test.mjs +0 -354
  510. package/scripts/huddle/huddle-prompt.test.mjs +0 -176
  511. package/scripts/local-triggers/autoupdate.test.mjs +0 -518
  512. package/scripts/local-triggers/generate-plists.test.mjs +0 -456
  513. package/scripts/media-generation/brand-clause.test.mjs +0 -135
  514. package/scripts/org/send-orgmail.first-contact.test.mjs +0 -102
  515. package/scripts/poller/inbox-privilege-injection.test.mjs +0 -167
  516. package/scripts/poller/inbox-scan-poller.test.mjs +0 -295
  517. package/scripts/poller/lib/cloud-relay-dedup.test.mjs +0 -133
  518. package/scripts/poller/slack-socket-mode.test.mjs +0 -805
  519. package/scripts/poller-launchd/install.test.mjs +0 -243
  520. package/scripts/restore-from-backup.test.mjs +0 -181
  521. package/scripts/session/feed.test.mjs +0 -196
  522. package/scripts/session/supervisor-sh.test.mjs +0 -218
  523. package/scripts/session/supervisor.test.mjs +0 -482
  524. package/scripts/setup/configure-macos.test.mjs +0 -306
  525. package/scripts/setup/gen-subagent-manifest.test.mjs +0 -124
  526. package/scripts/setup/generate-agent-package-json.test.mjs +0 -143
  527. package/scripts/setup/generate-capability.test.mjs +0 -134
  528. package/scripts/setup/init-agent.test.mjs +0 -370
  529. package/scripts/setup/init-skill-marketplace.test.mjs +0 -193
  530. package/scripts/vendor/sync-skill-packs.test.mjs +0 -103
  531. package/scripts/watchdog/memory-watchdog.test.mjs +0 -64
@@ -1,1013 +0,0 @@
1
- /**
2
- * dispatcher-governance.test.mjs — WS4 coverage for the dispatcher's
3
- * resource-governor / rate-breaker admission gating and the in-flight session
4
- * resume reconcile.
5
- *
6
- * The dispatcher is a stateful module that reads AGENT_DIR at import time and
7
- * spawns real `claude` children on the ADMIT path. To stay hermetic we:
8
- * • import a FRESH module per test (isolated tmpdir AGENT_DIR), and
9
- * • inject fake governor + rateGuard via setGovernanceForTests so we only
10
- * ever exercise the NON-spawning branches (DEFER/QUEUE) and the reconcile
11
- * path (which takes an injected spawnResume) — no child process is launched.
12
- *
13
- * The two invariants under test:
14
- * (1) DEFER never drops work and never burns retry budget — a deferred
15
- * backlog item is NOT claimed and NO session/queue entry is created, so
16
- * the on-disk queue item is retried by the next sweep untouched.
17
- * (2) Resume reconcile re-dispatches mid-flight work, and only after 3
18
- * strikes marks the item blocked (never bricks, never loops forever).
19
- */
20
-
21
- import { test } from "node:test";
22
- import assert from "node:assert/strict";
23
- import { promises as fsp } from "node:fs";
24
- import { writeFileSync, mkdirSync, existsSync, readFileSync, readdirSync } from "node:fs";
25
- import { tmpdir } from "node:os";
26
- import { join } from "node:path";
27
-
28
- async function freshDispatcher() {
29
- const dir = join(tmpdir(), `dispatcher-gov-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
30
- mkdirSync(join(dir, "state/sessions"), { recursive: true });
31
- mkdirSync(join(dir, "state/queues"), { recursive: true });
32
- mkdirSync(join(dir, "logs/daemon"), { recursive: true });
33
- process.env.AGENT_DIR = dir;
34
- const url = new URL("./dispatcher.mjs", import.meta.url);
35
- const mod = await import(`${url.href}?gov=${Math.random()}`);
36
- return { mod, dir };
37
- }
38
- async function cleanup(dir) { try { await fsp.rm(dir, { recursive: true, force: true }); } catch { /* */ } }
39
-
40
- /**
41
- * Read every diagnostic-event row the dispatcher appended to its tmp
42
- * logs/diagnostics/<UTC-date>.jsonl stream. Returns [] if nothing was written.
43
- */
44
- function readDiagnostics(dir) {
45
- const date = new Date().toISOString().slice(0, 10);
46
- const path = join(dir, "logs", "diagnostics", `${date}.jsonl`);
47
- let raw = "";
48
- try { raw = readFileSync(path, "utf-8"); } catch { return []; }
49
- return raw.split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
50
- }
51
-
52
- const fakeGovernor = (decision) => ({
53
- admit: () => ({ decision, reason: `forced-${decision}`, snapshot: {} }),
54
- defaultDeps: () => ({}),
55
- });
56
- const allowRate = { checkRateLimit: () => ({ allowed: true, retryAt: null }), classifyStderr: () => false, recordRateLimit: () => {}, recordSuccess: () => {} };
57
- const openRate = { checkRateLimit: () => ({ allowed: false, retryAt: Date.now() + 60_000 }), classifyStderr: () => false, recordRateLimit: () => {}, recordSuccess: () => {} };
58
- const noBudget = { dailyStatus: () => ({ essentialOnly: false }) };
59
-
60
- function itemClaimDir(dir) { return join(dir, "state/locks/item-claims"); }
61
- function claimFiles(dir) {
62
- try { return readdirSync(itemClaimDir(dir)).filter((f) => f.endsWith(".claim")); } catch { return []; }
63
- }
64
-
65
- // ---------------------------------------------------------------------------
66
- // Invariant 1 — DEFER never drops work, never claims, never burns budget
67
- // ---------------------------------------------------------------------------
68
-
69
- test("backlog DEFER: item is NOT claimed and NO session is created (sweep retries it)", async () => {
70
- const { mod, dir } = await freshDispatcher();
71
- try {
72
- mod.setGovernanceForTests({ governor: fakeGovernor("DEFER"), rateGuard: allowRate, budgetGuard: noBudget });
73
- mod.dispatch("prompt", { id: "BL-1", title: "deep work", source_file: "backlog.yaml" }, { summary: "deep work", priority: "normal", model: "sonnet" }, "backlog");
74
- const status = mod.getStatus();
75
- assert.equal(status.active_sessions, 0, "no session spawned on DEFER");
76
- assert.equal(status.priority_queue_length, 0);
77
- assert.equal(status.normal_queue_length, 0);
78
- // The crucial bit: no item claim was written, so the on-disk item is left
79
- // fully intact for the next backlog sweep.
80
- assert.deepEqual(claimFiles(dir), [], "DEFER must not claim the item");
81
- } finally { await cleanup(dir); }
82
- });
83
-
84
- test("backlog QUEUE (capacity): item left on disk, not claimed, not spawned", async () => {
85
- const { mod, dir } = await freshDispatcher();
86
- try {
87
- mod.setGovernanceForTests({ governor: fakeGovernor("QUEUE"), rateGuard: allowRate, budgetGuard: noBudget });
88
- mod.dispatch("prompt", { id: "BL-2", title: "task", source_file: "backlog.yaml" }, { summary: "task", priority: "normal", model: "sonnet" }, "backlog");
89
- const status = mod.getStatus();
90
- assert.equal(status.active_sessions, 0);
91
- assert.deepEqual(claimFiles(dir), [], "QUEUE must not claim the backlog item");
92
- } finally { await cleanup(dir); }
93
- });
94
-
95
- test("inbox DEFER is QUEUED, never dropped (user message preserved in memory)", async () => {
96
- const { mod, dir } = await freshDispatcher();
97
- try {
98
- mod.setGovernanceForTests({ governor: fakeGovernor("DEFER"), rateGuard: allowRate, budgetGuard: noBudget });
99
- mod.dispatch("prompt", { id: "IN-1", channel: "D123" }, { summary: "hi", priority: "normal", model: "sonnet" }, "inbox");
100
- const status = mod.getStatus();
101
- assert.equal(status.active_sessions, 0, "DEFER does not spawn");
102
- assert.equal(status.normal_queue_length, 1, "inbox DEFER is queued, not dropped");
103
- } finally { await cleanup(dir); }
104
- });
105
-
106
- test("rate breaker open: backlog deferred (no claim), inbox queued", async () => {
107
- const { mod, dir } = await freshDispatcher();
108
- try {
109
- // Governor would ADMIT, but the shared 429 breaker is open → gate spawns.
110
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: openRate, budgetGuard: noBudget });
111
-
112
- mod.dispatch("p", { id: "BL-3", title: "t", source_file: "q.yaml" }, { summary: "t", priority: "normal", model: "sonnet" }, "backlog");
113
- assert.deepEqual(claimFiles(dir), [], "rate-limited backlog must not claim");
114
- assert.equal(mod.getStatus().active_sessions, 0);
115
-
116
- mod.dispatch("p", { id: "IN-2", channel: "D9" }, { summary: "u", priority: "high", model: "sonnet" }, "inbox");
117
- const status = mod.getStatus();
118
- assert.equal(status.active_sessions, 0, "rate-limited inbox does not spawn");
119
- assert.equal(status.priority_queue_length, 1, "high-priority inbox queued under the breaker");
120
- } finally { await cleanup(dir); }
121
- });
122
-
123
- // ---------------------------------------------------------------------------
124
- // Invariant 2 — resume reconcile: re-dispatch mid-flight, block after 3 strikes
125
- // ---------------------------------------------------------------------------
126
-
127
- function plantMarker(dir, sessionId, marker) {
128
- const d = join(dir, "state/sessions/resume-pending");
129
- mkdirSync(d, { recursive: true });
130
- writeFileSync(join(d, `${sessionId}.json`), JSON.stringify({
131
- sessionId, claudeSessionId: `cs-${sessionId}`, source: "backlog",
132
- itemId: marker.itemId || null, sourceFile: marker.sourceFile || null,
133
- // H1: a real marker persists the original prompt + the exact model flag so
134
- // the resume re-spawns `--session-id <id> <prompt>` (not `--resume`).
135
- prompt: marker.prompt ?? `continue work on ${marker.itemId || sessionId}`,
136
- modelFlag: marker.modelFlag ?? "claude-sonnet-4-6",
137
- model: marker.model ?? "sonnet",
138
- startedAt: marker.startedAt ?? Date.now(), recoveryAttempts: marker.recoveryAttempts ?? 0,
139
- ...marker,
140
- }, null, 2));
141
- }
142
-
143
- test("reconcile re-dispatches a fresh in-flight marker via injected spawnResume", async () => {
144
- const { mod, dir } = await freshDispatcher();
145
- try {
146
- plantMarker(dir, "s-fresh", { itemId: "BL-9", sourceFile: "q.yaml", startedAt: Date.now() });
147
- const resumed = [];
148
- const stats = mod.reconcileResumePending({ spawnResume: ({ marker }) => resumed.push(marker.sessionId) });
149
- assert.equal(stats.resumed, 1);
150
- assert.deepEqual(resumed, ["s-fresh"]);
151
- // The marker's attempt count was bumped (so a crash mid-resume still
152
- // advances toward the strike cap), and the marker survives for the
153
- // resumed session's own close handler to clear.
154
- const m = JSON.parse(readFileSync(join(dir, "state/sessions/resume-pending/s-fresh.json"), "utf-8"));
155
- assert.equal(m.recoveryAttempts, 1);
156
- } finally { await cleanup(dir); }
157
- });
158
-
159
- test("reconcile blocks the item after 3 strikes instead of resuming forever", async () => {
160
- const { mod, dir } = await freshDispatcher();
161
- try {
162
- // A real queue file with the item open, so markItemBlocked can flip it.
163
- writeFileSync(join(dir, "state/queues/q.yaml"),
164
- `- id: BL-STUCK\n title: stuck task\n status: open\n priority: normal\n`);
165
- plantMarker(dir, "s-stuck", { itemId: "BL-STUCK", sourceFile: "q.yaml", startedAt: Date.now(), recoveryAttempts: 3 });
166
- const resumed = [];
167
- const stats = mod.reconcileResumePending({ spawnResume: ({ marker }) => resumed.push(marker.sessionId) });
168
- assert.equal(stats.blocked, 1);
169
- assert.equal(stats.resumed, 0, "must NOT resume past the strike cap");
170
- assert.deepEqual(resumed, []);
171
- // Marker is gone, and the queue item is now status: blocked.
172
- assert.equal(existsSync(join(dir, "state/sessions/resume-pending/s-stuck.json")), false);
173
- const q = readFileSync(join(dir, "state/queues/q.yaml"), "utf-8");
174
- assert.match(q, /status:\s*blocked/);
175
- assert.match(q, /WS4 recovery/);
176
- } finally { await cleanup(dir); }
177
- });
178
-
179
- test("reconcile blocks a marker that is older than the freshness window", async () => {
180
- const { mod, dir } = await freshDispatcher();
181
- try {
182
- writeFileSync(join(dir, "state/queues/q.yaml"),
183
- `- id: BL-OLD\n title: old\n status: open\n priority: low\n`);
184
- // 7h old > default 6h freshness window.
185
- plantMarker(dir, "s-old", { itemId: "BL-OLD", sourceFile: "q.yaml", startedAt: Date.now() - 7 * 60 * 60 * 1000, recoveryAttempts: 0 });
186
- const resumed = [];
187
- const stats = mod.reconcileResumePending({ spawnResume: ({ marker }) => resumed.push(marker.sessionId) });
188
- assert.equal(stats.expired, 1);
189
- assert.equal(stats.resumed, 0);
190
- assert.equal(existsSync(join(dir, "state/sessions/resume-pending/s-old.json")), false);
191
- } finally { await cleanup(dir); }
192
- });
193
-
194
- test("resume reconcile DEFERS (never re-storms) when the backlog budget is 0 (reactive-only seat)", async () => {
195
- // DAEMON_MAX_CONCURRENT=3 → backlogCap = 3 - RESERVED_INBOX_SLOTS(3) = 0, so a
196
- // reactive-only seat must resume NOTHING on boot — the fresh-seat storm root.
197
- process.env.DAEMON_MAX_CONCURRENT = "3";
198
- const { mod, dir } = await freshDispatcher();
199
- try {
200
- plantMarker(dir, "s-a", { itemId: "BL-A", sourceFile: "q.yaml", startedAt: Date.now() });
201
- plantMarker(dir, "s-b", { itemId: "BL-B", sourceFile: "q.yaml", startedAt: Date.now() });
202
- let spawned = 0;
203
- const stats = mod.reconcileResumePending({ spawnResume: () => { spawned++; } });
204
- assert.equal(spawned, 0, "no resume spawns on a budget-0 seat");
205
- assert.equal(stats.resumed, 0);
206
- assert.equal(stats.deferred, 2, "both live markers deferred, not blocked/expired");
207
- // markers are LEFT on disk (deferred, not retired) for a later reconcile
208
- const left = readdirSync(join(dir, "state/sessions/resume-pending")).filter((f) => f.endsWith(".json"));
209
- assert.equal(left.length, 2, "deferred markers persist");
210
- } finally { delete process.env.DAEMON_MAX_CONCURRENT; await cleanup(dir); }
211
- });
212
-
213
- test("resume reconcile is GATED (resumes nothing) while the shared breaker is open", async () => {
214
- const { mod, dir } = await freshDispatcher();
215
- try {
216
- mod.setGovernanceForTests({ rateGuard: { checkRateLimit: () => ({ allowed: false, retryAt: Date.now() + 60_000 }) } });
217
- plantMarker(dir, "s-x", { itemId: "BL-X", sourceFile: "q.yaml", startedAt: Date.now() });
218
- let spawned = 0;
219
- const stats = mod.reconcileResumePending({ spawnResume: () => { spawned++; } });
220
- assert.equal(spawned, 0, "an open breaker (e.g. a usage-limit hold) blocks all resume");
221
- assert.equal(stats.resumed, 0);
222
- assert.equal(stats.scanned, 0, "returns before scanning when the breaker is open");
223
- // the marker is untouched, ready for the next reconcile after the breaker clears
224
- assert.equal(readdirSync(join(dir, "state/sessions/resume-pending")).filter((f) => f.endsWith(".json")).length, 1);
225
- } finally { await cleanup(dir); }
226
- });
227
-
228
- test("reconcile on an empty resume-pending dir is a no-op", async () => {
229
- const { mod, dir } = await freshDispatcher();
230
- try {
231
- const stats = mod.reconcileResumePending({ spawnResume: () => { throw new Error("should not spawn"); } });
232
- assert.deepEqual(stats, { scanned: 0, resumed: 0, blocked: 0, expired: 0, deferred: 0 });
233
- } finally { await cleanup(dir); }
234
- });
235
-
236
- test("resetActiveSessions({reconcile:true}) drives the reconcile; plain call does not", async () => {
237
- const { mod, dir } = await freshDispatcher();
238
- try {
239
- plantMarker(dir, "s-r", { itemId: "BL-R", sourceFile: "q.yaml", startedAt: Date.now() });
240
- let spawns = 0;
241
- // Plain reset (shutdown path): clears active.json, does NOT reconcile.
242
- mod.resetActiveSessions();
243
- assert.equal(existsSync(join(dir, "state/sessions/resume-pending/s-r.json")), true, "plain reset leaves markers untouched");
244
- // Reconcile reset (startup path): re-dispatches.
245
- mod.resetActiveSessions({ reconcile: true, spawnResume: () => { spawns++; } });
246
- assert.equal(spawns, 1, "startup reconcile re-dispatched the marker");
247
- } finally { await cleanup(dir); }
248
- });
249
-
250
- // ---------------------------------------------------------------------------
251
- // H1 — the REAL resume spawner re-issues --session-id + a fresh prompt and
252
- // does NOT use --resume (the existing reconcile tests inject a fake spawnResume
253
- // so the real argv was previously untested). This is the regression guard for
254
- // the silent-work-loss / mass-blocking bug.
255
- // ---------------------------------------------------------------------------
256
-
257
- /** A child-process stub that captures argv and never launches anything. */
258
- function fakeProc() {
259
- const handlers = {};
260
- return {
261
- stdout: { on: () => {} },
262
- stderr: { on: () => {} },
263
- on: (ev, cb) => { handlers[ev] = cb; },
264
- kill: () => {},
265
- killed: false,
266
- _handlers: handlers,
267
- };
268
- }
269
-
270
- test("H1: defaultSpawnResume re-spawns `--session-id <id> <prompt>` and NEVER `--resume`", async () => {
271
- const { mod, dir } = await freshDispatcher();
272
- try {
273
- // A fresh, resumable marker carrying the original prompt + model flag.
274
- plantMarker(dir, "s-real", {
275
- itemId: "BL-REAL", sourceFile: "q.yaml", startedAt: Date.now(),
276
- claudeSessionId: "CS-FIXED-UUID", prompt: "finish drafting the board memo", modelFlag: "claude-opus-4-6",
277
- });
278
-
279
- const calls = [];
280
- const restore = mod.setSpawnForTests((bin, args) => { calls.push({ bin, args }); return fakeProc(); });
281
- try {
282
- // NO injected spawnResume → exercises the real defaultSpawnResume path.
283
- const stats = mod.reconcileResumePending();
284
- assert.equal(stats.resumed, 1, "the fresh marker should resume");
285
- } finally { restore(); }
286
-
287
- assert.equal(calls.length, 1, "exactly one resume spawn");
288
- const { args } = calls[0];
289
-
290
- // The blessed shape (mirrors responder.mjs):
291
- assert.ok(!args.includes("--resume"), "must NOT use --resume (the bug)");
292
- const sidIdx = args.indexOf("--session-id");
293
- assert.ok(sidIdx >= 0, "must pass --session-id");
294
- assert.equal(args[sidIdx + 1], "CS-FIXED-UUID", "resumes against the pre-minted session id");
295
- // The original prompt is the LAST positional arg (the work to continue).
296
- assert.equal(args[args.length - 1], "finish drafting the board memo", "carries the original prompt");
297
- // Re-spawns against the SAME backend/model the original used.
298
- const modelIdx = args.indexOf("--model");
299
- assert.ok(modelIdx >= 0, "must pass --model");
300
- assert.equal(args[modelIdx + 1], "claude-opus-4-6", "same model flag the original spawn used");
301
- // It is a print-mode spawn (json/print contract), like every daemon spawn.
302
- assert.ok(args.includes("--print"), "still a --print spawn");
303
- } finally { await cleanup(dir); }
304
- });
305
-
306
- test("H1: a marker missing the original prompt is retired, never spawned as a no-op", async () => {
307
- const { mod, dir } = await freshDispatcher();
308
- try {
309
- // Legacy / corrupt marker: has a session id but NO prompt.
310
- const d = join(dir, "state/sessions/resume-pending");
311
- mkdirSync(d, { recursive: true });
312
- writeFileSync(join(d, "s-legacy.json"), JSON.stringify({
313
- sessionId: "s-legacy", claudeSessionId: "CS-LEGACY", source: "backlog",
314
- itemId: "BL-LEGACY", sourceFile: "q.yaml", startedAt: Date.now(), recoveryAttempts: 0,
315
- // prompt intentionally absent
316
- }, null, 2));
317
-
318
- let spawned = 0;
319
- const restore = mod.setSpawnForTests(() => { spawned++; return fakeProc(); });
320
- try {
321
- const stats = mod.reconcileResumePending();
322
- assert.equal(stats.resumed, 0, "no prompt → cannot truly resume");
323
- assert.equal(stats.expired, 1, "retired instead");
324
- } finally { restore(); }
325
- assert.equal(spawned, 0, "must NOT spawn a promptless no-op the close handler would treat as done");
326
- assert.equal(existsSync(join(d, "s-legacy.json")), false, "the un-resumable marker is dropped");
327
- } finally { await cleanup(dir); }
328
- });
329
-
330
- // ---------------------------------------------------------------------------
331
- // M2 — an INTENTIONAL eviction clears the backlog item's resume marker, so a
332
- // later reboot reconcile can't re-dispatch it (no claim) while sweepBacklog
333
- // independently claims+dispatches the same item → double run.
334
- // ---------------------------------------------------------------------------
335
-
336
- test("M2: evicting a backlog session for a priority inbox item clears its resume marker", async () => {
337
- // Eviction only fires when ALL slots are full (activeSessions.size >=
338
- // MAX_CONCURRENT). With MAX_CONCURRENT=4 the backlog cap is 4 - RESERVED(3) =
339
- // 1, so we run exactly 1 (evictable) backlog session plus 3 inbox sessions to
340
- // saturate the daemon; the 5th (high-priority inbox) item must then preempt
341
- // the backlog session. MAX_CONCURRENT is read at module top, so set it BEFORE
342
- // the fresh import.
343
- process.env.DAEMON_MAX_CONCURRENT = "4";
344
- const { mod, dir } = await freshDispatcher();
345
- try {
346
- // ADMIT everything; never spawn a real child (fake spawn).
347
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
348
- const restore = mod.setSpawnForTests(() => fakeProc());
349
- try {
350
- // 1) One running backlog session — this writes a resume-pending marker.
351
- mod.dispatch("do the backlog work", { id: "BL-EVICT", title: "deep work", source_file: "q.yaml" },
352
- { summary: "deep work", priority: "low", model: "sonnet" }, "backlog");
353
- // 2) Saturate the remaining 3 slots with normal inbox sessions.
354
- for (let i = 0; i < 3; i++) {
355
- mod.dispatch("filler", { id: `IN-FILL-${i}`, channel: `D${i}` },
356
- { summary: `filler ${i}`, priority: "normal", model: "sonnet" }, "inbox");
357
- }
358
- assert.equal(mod.getStatus().active_sessions, 4, "all 4 slots are full (1 backlog + 3 inbox)");
359
- const markerDir = join(dir, "state/sessions/resume-pending");
360
- const before = readdirSync(markerDir).filter((f) => f.endsWith(".json"));
361
- assert.ok(before.length >= 1, "a resume marker exists for the running backlog session");
362
-
363
- // 3) A high-priority inbox item with no free slot → must evict the backlog
364
- // session, and on eviction the marker must be cleared (deliberate
365
- // preemption, not a crash). Only the backlog session is evictable.
366
- mod.dispatch("urgent ceo ask", { id: "IN-PRIO", channel: "DZ" },
367
- { summary: "ceo ask", priority: "high", model: "sonnet" }, "inbox");
368
-
369
- // The backlog session's marker (the only backlog source) is now gone.
370
- // (The fake process never emits "close", so the in-memory session map and
371
- // the 3 inbox markers persist — eviction's marker-clear is synchronous and
372
- // independent of the close handler, which is exactly the point: a reboot
373
- // happening right after the SIGTERM must NOT find a resumable marker.)
374
- const after = readdirSync(markerDir).filter((f) => f.endsWith(".json"));
375
- const remainingBacklog = after.filter((f) => {
376
- try { return JSON.parse(readFileSync(join(markerDir, f), "utf-8")).itemId === "BL-EVICT"; }
377
- catch { return false; }
378
- });
379
- assert.deepEqual(remainingBacklog, [], "the evicted backlog session's resume marker is cleared");
380
- // Sanity: the 3 inbox sessions' markers are untouched (eviction is targeted).
381
- assert.equal(after.length, 3, "only the backlog marker was cleared; inbox markers remain");
382
- } finally { restore(); }
383
- } finally {
384
- delete process.env.DAEMON_MAX_CONCURRENT;
385
- await cleanup(dir);
386
- }
387
- });
388
-
389
- // ---------------------------------------------------------------------------
390
- // yieldBacklogForReactive — a reply about to hit the subscription evicts
391
- // already-running BACKLOG down to REACTIVE_INFLIGHT_BACKLOG_MAX, and NEVER
392
- // touches an inbox/reactive session.
393
- // ---------------------------------------------------------------------------
394
-
395
- /** A child stub that records whether it was killed (never launches anything). */
396
- function killTrackingProc() {
397
- const handlers = {};
398
- const p = {
399
- stdout: { on: () => {} },
400
- stderr: { on: () => {} },
401
- on: (ev, cb) => { handlers[ev] = cb; },
402
- kill: () => { p.killed = true; },
403
- killed: false,
404
- _handlers: handlers,
405
- };
406
- return p;
407
- }
408
-
409
- test("yieldBacklogForReactive: evicts backlog down to the cap and spares every inbox session", async () => {
410
- process.env.DAEMON_MAX_CONCURRENT = "8";
411
- const { mod, dir } = await freshDispatcher();
412
- try {
413
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
414
- const procs = [];
415
- const restore = mod.setSpawnForTests(() => { const p = killTrackingProc(); procs.push(p); return p; });
416
- try {
417
- // 3 backlog sessions (dispatch order = age order) …
418
- for (let i = 0; i < 3; i++) {
419
- mod.dispatch("backlog work", { id: `BL-${i}`, title: `bl ${i}`, source_file: "q.yaml" },
420
- { summary: `bl ${i}`, priority: "low", model: "sonnet" }, "backlog");
421
- }
422
- // … and 2 inbox sessions, all running concurrently.
423
- for (let i = 0; i < 2; i++) {
424
- mod.dispatch("inbox work", { id: `IN-${i}`, channel: `D${i}` },
425
- { summary: `in ${i}`, priority: "normal", model: "sonnet" }, "inbox");
426
- }
427
- assert.equal(mod.getStatus().active_sessions, 5, "3 backlog + 2 inbox live");
428
-
429
- // A reply is about to generate → yield the subscription. Cap is 1, so 2 of
430
- // the 3 backlog sessions are evicted; the inbox sessions are never touched.
431
- const evicted = mod.yieldBacklogForReactive();
432
- assert.equal(evicted, 2, "evicts backlog down to REACTIVE_INFLIGHT_BACKLOG_MAX (1)");
433
-
434
- const backlogProcs = procs.slice(0, 3);
435
- const inboxProcs = procs.slice(3, 5);
436
- assert.equal(backlogProcs.filter((p) => p.killed).length, 2, "exactly two backlog procs killed");
437
- assert.equal(inboxProcs.filter((p) => p.killed).length, 0, "no inbox/reactive proc is ever killed");
438
-
439
- // Idempotent: already at the cap → a second call is a no-op.
440
- assert.equal(mod.yieldBacklogForReactive(), 0, "no further eviction once at the cap");
441
- } finally { restore(); }
442
- } finally {
443
- delete process.env.DAEMON_MAX_CONCURRENT;
444
- await cleanup(dir);
445
- }
446
- });
447
-
448
- test("yieldBacklogForReactive: no-op when backlog is already at/under the cap", async () => {
449
- process.env.DAEMON_MAX_CONCURRENT = "8";
450
- const { mod, dir } = await freshDispatcher();
451
- try {
452
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
453
- const restore = mod.setSpawnForTests(() => killTrackingProc());
454
- try {
455
- // Only inbox sessions running — nothing self-directed to yield.
456
- for (let i = 0; i < 3; i++) {
457
- mod.dispatch("inbox work", { id: `IN-${i}`, channel: `D${i}` },
458
- { summary: `in ${i}`, priority: "normal", model: "sonnet" }, "inbox");
459
- }
460
- assert.equal(mod.yieldBacklogForReactive(), 0, "nothing to evict");
461
- // One backlog session — at the cap of 1 → still a no-op.
462
- mod.dispatch("bl", { id: "BL-ONE", title: "one", source_file: "q.yaml" },
463
- { summary: "one", priority: "low", model: "sonnet" }, "backlog");
464
- assert.equal(mod.yieldBacklogForReactive(), 0, "a single backlog session is within the cap");
465
- } finally { restore(); }
466
- } finally {
467
- delete process.env.DAEMON_MAX_CONCURRENT;
468
- await cleanup(dir);
469
- }
470
- });
471
-
472
- // ---------------------------------------------------------------------------
473
- // M1 — a governor/budget/rate DEFER that force-queues an inbox item while NO
474
- // session is running must arm a single (debounced) re-drain timer, so the item
475
- // isn't stranded until the next external dispatch.
476
- // ---------------------------------------------------------------------------
477
-
478
- test("M1: force-queued inbox item with zero active sessions arms a single re-drain timer", async () => {
479
- const { mod, dir } = await freshDispatcher();
480
- try {
481
- // Governor DEFERs → inbox item is queued, not spawned, with 0 sessions.
482
- mod.setGovernanceForTests({ governor: fakeGovernor("DEFER"), rateGuard: allowRate, budgetGuard: noBudget });
483
- assert.equal(mod._hasReDrainArmed(), false, "no timer before any dispatch");
484
-
485
- mod.dispatch("hello", { id: "IN-M1", channel: "D1" }, { summary: "hi", priority: "normal", model: "sonnet" }, "inbox");
486
- assert.equal(mod.getStatus().normal_queue_length, 1, "DEFER queued the inbox item");
487
- assert.equal(mod.getStatus().active_sessions, 0, "nothing running to drive a close-drain");
488
- assert.equal(mod._hasReDrainArmed(), true, "a re-drain timer is armed to self-heal the stall");
489
-
490
- // Debounce: a second force-queue must NOT stack a second timer.
491
- mod.dispatch("hello again", { id: "IN-M1b", channel: "D2" }, { summary: "hi2", priority: "normal", model: "sonnet" }, "inbox");
492
- assert.equal(mod.getStatus().normal_queue_length, 2);
493
- assert.equal(mod._hasReDrainArmed(), true, "still exactly one armed timer (debounced)");
494
- } finally { await cleanup(dir); }
495
- });
496
-
497
- test("M1: a fully-admitted inbox dispatch (which spawns) does not arm a re-drain timer", async () => {
498
- const { mod, dir } = await freshDispatcher();
499
- try {
500
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
501
- const restore = mod.setSpawnForTests(() => fakeProc());
502
- try {
503
- mod.dispatch("hello", { id: "IN-OK", channel: "D1" }, { summary: "hi", priority: "normal", model: "sonnet" }, "inbox");
504
- assert.equal(mod.getStatus().active_sessions, 1, "ADMIT spawned a session");
505
- assert.equal(mod._hasReDrainArmed(), false, "a running session will drive the next drain — no timer needed");
506
- } finally { restore(); }
507
- } finally { await cleanup(dir); }
508
- });
509
-
510
- // ---------------------------------------------------------------------------
511
- // 0.6 — permission posture: the user-facing inbox spawn routes through
512
- // sessionPermissionArgs() instead of a hardcoded --dangerously-skip-permissions.
513
- // Default behaviour is byte-for-byte unchanged; opting in actually scopes tools.
514
- // ---------------------------------------------------------------------------
515
-
516
- /** A controllable child stub that can emit stdout then close on demand. */
517
- function controllableProc() {
518
- const handlers = {};
519
- return {
520
- stdout: { on: (ev, cb) => { if (ev === "data") handlers.stdout = cb; } },
521
- stderr: { on: (ev, cb) => { if (ev === "data") handlers.stderr = cb; } },
522
- on: (ev, cb) => { handlers[ev] = cb; },
523
- kill: () => {},
524
- killed: false,
525
- emitStdout(chunk) { if (handlers.stdout) handlers.stdout(Buffer.from(chunk)); },
526
- emitClose(code) { if (handlers.close) handlers.close(code); },
527
- };
528
- }
529
-
530
- test("0.6: inbox spawn argv uses sessionPermissionArgs default (--dangerously-skip-permissions), never a hardcoded literal", async () => {
531
- const prev = process.env.MAESTRO_SCOPED_PERMISSIONS;
532
- delete process.env.MAESTRO_SCOPED_PERMISSIONS; // default / back-compat mode
533
- const { mod, dir } = await freshDispatcher();
534
- try {
535
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
536
- const calls = [];
537
- const restore = mod.setSpawnForTests((bin, args) => { calls.push(args); return fakeProc(); });
538
- try {
539
- mod.dispatch("do the thing", { id: "IN-PERM", channel: "D1" }, { summary: "x", priority: "normal", model: "sonnet" }, "inbox");
540
- assert.equal(calls.length, 1, "exactly one spawn");
541
- const args = calls[0];
542
- // Default mode preserves the prior literal (no behaviour change for non-opted-in operators).
543
- assert.ok(args.includes("--dangerously-skip-permissions"), "default permission flag preserved");
544
- assert.ok(!args.includes("--allowedTools"), "no scoping in default mode");
545
- // Cost telemetry: the run is asked for JSON output so we can read real usage.
546
- assert.ok(args.includes("--output-format"), "spawn requests JSON output for cost capture");
547
- assert.equal(args[args.indexOf("--output-format") + 1], "json");
548
- } finally { restore(); }
549
- } finally {
550
- if (prev === undefined) delete process.env.MAESTRO_SCOPED_PERMISSIONS; else process.env.MAESTRO_SCOPED_PERMISSIONS = prev;
551
- await cleanup(dir);
552
- }
553
- });
554
-
555
- test("0.6: with MAESTRO_SCOPED_PERMISSIONS=1 the inbox spawn is scoped (--allowedTools), not skip-permissions", async () => {
556
- const prev = process.env.MAESTRO_SCOPED_PERMISSIONS;
557
- process.env.MAESTRO_SCOPED_PERMISSIONS = "1"; // operator opts into scoping
558
- const { mod, dir } = await freshDispatcher();
559
- try {
560
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
561
- const calls = [];
562
- const restore = mod.setSpawnForTests((bin, args) => { calls.push(args); return fakeProc(); });
563
- try {
564
- mod.dispatch("do the thing", { id: "IN-PERM2", channel: "D1" }, { summary: "x", priority: "normal", model: "sonnet" }, "inbox");
565
- const args = calls[0];
566
- assert.ok(!args.includes("--dangerously-skip-permissions"), "scoped mode must NOT skip permissions");
567
- const idx = args.indexOf("--allowedTools");
568
- assert.ok(idx >= 0, "scoped mode passes --allowedTools");
569
- assert.ok(typeof args[idx + 1] === "string" && args[idx + 1].length > 0, "with a non-empty tool list");
570
- } finally { restore(); }
571
- } finally {
572
- if (prev === undefined) delete process.env.MAESTRO_SCOPED_PERMISSIONS; else process.env.MAESTRO_SCOPED_PERMISSIONS = prev;
573
- await cleanup(dir);
574
- }
575
- });
576
-
577
- // ---------------------------------------------------------------------------
578
- // 0.3 — cost telemetry: the dispatcher parser recovers REAL token usage from a
579
- // `--output-format json` run, and the close handler writes a truthful ledger
580
- // row (no more --input-tokens 0 fabrication).
581
- // ---------------------------------------------------------------------------
582
-
583
- test("0.3: parseUsageFromText recovers real token usage + total_cost_usd from a JSON result", async () => {
584
- const { mod, dir } = await freshDispatcher();
585
- try {
586
- const json = JSON.stringify({
587
- result: "done",
588
- usage: { input_tokens: 4200, output_tokens: 530, cache_read_input_tokens: 1000 },
589
- total_cost_usd: 0.071,
590
- model: "claude-opus-4-6",
591
- });
592
- const u = mod.parseUsageFromText(json);
593
- assert.equal(u.ok, true);
594
- assert.equal(u.inputTokens, 4200);
595
- assert.equal(u.outputTokens, 530);
596
- assert.equal(u.cacheReadTokens, 1000);
597
- assert.equal(u.totalCostUsd, 0.071);
598
- assert.equal(u.model, "opus", "resolved model id maps to the tracker's coarse class");
599
-
600
- // A banner-prefixed JSON tail still parses (tolerant path).
601
- const u2 = mod.parseUsageFromText(`[some-warning]\n${json}`);
602
- assert.equal(u2.ok, true);
603
- assert.equal(u2.inputTokens, 4200);
604
-
605
- // Non-JSON / no usage → ok:false with a reason, NEVER fabricated zeros.
606
- assert.equal(mod.parseUsageFromText("plain text reply").ok, false);
607
- assert.equal(mod.parseUsageFromText("").reason, "empty-stdout");
608
- assert.equal(mod.parseUsageFromText(JSON.stringify({ result: "x" })).reason, "no-usage-field");
609
- } finally { await cleanup(dir); }
610
- });
611
-
612
- test("0.3: a finished inbox session writes a nonzero cost-ledger row from its real usage", async () => {
613
- const { mod, dir } = await freshDispatcher();
614
- try {
615
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
616
- // Ledger dir + a real tracker so the close handler's detached `record` call
617
- // actually appends a row. (The dispatcher invokes the on-disk tracker.)
618
- await fsp.mkdir(join(dir, "state/cost-tracking"), { recursive: true });
619
- await fsp.mkdir(join(dir, "scripts/cost"), { recursive: true });
620
- await fsp.copyFile(
621
- new URL("../cost/track-claude-usage.mjs", import.meta.url),
622
- join(dir, "scripts/cost/track-claude-usage.mjs")
623
- );
624
- // The tracker imports the shared billing contract (lib/cost/ledger-row.mjs)
625
- // relative to itself, so a synthetic agent root needs it too — otherwise the
626
- // detached `record` spawn dies on import and writes nothing. (In the wild
627
- // that failure is silent, which is why doctor's tripwire now goes RED when
628
- // the daemon logs sessions that never reach the ledger.)
629
- await fsp.mkdir(join(dir, "lib/cost"), { recursive: true });
630
- await fsp.copyFile(
631
- new URL("../../lib/cost/ledger-row.mjs", import.meta.url),
632
- join(dir, "lib/cost/ledger-row.mjs")
633
- );
634
-
635
- const proc = controllableProc();
636
- const restore = mod.setSpawnForTests(() => proc);
637
- try {
638
- mod.dispatch("work", { id: "IN-COST", channel: "D1" }, { summary: "x", priority: "normal", model: "sonnet" }, "inbox");
639
- // Feed the run's JSON result then close cleanly.
640
- proc.emitStdout(JSON.stringify({
641
- result: "ok",
642
- usage: { input_tokens: 2000, output_tokens: 400 },
643
- total_cost_usd: 0.012,
644
- model: "claude-sonnet-4-6",
645
- }));
646
- proc.emitClose(0);
647
- } finally { restore(); }
648
-
649
- // The tracker is spawned detached; poll briefly for the ledger row.
650
- const date = new Date().toISOString().slice(0, 10);
651
- const ledger = join(dir, "state/cost-tracking", `${date}.jsonl`);
652
- let body = "";
653
- for (let i = 0; i < 80 && !body.trim(); i++) {
654
- try { body = readFileSync(ledger, "utf-8"); } catch { /* not yet */ }
655
- if (!body.trim()) await new Promise((r) => setTimeout(r, 25));
656
- }
657
- assert.ok(body.trim(), "a cost row was appended for the dispatcher session");
658
- const row = JSON.parse(body.trim().split("\n").pop());
659
- assert.equal(row.source, "dispatcher", "row attributed to the dispatcher spawn source");
660
- assert.equal(row.input_tokens, 2000, "REAL input tokens recorded (not 0)");
661
- assert.equal(row.output_tokens, 400, "REAL output tokens recorded (not 0)");
662
- assert.ok(row.estimated_usd > 0, `estimated_usd must be nonzero, got ${row.estimated_usd}`);
663
- assert.equal(row.total_cost_usd, 0.012, "CLI authoritative cost stored for reconciliation");
664
- } finally { await cleanup(dir); }
665
- });
666
-
667
- // ---------------------------------------------------------------------------
668
- // Phase 3-4 COVERAGE — the dispatcher routes session spawns through the v2
669
- // resolveChain path when the agent opts into a `schema_version: 2` config. The
670
- // RouteDecision drives the --model flag + spawn knobs (--max-turns / --agents),
671
- // and its decision_id is carried onto the resume marker (and the ledger row).
672
- // A v2 config that resolves to an Anthropic session keeps stock keychain auth
673
- // (no retarget env), so this stays byte-compatible with the Max-subscription
674
- // default for the model id Anthropic resolves.
675
- // ---------------------------------------------------------------------------
676
-
677
- /**
678
- * Write a minimal `schema_version: 2` routing config (JSON form, so the loader
679
- * needs no js-yaml) into the agent dir. The default rule resolves a session to
680
- * the Anthropic Sonnet row in the bundled catalog (grade A — the only reachable
681
- * session backend without third-party keys).
682
- */
683
- function writeV2Config(dir) {
684
- mkdirSync(join(dir, "config"), { recursive: true });
685
- const cfg = {
686
- schema_version: 2,
687
- aliases: {
688
- frontier: "anthropic/claude-opus-4-8",
689
- default: "anthropic/claude-sonnet-4-6",
690
- fast: "anthropic/claude-haiku-4-5",
691
- },
692
- defaults: { needs_tool_use_for_sessions: true, data_class: "sensitive", cache_ttl: "1h" },
693
- backends: { anthropic: { allowed_data_classes: ["public", "internal", "sensitive"] } },
694
- routing_policy: [{ default: true, chain: ["default", "fast"] }],
695
- fallback_to_anthropic: true,
696
- };
697
- writeFileSync(join(dir, "config/model-routing.json"), JSON.stringify(cfg, null, 2));
698
- }
699
-
700
- test("COVERAGE: a v2 config routes the inbox spawn through resolveChain (--model + --max-turns + --agents)", async () => {
701
- const { mod, dir } = await freshDispatcher();
702
- try {
703
- writeV2Config(dir);
704
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
705
- const calls = [];
706
- const restore = mod.setSpawnForTests((bin, args) => { calls.push(args); return fakeProc(); });
707
- try {
708
- mod.dispatch("respond to the user", { id: "IN-V2", channel: "D1" }, { summary: "v2", priority: "normal", model: "sonnet" }, "inbox");
709
- assert.equal(calls.length, 1, "exactly one spawn");
710
- const args = calls[0];
711
- // Cost telemetry + JSON contract preserved.
712
- assert.ok(args.includes("--print"));
713
- assert.equal(args[args.indexOf("--output-format") + 1], "json");
714
- // The decision's chosen model flows onto --model (concrete catalog id).
715
- const mIdx = args.indexOf("--model");
716
- assert.ok(mIdx >= 0, "must pass --model");
717
- assert.equal(args[mIdx + 1], "claude-sonnet-4-6", "routed to the v2 default (Sonnet) catalog id");
718
- // Session.responder spawn knobs (SPEC §6.5): --max-turns + Haiku-Explore --agents.
719
- const mtIdx = args.indexOf("--max-turns");
720
- assert.ok(mtIdx >= 0, "v2 spawn carries --max-turns");
721
- assert.equal(args[mtIdx + 1], "40", "session.responder maxTurns default");
722
- const agIdx = args.indexOf("--agents");
723
- assert.ok(agIdx >= 0, "v2 spawn carries the --agents cheap-subagent map");
724
- assert.ok(/Haiku-Explore/.test(args[agIdx + 1]), "the agents map is the Haiku-Explore fan-out");
725
- // Permission posture unchanged (default skip-permissions).
726
- assert.ok(args.includes("--dangerously-skip-permissions"), "permission posture preserved");
727
- // The prompt is still the last positional arg.
728
- assert.equal(args[args.length - 1], "respond to the user", "prompt remains the trailing positional");
729
- } finally { restore(); }
730
- } finally { await cleanup(dir); }
731
- });
732
-
733
- test("COVERAGE: the v2 resume marker carries the RouteDecision decision_id", async () => {
734
- const { mod, dir } = await freshDispatcher();
735
- try {
736
- writeV2Config(dir);
737
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
738
- const restore = mod.setSpawnForTests(() => fakeProc());
739
- try {
740
- mod.dispatch("work", { id: "IN-DID", channel: "D1" }, { summary: "did", priority: "normal", model: "sonnet" }, "inbox");
741
- const markerDir = join(dir, "state/sessions/resume-pending");
742
- const files = readdirSync(markerDir).filter((f) => f.endsWith(".json"));
743
- assert.equal(files.length, 1, "one resume marker written");
744
- const marker = JSON.parse(readFileSync(join(markerDir, files[0]), "utf-8"));
745
- assert.ok(typeof marker.decision_id === "string" && marker.decision_id.length > 0, "marker carries a v2 decision_id");
746
- assert.equal(marker.modelFlag, "claude-sonnet-4-6", "marker pins the routed model flag");
747
- } finally { restore(); }
748
- } finally { await cleanup(dir); }
749
- });
750
-
751
- test("COVERAGE: MAESTRO_ROUTER_FORCE_ANTHROPIC still short-circuits under a v2 config", async () => {
752
- const prev = process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC;
753
- process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC = "1";
754
- const { mod, dir } = await freshDispatcher();
755
- try {
756
- writeV2Config(dir);
757
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
758
- const calls = [];
759
- const restore = mod.setSpawnForTests((bin, args) => { calls.push(args); return fakeProc(); });
760
- try {
761
- mod.dispatch("hi", { id: "IN-KILL", channel: "D1" }, { summary: "kill", priority: "normal", model: "sonnet" }, "inbox");
762
- const args = calls[0];
763
- // Kill switch → Anthropic-only chain; spawn still happens, env is NOT a
764
- // third-party retarget (no ANTHROPIC_BASE_URL injected for an Anthropic row).
765
- assert.ok(args.includes("--print"));
766
- assert.ok(args.includes("--model"), "kill switch still spawns with a concrete --model");
767
- } finally { restore(); }
768
- } finally {
769
- if (prev === undefined) delete process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC; else process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC = prev;
770
- await cleanup(dir);
771
- }
772
- });
773
-
774
- // ---------------------------------------------------------------------------
775
- // F1/H2 — dispatch onClose: the spawn-close notification that lets the daemon
776
- // defer markProcessed to success and re-deliver on crash. The callback must
777
- // fire EXACTLY ONCE per session, with ok=true only on a clean (exit 0) close
778
- // and ok=false on a non-zero close OR a spawn error.
779
- // ---------------------------------------------------------------------------
780
-
781
- /** A controllable stub that can emit stdout, close, or error on demand. */
782
- function closableProc() {
783
- const handlers = {};
784
- return {
785
- stdout: { on: (ev, cb) => { if (ev === "data") handlers.stdout = cb; } },
786
- stderr: { on: (ev, cb) => { if (ev === "data") handlers.stderr = cb; } },
787
- on: (ev, cb) => { handlers[ev] = cb; },
788
- kill: () => {},
789
- killed: false,
790
- emitStdout(chunk) { if (handlers.stdout) handlers.stdout(Buffer.from(chunk)); },
791
- emitClose(code) { if (handlers.close) handlers.close(code); },
792
- emitError(err) { if (handlers.error) handlers.error(err); },
793
- };
794
- }
795
-
796
- test("F1/H2: a clean (exit 0) close fires onClose once with ok:true", async () => {
797
- const { mod, dir } = await freshDispatcher();
798
- try {
799
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
800
- const proc = closableProc();
801
- const restore = mod.setSpawnForTests(() => proc);
802
- const calls = [];
803
- try {
804
- mod.dispatch("work", { id: "IN-OK", raw_ref: "slack:C1:111", channel: "D1" },
805
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox",
806
- { onClose: (r) => calls.push(r) });
807
- assert.equal(mod.getStatus().active_sessions, 1, "session spawned");
808
- assert.equal(calls.length, 0, "onClose has NOT fired before close (markProcessed must be deferred)");
809
- proc.emitClose(0);
810
- } finally { restore(); }
811
- assert.equal(calls.length, 1, "onClose fired exactly once on close");
812
- assert.equal(calls[0].ok, true, "exit 0 → ok:true (finalize)");
813
- assert.equal(calls[0].code, 0);
814
- assert.equal(calls[0].item.id, "IN-OK", "the original item is handed back to the caller");
815
- } finally { await cleanup(dir); }
816
- });
817
-
818
- test("F1/H2: a non-zero close fires onClose once with ok:false (item left re-deliverable)", async () => {
819
- const { mod, dir } = await freshDispatcher();
820
- try {
821
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
822
- const proc = closableProc();
823
- const restore = mod.setSpawnForTests(() => proc);
824
- const calls = [];
825
- try {
826
- mod.dispatch("work", { id: "IN-FAIL", raw_ref: "slack:C2:222", channel: "D2" },
827
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox",
828
- { onClose: (r) => calls.push(r) });
829
- proc.emitClose(1);
830
- } finally { restore(); }
831
- assert.equal(calls.length, 1, "onClose fired exactly once");
832
- assert.equal(calls[0].ok, false, "non-zero exit → ok:false (do NOT finalize)");
833
- } finally { await cleanup(dir); }
834
- });
835
-
836
- test("F1/H2: a spawn error fires onClose once with ok:false and is not double-fired by the trailing close", async () => {
837
- const { mod, dir } = await freshDispatcher();
838
- try {
839
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
840
- const proc = closableProc();
841
- const restore = mod.setSpawnForTests(() => proc);
842
- const calls = [];
843
- try {
844
- mod.dispatch("work", { id: "IN-ERR", raw_ref: "slack:C3:333", channel: "D3" },
845
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox",
846
- { onClose: (r) => calls.push(r) });
847
- // ENOENT-style failure emits "error" then a trailing "close" (the
848
- // dispatcher's spawnErrorHandled guard). onClose must fire only once.
849
- const err = new Error("spawn ENOENT"); err.code = "ENOENT";
850
- proc.emitError(err);
851
- proc.emitClose(null);
852
- } finally { restore(); }
853
- assert.equal(calls.length, 1, "onClose fired exactly once despite error+close");
854
- assert.equal(calls[0].ok, false, "spawn failure → ok:false");
855
- } finally { await cleanup(dir); }
856
- });
857
-
858
- test("F1/H2: onClose survives queueing — a DEFER'd inbox item still fires onClose once drained+spawned", async () => {
859
- const { mod, dir } = await freshDispatcher();
860
- try {
861
- // The queued entry must carry its onClose through to a later drain. Flip the
862
- // governor decision between dispatches: the FIRST inbox item is DEFER'd
863
- // (queued, no spawn), then we flip to ADMIT so a SECOND item spawns; closing
864
- // that second session drives drainQueue, which spawns the queued first item
865
- // — its onClose must still fire.
866
- let decision = "DEFER";
867
- const swingGovernor = { admit: () => ({ decision, reason: `forced-${decision}`, snapshot: {} }), defaultDeps: () => ({}) };
868
- mod.setGovernanceForTests({ governor: swingGovernor, rateGuard: allowRate, budgetGuard: noBudget });
869
- const byPrompt = new Map();
870
- const restore = mod.setSpawnForTests((bin, args) => {
871
- const p = closableProc();
872
- byPrompt.set(args[args.length - 1], p); // key by trailing prompt positional
873
- return p;
874
- });
875
- const queuedCalls = [];
876
- try {
877
- // 1) DEFER → queued, no spawn yet, onClose pending.
878
- mod.dispatch("queued-work", { id: "IN-Q", raw_ref: "slack:C4:444", channel: "D4" },
879
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox",
880
- { onClose: (r) => queuedCalls.push(r) });
881
- assert.equal(mod.getStatus().normal_queue_length, 1, "DEFER queued the first item");
882
- assert.equal(byPrompt.size, 0, "nothing spawned under DEFER");
883
-
884
- // 2) Flip to ADMIT and dispatch a driver item that actually spawns.
885
- decision = "ADMIT";
886
- mod.dispatch("driver-work", { id: "IN-DRV", raw_ref: "slack:C4:445", channel: "D4b" },
887
- { summary: "y", priority: "normal", model: "sonnet" }, "inbox", { onClose: () => {} });
888
- assert.ok(byPrompt.has("driver-work"), "driver session spawned under ADMIT");
889
- assert.equal(queuedCalls.length, 0, "queued item's onClose has NOT fired yet");
890
-
891
- // 3) Close the driver → drainQueue spawns the queued IN-Q (carrying onClose).
892
- byPrompt.get("driver-work").emitClose(0);
893
- assert.ok(byPrompt.has("queued-work"), "the queued item spawned on drain");
894
- assert.equal(queuedCalls.length, 0, "still not fired until the queued session itself closes");
895
-
896
- // 4) Close the queued session → its onClose finally fires (ok:true).
897
- byPrompt.get("queued-work").emitClose(0);
898
- } finally { restore(); }
899
- assert.equal(queuedCalls.length, 1, "the queued item's onClose fired exactly once after spawn+close");
900
- assert.equal(queuedCalls[0].ok, true, "clean close → ok:true");
901
- assert.equal(queuedCalls[0].item.id, "IN-Q", "onClose carries the originally-queued item");
902
- } finally { await cleanup(dir); }
903
- });
904
-
905
- // ---------------------------------------------------------------------------
906
- // DIAG — the observability spine: the dispatcher emits dispatched →
907
- // session_opened → session_closed onto logs/diagnostics, all carrying the
908
- // interaction's trace_id (handed off explicitly on item.trace_id, since the
909
- // proc-close handler fires outside any withTrace scope) so the audit can join
910
- // every hop of one interaction by a single id. STRICT additive: emitEvent is
911
- // fail-open and never alters dispatch/spawn/close semantics.
912
- // ---------------------------------------------------------------------------
913
-
914
- test("DIAG: a spawned+closed inbox session emits dispatched→session_opened→session_closed carrying ONE stable trace_id", async () => {
915
- const { mod, dir } = await freshDispatcher();
916
- try {
917
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
918
- const proc = closableProc();
919
- const restore = mod.setSpawnForTests(() => proc);
920
- const TRACE = "01HZZZTRACEDISPATCHERTEST0"; // 26-char ULID-shaped id the daemon would have minted
921
- try {
922
- // The daemon sets item.trace_id at item_received; the dispatcher reads it.
923
- mod.dispatch("work", { id: "IN-TRACE", raw_ref: "slack:C1:1", channel: "D1", trace_id: TRACE },
924
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox", { onClose: () => {} });
925
- proc.emitClose(0);
926
- } finally { restore(); }
927
-
928
- const rows = readDiagnostics(dir);
929
- const byType = (t) => rows.filter((r) => r.type === t);
930
- const dispatched = byType("dispatched");
931
- const opened = byType("session_opened");
932
- const closed = byType("session_closed");
933
- assert.equal(dispatched.length, 1, "exactly one dispatched event");
934
- assert.equal(opened.length, 1, "exactly one session_opened event");
935
- assert.equal(closed.length, 1, "exactly one session_closed event");
936
- // The crucial invariant: a single stable trace_id across every hop.
937
- for (const r of [dispatched[0], opened[0], closed[0]]) {
938
- assert.equal(r.trace_id, TRACE, `${r.type} carries the interaction trace_id`);
939
- }
940
- assert.equal(closed[0].attrs.exit_code, 0, "session_closed records the clean exit code");
941
- // Same session_id ties the three rows to one spawn.
942
- assert.equal(dispatched[0].attrs.session_id, opened[0].attrs.session_id);
943
- assert.equal(opened[0].attrs.session_id, closed[0].attrs.session_id);
944
- } finally { await cleanup(dir); }
945
- });
946
-
947
- test("DIAG: a spawn ERROR still emits session_closed once (exit_code null, error carried), carrying the trace_id", async () => {
948
- const { mod, dir } = await freshDispatcher();
949
- try {
950
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
951
- const proc = closableProc();
952
- const restore = mod.setSpawnForTests(() => proc);
953
- const TRACE = "01HZZZTRACEDISPATCHERERR00";
954
- try {
955
- mod.dispatch("work", { id: "IN-ERR", raw_ref: "slack:C2:2", channel: "D2", trace_id: TRACE },
956
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox", { onClose: () => {} });
957
- const err = new Error("spawn ENOENT"); err.code = "ENOENT";
958
- proc.emitError(err);
959
- proc.emitClose(null); // trailing close (spawnErrorHandled guard) must NOT re-emit
960
- } finally { restore(); }
961
-
962
- const closed = readDiagnostics(dir).filter((r) => r.type === "session_closed");
963
- assert.equal(closed.length, 1, "exactly one session_closed even with error+trailing-close");
964
- assert.equal(closed[0].trace_id, TRACE, "error-path session_closed carries the trace_id");
965
- assert.equal(closed[0].attrs.exit_code, null, "spawn-error close has no exit code");
966
- assert.equal(closed[0].attrs.error, "ENOENT", "the spawn error code is recorded");
967
- } finally { await cleanup(dir); }
968
- });
969
-
970
- test("DIAG: a v2-routed spawn carries the RouteDecision decision_id onto every diagnostic hop", async () => {
971
- const { mod, dir } = await freshDispatcher();
972
- try {
973
- writeV2Config(dir);
974
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
975
- const proc = closableProc();
976
- const restore = mod.setSpawnForTests(() => proc);
977
- const TRACE = "01HZZZTRACEDISPATCHERV2000";
978
- try {
979
- mod.dispatch("work", { id: "IN-V2D", channel: "D1", trace_id: TRACE },
980
- { summary: "v2", priority: "normal", model: "sonnet" }, "inbox", { onClose: () => {} });
981
- proc.emitClose(0);
982
- } finally { restore(); }
983
-
984
- const rows = readDiagnostics(dir).filter((r) => ["dispatched", "session_opened", "session_closed"].includes(r.type));
985
- assert.equal(rows.length, 3, "all three hops emitted");
986
- for (const r of rows) {
987
- assert.ok(typeof r.attrs.decision_id === "string" && r.attrs.decision_id.length > 0,
988
- `${r.type} carries a v2 decision_id`);
989
- }
990
- } finally { await cleanup(dir); }
991
- });
992
-
993
- test("DIAG: emitEvent is fail-open — a session with no trace_id still closes cleanly (trace_id null, no throw)", async () => {
994
- const { mod, dir } = await freshDispatcher();
995
- try {
996
- mod.setGovernanceForTests({ governor: fakeGovernor("ADMIT"), rateGuard: allowRate, budgetGuard: noBudget });
997
- const proc = closableProc();
998
- const restore = mod.setSpawnForTests(() => proc);
999
- const calls = [];
1000
- try {
1001
- // No trace_id on the item (an un-instrumented call path). The dispatch +
1002
- // close must work exactly as before; diagnostics degrade to trace_id null.
1003
- mod.dispatch("work", { id: "IN-NOTRACE", raw_ref: "slack:C9:9", channel: "D9" },
1004
- { summary: "x", priority: "normal", model: "sonnet" }, "inbox", { onClose: (r) => calls.push(r) });
1005
- proc.emitClose(0);
1006
- } finally { restore(); }
1007
- assert.equal(calls.length, 1, "onClose still fired (semantics preserved)");
1008
- assert.equal(calls[0].ok, true, "clean close → ok:true unchanged");
1009
- const closed = readDiagnostics(dir).filter((r) => r.type === "session_closed");
1010
- assert.equal(closed.length, 1);
1011
- assert.equal(closed[0].trace_id, null, "no interaction trace → trace_id null (degrades, never throws)");
1012
- } finally { await cleanup(dir); }
1013
- });