@cohortapp/agent-sdk 2.17.0 → 2.18.4

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 (526) 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.mjs +8 -6
  23. package/lib/collective/global-config.mjs +63 -1
  24. package/lib/collective/presence.mjs +142 -5
  25. package/lib/comms/send-gate.mjs +559 -1
  26. package/lib/diagnostics/alerts.mjs +49 -0
  27. package/lib/diagnostics/cadence-output-freshness.mjs +288 -0
  28. package/lib/engine/agents/definitions.mjs +343 -0
  29. package/lib/engine/agents/persist.mjs +275 -0
  30. package/lib/engine/agents/runtime.mjs +748 -0
  31. package/lib/engine/agents/usage.mjs +95 -0
  32. package/lib/engine/auth-status.mjs +139 -0
  33. package/lib/engine/budget.mjs +194 -0
  34. package/lib/engine/cli.mjs +1204 -0
  35. package/lib/engine/commands/index.mjs +269 -0
  36. package/lib/engine/context/budget.mjs +219 -0
  37. package/lib/engine/context/cache.mjs +125 -0
  38. package/lib/engine/context/child-env.mjs +215 -0
  39. package/lib/engine/context/compaction.mjs +342 -0
  40. package/lib/engine/context/images.mjs +90 -0
  41. package/lib/engine/context/instructions.mjs +327 -0
  42. package/lib/engine/context/lazy-instructions.mjs +169 -0
  43. package/lib/engine/context/manager.mjs +182 -0
  44. package/lib/engine/context/real-path.mjs +91 -0
  45. package/lib/engine/context/secret-values.mjs +163 -0
  46. package/lib/engine/context/settings.mjs +274 -0
  47. package/lib/engine/context/stream-input.mjs +159 -0
  48. package/lib/engine/guard.mjs +152 -0
  49. package/lib/engine/hooks.mjs +713 -0
  50. package/lib/engine/loop.mjs +560 -0
  51. package/lib/engine/mcp/client.mjs +254 -0
  52. package/lib/engine/mcp/config.mjs +301 -0
  53. package/lib/engine/mcp/http.mjs +201 -0
  54. package/lib/engine/mcp/index.mjs +146 -0
  55. package/lib/engine/mcp/jsonrpc.mjs +147 -0
  56. package/lib/engine/mcp/naming.mjs +66 -0
  57. package/lib/engine/mcp/resources.mjs +89 -0
  58. package/lib/engine/mcp/results.mjs +133 -0
  59. package/lib/engine/mcp/stdio.mjs +137 -0
  60. package/lib/engine/mcp/supervisor.mjs +116 -0
  61. package/lib/engine/messages.mjs +104 -0
  62. package/lib/engine/output/json.mjs +164 -0
  63. package/lib/engine/output/stream-json.mjs +266 -0
  64. package/lib/engine/permissions.mjs +845 -0
  65. package/lib/engine/process-identity.mjs +164 -0
  66. package/lib/engine/process-tree.mjs +551 -0
  67. package/lib/engine/prompt.mjs +60 -0
  68. package/lib/engine/session/store.mjs +299 -0
  69. package/lib/engine/session-runtime/args.mjs +97 -0
  70. package/lib/engine/session-runtime/host.mjs +143 -0
  71. package/lib/engine/session-runtime/inbox.mjs +122 -0
  72. package/lib/engine/session-runtime/notifications.mjs +129 -0
  73. package/lib/engine/session-runtime/registry.mjs +328 -0
  74. package/lib/engine/session-runtime/runner.mjs +344 -0
  75. package/lib/engine/session-runtime/socket.mjs +212 -0
  76. package/lib/engine/session-runtime/wakeup.mjs +115 -0
  77. package/lib/engine/skills/index.mjs +321 -0
  78. package/lib/engine/tools/bash-background.mjs +533 -0
  79. package/lib/engine/tools/bash.mjs +216 -0
  80. package/lib/engine/tools/edit.mjs +97 -0
  81. package/lib/engine/tools/glob.mjs +81 -0
  82. package/lib/engine/tools/grep.mjs +224 -0
  83. package/lib/engine/tools/index.mjs +84 -0
  84. package/lib/engine/tools/list-agents.mjs +32 -0
  85. package/lib/engine/tools/ls.mjs +127 -0
  86. package/lib/engine/tools/monitor.mjs +82 -0
  87. package/lib/engine/tools/notebook-edit.mjs +218 -0
  88. package/lib/engine/tools/read.mjs +103 -0
  89. package/lib/engine/tools/schedule-wakeup.mjs +45 -0
  90. package/lib/engine/tools/schema.mjs +144 -0
  91. package/lib/engine/tools/send-message.mjs +77 -0
  92. package/lib/engine/tools/session.mjs +70 -0
  93. package/lib/engine/tools/todo.mjs +144 -0
  94. package/lib/engine/tools/toolsearch.mjs +217 -0
  95. package/lib/engine/tools/walk.mjs +193 -0
  96. package/lib/engine/tools/web-switch.mjs +31 -0
  97. package/lib/engine/tools/webfetch-html.mjs +387 -0
  98. package/lib/engine/tools/webfetch-net.mjs +340 -0
  99. package/lib/engine/tools/webfetch.mjs +198 -0
  100. package/lib/engine/tools/websearch.mjs +91 -0
  101. package/lib/engine/tools/workflow.mjs +95 -0
  102. package/lib/engine/tools/write.mjs +76 -0
  103. package/lib/engine/tui/line-editor.mjs +137 -0
  104. package/lib/engine/tui/render.mjs +86 -0
  105. package/lib/engine/tui/tui.mjs +274 -0
  106. package/lib/engine/wire/anthropic-messages.mjs +263 -0
  107. package/lib/engine/wire/effort.mjs +36 -0
  108. package/lib/engine/wire/errors.mjs +496 -0
  109. package/lib/engine/wire/http.mjs +441 -0
  110. package/lib/engine/wire/index.mjs +76 -0
  111. package/lib/engine/wire/openai-chat.mjs +332 -0
  112. package/lib/engine/wire/prompt-cache.mjs +79 -0
  113. package/lib/engine/wire/search.mjs +140 -0
  114. package/lib/engine/wire/sse.mjs +114 -0
  115. package/lib/engine/wire/stall.mjs +349 -0
  116. package/lib/engine/wire/token-provider.mjs +175 -0
  117. package/lib/engine/wire/usage.mjs +192 -0
  118. package/lib/engine/workflow/host.mjs +524 -0
  119. package/lib/engine/workflow/journal.mjs +188 -0
  120. package/lib/engine/workflow/json-schema.mjs +171 -0
  121. package/lib/engine/workflow/meta.mjs +329 -0
  122. package/lib/engine/workflow/notifications.mjs +52 -0
  123. package/lib/engine/workflow/runtime.mjs +447 -0
  124. package/lib/engine/workflow/sandbox.mjs +534 -0
  125. package/lib/engine/workflow/worker.mjs +141 -0
  126. package/lib/engine/workflow/worktree.mjs +74 -0
  127. package/lib/execution/disposition.mjs +1 -1
  128. package/lib/execution/intake.mjs +10 -0
  129. package/lib/execution/surface-policy.mjs +15 -0
  130. package/lib/learning/curator.mjs +8 -6
  131. package/lib/learning/reflect.mjs +8 -6
  132. package/lib/model-router/catalog/cohort.yaml +137 -0
  133. package/lib/model-router/catalog.mjs +118 -1
  134. package/lib/model-router/failover.mjs +67 -16
  135. package/lib/model-router/llm-task.mjs +39 -3
  136. package/lib/model-router/resolve.mjs +89 -3
  137. package/lib/model-router/spawn.mjs +46 -47
  138. package/lib/model-router/taxonomy.mjs +126 -4
  139. package/lib/org/cost-sync.mjs +141 -11
  140. package/lib/org/inbound/broadcast.mjs +289 -0
  141. package/lib/org/inbound/collective.mjs +375 -0
  142. package/lib/org/inbound/directedness.mjs +96 -8
  143. package/lib/org/inbound/facts.mjs +78 -2
  144. package/lib/org/inbound/project.mjs +22 -0
  145. package/lib/org/inbound/surfaces.mjs +14 -0
  146. package/lib/org/llm-token.mjs +879 -0
  147. package/lib/org/mesh.mjs +61 -0
  148. package/lib/org/messaging.mjs +3 -1
  149. package/lib/org/protocol.checksum +1 -1
  150. package/lib/org/protocol.mjs +15 -0
  151. package/lib/org/quota.mjs +520 -0
  152. package/lib/org/tool-surface.mjs +104 -16
  153. package/lib/org/ui-parity.mjs +16 -1
  154. package/lib/org/work-ledger.mjs +37 -6
  155. package/lib/rate-guard.mjs +114 -1
  156. package/lib/resource-governor.mjs +41 -6
  157. package/lib/runtime/adapter.mjs +823 -0
  158. package/lib/runtime/child-env.mjs +191 -0
  159. package/lib/runtime/legacy-shell-guard.mjs +97 -0
  160. package/lib/runtime/seat-engine.mjs +162 -0
  161. package/lib/session/ask-ledger.mjs +271 -0
  162. package/lib/session/current-work.mjs +676 -0
  163. package/lib/session/feed-core.mjs +40 -3
  164. package/lib/session/launch-args.mjs +56 -4
  165. package/lib/session/status-summary.mjs +26 -9
  166. package/lib/session/upgrade-notice.mjs +42 -0
  167. package/lib/setup/claude-probe.mjs +117 -13
  168. package/lib/setup/enrich.mjs +13 -10
  169. package/lib/setup/sections/model.mjs +39 -13
  170. package/lib/telemetry/collect.mjs +208 -9
  171. package/lib/upgrade/ignored-drift.mjs +105 -0
  172. package/lib/voice/post-call-brief.mjs +30 -17
  173. package/package.json +13 -3
  174. package/plugins/maestro-skills/skills/board-work.md +5 -0
  175. package/plugins/maestro-skills/skills/inbound-triage.md +56 -15
  176. package/plugins/maestro-skills/skills/main-session.md +18 -7
  177. package/scripts/ci/check-tarball-fidelity.mjs +126 -2
  178. package/scripts/ci/run-tests.mjs +47 -19
  179. package/scripts/cohort-llm/api-key-helper.mjs +92 -0
  180. package/scripts/collective/hook-runner.mjs +29 -2
  181. package/scripts/continuous-monitor.sh +13 -0
  182. package/scripts/cost/track-claude-usage.mjs +15 -0
  183. package/scripts/daemon/agent-daemon.mjs +408 -20
  184. package/scripts/daemon/assurance.mjs +48 -12
  185. package/scripts/daemon/cadence-consumer.mjs +218 -68
  186. package/scripts/daemon/cadence-handlers.mjs +73 -4
  187. package/scripts/daemon/classifier.mjs +75 -26
  188. package/scripts/daemon/context-compiler.mjs +51 -37
  189. package/scripts/daemon/deliver.mjs +30 -1
  190. package/scripts/daemon/dispatcher.mjs +595 -149
  191. package/scripts/daemon/health.mjs +14 -1
  192. package/scripts/daemon/maestro-daemon.mjs +11 -0
  193. package/scripts/daemon/prompt-builder.mjs +24 -0
  194. package/scripts/daemon/responder.mjs +246 -79
  195. package/scripts/daemon/sdk-version.mjs +98 -16
  196. package/scripts/eval/probe-gateway.mjs +635 -0
  197. package/scripts/eval/replay/extract.mjs +270 -0
  198. package/scripts/eval/replay/grade.mjs +260 -0
  199. package/scripts/eval/replay/lib/config.mjs +50 -0
  200. package/scripts/eval/replay/lib/effects.mjs +65 -0
  201. package/scripts/eval/replay/lib/fixture.mjs +188 -0
  202. package/scripts/eval/replay/lib/judge.mjs +72 -0
  203. package/scripts/eval/replay/lib/redact.mjs +136 -0
  204. package/scripts/eval/replay/lib/sandbox.mjs +170 -0
  205. package/scripts/eval/replay/lib/schema-check.mjs +63 -0
  206. package/scripts/eval/replay/lib/transcript.mjs +76 -0
  207. package/scripts/eval/replay/mcp-replay-stub.mjs +101 -0
  208. package/scripts/eval/replay/report.mjs +185 -0
  209. package/scripts/eval/replay/run.mjs +404 -0
  210. package/scripts/fleet/rollout.mjs +1094 -0
  211. package/scripts/hooks/pre-send-audit.sh +36 -245
  212. package/scripts/hooks/pre-write-yaml-validate.mjs +275 -0
  213. package/scripts/hooks/validate-state-yaml.sh +190 -0
  214. package/scripts/huddle/huddle-llm.mjs +361 -0
  215. package/scripts/huddle/huddle-server.mjs +46 -121
  216. package/scripts/local-triggers/autoupdate.sh +448 -78
  217. package/scripts/local-triggers/run-trigger.sh +13 -0
  218. package/scripts/maintenance/pin-integrity.mjs +364 -0
  219. package/scripts/poll-slack-events.sh +41 -9
  220. package/scripts/poller/slack-socket-mode.mjs +28 -3
  221. package/scripts/session/supervisor.mjs +80 -13
  222. package/scripts/spawn-session.sh +13 -0
  223. package/bin/maestro.test.mjs +0 -1574
  224. package/lib/action-executor.test.mjs +0 -871
  225. package/lib/archetype.test.mjs +0 -132
  226. package/lib/assurance/plan-note.test.mjs +0 -234
  227. package/lib/assurance/room-budget.test.mjs +0 -486
  228. package/lib/assurance/tier.test.mjs +0 -174
  229. package/lib/autonomy.test.mjs +0 -66
  230. package/lib/backlog.test.mjs +0 -302
  231. package/lib/backup/policy.test.mjs +0 -305
  232. package/lib/budget-escalate.test.mjs +0 -232
  233. package/lib/budget-guard.envelope.test.mjs +0 -476
  234. package/lib/budget-guard.test.mjs +0 -427
  235. package/lib/cadence-bus-requeue.test.mjs +0 -83
  236. package/lib/cadence-bus-schedule.test.mjs +0 -194
  237. package/lib/cadence-bus.test.mjs +0 -720
  238. package/lib/cadences.test.mjs +0 -230
  239. package/lib/capability/inventory.test.mjs +0 -232
  240. package/lib/capability.test.mjs +0 -78
  241. package/lib/channels/base-adapter.test.mjs +0 -590
  242. package/lib/channels/channels.test.mjs +0 -371
  243. package/lib/channels/contract.test.mjs +0 -162
  244. package/lib/channels/inbox-item.test.mjs +0 -368
  245. package/lib/channels/orgmail/adapter.test.mjs +0 -448
  246. package/lib/channels/pairing.test.mjs +0 -270
  247. package/lib/channels/repeat-suppressor.test.mjs +0 -134
  248. package/lib/channels/slack-adapter.test.mjs +0 -212
  249. package/lib/channels/telegram-adapter.test.mjs +0 -306
  250. package/lib/channels/voice/adapter.test.mjs +0 -278
  251. package/lib/channels/whatsapp/adapter-baileys.test.mjs +0 -359
  252. package/lib/channels/whatsapp/baileys-typing.test.mjs +0 -154
  253. package/lib/charter.test.mjs +0 -89
  254. package/lib/claude-bin.test.mjs +0 -131
  255. package/lib/cli/board.test.mjs +0 -227
  256. package/lib/cli/design.test.mjs +0 -270
  257. package/lib/cli/doctor-checks.test.mjs +0 -336
  258. package/lib/cli/global-setup-extras.test.mjs +0 -462
  259. package/lib/cli/inbox.test.mjs +0 -230
  260. package/lib/cli/session-ack.test.mjs +0 -63
  261. package/lib/cli/session.test.mjs +0 -613
  262. package/lib/collective/capture.test.mjs +0 -121
  263. package/lib/collective/cards.test.mjs +0 -114
  264. package/lib/collective/config.test.mjs +0 -123
  265. package/lib/collective/global-config.test.mjs +0 -220
  266. package/lib/collective/global-skills.test.mjs +0 -126
  267. package/lib/collective/presence.test.mjs +0 -95
  268. package/lib/collective/recall.test.mjs +0 -116
  269. package/lib/collective/vendor-skills.test.mjs +0 -306
  270. package/lib/comms/send-gate.test.mjs +0 -770
  271. package/lib/comms.test.mjs +0 -41
  272. package/lib/context/budget.test.mjs +0 -252
  273. package/lib/context/history-scope.test.mjs +0 -79
  274. package/lib/cost/ledger-row.test.mjs +0 -183
  275. package/lib/design/design-md.test.mjs +0 -318
  276. package/lib/design/fixtures/DESIGN.golden.md +0 -238
  277. package/lib/design/fixtures/PRODUCT.golden.md +0 -67
  278. package/lib/design/fixtures/foundation.json +0 -133
  279. package/lib/design/refresh-gate.test.mjs +0 -144
  280. package/lib/design/write.test.mjs +0 -241
  281. package/lib/diagnostics/alerts.test.mjs +0 -318
  282. package/lib/diagnostics/backup-freshness.test.mjs +0 -185
  283. package/lib/diagnostics/counters.test.mjs +0 -206
  284. package/lib/diagnostics/events.test.mjs +0 -290
  285. package/lib/diagnostics/otel.test.mjs +0 -196
  286. package/lib/diagnostics/trace.test.mjs +0 -251
  287. package/lib/env-compat.test.mjs +0 -104
  288. package/lib/execution/disposition.test.mjs +0 -553
  289. package/lib/execution/drive.test.mjs +0 -270
  290. package/lib/execution/effects.test.mjs +0 -344
  291. package/lib/execution/intake.test.mjs +0 -389
  292. package/lib/execution/journal.test.mjs +0 -261
  293. package/lib/execution/match.test.mjs +0 -235
  294. package/lib/execution/pipeline.test.mjs +0 -392
  295. package/lib/execution/route.test.mjs +0 -186
  296. package/lib/execution/surface-policy.test.mjs +0 -162
  297. package/lib/fs-atomic.test.mjs +0 -72
  298. package/lib/fs-ownership.test.mjs +0 -158
  299. package/lib/goals/admission.test.mjs +0 -164
  300. package/lib/goals/classify.test.mjs +0 -167
  301. package/lib/goals/collaborate.test.mjs +0 -336
  302. package/lib/goals/gaps.test.mjs +0 -284
  303. package/lib/goals/loop.test.mjs +0 -845
  304. package/lib/hooks/bus.test.mjs +0 -387
  305. package/lib/identity/persona.test.mjs +0 -142
  306. package/lib/kpi-sensors.test.mjs +0 -278
  307. package/lib/kpi.test.mjs +0 -244
  308. package/lib/learning/config.test.mjs +0 -75
  309. package/lib/learning/counters.test.mjs +0 -69
  310. package/lib/learning/curator-consolidate.test.mjs +0 -238
  311. package/lib/learning/curator.test.mjs +0 -106
  312. package/lib/learning/reflect.test.mjs +0 -0
  313. package/lib/learning/session-index.test.mjs +0 -125
  314. package/lib/learning/skill-writer.test.mjs +0 -210
  315. package/lib/mandate/audit.test.mjs +0 -195
  316. package/lib/mandate/contract.test.mjs +0 -185
  317. package/lib/mandate/derive.test.mjs +0 -274
  318. package/lib/mandate/model.test.mjs +0 -164
  319. package/lib/mandate/refresh.test.mjs +0 -389
  320. package/lib/mcp/server.test.mjs +0 -426
  321. package/lib/model-router/auth-profiles.test.mjs +0 -580
  322. package/lib/model-router/catalog.test.mjs +0 -385
  323. package/lib/model-router/economics.test.mjs +0 -438
  324. package/lib/model-router/failover.test.mjs +0 -439
  325. package/lib/model-router/health.test.mjs +0 -338
  326. package/lib/model-router/integration-coverage.test.mjs +0 -831
  327. package/lib/model-router/integration.test.mjs +0 -564
  328. package/lib/model-router/ledger.test.mjs +0 -415
  329. package/lib/model-router/llm-task.test.mjs +0 -392
  330. package/lib/model-router/org-credentials.test.mjs +0 -265
  331. package/lib/model-router/pricing-refresh.test.mjs +0 -286
  332. package/lib/model-router/reconcile.test.mjs +0 -316
  333. package/lib/model-router/repair.test.mjs +0 -180
  334. package/lib/model-router/spawn.test.mjs +0 -446
  335. package/lib/model-router/taxonomy.test.mjs +0 -410
  336. package/lib/model-router.test.mjs +0 -1207
  337. package/lib/org/activity.test.mjs +0 -134
  338. package/lib/org/approvals.test.mjs +0 -216
  339. package/lib/org/awareness.test.mjs +0 -159
  340. package/lib/org/board-mine-cache.test.mjs +0 -53
  341. package/lib/org/board.test.mjs +0 -187
  342. package/lib/org/bootstrap-context.test.mjs +0 -153
  343. package/lib/org/client.test.mjs +0 -1206
  344. package/lib/org/cohort-client.test.mjs +0 -126
  345. package/lib/org/cost-sync.test.mjs +0 -153
  346. package/lib/org/doctor.test.mjs +0 -346
  347. package/lib/org/engagement-ledger.test.mjs +0 -112
  348. package/lib/org/engagement.test.mjs +0 -739
  349. package/lib/org/handoff.test.mjs +0 -269
  350. package/lib/org/inbound/directedness.test.mjs +0 -668
  351. package/lib/org/inbound/facts.test.mjs +0 -471
  352. package/lib/org/inbound/hydrate.test.mjs +0 -908
  353. package/lib/org/inbound/index.test.mjs +0 -429
  354. package/lib/org/inbound/project.test.mjs +0 -287
  355. package/lib/org/integration-tools.test.mjs +0 -160
  356. package/lib/org/keys.test.mjs +0 -92
  357. package/lib/org/knowledge.test.mjs +0 -326
  358. package/lib/org/leases.test.mjs +0 -235
  359. package/lib/org/mesh-directives.test.mjs +0 -110
  360. package/lib/org/mesh-integration.test.mjs +0 -127
  361. package/lib/org/mesh.test.mjs +0 -400
  362. package/lib/org/messaging.test.mjs +0 -471
  363. package/lib/org/param-contract.test.mjs +0 -477
  364. package/lib/org/policy.test.mjs +0 -237
  365. package/lib/org/protocol.checksum.test.mjs +0 -90
  366. package/lib/org/protocol.test.mjs +0 -323
  367. package/lib/org/push.test.mjs +0 -792
  368. package/lib/org/registry.test.mjs +0 -100
  369. package/lib/org/resource-tools.test.mjs +0 -361
  370. package/lib/org/tool-access.test.mjs +0 -144
  371. package/lib/org/tool-surface-integration.test.mjs +0 -120
  372. package/lib/org/tool-surface.test.mjs +0 -1268
  373. package/lib/org/typing.test.mjs +0 -291
  374. package/lib/org/ui-parity.test.mjs +0 -560
  375. package/lib/org/verify.test.mjs +0 -194
  376. package/lib/org/work-ledger.test.mjs +0 -273
  377. package/lib/plan/adoption-e2e.test.mjs +0 -366
  378. package/lib/plan/budget-enforcement.test.mjs +0 -400
  379. package/lib/plan/compile.test.mjs +0 -382
  380. package/lib/plan/emit.test.mjs +0 -269
  381. package/lib/plan/explain.test.mjs +0 -188
  382. package/lib/prompts/parallelism.test.mjs +0 -177
  383. package/lib/rag/rag.test.mjs +0 -505
  384. package/lib/rate-guard.test.mjs +0 -272
  385. package/lib/reactive-gate.test.mjs +0 -57
  386. package/lib/render.test.mjs +0 -68
  387. package/lib/resource-governor.test.mjs +0 -488
  388. package/lib/scheduling/dynamic-jobs.test.mjs +0 -344
  389. package/lib/scheduling/jitter.test.mjs +0 -140
  390. package/lib/secrets/broker.test.mjs +0 -280
  391. package/lib/secrets/providers.test.mjs +0 -274
  392. package/lib/security/audit-engine.test.mjs +0 -424
  393. package/lib/security/coerce-args.test.mjs +0 -281
  394. package/lib/security/dangerous-tools.test.mjs +0 -68
  395. package/lib/security/external-content.test.mjs +0 -84
  396. package/lib/security/redact.test.mjs +0 -441
  397. package/lib/security/secret-equal.test.mjs +0 -55
  398. package/lib/session/config.test.mjs +0 -92
  399. package/lib/session/feed-core.test.mjs +0 -198
  400. package/lib/session/first-run.test.mjs +0 -121
  401. package/lib/session/frontdoor.test.mjs +0 -205
  402. package/lib/session/handoffs.test.mjs +0 -183
  403. package/lib/session/identity.test.mjs +0 -180
  404. package/lib/session/inbox-claims.test.mjs +0 -286
  405. package/lib/session/launch-args.test.mjs +0 -157
  406. package/lib/session/liveness.test.mjs +0 -100
  407. package/lib/session/status-summary.test.mjs +0 -118
  408. package/lib/session-permissions.test.mjs +0 -120
  409. package/lib/setup/claude-probe.test.mjs +0 -187
  410. package/lib/setup/completeness.test.mjs +0 -110
  411. package/lib/setup/context-pack.test.mjs +0 -89
  412. package/lib/setup/enrich.test.mjs +0 -115
  413. package/lib/setup/enroll-from-cohort.test.mjs +0 -300
  414. package/lib/setup/integration.test.mjs +0 -162
  415. package/lib/setup/io.test.mjs +0 -77
  416. package/lib/setup/runner.test.mjs +0 -132
  417. package/lib/setup/sections/identity.test.mjs +0 -234
  418. package/lib/setup/sections/inventory.test.mjs +0 -198
  419. package/lib/setup/sections/learning.test.mjs +0 -81
  420. package/lib/setup/sections/mandate.test.mjs +0 -388
  421. package/lib/setup/sections/messaging.test.mjs +0 -127
  422. package/lib/setup/sections/model.test.mjs +0 -240
  423. package/lib/setup/sections/org.test.mjs +0 -346
  424. package/lib/setup/sections/orgmail.test.mjs +0 -118
  425. package/lib/setup/sections/recovery.test.mjs +0 -98
  426. package/lib/setup/sections/subagents.test.mjs +0 -429
  427. package/lib/setup/sections/verify.test.mjs +0 -175
  428. package/lib/setup/sot.test.mjs +0 -81
  429. package/lib/setup/state.test.mjs +0 -115
  430. package/lib/singleton.test.mjs +0 -151
  431. package/lib/subagents/cli.test.mjs +0 -389
  432. package/lib/subagents/client.test.mjs +0 -309
  433. package/lib/subagents/gap.test.mjs +0 -234
  434. package/lib/subagents/lock.test.mjs +0 -248
  435. package/lib/subagents/manifest.test.mjs +0 -175
  436. package/lib/subagents/refs.test.mjs +0 -204
  437. package/lib/subagents/resolve.test.mjs +0 -422
  438. package/lib/subagents/schema.test.mjs +0 -328
  439. package/lib/telemetry/alerts.test.mjs +0 -109
  440. package/lib/telemetry/collect.test.mjs +0 -1274
  441. package/lib/tool-definitions-integration.test.mjs +0 -83
  442. package/lib/tool-definitions.test.mjs +0 -437
  443. package/lib/upgrade/global-refresh.test.mjs +0 -65
  444. package/lib/upgrade/launchd-reconcile.test.mjs +0 -272
  445. package/lib/upgrade/post-steps.test.mjs +0 -200
  446. package/lib/upgrade/verify.test.mjs +0 -164
  447. package/lib/util/fetch-timeout.test.mjs +0 -202
  448. package/lib/util/reconnect.test.mjs +0 -369
  449. package/lib/util/unhandled.test.mjs +0 -216
  450. package/lib/voice/outbound.test.mjs +0 -69
  451. package/lib/voice/session-rotation.test.mjs +0 -114
  452. package/lib/voice/stt.test.mjs +0 -226
  453. package/lib/voice/voice.test.mjs +0 -990
  454. package/scripts/cadence/enqueue-cadence-tick.test.mjs +0 -187
  455. package/scripts/ci/check-docs-accuracy.test.mjs +0 -409
  456. package/scripts/ci/check-durable-write-seam.test.mjs +0 -90
  457. package/scripts/ci/check-no-build-artifacts.test.mjs +0 -71
  458. package/scripts/ci/check-no-residual-identity.test.mjs +0 -202
  459. package/scripts/ci/check-skill-packs.test.mjs +0 -495
  460. package/scripts/ci/check-subagent-frontmatter.test.mjs +0 -124
  461. package/scripts/ci/check.test.mjs +0 -194
  462. package/scripts/ci/conformance-org-api.test.mjs +0 -425
  463. package/scripts/cloud-relay/voice/relay-identity.test.mjs +0 -96
  464. package/scripts/collective/hook-runner.test.mjs +0 -173
  465. package/scripts/cost/fleet-digest.test.mjs +0 -207
  466. package/scripts/cost/track-claude-usage-pricing.test.mjs +0 -183
  467. package/scripts/cost/track-claude-usage.test.mjs +0 -148
  468. package/scripts/daemon/agent-daemon-board-mine.test.mjs +0 -96
  469. package/scripts/daemon/agent-daemon-design.test.mjs +0 -238
  470. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +0 -60
  471. package/scripts/daemon/agent-daemon.test.mjs +0 -995
  472. package/scripts/daemon/assurance-e2e.test.mjs +0 -613
  473. package/scripts/daemon/assurance.test.mjs +0 -1791
  474. package/scripts/daemon/board-mirror.test.mjs +0 -165
  475. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +0 -393
  476. package/scripts/daemon/cadence-consumer-governance.test.mjs +0 -276
  477. package/scripts/daemon/cadence-consumer.test.mjs +0 -776
  478. package/scripts/daemon/cadence-handlers.test.mjs +0 -837
  479. package/scripts/daemon/classifier-identity.test.mjs +0 -137
  480. package/scripts/daemon/classifier.test.mjs +0 -266
  481. package/scripts/daemon/classify-kind.test.mjs +0 -40
  482. package/scripts/daemon/context-compiler.test.mjs +0 -406
  483. package/scripts/daemon/deliver.test.mjs +0 -564
  484. package/scripts/daemon/dispatcher-cooldown.test.mjs +0 -122
  485. package/scripts/daemon/dispatcher-governance.test.mjs +0 -1013
  486. package/scripts/daemon/dispatcher-resume.test.mjs +0 -166
  487. package/scripts/daemon/dispatcher-session-continuity.test.mjs +0 -365
  488. package/scripts/daemon/execution-ladder.test.mjs +0 -470
  489. package/scripts/daemon/goal-steward-cadence.test.mjs +0 -312
  490. package/scripts/daemon/inbox-deferral-session.test.mjs +0 -49
  491. package/scripts/daemon/inbox-deferral.test.mjs +0 -336
  492. package/scripts/daemon/inbox-wake.test.mjs +0 -199
  493. package/scripts/daemon/integration.test.mjs +0 -149
  494. package/scripts/daemon/lib/self-echo.test.mjs +0 -153
  495. package/scripts/daemon/lib/session-router.test.mjs +0 -554
  496. package/scripts/daemon/prompt-builder-preamble.test.mjs +0 -210
  497. package/scripts/daemon/prompt-builder.test.mjs +0 -556
  498. package/scripts/daemon/responder-cost.test.mjs +0 -68
  499. package/scripts/daemon/responder-history.test.mjs +0 -221
  500. package/scripts/daemon/sdk-version.test.mjs +0 -31
  501. package/scripts/daemon/session-lock.test.mjs +0 -252
  502. package/scripts/daemon/session-outcomes.test.mjs +0 -533
  503. package/scripts/daemon/typing-registry.test.mjs +0 -102
  504. package/scripts/hooks/pre-send-audit.test.mjs +0 -354
  505. package/scripts/huddle/huddle-prompt.test.mjs +0 -176
  506. package/scripts/local-triggers/autoupdate.test.mjs +0 -518
  507. package/scripts/local-triggers/generate-plists.test.mjs +0 -456
  508. package/scripts/media-generation/brand-clause.test.mjs +0 -135
  509. package/scripts/org/send-orgmail.first-contact.test.mjs +0 -102
  510. package/scripts/poller/inbox-privilege-injection.test.mjs +0 -167
  511. package/scripts/poller/inbox-scan-poller.test.mjs +0 -295
  512. package/scripts/poller/lib/cloud-relay-dedup.test.mjs +0 -133
  513. package/scripts/poller/slack-socket-mode.test.mjs +0 -805
  514. package/scripts/poller-launchd/install.test.mjs +0 -243
  515. package/scripts/restore-from-backup.test.mjs +0 -181
  516. package/scripts/session/feed.test.mjs +0 -196
  517. package/scripts/session/supervisor-sh.test.mjs +0 -218
  518. package/scripts/session/supervisor.test.mjs +0 -482
  519. package/scripts/setup/configure-macos.test.mjs +0 -306
  520. package/scripts/setup/gen-subagent-manifest.test.mjs +0 -124
  521. package/scripts/setup/generate-agent-package-json.test.mjs +0 -143
  522. package/scripts/setup/generate-capability.test.mjs +0 -134
  523. package/scripts/setup/init-agent.test.mjs +0 -370
  524. package/scripts/setup/init-skill-marketplace.test.mjs +0 -193
  525. package/scripts/vendor/sync-skill-packs.test.mjs +0 -103
  526. package/scripts/watchdog/memory-watchdog.test.mjs +0 -64
@@ -1,776 +0,0 @@
1
- /**
2
- * cadence-consumer.test.mjs — node:test coverage for the cadence consumer.
3
- *
4
- * Uses startConsumer({ spawnSession }) to inject a stub sub-session spawner
5
- * so no real Claude Code process is ever launched. Each test creates its own
6
- * AGENT_ROOT under tmpdir() and tears it down afterwards.
7
- */
8
-
9
- import { test } from "node:test";
10
- import assert from "node:assert/strict";
11
- import { promises as fsp } from "fs";
12
- import { writeFileSync, mkdirSync } from "node:fs";
13
- import { tmpdir } from "os";
14
- import { join, dirname } from "path";
15
-
16
- import { enqueueTick, listInbox, listClaimed, busDepth, getBusPaths } from "../../lib/cadence-bus.mjs";
17
- import { startConsumer as startConsumerRaw, parseUsageFromStdout, routeCadenceSpawn } from "./cadence-consumer.mjs";
18
- import { statSync } from "node:fs";
19
-
20
- // WS4 added a resource-governor + 429-breaker + budget gate to the consumer's
21
- // escalation path. These tests exercise the cadence routing / reliability layer
22
- // (inline vs guarded vs escalate, circuit breaker, stale recovery), which is
23
- // ORTHOGONAL to host-resource gating — so we neutralise WS4 with always-admit
24
- // stubs here. The governance gate itself is covered by
25
- // cadence-consumer-governance.test.mjs + resource-governor/rate-guard tests.
26
- const ADMIT_ALL = { admit: () => ({ decision: "ADMIT", reason: "test", snapshot: {} }), defaultDeps: () => ({}) };
27
- const RATE_OK = { checkRateLimit: () => ({ allowed: true, retryAt: null }), classifyStderr: () => false, recordRateLimit: () => {}, recordSuccess: () => {} };
28
- const BUDGET_OK = { dailyStatus: () => ({ essentialOnly: false }) };
29
- function startConsumer(opts = {}) {
30
- return startConsumerRaw({ governor: ADMIT_ALL, rateGuard: RATE_OK, budgetGuard: BUDGET_OK, ...opts });
31
- }
32
-
33
- async function makeAgentRoot() {
34
- const path = join(
35
- tmpdir(),
36
- `cadence-consumer-test-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
37
- );
38
- await fsp.mkdir(path, { recursive: true });
39
- return path;
40
- }
41
-
42
- async function rmRoot(path) {
43
- try { await fsp.rm(path, { recursive: true, force: true }); } catch { /* */ }
44
- }
45
-
46
- /**
47
- * Seed an agent root with a trigger prompt for a given cadence. Lets the
48
- * consumer's "escalate" path find a real prompt file when our stub spawner
49
- * is invoked.
50
- */
51
- function plantPrompt(root, cadence, body = `# ${cadence} trigger prompt`) {
52
- const path = join(root, "schedules/triggers", `${cadence}.md`);
53
- mkdirSync(dirname(path), { recursive: true });
54
- writeFileSync(path, body);
55
- return path;
56
- }
57
-
58
- /**
59
- * Wait until `predicate()` returns truthy or the deadline expires. Polls
60
- * every 25ms — fast enough for sub-200ms drain cycles, slow enough that
61
- * tests don't burn CPU.
62
- */
63
- async function waitFor(predicate, { timeoutMs = 5_000, intervalMs = 25 } = {}) {
64
- const deadline = Date.now() + timeoutMs;
65
- while (Date.now() < deadline) {
66
- if (await predicate()) return true;
67
- await new Promise((r) => setTimeout(r, intervalMs));
68
- }
69
- return false;
70
- }
71
-
72
- // ---------------------------------------------------------------------------
73
- // Inline handlers
74
- // ---------------------------------------------------------------------------
75
-
76
- test("consumer processes a registry-inline cadence without spawning", async () => {
77
- const root = await makeAgentRoot();
78
- const spawnCalls = [];
79
- const consumer = startConsumer({
80
- agentRoot: root,
81
- pollMs: 50,
82
- heartbeatMs: 1_000,
83
- recoveryMs: 60_000,
84
- spawnSession: async (opts) => { spawnCalls.push(opts); return { ok: true, exit_code: 0, duration_ms: 1 }; },
85
- });
86
- try {
87
- enqueueTick({ cadence: "cadence-bus-heartbeat", source: "manual", agentRoot: root });
88
- const ok = await waitFor(() => consumer.getStats().inline >= 1);
89
- assert.ok(ok, "heartbeat cadence should drain inline");
90
- assert.equal(spawnCalls.length, 0, "inline cadence must not spawn");
91
- assert.equal(busDepth(root).inbox, 0);
92
- assert.equal(busDepth(root).claimed, 0);
93
- } finally {
94
- await consumer.stop();
95
- await rmRoot(root);
96
- }
97
- });
98
-
99
- // ---------------------------------------------------------------------------
100
- // Guarded handlers
101
- // ---------------------------------------------------------------------------
102
-
103
- test("guarded cadence completes inline when there's no work", async () => {
104
- const root = await makeAgentRoot();
105
- const spawnCalls = [];
106
- const consumer = startConsumer({
107
- agentRoot: root,
108
- pollMs: 50,
109
- spawnSession: async (opts) => { spawnCalls.push(opts); return { ok: true, exit_code: 0 }; },
110
- });
111
- try {
112
- // No inbox files, no queues with items → guard returns "inline".
113
- enqueueTick({ cadence: "inbox-processor", source: "launchd", agentRoot: root });
114
- const ok = await waitFor(() => consumer.getStats().inline >= 1);
115
- assert.ok(ok);
116
- assert.equal(spawnCalls.length, 0, "inbox empty → no spawn");
117
- } finally {
118
- await consumer.stop();
119
- await rmRoot(root);
120
- }
121
- });
122
-
123
- test("guarded cadence escalates when guard says work is pending", async () => {
124
- const root = await makeAgentRoot();
125
- // Seed an inbox item so the inbox-processor guard returns "escalate".
126
- // Also set INBOX_CADENCE_ESCALATE=1 because the default behaviour is
127
- // now inline (reactive daemon owns inbox dispatch — see cadence-handlers.mjs).
128
- mkdirSync(join(root, "state/inbox/slack"), { recursive: true });
129
- writeFileSync(join(root, "state/inbox/slack/item.json"), JSON.stringify({ id: "msg1" }));
130
- plantPrompt(root, "inbox-processor");
131
- const prevEnv = process.env.INBOX_CADENCE_ESCALATE;
132
- process.env.INBOX_CADENCE_ESCALATE = "1";
133
- const spawnCalls = [];
134
- const consumer = startConsumer({
135
- agentRoot: root,
136
- pollMs: 50,
137
- spawnSession: async (opts) => {
138
- spawnCalls.push(opts);
139
- return { ok: true, exit_code: 0, duration_ms: 5 };
140
- },
141
- });
142
- try {
143
- enqueueTick({ cadence: "inbox-processor", source: "launchd", agentRoot: root });
144
- const ok = await waitFor(() => consumer.getStats().escalated >= 1);
145
- assert.ok(ok, "guard with pending work should escalate");
146
- assert.equal(spawnCalls.length, 1);
147
- assert.equal(spawnCalls[0].cadence, "inbox-processor");
148
- assert.match(spawnCalls[0].promptPath, /schedules\/triggers\/inbox-processor\.md$/);
149
- } finally {
150
- await consumer.stop();
151
- await rmRoot(root);
152
- if (prevEnv === undefined) delete process.env.INBOX_CADENCE_ESCALATE;
153
- else process.env.INBOX_CADENCE_ESCALATE = prevEnv;
154
- }
155
- });
156
-
157
- // ---------------------------------------------------------------------------
158
- // Escalate path
159
- // ---------------------------------------------------------------------------
160
-
161
- test("escalate-mode cadence spawns with the configured prompt", async () => {
162
- const root = await makeAgentRoot();
163
- plantPrompt(root, "weekly-strategic-memo");
164
- const spawnCalls = [];
165
- const consumer = startConsumer({
166
- agentRoot: root,
167
- pollMs: 50,
168
- spawnSession: async (opts) => {
169
- spawnCalls.push(opts);
170
- return { ok: true, exit_code: 0, duration_ms: 10 };
171
- },
172
- });
173
- try {
174
- enqueueTick({ cadence: "weekly-strategic-memo", source: "launchd", agentRoot: root });
175
- const ok = await waitFor(() => consumer.getStats().escalated >= 1);
176
- assert.ok(ok);
177
- assert.equal(spawnCalls[0].cadence, "weekly-strategic-memo");
178
- } finally {
179
- await consumer.stop();
180
- await rmRoot(root);
181
- }
182
- });
183
-
184
- test("unknown cadence with a prompt file falls back to escalate", async () => {
185
- const root = await makeAgentRoot();
186
- plantPrompt(root, "custom-cadence");
187
- const spawnCalls = [];
188
- const consumer = startConsumer({
189
- agentRoot: root,
190
- pollMs: 50,
191
- spawnSession: async (opts) => {
192
- spawnCalls.push(opts);
193
- return { ok: true, exit_code: 0 };
194
- },
195
- });
196
- try {
197
- enqueueTick({ cadence: "custom-cadence", source: "manual", agentRoot: root });
198
- const ok = await waitFor(() => consumer.getStats().escalated >= 1);
199
- assert.ok(ok);
200
- assert.equal(spawnCalls.length, 1);
201
- } finally {
202
- await consumer.stop();
203
- await rmRoot(root);
204
- }
205
- });
206
-
207
- test("unknown cadence with no prompt file DLQ's immediately", async () => {
208
- const root = await makeAgentRoot();
209
- const spawnCalls = [];
210
- const consumer = startConsumer({
211
- agentRoot: root,
212
- pollMs: 50,
213
- spawnSession: async (opts) => { spawnCalls.push(opts); return { ok: true, exit_code: 0 }; },
214
- });
215
- try {
216
- enqueueTick({ cadence: "totally-unknown-thing", source: "manual", agentRoot: root });
217
- const ok = await waitFor(() => consumer.getStats().dlq >= 1);
218
- assert.ok(ok);
219
- assert.equal(spawnCalls.length, 0);
220
- } finally {
221
- await consumer.stop();
222
- await rmRoot(root);
223
- }
224
- });
225
-
226
- // ---------------------------------------------------------------------------
227
- // Spawn failures
228
- // ---------------------------------------------------------------------------
229
-
230
- test("spawn failure retries within the budget, then DLQs", async () => {
231
- const root = await makeAgentRoot();
232
- plantPrompt(root, "weekly-strategic-memo");
233
- // Disable back-off + raise circuit threshold so the test exercises the
234
- // retry-then-DLQ path without waiting for back-off windows. The
235
- // real defaults (30s/2m back-off, 3-failure circuit) are exercised by
236
- // dedicated tests below.
237
- const consumer = startConsumer({
238
- agentRoot: root,
239
- pollMs: 25,
240
- backoffSchedule: [0, 0, 0],
241
- circuitThreshold: 999,
242
- maxAttempts: 2,
243
- spawnSession: async () => ({ ok: false, exit_code: 1, error: "always-fail", duration_ms: 1 }),
244
- });
245
- try {
246
- enqueueTick({ cadence: "weekly-strategic-memo", source: "launchd", agentRoot: root });
247
- const ok = await waitFor(() => consumer.getStats().dlq >= 1, { timeoutMs: 15_000 });
248
- assert.ok(ok, `event should DLQ eventually; stats=${JSON.stringify(consumer.getStats())}`);
249
- assert.ok(consumer.getStats().spawn_failures >= 1);
250
- } finally {
251
- await consumer.stop();
252
- await rmRoot(root);
253
- }
254
- });
255
-
256
- test("circuit breaker opens after consecutive failures and blocks further spawns", async () => {
257
- const root = await makeAgentRoot();
258
- plantPrompt(root, "weekly-strategic-memo");
259
- let spawnCount = 0;
260
- const consumer = startConsumer({
261
- agentRoot: root,
262
- pollMs: 20,
263
- backoffSchedule: [0, 0, 0],
264
- circuitThreshold: 2,
265
- circuitDurationMs: 60_000, // 1 min — long enough for the assertion window
266
- maxAttempts: 1, // each event DLQs on first failure so we don't conflate retry-counts
267
- spawnSession: async () => { spawnCount++; return { ok: false, exit_code: 1, error: "fail", duration_ms: 1 }; },
268
- });
269
- try {
270
- // Enqueue 5 events; circuit should open after 2 failures, blocking the rest.
271
- for (let i = 0; i < 5; i++) {
272
- enqueueTick({ cadence: "weekly-strategic-memo", source: "launchd", agentRoot: root });
273
- }
274
- const opened = await waitFor(() => consumer.getStats().skipped_circuit_open >= 1, { timeoutMs: 10_000 });
275
- assert.ok(opened, `circuit should open; stats=${JSON.stringify(consumer.getStats())}`);
276
- // Spawn count must NOT keep climbing once the circuit is open.
277
- const spawnsAtOpen = spawnCount;
278
- await new Promise((r) => setTimeout(r, 500));
279
- assert.equal(spawnCount, spawnsAtOpen, `spawns must stop once circuit opens (was ${spawnsAtOpen}, now ${spawnCount})`);
280
- } finally {
281
- await consumer.stop();
282
- await rmRoot(root);
283
- }
284
- });
285
-
286
- test("back-off skips re-spawning until the cooldown elapses", async () => {
287
- const root = await makeAgentRoot();
288
- plantPrompt(root, "weekly-strategic-memo");
289
- let spawnCount = 0;
290
- const consumer = startConsumer({
291
- agentRoot: root,
292
- pollMs: 20,
293
- backoffSchedule: [0, 300, 300], // 300ms cooldown after each failure
294
- circuitThreshold: 999,
295
- maxAttempts: 1,
296
- spawnSession: async () => { spawnCount++; return { ok: false, exit_code: 1, error: "fail", duration_ms: 1 }; },
297
- });
298
- try {
299
- // Enqueue 2 events back-to-back. The 1st triggers a spawn (fails). The
300
- // 2nd should be held back by the 300ms back-off window.
301
- enqueueTick({ cadence: "weekly-strategic-memo", source: "launchd", agentRoot: root });
302
- enqueueTick({ cadence: "weekly-strategic-memo", source: "launchd", agentRoot: root });
303
- await waitFor(() => spawnCount >= 1, { timeoutMs: 5_000 });
304
- const spawnsBeforeWait = spawnCount;
305
- // During the back-off window no new spawn should fire.
306
- await new Promise((r) => setTimeout(r, 150));
307
- assert.ok(spawnCount === spawnsBeforeWait, `spawns must wait for back-off (was ${spawnsBeforeWait}, now ${spawnCount})`);
308
- assert.ok(consumer.getStats().skipped_backoff >= 1, "skipped_backoff should be recorded");
309
- // After the window passes, the next event should be processed.
310
- await waitFor(() => spawnCount > spawnsBeforeWait, { timeoutMs: 5_000 });
311
- assert.ok(spawnCount > spawnsBeforeWait, "spawning resumes after back-off");
312
- } finally {
313
- await consumer.stop();
314
- await rmRoot(root);
315
- }
316
- });
317
-
318
- // ---------------------------------------------------------------------------
319
- // Emergency stop
320
- // ---------------------------------------------------------------------------
321
-
322
- test("consumer skips processing while .emergency-stop exists", async () => {
323
- const root = await makeAgentRoot();
324
- writeFileSync(join(root, ".emergency-stop"), "now");
325
- plantPrompt(root, "weekly-strategic-memo");
326
- let spawnCount = 0;
327
- const consumer = startConsumer({
328
- agentRoot: root,
329
- pollMs: 50,
330
- spawnSession: async () => { spawnCount++; return { ok: true, exit_code: 0 }; },
331
- });
332
- try {
333
- // Enqueue directly to the inbox: the bus's emergency-stop check is on
334
- // enqueue, so we must bypass it. Drop a file straight in inbox/.
335
- const paths = getBusPaths(root);
336
- writeFileSync(join(paths.inbox, "evt-test.json"), JSON.stringify({
337
- id: "evt-test", type: "cadence_tick", source: "manual", ts: new Date().toISOString(),
338
- cadence: "weekly-strategic-memo", workflow: null, correlation_id: null,
339
- priority: "normal", metadata: {}, attempts: 0,
340
- }));
341
- await new Promise((r) => setTimeout(r, 300));
342
- const stats = consumer.getStats();
343
- assert.equal(spawnCount, 0, "no spawn during emergency stop");
344
- assert.ok(stats.skipped_emergency_stop >= 1);
345
- assert.equal(listInbox(root).length, 1, "event remains in inbox until stop lifts");
346
- } finally {
347
- await consumer.stop();
348
- await rmRoot(root);
349
- }
350
- });
351
-
352
- test("consumer resumes after .emergency-stop is removed", async () => {
353
- const root = await makeAgentRoot();
354
- writeFileSync(join(root, ".emergency-stop"), "now");
355
- plantPrompt(root, "weekly-strategic-memo");
356
- let spawnCount = 0;
357
- const consumer = startConsumer({
358
- agentRoot: root,
359
- pollMs: 25,
360
- spawnSession: async () => { spawnCount++; return { ok: true, exit_code: 0 }; },
361
- });
362
- try {
363
- const paths = getBusPaths(root);
364
- writeFileSync(join(paths.inbox, "evt-test.json"), JSON.stringify({
365
- id: "evt-test", type: "cadence_tick", source: "manual", ts: new Date().toISOString(),
366
- cadence: "weekly-strategic-memo", workflow: null, correlation_id: null,
367
- priority: "normal", metadata: {}, attempts: 0,
368
- }));
369
- await new Promise((r) => setTimeout(r, 200));
370
- assert.equal(spawnCount, 0);
371
- // Lift the stop.
372
- await fsp.unlink(join(root, ".emergency-stop"));
373
- const ok = await waitFor(() => spawnCount >= 1);
374
- assert.ok(ok, "should process after stop lifts");
375
- assert.ok(consumer.getStats().escalated >= 1);
376
- } finally {
377
- await consumer.stop();
378
- await rmRoot(root);
379
- }
380
- });
381
-
382
- // ---------------------------------------------------------------------------
383
- // Stale claim recovery on tick
384
- // ---------------------------------------------------------------------------
385
-
386
- test("consumer recovers stale claims on its periodic sweep", async () => {
387
- const root = await makeAgentRoot();
388
- // Plant a stale claim directly.
389
- const paths = getBusPaths(root);
390
- mkdirSync(paths.claimed, { recursive: true });
391
- const stalePath = join(paths.claimed, "evt-stale.json");
392
- writeFileSync(stalePath, JSON.stringify({
393
- id: "evt-stale", cadence: "cadence-bus-heartbeat",
394
- source: "manual", ts: "2026-01-01T00:00:00.000Z",
395
- workflow: null, correlation_id: null, priority: "normal",
396
- metadata: {}, attempts: 1, type: "cadence_tick",
397
- }));
398
- const oldMs = Date.now() - 60 * 60 * 1000; // 1h old
399
- await fsp.utimes(stalePath, new Date(oldMs), new Date(oldMs));
400
-
401
- const consumer = startConsumer({
402
- agentRoot: root, pollMs: 50,
403
- spawnSession: async () => ({ ok: true, exit_code: 0 }),
404
- });
405
- try {
406
- // tickOnce manually so we don't depend on the periodic recovery timer.
407
- await consumer.tickOnce();
408
- const ok = await waitFor(() => consumer.getStats().inline >= 1, { timeoutMs: 5_000 });
409
- assert.ok(ok, "stale claim should be recovered and processed");
410
- } finally {
411
- await consumer.stop();
412
- await rmRoot(root);
413
- }
414
- });
415
-
416
- // ---------------------------------------------------------------------------
417
- // Audit L6 — a known-active claim must NOT be swept by stale recovery, while a
418
- // genuinely stale (crashed-handler) claim IS recovered.
419
- // ---------------------------------------------------------------------------
420
-
421
- /** Plant a claimed/<id>.json with a given mtime (ms). */
422
- async function plantClaim(paths, id, ageMs) {
423
- mkdirSync(paths.claimed, { recursive: true });
424
- const p = join(paths.claimed, `${id}.json`);
425
- writeFileSync(p, JSON.stringify({
426
- id, cadence: "weekly-strategic-memo",
427
- source: "manual", ts: "2026-01-01T00:00:00.000Z",
428
- workflow: null, correlation_id: null, priority: "normal",
429
- metadata: {}, attempts: 1, type: "cadence_tick",
430
- }));
431
- const when = new Date(Date.now() - ageMs);
432
- await fsp.utimes(p, when, when);
433
- return p;
434
- }
435
-
436
- test("L6: an in-flight claim is kept fresh and not recovered, but a stale crashed claim is", async () => {
437
- const root = await makeAgentRoot();
438
- const paths = getBusPaths(root);
439
-
440
- const consumer = startConsumer({
441
- agentRoot: root,
442
- pollMs: 60_000, // don't let the poll loop drain/recover on its own
443
- heartbeatMs: 60_000,
444
- recoveryMs: 60_000,
445
- spawnSession: async () => ({ ok: true, exit_code: 0 }),
446
- });
447
- try {
448
- // Plant the claims AFTER startConsumer: startConsumer runs an initial
449
- // recoverStaleClaimsGuarded() at construction time, and at that point no id
450
- // is marked in-flight — so a pre-planted aged claim would be swept before
451
- // the test could mark it. Plant + mark here, then drive recovery manually.
452
- //
453
- // ACTIVE: a claim the consumer knows is in-flight (long-running escalate).
454
- // Its mtime is old enough to look stale to the mtime fallback alone.
455
- const activePath = await plantClaim(paths, "evt-active", 60 * 60 * 1000); // 1h old
456
- // STALE: a genuinely crashed handler — old mtime, NOT in the in-flight set.
457
- await plantClaim(paths, "evt-stale", 60 * 60 * 1000); // 1h old
458
-
459
- // Mark evt-active as in-flight, exactly as escalate() would.
460
- consumer._markInFlight("evt-active");
461
-
462
- const activeMtimeBefore = statSync(activePath).mtimeMs;
463
-
464
- // Run the guarded recovery directly (deterministic; no real spawn).
465
- const out = consumer._recoverStaleClaimsGuarded();
466
-
467
- // The active claim must have had its mtime bumped to ~now (kept fresh) and
468
- // must still be present in claimed/.
469
- const activeMtimeAfter = statSync(activePath).mtimeMs;
470
- assert.ok(
471
- activeMtimeAfter > activeMtimeBefore,
472
- `active claim mtime should be refreshed (before ${activeMtimeBefore}, after ${activeMtimeAfter})`,
473
- );
474
- const claimedNow = listClaimed(root);
475
- assert.ok(claimedNow.includes("evt-active"), "in-flight claim must survive recovery");
476
-
477
- // The genuinely stale claim must have been recovered (removed from claimed/).
478
- assert.ok(!claimedNow.includes("evt-stale"), "crashed-handler claim must be recovered");
479
- assert.ok(out.scanned >= 1, `recovery should have scanned claims; out=${JSON.stringify(out)}`);
480
-
481
- // Once it's no longer in-flight, the previously-active claim becomes
482
- // eligible again: backdate its mtime and recover.
483
- consumer._clearInFlight("evt-active");
484
- const old = new Date(Date.now() - 60 * 60 * 1000);
485
- await fsp.utimes(activePath, old, old);
486
- consumer._recoverStaleClaimsGuarded();
487
- assert.ok(!listClaimed(root).includes("evt-active"), "claim recovers after it stops being in-flight");
488
- } finally {
489
- await consumer.stop();
490
- await rmRoot(root);
491
- }
492
- });
493
-
494
- // ---------------------------------------------------------------------------
495
- // Health
496
- // ---------------------------------------------------------------------------
497
-
498
- test("consumer writes a heartbeat to state/cadence-bus/health.json", async () => {
499
- const root = await makeAgentRoot();
500
- const consumer = startConsumer({
501
- agentRoot: root,
502
- pollMs: 100,
503
- heartbeatMs: 50, // force frequent heartbeats so the test doesn't drag
504
- spawnSession: async () => ({ ok: true, exit_code: 0 }),
505
- });
506
- try {
507
- const ok = await waitFor(async () => {
508
- try {
509
- const raw = await fsp.readFile(join(root, "state/cadence-bus/health.json"), "utf-8");
510
- const h = JSON.parse(raw);
511
- return typeof h.ts === "string" && h.version;
512
- } catch { return false; }
513
- });
514
- assert.ok(ok, "health.json must be written");
515
- } finally {
516
- await consumer.stop();
517
- await rmRoot(root);
518
- }
519
- });
520
-
521
- // ---------------------------------------------------------------------------
522
- // Sub-session policy boundary
523
- // ---------------------------------------------------------------------------
524
-
525
- test("explicit reason is attached to event metadata before escalation", async () => {
526
- // The consumer must surface WHY a sub-session was spawned. For guarded
527
- // cadences this comes from the guard's reason/result. For unknown
528
- // cadences with prompts, the registry policy log line is sufficient,
529
- // but for audit visibility we attach guard data to event.metadata.
530
- const root = await makeAgentRoot();
531
- // Force a guard:escalate outcome via inbox-processor with pending items.
532
- // Default behaviour is now inline (reactive daemon owns inbox), so
533
- // override with INBOX_CADENCE_ESCALATE=1.
534
- mkdirSync(join(root, "state/inbox/internal"), { recursive: true });
535
- writeFileSync(join(root, "state/inbox/internal/x.json"), "{}");
536
- plantPrompt(root, "inbox-processor");
537
- const prevEnv = process.env.INBOX_CADENCE_ESCALATE;
538
- process.env.INBOX_CADENCE_ESCALATE = "1";
539
- const seen = [];
540
- const consumer = startConsumer({
541
- agentRoot: root, pollMs: 50,
542
- spawnSession: async (opts) => { seen.push(opts); return { ok: true, exit_code: 0 }; },
543
- });
544
- try {
545
- enqueueTick({ cadence: "inbox-processor", source: "launchd", agentRoot: root });
546
- const ok = await waitFor(() => seen.length > 0);
547
- assert.ok(ok);
548
- // The event archive should record guard_result so future audits can
549
- // trace why the sub-session ran.
550
- const procDir = join(root, "state/cadence-bus/processed");
551
- // Drill down by date
552
- const dates = (await fsp.readdir(procDir)).filter((n) => /^\d{4}-\d{2}-\d{2}$/.test(n));
553
- assert.ok(dates.length >= 1);
554
- const files = await fsp.readdir(join(procDir, dates[0]));
555
- const archive = JSON.parse(await fsp.readFile(join(procDir, dates[0], files[0]), "utf-8"));
556
- assert.equal(archive.result.decision, "escalated");
557
- // The consumer attaches the guard's outcome to the event metadata so
558
- // audits can trace exactly why a sub-session ran. We expect either a
559
- // recorded reason string or the full guard object.
560
- assert.ok(
561
- archive.metadata && (archive.metadata.reason || archive.metadata.guard),
562
- `expected metadata.reason or metadata.guard; got ${JSON.stringify(archive.metadata)}`,
563
- );
564
- } finally {
565
- await consumer.stop();
566
- await rmRoot(root);
567
- if (prevEnv === undefined) delete process.env.INBOX_CADENCE_ESCALATE;
568
- else process.env.INBOX_CADENCE_ESCALATE = prevEnv;
569
- }
570
- });
571
-
572
- // ---------------------------------------------------------------------------
573
- // 0.3 — cost telemetry: parse REAL token usage from a --output-format json run
574
- // so the ledger stops recording $0 forever (recovery C1). parseUsageFromStdout
575
- // reads the run's captured stdout file; on a parse failure it returns
576
- // { ok:false, reason } so the caller records a marker rather than fake zeros.
577
- // ---------------------------------------------------------------------------
578
-
579
- test("parseUsageFromStdout: reads real usage + total_cost_usd from a JSON result file", async () => {
580
- const root = await makeAgentRoot();
581
- try {
582
- const p = join(root, "out.json");
583
- writeFileSync(p, JSON.stringify({
584
- result: "tick done",
585
- usage: { input_tokens: 3100, output_tokens: 740, cache_read_input_tokens: 500 },
586
- total_cost_usd: 0.022,
587
- model: "claude-sonnet-4-6",
588
- }));
589
- const u = parseUsageFromStdout(p);
590
- assert.equal(u.ok, true);
591
- assert.equal(u.inputTokens, 3100);
592
- assert.equal(u.outputTokens, 740);
593
- assert.equal(u.cacheReadTokens, 500);
594
- assert.equal(u.totalCostUsd, 0.022);
595
- assert.equal(u.model, "sonnet");
596
- } finally { await rmRoot(root); }
597
- });
598
-
599
- test("parseUsageFromStdout: tolerates a banner before the JSON tail", async () => {
600
- const root = await makeAgentRoot();
601
- try {
602
- const p = join(root, "out.json");
603
- writeFileSync(p, `Some launchd banner line\n${JSON.stringify({ usage: { input_tokens: 10, output_tokens: 5 } })}`);
604
- const u = parseUsageFromStdout(p);
605
- assert.equal(u.ok, true);
606
- assert.equal(u.inputTokens, 10);
607
- assert.equal(u.outputTokens, 5);
608
- } finally { await rmRoot(root); }
609
- });
610
-
611
- test("parseUsageFromStdout: failure modes return ok:false with a reason (never fabricated zeros)", async () => {
612
- const root = await makeAgentRoot();
613
- try {
614
- const empty = join(root, "empty.json");
615
- writeFileSync(empty, "");
616
- assert.equal(parseUsageFromStdout(empty).reason, "empty-stdout");
617
-
618
- const plain = join(root, "plain.txt");
619
- writeFileSync(plain, "this is a plain-text reply, not json");
620
- assert.equal(parseUsageFromStdout(plain).ok, false);
621
-
622
- const noUsage = join(root, "nousage.json");
623
- writeFileSync(noUsage, JSON.stringify({ result: "x" }));
624
- assert.equal(parseUsageFromStdout(noUsage).reason, "no-usage-field");
625
-
626
- // A missing file does not throw — it reports a read failure.
627
- assert.equal(parseUsageFromStdout(join(root, "does-not-exist.json")).ok, false);
628
- } finally { await rmRoot(root); }
629
- });
630
-
631
- test("0.3: realSpawnSession argv requests --output-format json and records real usage end-to-end", async () => {
632
- // Drive the REAL (non-injected) spawner against a fake `claude` shim that
633
- // (a) echoes its argv to a side file so we can assert the spawn shape, and
634
- // (b) prints a --output-format json result so the cost ledger gets REAL
635
- // tokens. lib/claude-bin.mjs memoizes the resolved binary per process, so we
636
- // run the whole thing in a FRESH child process via `node -e` with CLAUDE_BIN
637
- // pointed at the shim (claude-bin's safety check requires an owner-only,
638
- // non-writable executable, which our shim satisfies).
639
- const { spawnSync } = await import("node:child_process");
640
- const root = await makeAgentRoot();
641
- try {
642
- plantPrompt(root, "weekly-strategic-memo");
643
- // A copy of the real tracker so the detached `record` call appends a row.
644
- mkdirSync(join(root, "scripts/cost"), { recursive: true });
645
- await fsp.copyFile(
646
- new URL("../cost/track-claude-usage.mjs", import.meta.url),
647
- join(root, "scripts/cost/track-claude-usage.mjs")
648
- );
649
- // ...and the shared billing contract it imports relative to itself.
650
- mkdirSync(join(root, "lib/cost"), { recursive: true });
651
- await fsp.copyFile(
652
- new URL("../../lib/cost/ledger-row.mjs", import.meta.url),
653
- join(root, "lib/cost/ledger-row.mjs")
654
- );
655
-
656
- const argvFile = join(root, "shim-argv.txt");
657
- const shim = join(root, "claude-shim");
658
- // The shim writes its argv, then prints a JSON usage object on stdout.
659
- writeFileSync(shim, [
660
- "#!/usr/bin/env node",
661
- `const fs=require("fs");`,
662
- `fs.writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2)));`,
663
- `process.stdout.write(JSON.stringify({ result: "ok", usage: { input_tokens: 1234, output_tokens: 99 }, total_cost_usd: 0.005, model: "claude-sonnet-4-6" }));`,
664
- "",
665
- ].join("\n"));
666
- await fsp.chmod(shim, 0o755);
667
-
668
- const driver = `
669
- import { startConsumer } from ${JSON.stringify(new URL("./cadence-consumer.mjs", import.meta.url).href)};
670
- import { enqueueTick } from ${JSON.stringify(new URL("../../lib/cadence-bus.mjs", import.meta.url).href)};
671
- const root = ${JSON.stringify(root)};
672
- const c = startConsumer({ agentRoot: root, pollMs: 30,
673
- governor: { admit: () => ({ decision: "ADMIT" }), defaultDeps: () => ({}) },
674
- rateGuard: { checkRateLimit: () => ({ allowed: true }), classifyStderr: () => false, recordRateLimit: () => {}, recordSuccess: () => {} },
675
- budgetGuard: { dailyStatus: () => ({ essentialOnly: false }) } });
676
- enqueueTick({ cadence: "weekly-strategic-memo", source: "test", agentRoot: root });
677
- const deadline = Date.now() + 8000;
678
- while (Date.now() < deadline && c.getStats().escalated < 1) { await new Promise(r => setTimeout(r, 30)); }
679
- await c.stop();
680
- process.exit(0);
681
- `;
682
- const res = spawnSync(process.execPath, ["--input-type=module", "-e", driver], {
683
- env: { ...process.env, CLAUDE_BIN: shim, AGENT_ROOT: root, MAESTRO_PREFER_SUBSCRIPTION_AUTH: "1" },
684
- timeout: 20_000,
685
- encoding: "utf-8",
686
- });
687
-
688
- // The spawn argv must request JSON output (so usage is capturable).
689
- const argv = JSON.parse(await fsp.readFile(argvFile, "utf-8"));
690
- assert.ok(argv.includes("--print"), `argv should include --print: ${res.stderr}`);
691
- const ofIdx = argv.indexOf("--output-format");
692
- assert.ok(ofIdx >= 0, "argv should request --output-format");
693
- assert.equal(argv[ofIdx + 1], "json");
694
-
695
- // And the ledger should carry the shim's REAL token counts (not 0).
696
- const date = new Date().toISOString().slice(0, 10);
697
- const ledger = join(root, "state/cost-tracking", `${date}.jsonl`);
698
- let body = "";
699
- for (let i = 0; i < 80 && !body.trim(); i++) {
700
- try { body = await fsp.readFile(ledger, "utf-8"); } catch { /* */ }
701
- if (!body.trim()) await new Promise((r) => setTimeout(r, 25));
702
- }
703
- assert.ok(body.trim(), `expected a cost row in the ledger; driver stderr: ${res.stderr}`);
704
- const row = JSON.parse(body.trim().split("\n").pop());
705
- assert.equal(row.source, "cadence-consumer");
706
- assert.equal(row.input_tokens, 1234, "REAL input tokens (not 0)");
707
- assert.equal(row.output_tokens, 99, "REAL output tokens (not 0)");
708
- assert.ok(row.estimated_usd > 0, `estimated_usd should be nonzero, got ${row.estimated_usd}`);
709
- } finally {
710
- await rmRoot(root);
711
- }
712
- });
713
-
714
- // ---------------------------------------------------------------------------
715
- // Phase 3-4 COVERAGE — routeCadenceSpawn drives the cadence sub-session model
716
- // through resolveChain when the agent opts into a `schema_version: 2` config.
717
- // No config / a v1 config returns null (stock-CLI cadence spawn, unchanged).
718
- // ---------------------------------------------------------------------------
719
-
720
- /** Write a v2 routing config (JSON, no js-yaml needed) into an agent root. */
721
- function writeV2CadenceConfig(root) {
722
- mkdirSync(join(root, "config"), { recursive: true });
723
- const cfg = {
724
- schema_version: 2,
725
- aliases: {
726
- frontier: "anthropic/claude-opus-4-8",
727
- default: "anthropic/claude-sonnet-4-6",
728
- fast: "anthropic/claude-haiku-4-5",
729
- },
730
- defaults: { needs_tool_use_for_sessions: true, data_class: "sensitive", cache_ttl: "1h" },
731
- backends: { anthropic: { allowed_data_classes: ["public", "internal", "sensitive"] } },
732
- routing_policy: [{ default: true, chain: ["default", "fast"] }],
733
- fallback_to_anthropic: true,
734
- };
735
- writeFileSync(join(root, "config/model-routing.json"), JSON.stringify(cfg, null, 2));
736
- }
737
-
738
- test("COVERAGE: routeCadenceSpawn returns null with no routing config (stock-CLI cadence spawn)", async () => {
739
- const root = await makeAgentRoot();
740
- try {
741
- assert.equal(routeCadenceSpawn(root, "weekly-strategic-memo"), null);
742
- } finally { await rmRoot(root); }
743
- });
744
-
745
- test("COVERAGE: routeCadenceSpawn resolves a v2 cadence to a catalog model + knobs + decision_id", async () => {
746
- const root = await makeAgentRoot();
747
- try {
748
- writeV2CadenceConfig(root);
749
- const t = routeCadenceSpawn(root, "weekly-strategic-memo");
750
- assert.ok(t, "v2 config produces a routing target");
751
- assert.equal(t.backend, "anthropic", "default rule resolves to the Anthropic session backend");
752
- assert.equal(t.modelFlag, "claude-sonnet-4-6", "routed to the v2 default (Sonnet) catalog id");
753
- assert.ok(typeof t.decisionId === "string" && t.decisionId.length > 0, "carries a decision_id");
754
- assert.ok(Number.isFinite(Number(t.maxTurns)) && Number(t.maxTurns) > 0, "carries a maxTurns knob");
755
- // An Anthropic session is not a third-party retarget → no BASE_URL injected.
756
- assert.ok(!(t.envForSpawn && t.envForSpawn.ANTHROPIC_BASE_URL), "Anthropic session keeps stock keychain auth");
757
- } finally { await rmRoot(root); }
758
- });
759
-
760
- test("COVERAGE: routeCadenceSpawn honours MAESTRO_ROUTER_FORCE_ANTHROPIC (kill switch)", async () => {
761
- const prev = process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC;
762
- process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC = "1";
763
- const root = await makeAgentRoot();
764
- try {
765
- writeV2CadenceConfig(root);
766
- const t = routeCadenceSpawn(root, "weekly-strategic-memo");
767
- // Kill switch → an Anthropic-only decision; still a usable target, never a
768
- // third-party retarget.
769
- assert.ok(t, "kill switch still yields an Anthropic target");
770
- assert.equal(t.backend, "anthropic");
771
- assert.ok(!(t.envForSpawn && t.envForSpawn.ANTHROPIC_BASE_URL), "no third-party retarget under the kill switch");
772
- } finally {
773
- if (prev === undefined) delete process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC; else process.env.MAESTRO_ROUTER_FORCE_ANTHROPIC = prev;
774
- await rmRoot(root);
775
- }
776
- });