@ouro.bot/cli 0.1.0-alpha.8 → 0.1.0-alpha.800

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 (624) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +249 -176
  3. package/RepairGuide.ouro/agent.json +5 -0
  4. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  5. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  6. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  7. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  8. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  9. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  10. package/SerpentGuide.ouro/agent.json +83 -0
  11. package/SerpentGuide.ouro/psyche/SOUL.md +25 -0
  12. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +2 -2
  13. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  14. package/assets/bluebubbles-host +264 -0
  15. package/assets/ouroboros.png +0 -0
  16. package/changelog.json +5563 -0
  17. package/deploy/unraid/Dockerfile +48 -0
  18. package/deploy/unraid/README.txt +3012 -0
  19. package/deploy/unraid/audit-container-spec.sh +4 -0
  20. package/deploy/unraid/container-runtime.json +1 -0
  21. package/deploy/unraid/docker-man-template-transaction.mjs +526 -0
  22. package/deploy/unraid/docker-man-template-xml.cjs +105 -0
  23. package/deploy/unraid/migrate-sanctuary-bundle.mjs +60 -0
  24. package/deploy/unraid/ouro-events/bootstrap-spool.sh +92 -0
  25. package/deploy/unraid/ouro-events/emit-event.mjs +310 -0
  26. package/deploy/unraid/ouro-events/emit-usenet-event.sh +54 -0
  27. package/deploy/unraid/ouro-events/install-usenet-guard.sh +435 -0
  28. package/deploy/unraid/ouro-events/usenet-health.sh +176 -0
  29. package/deploy/unraid/sanctuary-acceptance-adapter.sh +43 -0
  30. package/deploy/unraid/sanctuary-acceptance-contract.json +198 -0
  31. package/deploy/unraid/sanctuary-acceptance-harness.sh +23 -0
  32. package/deploy/unraid/sanctuary-deployment-target.mjs +709 -0
  33. package/deploy/unraid/sanctuary-safe-rename.py +24 -0
  34. package/deploy/unraid/sanctuary-unit16-host-broker.mjs +2030 -0
  35. package/deploy/unraid/sanctuary-unit16-run.sh +560 -0
  36. package/deploy/unraid/sanctuary-unit18-target-audit.sh +27 -0
  37. package/deploy/unraid/sanctuary.ouro/agent.json +24 -0
  38. package/deploy/unraid/sanctuary.ouro/arc/README.md +3 -0
  39. package/deploy/unraid/sanctuary.ouro/bundle-meta.json +5 -0
  40. package/deploy/unraid/sanctuary.ouro/habits/sanctuary-health.md +8 -0
  41. package/deploy/unraid/sanctuary.ouro/provider-readiness.json +11 -0
  42. package/deploy/unraid/sanctuary.ouro/psyche/ASPIRATIONS.md +5 -0
  43. package/deploy/unraid/sanctuary.ouro/psyche/IDENTITY.md +5 -0
  44. package/deploy/unraid/sanctuary.ouro/psyche/LORE.md +11 -0
  45. package/deploy/unraid/sanctuary.ouro/psyche/SOUL.md +25 -0
  46. package/deploy/unraid/sanctuary.ouro/psyche/TACIT.md +11 -0
  47. package/deploy/unraid/sanctuary.ouro/state/policy/steward.json +7 -0
  48. package/deploy/unraid/sanctuary.ouro/tool-profiles.json +23 -0
  49. package/deploy/unraid/sanctuary.xml +27 -0
  50. package/dist/a2a/card.js +57 -0
  51. package/dist/a2a/client.js +180 -0
  52. package/dist/a2a/config.js +50 -0
  53. package/dist/a2a/delegation-stores.js +56 -0
  54. package/dist/a2a/did-resolution.js +93 -0
  55. package/dist/a2a/identity.js +170 -0
  56. package/dist/a2a/inbound-share.js +107 -0
  57. package/dist/a2a/mission-result-wire.js +196 -0
  58. package/dist/a2a/onboarding.js +115 -0
  59. package/dist/a2a/pin-store.js +132 -0
  60. package/dist/a2a/seen-ledger.js +120 -0
  61. package/dist/a2a/server.js +604 -0
  62. package/dist/a2a/task-store.js +69 -0
  63. package/dist/a2a/transport.js +45 -0
  64. package/dist/a2a/types.js +3 -0
  65. package/dist/arc/attention-types.js +8 -0
  66. package/dist/arc/cares.js +360 -0
  67. package/dist/arc/episodes.js +118 -0
  68. package/dist/arc/evolution.js +490 -0
  69. package/dist/arc/flight-recorder.js +1034 -0
  70. package/dist/arc/intentions.js +134 -0
  71. package/dist/arc/json-store.js +117 -0
  72. package/dist/arc/obligations.js +386 -0
  73. package/dist/arc/packets.js +336 -0
  74. package/dist/arc/presence.js +185 -0
  75. package/dist/arc/task-lifecycle.js +57 -0
  76. package/dist/commerce/store.js +755 -0
  77. package/dist/commerce/types.js +3 -0
  78. package/dist/heart/active-work.js +1009 -0
  79. package/dist/heart/agent-entry.js +252 -3
  80. package/dist/heart/approval-files.js +113 -0
  81. package/dist/heart/approval-store.js +950 -0
  82. package/dist/heart/attachments/image-normalize.js +194 -0
  83. package/dist/heart/attachments/materialize.js +97 -0
  84. package/dist/heart/attachments/originals.js +88 -0
  85. package/dist/heart/attachments/render.js +29 -0
  86. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  87. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  88. package/dist/heart/attachments/sources/index.js +18 -0
  89. package/dist/heart/attachments/sources/telegram.js +71 -0
  90. package/dist/heart/attachments/store.js +132 -0
  91. package/dist/heart/attachments/types.js +93 -0
  92. package/dist/heart/auth/auth-flow.js +495 -0
  93. package/dist/heart/autonomy-budget.js +478 -0
  94. package/dist/heart/awaiting/await-alert.js +148 -0
  95. package/dist/heart/awaiting/await-expiry.js +143 -0
  96. package/dist/heart/awaiting/await-loader.js +91 -0
  97. package/dist/heart/awaiting/await-parser.js +149 -0
  98. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  99. package/dist/heart/awaiting/await-scheduler.js +382 -0
  100. package/dist/heart/background-operations.js +281 -0
  101. package/dist/heart/bridges/manager.js +478 -0
  102. package/dist/heart/bridges/state-machine.js +135 -0
  103. package/dist/heart/bridges/store.js +135 -0
  104. package/dist/heart/bundle-state.js +168 -0
  105. package/dist/heart/commitments.js +135 -0
  106. package/dist/heart/config-registry.js +331 -0
  107. package/dist/heart/config.js +195 -137
  108. package/dist/heart/context-loss-gauntlet.js +387 -0
  109. package/dist/heart/context-loss-sentinel.js +1157 -0
  110. package/dist/heart/core.js +2257 -338
  111. package/dist/heart/cross-chat-delivery.js +133 -0
  112. package/dist/heart/daemon/agent-config-check.js +451 -0
  113. package/dist/heart/daemon/agent-discovery.js +263 -0
  114. package/dist/heart/daemon/agent-service.js +542 -0
  115. package/dist/heart/daemon/agentic-repair.js +547 -0
  116. package/dist/heart/daemon/await-private-wake.js +59 -0
  117. package/dist/heart/daemon/bluebubbles-cli-integration.js +71 -0
  118. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  119. package/dist/heart/daemon/bluebubbles-host-protocol.js +433 -0
  120. package/dist/heart/daemon/bluebubbles-host.js +273 -0
  121. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  122. package/dist/heart/daemon/cadence.js +180 -0
  123. package/dist/heart/daemon/cli-defaults.js +836 -0
  124. package/dist/heart/daemon/cli-desk.js +322 -0
  125. package/dist/heart/daemon/cli-exec.js +8730 -0
  126. package/dist/heart/daemon/cli-help.js +710 -0
  127. package/dist/heart/daemon/cli-parse.js +2719 -0
  128. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  129. package/dist/heart/daemon/cli-render.js +777 -0
  130. package/dist/heart/daemon/cli-types.js +8 -0
  131. package/dist/heart/daemon/connect-bay.js +323 -0
  132. package/dist/heart/daemon/container-credential-bootstrap.js +273 -0
  133. package/dist/heart/daemon/container-healthcheck.js +112 -0
  134. package/dist/heart/daemon/container-runtime.js +97 -0
  135. package/dist/heart/daemon/container-spec-auditor-main.js +170 -0
  136. package/dist/heart/daemon/container-spec-auditor.js +236 -0
  137. package/dist/heart/daemon/daemon-bootstrap-startup.js +107 -0
  138. package/dist/heart/daemon/daemon-cli.js +30 -786
  139. package/dist/heart/daemon/daemon-entry.js +971 -13
  140. package/dist/heart/daemon/daemon-health.js +186 -0
  141. package/dist/heart/daemon/daemon-rollup.js +57 -0
  142. package/dist/heart/daemon/daemon-runtime-sync.js +287 -0
  143. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  144. package/dist/heart/daemon/daemon.js +2156 -28
  145. package/dist/heart/daemon/dns-workflow.js +394 -0
  146. package/dist/heart/daemon/doctor-types.js +8 -0
  147. package/dist/heart/daemon/doctor.js +1755 -0
  148. package/dist/heart/daemon/freshness.js +345 -0
  149. package/dist/heart/daemon/habit-private-wake.js +61 -0
  150. package/dist/heart/daemon/health-monitor.js +142 -11
  151. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  152. package/dist/heart/daemon/hooks/bundle-meta.js +226 -0
  153. package/dist/heart/daemon/http-health-probe.js +80 -0
  154. package/dist/heart/daemon/human-command-screens.js +234 -0
  155. package/dist/heart/daemon/human-readiness.js +114 -0
  156. package/dist/heart/daemon/inner-status.js +78 -0
  157. package/dist/heart/daemon/interactive-repair.js +394 -0
  158. package/dist/heart/daemon/launchd.js +188 -0
  159. package/dist/heart/daemon/log-tailer.js +82 -12
  160. package/dist/heart/daemon/logs-prune.js +132 -0
  161. package/dist/heart/daemon/mcp-canary.js +524 -0
  162. package/dist/heart/daemon/message-router.js +80 -11
  163. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  164. package/dist/heart/daemon/os-cron-deps.js +135 -0
  165. package/dist/heart/daemon/os-cron.js +22 -14
  166. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  167. package/dist/heart/daemon/ouro-entry.js +3 -1
  168. package/dist/heart/daemon/plugin-cli.js +432 -0
  169. package/dist/heart/daemon/process-manager.js +739 -54
  170. package/dist/heart/daemon/provider-discovery.js +137 -0
  171. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  172. package/dist/heart/daemon/prunable-bundle.js +144 -0
  173. package/dist/heart/daemon/pulse.js +511 -0
  174. package/dist/heart/daemon/readiness-repair.js +365 -0
  175. package/dist/heart/daemon/run-hooks.js +39 -0
  176. package/dist/heart/daemon/runtime-logging.js +92 -16
  177. package/dist/heart/daemon/runtime-metadata.js +191 -0
  178. package/dist/{repertoire/tasks/lifecycle.js → heart/daemon/runtime-mode.js} +37 -39
  179. package/dist/heart/daemon/safe-mode.js +161 -0
  180. package/dist/heart/daemon/sanctuary-acceptance-adapter.js +2609 -0
  181. package/dist/heart/daemon/sanctuary-acceptance-harness.js +1866 -0
  182. package/dist/heart/daemon/sanctuary-acceptance-marker.js +267 -0
  183. package/dist/heart/daemon/sanctuary-acceptance-scenarios.js +976 -0
  184. package/dist/heart/daemon/sanctuary-bundle-migration.js +728 -0
  185. package/dist/heart/daemon/sanctuary-package-management.js +103 -0
  186. package/dist/heart/daemon/sanctuary-scheduler-liveness.js +227 -0
  187. package/dist/heart/daemon/sanctuary-scheduler-origin.js +132 -0
  188. package/dist/heart/daemon/sense-manager.js +948 -0
  189. package/dist/heart/daemon/session-id-resolver.js +131 -0
  190. package/dist/heart/daemon/skill-management-installer.js +94 -0
  191. package/dist/heart/daemon/socket-client.js +370 -0
  192. package/dist/heart/daemon/stale-bundle-prune.js +113 -0
  193. package/dist/heart/daemon/startup-tui.js +339 -0
  194. package/dist/heart/daemon/supercronic-supervisor.js +282 -0
  195. package/dist/heart/daemon/task-scheduler.js +117 -39
  196. package/dist/heart/daemon/terminal-ui.js +499 -0
  197. package/dist/heart/daemon/thoughts.js +591 -0
  198. package/dist/heart/daemon/up-progress.js +366 -0
  199. package/dist/heart/daemon/vault-items.js +56 -0
  200. package/dist/heart/delegation.js +59 -0
  201. package/dist/heart/external-events/router.js +1414 -0
  202. package/dist/heart/habits/habit-cancel.js +810 -0
  203. package/dist/heart/habits/habit-lifecycle.js +1327 -0
  204. package/dist/heart/habits/habit-migration.js +194 -0
  205. package/dist/heart/habits/habit-parser.js +278 -0
  206. package/dist/heart/habits/habit-runtime-state.js +93 -0
  207. package/dist/heart/habits/habit-scheduler.js +653 -0
  208. package/dist/heart/habits/habit-session-summary.js +318 -0
  209. package/dist/heart/habits/habit-session.js +636 -0
  210. package/dist/heart/{daemon → hatch}/hatch-animation.js +10 -3
  211. package/dist/heart/{daemon → hatch}/hatch-flow.js +57 -139
  212. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  213. package/dist/heart/hatch/specialist-orchestrator.js +129 -0
  214. package/dist/heart/hatch/specialist-prompt.js +102 -0
  215. package/dist/heart/hatch/specialist-tools.js +318 -0
  216. package/dist/heart/identity.js +297 -67
  217. package/dist/heart/kept-notes.js +289 -0
  218. package/dist/heart/kicks.js +2 -20
  219. package/dist/heart/machine-identity.js +161 -0
  220. package/dist/heart/mail-import-discovery.js +353 -0
  221. package/dist/heart/mailbox/mailbox-http-hooks.js +98 -0
  222. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  223. package/dist/heart/mailbox/mailbox-http-routes.js +398 -0
  224. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  225. package/dist/heart/mailbox/mailbox-http-transport.js +129 -0
  226. package/dist/heart/mailbox/mailbox-http.js +99 -0
  227. package/dist/heart/mailbox/mailbox-read.js +39 -0
  228. package/dist/heart/mailbox/mailbox-types.js +27 -0
  229. package/dist/heart/mailbox/mailbox-view.js +197 -0
  230. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  231. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  232. package/dist/heart/mailbox/readers/mail.js +375 -0
  233. package/dist/heart/mailbox/readers/runtime-readers.js +823 -0
  234. package/dist/heart/mailbox/readers/sessions.js +232 -0
  235. package/dist/heart/mailbox/readers/shared.js +111 -0
  236. package/dist/heart/mcp/mcp-server.js +696 -0
  237. package/dist/heart/migrate-config.js +100 -0
  238. package/dist/heart/model-capabilities.js +59 -0
  239. package/dist/heart/orientation-frame.js +345 -0
  240. package/dist/heart/platform.js +81 -0
  241. package/dist/heart/primitives.js +1 -1
  242. package/dist/heart/private-runtime/decision-renderer.js +158 -0
  243. package/dist/heart/private-runtime/index.js +18 -0
  244. package/dist/heart/private-runtime/ledger.js +221 -0
  245. package/dist/heart/private-runtime/policy.js +252 -0
  246. package/dist/heart/private-runtime/types.js +2 -0
  247. package/dist/heart/progress-story.js +42 -0
  248. package/dist/heart/provider-attempt.js +137 -0
  249. package/dist/heart/provider-binding-resolver.js +273 -0
  250. package/dist/heart/provider-credentials.js +449 -0
  251. package/dist/heart/provider-failover.js +311 -0
  252. package/dist/heart/provider-models.js +96 -0
  253. package/dist/heart/provider-ping.js +265 -0
  254. package/dist/heart/provider-readiness-cache.js +119 -0
  255. package/dist/heart/provider-visibility.js +188 -0
  256. package/dist/heart/providers/anthropic-token.js +131 -0
  257. package/dist/heart/providers/anthropic.js +236 -58
  258. package/dist/heart/providers/azure.js +104 -13
  259. package/dist/heart/providers/error-classification.js +127 -0
  260. package/dist/heart/providers/github-copilot.js +145 -0
  261. package/dist/heart/providers/minimax-vlm.js +189 -0
  262. package/dist/heart/providers/minimax.js +29 -7
  263. package/dist/heart/providers/openai-codex-token.js +349 -0
  264. package/dist/heart/providers/openai-codex.js +63 -39
  265. package/dist/heart/providers/openai-compatible.js +177 -0
  266. package/dist/heart/run-ledger.js +247 -0
  267. package/dist/heart/runtime-capability-check.js +170 -0
  268. package/dist/heart/runtime-credentials.js +607 -0
  269. package/dist/heart/runtime-cwd.js +87 -0
  270. package/dist/heart/sense-truth.js +79 -0
  271. package/dist/heart/session-activity.js +235 -0
  272. package/dist/heart/session-events.js +1318 -0
  273. package/dist/heart/session-playback-cli-main.js +5 -0
  274. package/dist/heart/session-playback-cli.js +36 -0
  275. package/dist/heart/session-playback.js +231 -0
  276. package/dist/heart/session-stats-cli-main.js +5 -0
  277. package/dist/heart/session-stats.js +182 -0
  278. package/dist/heart/session-transcript.js +133 -0
  279. package/dist/heart/start-of-turn-packet.js +372 -0
  280. package/dist/heart/steward-policy.js +302 -0
  281. package/dist/heart/streaming.js +682 -207
  282. package/dist/heart/structured-output.js +196 -0
  283. package/dist/heart/sync-classification.js +176 -0
  284. package/dist/heart/sync.js +449 -0
  285. package/dist/heart/target-resolution.js +127 -0
  286. package/dist/heart/tempo.js +93 -0
  287. package/dist/heart/temporal-view.js +41 -0
  288. package/dist/heart/timeouts.js +101 -0
  289. package/dist/heart/tool-activity-callbacks.js +59 -0
  290. package/dist/heart/tool-approval.js +342 -0
  291. package/dist/heart/tool-description.js +155 -0
  292. package/dist/heart/tool-friction.js +55 -0
  293. package/dist/heart/tool-loop.js +200 -0
  294. package/dist/heart/turn-context.js +481 -0
  295. package/dist/heart/turn-coordinator.js +28 -0
  296. package/dist/heart/versioning/ouro-bot-global-installer.js +129 -0
  297. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  298. package/dist/heart/versioning/ouro-path-installer.js +432 -0
  299. package/dist/heart/versioning/ouro-recovery-launcher.js +76 -0
  300. package/dist/heart/{daemon → versioning}/ouro-uti.js +11 -2
  301. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  302. package/dist/heart/versioning/staged-restart.js +146 -0
  303. package/dist/heart/versioning/update-checker.js +116 -0
  304. package/dist/heart/versioning/update-hooks.js +154 -0
  305. package/dist/heart/versioning/version-intent.js +114 -0
  306. package/dist/heart/versioning/wrapper-publish-guard.js +86 -0
  307. package/dist/heart/work-card.js +380 -0
  308. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  309. package/dist/mailbox-ui/assets/index-J8zDwHmE.js +1 -0
  310. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  311. package/dist/mailbox-ui/index.html +16 -0
  312. package/dist/mailroom/attention.js +167 -0
  313. package/dist/mailroom/autonomy.js +209 -0
  314. package/dist/mailroom/blob-store.js +889 -0
  315. package/dist/mailroom/body-cache.js +61 -0
  316. package/dist/mailroom/cache-sync-cli.js +58 -0
  317. package/dist/mailroom/core.js +803 -0
  318. package/dist/mailroom/entry.js +160 -0
  319. package/dist/mailroom/file-store.js +568 -0
  320. package/dist/mailroom/hosted-cache-sync.js +384 -0
  321. package/dist/mailroom/mbox-import.js +393 -0
  322. package/dist/mailroom/migration.js +164 -0
  323. package/dist/mailroom/outbound.js +380 -0
  324. package/dist/mailroom/policy.js +263 -0
  325. package/dist/mailroom/reader.js +292 -0
  326. package/dist/mailroom/search-cache.js +513 -0
  327. package/dist/mailroom/search-relevance.js +319 -0
  328. package/dist/mailroom/smtp-ingress.js +176 -0
  329. package/dist/mailroom/source-state.js +176 -0
  330. package/dist/mailroom/thread.js +109 -0
  331. package/dist/mailroom/travel-extract.js +89 -0
  332. package/dist/mind/bundle-manifest.js +93 -1
  333. package/dist/mind/context.js +287 -104
  334. package/dist/mind/desk-section.js +362 -0
  335. package/dist/mind/diary-integrity.js +60 -0
  336. package/dist/mind/{memory.js → diary.js} +90 -98
  337. package/dist/mind/embedding-provider.js +60 -0
  338. package/dist/mind/file-state.js +179 -0
  339. package/dist/mind/first-impressions.js +16 -2
  340. package/dist/mind/{associative-recall.js → note-search.js} +61 -60
  341. package/dist/mind/obligation-steering.js +227 -0
  342. package/dist/mind/pending.js +102 -9
  343. package/dist/mind/phrases.js +1 -0
  344. package/dist/mind/prompt-budget.js +479 -0
  345. package/dist/mind/prompt-refresh.js +3 -2
  346. package/dist/mind/prompt.js +1377 -140
  347. package/dist/mind/provenance-trust.js +26 -0
  348. package/dist/mind/record-paths.js +312 -0
  349. package/dist/mind/scrutiny.js +173 -0
  350. package/dist/mind/session-transaction.js +415 -0
  351. package/dist/mind/token-estimate.js +8 -12
  352. package/dist/nerves/cli-logging.js +22 -3
  353. package/dist/nerves/coverage/audit-rules.js +15 -6
  354. package/dist/nerves/coverage/audit.js +28 -2
  355. package/dist/nerves/coverage/cli.js +1 -1
  356. package/dist/nerves/coverage/contract.js +5 -5
  357. package/dist/nerves/coverage/file-completeness.js +139 -5
  358. package/dist/nerves/coverage/run-artifacts.js +56 -36
  359. package/dist/nerves/coverage/source-scanner.js +4 -4
  360. package/dist/nerves/event-buffer.js +111 -0
  361. package/dist/nerves/index.js +305 -9
  362. package/dist/nerves/observation.js +20 -0
  363. package/dist/nerves/redact.js +79 -0
  364. package/dist/nerves/review/cli-main.js +5 -0
  365. package/dist/nerves/review/cli.js +156 -0
  366. package/dist/nerves/review/core.js +159 -0
  367. package/dist/nerves/runtime.js +17 -1
  368. package/dist/repertoire/ado-client.js +17 -56
  369. package/dist/repertoire/ado-semantic.js +16 -10
  370. package/dist/repertoire/api-client.js +97 -0
  371. package/dist/repertoire/bitwarden-store.js +1045 -0
  372. package/dist/repertoire/bundle-templates.js +71 -0
  373. package/dist/repertoire/bw-installer.js +180 -0
  374. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  375. package/dist/repertoire/coding/context-pack.js +331 -0
  376. package/dist/repertoire/coding/feedback.js +322 -0
  377. package/dist/repertoire/coding/index.js +18 -3
  378. package/dist/repertoire/coding/manager.js +228 -14
  379. package/dist/repertoire/coding/spawner.js +61 -14
  380. package/dist/repertoire/coding/tools.js +279 -12
  381. package/dist/repertoire/coding/workbench-client.js +272 -0
  382. package/dist/repertoire/coding/workbench-manager.js +346 -0
  383. package/dist/repertoire/commerce-errors.js +109 -0
  384. package/dist/repertoire/commerce-self-test.js +156 -0
  385. package/dist/repertoire/credential-access.js +178 -0
  386. package/dist/repertoire/data/ado-endpoints.json +188 -0
  387. package/dist/repertoire/desk/classifier.js +362 -0
  388. package/dist/repertoire/duffel-client.js +185 -0
  389. package/dist/repertoire/github-client.js +14 -55
  390. package/dist/repertoire/graph-client.js +11 -52
  391. package/dist/repertoire/guardrails.js +1083 -0
  392. package/dist/repertoire/mcp-client.js +295 -0
  393. package/dist/repertoire/mcp-manager.js +434 -0
  394. package/dist/repertoire/mcp-tools.js +83 -0
  395. package/dist/repertoire/plugin-mcp.js +175 -0
  396. package/dist/repertoire/plugins.js +253 -0
  397. package/dist/repertoire/relationship-authorization.js +194 -0
  398. package/dist/repertoire/shell-sessions.js +133 -0
  399. package/dist/repertoire/skills.js +45 -24
  400. package/dist/repertoire/stripe-client.js +131 -0
  401. package/dist/repertoire/tool-arguments.js +148 -0
  402. package/dist/repertoire/tool-results.js +29 -0
  403. package/dist/repertoire/tools-a2a.js +699 -0
  404. package/dist/repertoire/tools-attachments.js +322 -0
  405. package/dist/repertoire/tools-awaiting.js +575 -0
  406. package/dist/repertoire/tools-base.js +85 -707
  407. package/dist/repertoire/tools-bluebubbles.js +95 -0
  408. package/dist/repertoire/tools-bridge.js +144 -0
  409. package/dist/repertoire/tools-bundle.js +993 -0
  410. package/dist/repertoire/tools-commerce.js +253 -0
  411. package/dist/repertoire/tools-config.js +186 -0
  412. package/dist/repertoire/tools-continuity.js +575 -0
  413. package/dist/repertoire/tools-credential.js +383 -0
  414. package/dist/repertoire/tools-evolution.js +527 -0
  415. package/dist/repertoire/tools-files.js +344 -0
  416. package/dist/repertoire/tools-flight.js +290 -0
  417. package/dist/repertoire/tools-flow.js +119 -0
  418. package/dist/repertoire/tools-github.js +3 -8
  419. package/dist/repertoire/tools-habits.js +103 -0
  420. package/dist/repertoire/tools-mail.js +1828 -0
  421. package/dist/repertoire/tools-notes.js +485 -0
  422. package/dist/repertoire/tools-obligations.js +182 -0
  423. package/dist/repertoire/tools-orientation.js +31 -0
  424. package/dist/repertoire/tools-record.js +482 -0
  425. package/dist/repertoire/tools-rsvp.js +139 -0
  426. package/dist/repertoire/tools-runtime.js +150 -0
  427. package/dist/repertoire/tools-session.js +1108 -0
  428. package/dist/repertoire/tools-shell.js +133 -0
  429. package/dist/repertoire/tools-steward-policy.js +95 -0
  430. package/dist/repertoire/tools-stripe.js +224 -0
  431. package/dist/repertoire/tools-surface.js +369 -0
  432. package/dist/repertoire/tools-teams.js +67 -61
  433. package/dist/repertoire/tools-telegram-contacts.js +37 -0
  434. package/dist/repertoire/tools-travel.js +125 -0
  435. package/dist/repertoire/tools-trip.js +982 -0
  436. package/dist/repertoire/tools-unraid.js +484 -0
  437. package/dist/repertoire/tools-user-profile.js +146 -0
  438. package/dist/repertoire/tools-vault.js +40 -0
  439. package/dist/repertoire/tools-voice.js +145 -0
  440. package/dist/repertoire/tools.js +441 -102
  441. package/dist/repertoire/travel-api-client.js +360 -0
  442. package/dist/repertoire/unraid-client.js +155 -0
  443. package/dist/repertoire/unraid-restart.js +212 -0
  444. package/dist/repertoire/user-profile.js +131 -0
  445. package/dist/repertoire/vault-setup.js +246 -0
  446. package/dist/repertoire/vault-unlock.js +628 -0
  447. package/dist/rsvp/aisleplanner-client.js +354 -0
  448. package/dist/rsvp/cli.js +926 -0
  449. package/dist/rsvp/config.js +327 -0
  450. package/dist/rsvp/cutover.js +433 -0
  451. package/dist/rsvp/diagnostics.js +232 -0
  452. package/dist/rsvp/diff-renderer.js +176 -0
  453. package/dist/rsvp/habit-policy.js +110 -0
  454. package/dist/rsvp/habit-stage.js +123 -0
  455. package/dist/rsvp/incident-bundle.js +97 -0
  456. package/dist/rsvp/migration.js +204 -0
  457. package/dist/rsvp/native-habit-runner.js +630 -0
  458. package/dist/rsvp/outbound-state.js +628 -0
  459. package/dist/rsvp/query.js +118 -0
  460. package/dist/rsvp/replay.js +233 -0
  461. package/dist/rsvp/snapshot.js +232 -0
  462. package/dist/rsvp/spend-ledger.js +175 -0
  463. package/dist/scripts/claude-code-hook.js +41 -0
  464. package/dist/scripts/claude-code-stop-hook.js +47 -0
  465. package/dist/senses/a2a-entry.js +115 -0
  466. package/dist/senses/attention-queue.js +186 -0
  467. package/dist/senses/await-turn-message.js +58 -0
  468. package/dist/senses/bluebubbles/active-turns.js +216 -0
  469. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  470. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  471. package/dist/senses/bluebubbles/client.js +799 -0
  472. package/dist/senses/bluebubbles/context-packet.js +207 -0
  473. package/dist/senses/bluebubbles/context-smoke.js +144 -0
  474. package/dist/senses/bluebubbles/entry.js +90 -0
  475. package/dist/senses/bluebubbles/inbound-log.js +127 -0
  476. package/dist/senses/bluebubbles/index.js +3839 -0
  477. package/dist/senses/bluebubbles/latest-turn.js +311 -0
  478. package/dist/senses/bluebubbles/media.js +389 -0
  479. package/dist/senses/bluebubbles/model.js +392 -0
  480. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +57 -6
  481. package/dist/senses/bluebubbles/outbound-state.js +308 -0
  482. package/dist/senses/bluebubbles/processed-log.js +133 -0
  483. package/dist/senses/bluebubbles/reaction-policy.js +47 -0
  484. package/dist/senses/bluebubbles/replay.js +284 -0
  485. package/dist/senses/bluebubbles/runtime-state.js +137 -0
  486. package/dist/senses/bluebubbles/semantic-receipts.js +1986 -0
  487. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  488. package/dist/senses/bluebubbles/webhook-registration.js +228 -0
  489. package/dist/senses/bluebubbles-meta-guard.js +39 -0
  490. package/dist/senses/cli/bracketed-paste.js +82 -0
  491. package/dist/senses/cli/image-paste.js +287 -0
  492. package/dist/senses/cli/image-ref-navigation.js +75 -0
  493. package/dist/senses/cli/ink-app.js +156 -0
  494. package/dist/senses/cli/inline-diff.js +64 -0
  495. package/dist/senses/cli/input-keys.js +174 -0
  496. package/dist/senses/cli/kill-ring.js +86 -0
  497. package/dist/senses/cli/message-list.js +51 -0
  498. package/dist/senses/cli/ouro-tui.js +607 -0
  499. package/dist/senses/cli/spinner-imperative.js +135 -0
  500. package/dist/senses/cli/spinner.js +101 -0
  501. package/dist/senses/cli/status-line.js +60 -0
  502. package/dist/senses/cli/streaming-markdown.js +526 -0
  503. package/dist/senses/cli/tool-display.js +85 -0
  504. package/dist/senses/cli/tool-render.js +85 -0
  505. package/dist/senses/cli/tui-store.js +241 -0
  506. package/dist/senses/cli/virtual-list.js +35 -0
  507. package/dist/senses/cli-entry.js +60 -8
  508. package/dist/senses/cli-layout.js +187 -0
  509. package/dist/senses/cli.js +813 -281
  510. package/dist/senses/commands.js +66 -3
  511. package/dist/senses/context-packet-ledger.js +371 -0
  512. package/dist/senses/context-packets.js +154 -0
  513. package/dist/senses/continuity.js +94 -0
  514. package/dist/senses/habit-lifecycle-guard.js +24 -0
  515. package/dist/senses/habit-turn-message.js +160 -0
  516. package/dist/senses/ingress-evidence.js +2 -0
  517. package/dist/senses/mail-entry.js +66 -0
  518. package/dist/senses/mail.js +524 -0
  519. package/dist/senses/pipeline.js +1213 -0
  520. package/dist/senses/private-runtime-worker.js +859 -0
  521. package/dist/senses/private-runtime.js +1496 -0
  522. package/dist/senses/proactive-content-guard.js +51 -0
  523. package/dist/senses/sanctuary-download-credit-presentation.js +31 -0
  524. package/dist/senses/sanctuary-full-visibility-contract.js +302 -0
  525. package/dist/senses/sanctuary-grounding.js +118 -0
  526. package/dist/senses/sanctuary-health-acceptance-probe-entry.js +12 -0
  527. package/dist/senses/sanctuary-health-acceptance-probe.js +774 -0
  528. package/dist/senses/sanctuary-health-runner.js +101 -0
  529. package/dist/senses/sanctuary-health.js +408 -0
  530. package/dist/senses/sanctuary-interactive-control.js +306 -0
  531. package/dist/senses/sanctuary-media-catalog-contract.js +235 -0
  532. package/dist/senses/sanctuary-media-optimization.js +514 -0
  533. package/dist/senses/sanctuary-runtime.js +338 -0
  534. package/dist/senses/sanctuary-sab.js +85 -0
  535. package/dist/senses/sanctuary-storage-optimization-contract.js +32 -0
  536. package/dist/senses/shared-turn.js +571 -0
  537. package/dist/senses/surface-tool.js +109 -0
  538. package/dist/senses/teams-entry.js +60 -8
  539. package/dist/senses/teams.js +953 -211
  540. package/dist/senses/telegram-admission.js +711 -0
  541. package/dist/senses/telegram-approval-runtime.js +566 -0
  542. package/dist/senses/telegram-attachments.js +182 -0
  543. package/dist/senses/telegram-audit-ledger.js +220 -0
  544. package/dist/senses/telegram-client.js +1677 -0
  545. package/dist/senses/telegram-effect-adapter.js +859 -0
  546. package/dist/senses/telegram-entry.js +83 -0
  547. package/dist/senses/telegram.js +2026 -0
  548. package/dist/senses/trust-gate.js +207 -2
  549. package/dist/senses/voice/audio-playback.js +237 -0
  550. package/dist/senses/voice/audio-routing.js +119 -0
  551. package/dist/senses/voice/elevenlabs.js +202 -0
  552. package/dist/senses/voice/floor-control.js +431 -0
  553. package/dist/senses/voice/floor-controller.js +115 -0
  554. package/dist/senses/voice/golden-path.js +116 -0
  555. package/dist/senses/voice/index.js +29 -0
  556. package/dist/senses/voice/meeting.js +113 -0
  557. package/dist/senses/voice/outbound.js +190 -0
  558. package/dist/senses/voice/phone.js +33 -0
  559. package/dist/senses/voice/playback.js +139 -0
  560. package/dist/senses/voice/realtime-eval.js +496 -0
  561. package/dist/senses/voice/realtime-trace.js +531 -0
  562. package/dist/senses/voice/transcript.js +70 -0
  563. package/dist/senses/voice/turn.js +191 -0
  564. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  565. package/dist/senses/voice/twilio-phone.js +5081 -0
  566. package/dist/senses/voice/types.js +2 -0
  567. package/dist/senses/voice/whisper.js +161 -0
  568. package/dist/senses/voice-entry.js +81 -0
  569. package/dist/senses/voice-realtime-eval-command.js +99 -0
  570. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  571. package/dist/senses/voice-twilio-entry.js +87 -0
  572. package/dist/trips/core.js +138 -0
  573. package/dist/trips/store.js +265 -0
  574. package/dist/util/frontmatter.js +69 -0
  575. package/npm-shrinkwrap.json +8144 -0
  576. package/package.json +82 -12
  577. package/skills/agent-commerce.md +113 -0
  578. package/skills/browser-navigation.md +117 -0
  579. package/skills/commerce-setup-guide.md +116 -0
  580. package/skills/commerce-setup.md +84 -0
  581. package/skills/configure-dev-tools.md +99 -0
  582. package/skills/travel-planning.md +138 -0
  583. package/AdoptionSpecialist.ouro/agent.json +0 -20
  584. package/AdoptionSpecialist.ouro/psyche/SOUL.md +0 -22
  585. package/dist/heart/daemon/specialist-orchestrator.js +0 -160
  586. package/dist/heart/daemon/specialist-prompt.js +0 -47
  587. package/dist/heart/daemon/specialist-session.js +0 -142
  588. package/dist/heart/daemon/specialist-tools.js +0 -132
  589. package/dist/heart/daemon/subagent-installer.js +0 -125
  590. package/dist/inner-worker-entry.js +0 -4
  591. package/dist/mind/friends/channel.js +0 -49
  592. package/dist/mind/friends/resolver.js +0 -84
  593. package/dist/mind/friends/store-file.js +0 -171
  594. package/dist/mind/friends/store.js +0 -4
  595. package/dist/mind/friends/tokens.js +0 -26
  596. package/dist/mind/friends/types.js +0 -21
  597. package/dist/repertoire/tasks/board.js +0 -122
  598. package/dist/repertoire/tasks/index.js +0 -210
  599. package/dist/repertoire/tasks/middleware.js +0 -65
  600. package/dist/repertoire/tasks/parser.js +0 -173
  601. package/dist/repertoire/tasks/scanner.js +0 -132
  602. package/dist/repertoire/tasks/transitions.js +0 -145
  603. package/dist/senses/bluebubbles-client.js +0 -279
  604. package/dist/senses/bluebubbles-entry.js +0 -11
  605. package/dist/senses/bluebubbles-model.js +0 -253
  606. package/dist/senses/bluebubbles.js +0 -332
  607. package/dist/senses/inner-dialog-worker.js +0 -61
  608. package/dist/senses/inner-dialog.js +0 -231
  609. package/subagents/README.md +0 -73
  610. package/subagents/work-doer.md +0 -233
  611. package/subagents/work-merger.md +0 -624
  612. package/subagents/work-planner.md +0 -373
  613. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  614. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  615. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  616. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  617. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  618. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  619. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  620. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  621. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  622. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  623. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  624. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
@@ -34,19 +34,471 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.messageFromHabitPokeError = messageFromHabitPokeError;
38
+ exports.parseOrphanPidsFromPs = parseOrphanPidsFromPs;
39
+ exports.filterPidfilePidsToActualOrphans = filterPidfilePidsToActualOrphans;
40
+ exports.mergeUniqueOrphanPids = mergeUniqueOrphanPids;
41
+ exports.waitForOrphanProcessesToSettle = waitForOrphanProcessesToSettle;
42
+ exports.assertOrphanCleanupComplete = assertOrphanCleanupComplete;
43
+ exports.drainOrphanProcessesBeforeStartup = drainOrphanProcessesBeforeStartup;
44
+ exports.killOrphanProcesses = killOrphanProcesses;
45
+ exports.writePidfile = writePidfile;
46
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
47
+ exports.handleAgentAskTurn = handleAgentAskTurn;
37
48
  const fs = __importStar(require("fs"));
38
49
  const net = __importStar(require("net"));
50
+ const os = __importStar(require("os"));
39
51
  const path = __importStar(require("path"));
52
+ const node_crypto_1 = require("node:crypto");
40
53
  const identity_1 = require("../identity");
54
+ const agent_discovery_1 = require("./agent-discovery");
41
55
  const runtime_1 = require("../../nerves/runtime");
42
- function formatStatusSummary(snapshots) {
43
- if (snapshots.length === 0)
56
+ const runtime_metadata_1 = require("./runtime-metadata");
57
+ const runtime_mode_1 = require("./runtime-mode");
58
+ const update_hooks_1 = require("../versioning/update-hooks");
59
+ const bundle_meta_1 = require("./hooks/bundle-meta");
60
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
61
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
62
+ const update_checker_1 = require("../versioning/update-checker");
63
+ const child_process_1 = require("child_process");
64
+ const pending_1 = require("../../mind/pending");
65
+ const agent_service_1 = require("./agent-service");
66
+ const friends_1 = require("@ouro.bot/friends");
67
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
68
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
69
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
70
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
71
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
72
+ const provider_visibility_1 = require("../provider-visibility");
73
+ const provider_binding_resolver_1 = require("../provider-binding-resolver");
74
+ const private_runtime_1 = require("../private-runtime");
75
+ const socket_client_1 = require("./socket-client");
76
+ const flight_recorder_1 = require("../../arc/flight-recorder");
77
+ const await_private_wake_1 = require("./await-private-wake");
78
+ const habit_private_wake_1 = require("./habit-private-wake");
79
+ const habit_parser_1 = require("../habits/habit-parser");
80
+ const habit_runtime_state_1 = require("../habits/habit-runtime-state");
81
+ const router_1 = require("../external-events/router");
82
+ const habit_policy_1 = require("../../rsvp/habit-policy");
83
+ const container_runtime_1 = require("./container-runtime");
84
+ const habit_session_1 = require("../habits/habit-session");
85
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
86
+ /**
87
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
88
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
89
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
90
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
91
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
92
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
93
+ * by a vitest test that called daemon.start()).
94
+ *
95
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
96
+ * to make the production pidfile sacred. Tests that need to verify these
97
+ * functions' behavior should use the extracted pure helpers
98
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
99
+ */
100
+ function isVitestProcess() {
101
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
102
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
103
+ return false;
104
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
105
+ }
106
+ function messageFromHabitPokeError(error) {
107
+ if (error instanceof Error)
108
+ return error.message;
109
+ /* v8 ignore next -- defensive fallback for hostile/non-Error throws from filesystem or parsers @preserve */
110
+ return String(error);
111
+ }
112
+ /**
113
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
114
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
115
+ * that are safe to SIGTERM — true orphans, not children of live sibling
116
+ * daemons running from worktrees, test suites, or other users of the harness.
117
+ *
118
+ * Exported so unit tests can exercise the filter without shelling out.
119
+ */
120
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
121
+ const orphans = [];
122
+ for (const line of psOutput.split("\n")) {
123
+ // Explicitly exclude MCP server processes — they share a harness entry
124
+ // point but are not daemon children and must never be killed.
125
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
126
+ continue;
127
+ // Match only daemon-owned JS entry points.
128
+ if (!line.includes("agent-entry.js")
129
+ && !line.includes("daemon-entry.js")
130
+ && !line.includes("bluebubbles/entry.js")
131
+ && !line.includes("mail-entry.js")
132
+ && !line.includes("teams-entry.js")
133
+ && !line.includes("a2a-entry.js")
134
+ && !line.includes("telegram-entry.js")
135
+ && !line.includes("voice-entry.js"))
136
+ continue;
137
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
138
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
139
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
140
+ if (!match)
141
+ continue;
142
+ const pid = parseInt(match[1], 10);
143
+ const ppid = parseInt(match[2], 10);
144
+ if (pid === selfPid)
145
+ continue;
146
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
147
+ // PPID means the process belongs to another daemon instance (parallel
148
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
149
+ // Killing those will crash unrelated harnesses — we saw this in B6
150
+ // when a vitest worker's daemon killed a production agent's children.
151
+ if (ppid !== 1)
152
+ continue;
153
+ orphans.push(pid);
154
+ }
155
+ return orphans;
156
+ }
157
+ /**
158
+ * Given a list of PIDs from the pidfile, return only those that are actual
159
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
160
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
161
+ *
162
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
163
+ * Returns the empty list if ps fails — safer to skip cleanup than to
164
+ * wildcard-kill on a bad read.
165
+ *
166
+ * Exported for direct unit coverage.
167
+ */
168
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
169
+ if (candidatePids.length === 0)
170
+ return [];
171
+ const psOutput = psRunner(candidatePids);
172
+ if (psOutput === null)
173
+ return [];
174
+ const survivingOrphans = [];
175
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
176
+ // PIDs not found (already exited) are silently omitted — which is the
177
+ // correct behavior for us: we only want to kill live orphans.
178
+ for (const line of psOutput.split("\n")) {
179
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
180
+ if (!match)
181
+ continue;
182
+ const pid = parseInt(match[1], 10);
183
+ const ppid = parseInt(match[2], 10);
184
+ if (ppid !== 1)
185
+ continue;
186
+ if (!candidatePids.includes(pid))
187
+ continue;
188
+ survivingOrphans.push(pid);
189
+ }
190
+ return survivingOrphans;
191
+ }
192
+ function mergeUniqueOrphanPids(...sources) {
193
+ const merged = [];
194
+ const seen = new Set();
195
+ for (const source of sources) {
196
+ for (const pid of source) {
197
+ if (seen.has(pid))
198
+ continue;
199
+ seen.add(pid);
200
+ merged.push(pid);
201
+ }
202
+ }
203
+ return merged;
204
+ }
205
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
206
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
207
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
208
+ function defaultIsPidAlive(pid) {
209
+ try {
210
+ process.kill(pid, 0);
211
+ return true;
212
+ }
213
+ catch (error) {
214
+ return error.code === "EPERM";
215
+ }
216
+ }
217
+ /* v8 ignore stop */
218
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
219
+ async function defaultSettleSleep(ms) {
220
+ await new Promise((resolve) => setTimeout(resolve, ms));
221
+ }
222
+ /* v8 ignore stop */
223
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
224
+ if (pids.length === 0)
225
+ return [];
226
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
227
+ const now = deps.now ?? Date.now;
228
+ const sleep = deps.sleep ?? defaultSettleSleep;
229
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
230
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
231
+ const deadline = now() + timeoutMs;
232
+ let survivors = pids.filter(isPidAlive);
233
+ while (survivors.length > 0 && now() < deadline) {
234
+ await sleep(pollIntervalMs);
235
+ survivors = pids.filter(isPidAlive);
236
+ }
237
+ return survivors;
238
+ }
239
+ function assertOrphanCleanupComplete(survivingPids) {
240
+ if (survivingPids.length === 0)
241
+ return;
242
+ const errorReason = `refusing startup while ${survivingPids.length} orphaned Ouro processes remain: ${survivingPids.join(", ")}`;
243
+ (0, runtime_1.emitNervesEvent)({
244
+ level: "error",
245
+ component: "daemon",
246
+ event: "daemon.orphan_cleanup_incomplete",
247
+ message: errorReason,
248
+ meta: { survivingPids },
249
+ });
250
+ throw new Error(errorReason);
251
+ }
252
+ const ORPHAN_CLEANUP_MAX_SIGNAL_PASSES = 8;
253
+ async function drainOrphanProcessesBeforeStartup(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH, deps = {}) {
254
+ const signalOrphans = deps.signalOrphans ?? killOrphanProcesses;
255
+ const settleOrphans = deps.settleOrphans ?? waitForOrphanProcessesToSettle;
256
+ const maxSignalPasses = deps.maxSignalPasses ?? ORPHAN_CLEANUP_MAX_SIGNAL_PASSES;
257
+ for (let pass = 0; pass < maxSignalPasses; pass += 1) {
258
+ const signaledPids = signalOrphans(socketPath);
259
+ if (signaledPids.length === 0)
260
+ return;
261
+ const survivingPids = await settleOrphans(signaledPids);
262
+ assertOrphanCleanupComplete(survivingPids);
263
+ }
264
+ const errorReason = `orphan cleanup did not reach a fixed point after ${maxSignalPasses} signaling round(s)`;
265
+ (0, runtime_1.emitNervesEvent)({
266
+ level: "error",
267
+ component: "daemon",
268
+ event: "daemon.orphan_cleanup_not_converged",
269
+ message: errorReason,
270
+ meta: { maxSignalPasses },
271
+ });
272
+ throw new Error(errorReason);
273
+ }
274
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
275
+ function runPsCheck(pids) {
276
+ try {
277
+ const csv = pids.join(",");
278
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
279
+ }
280
+ catch {
281
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
282
+ // "no survivors" rather than an error.
283
+ return "";
284
+ }
285
+ }
286
+ /* v8 ignore stop */
287
+ /**
288
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
289
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
290
+ * deletes the file. The new daemon writes its own PIDs after spawning.
291
+ *
292
+ * Safety: pidfile contents are verified before being killed — each PID must
293
+ * be an actual orphan (PPID reparented to init/PID 1) via
294
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
295
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
296
+ * OS) could SIGTERM unrelated processes.
297
+ *
298
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
299
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
300
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
301
+ */
302
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
303
+ function isProductionDaemonSocketPath(socketPath) {
304
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
305
+ }
306
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
307
+ if (!isProductionDaemonSocketPath(socketPath)) {
308
+ (0, runtime_1.emitNervesEvent)({
309
+ level: "warn",
310
+ component: "daemon",
311
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
312
+ message: "blocked orphan cleanup for non-production daemon socket",
313
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
314
+ });
315
+ return [];
316
+ }
317
+ if (isVitestProcess()) {
318
+ (0, runtime_1.emitNervesEvent)({
319
+ level: "warn",
320
+ component: "daemon",
321
+ event: "daemon.orphan_cleanup_test_blocked",
322
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
323
+ meta: { pidfilePath: PIDFILE_PATH },
324
+ });
325
+ return [];
326
+ }
327
+ try {
328
+ let pidfileOrphans = [];
329
+ let scanOrphans = [];
330
+ // Primary: read pidfile from previous daemon
331
+ try {
332
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
333
+ const candidates = raw.split("\n")
334
+ .map((s) => parseInt(s.trim(), 10))
335
+ .filter((n) => !isNaN(n) && n !== process.pid);
336
+ // Verify each candidate is an actual live orphan before killing. See
337
+ // docstring above for why this matters.
338
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
339
+ fs.unlinkSync(PIDFILE_PATH);
340
+ }
341
+ catch {
342
+ // No pidfile — the ps scan below still covers true orphans.
343
+ }
344
+ // Always supplement the pidfile with the scoped ps scan. A stale or
345
+ // partial pidfile can otherwise kill one old daemon while leaving a
346
+ // sibling PPID=1 daemon alive without a socket.
347
+ try {
348
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
349
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
350
+ }
351
+ catch (error) {
352
+ const detail = error instanceof Error ? error.message : String(error);
353
+ throw new Error(`could not discover orphaned Ouro processes: ${detail}`);
354
+ }
355
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
356
+ if (pidsToKill.length > 0) {
357
+ for (const pid of pidsToKill) {
358
+ try {
359
+ process.kill(pid, "SIGTERM");
360
+ }
361
+ catch { /* already exited */ }
362
+ }
363
+ (0, runtime_1.emitNervesEvent)({
364
+ component: "daemon",
365
+ event: "daemon.orphan_cleanup",
366
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
367
+ meta: { pids: pidsToKill },
368
+ });
369
+ }
370
+ return pidsToKill;
371
+ }
372
+ catch (error) {
373
+ (0, runtime_1.emitNervesEvent)({
374
+ level: "error",
375
+ component: "daemon",
376
+ event: "daemon.orphan_cleanup_error",
377
+ message: "failed to clean up orphaned ouro processes",
378
+ meta: { error: error instanceof Error ? error.message : String(error) },
379
+ });
380
+ throw error instanceof Error ? error : new Error(String(error));
381
+ }
382
+ }
383
+ /**
384
+ * Write all managed PIDs (daemon + children) to the pidfile.
385
+ * Called after all agents and senses are spawned.
386
+ */
387
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
388
+ if (!isProductionDaemonSocketPath(socketPath)) {
389
+ (0, runtime_1.emitNervesEvent)({
390
+ level: "warn",
391
+ component: "daemon",
392
+ event: "daemon.write_pidfile_nonproduction_blocked",
393
+ message: "blocked production pidfile write for non-production daemon socket",
394
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
395
+ });
396
+ return;
397
+ }
398
+ if (isVitestProcess()) {
399
+ (0, runtime_1.emitNervesEvent)({
400
+ level: "warn",
401
+ component: "daemon",
402
+ event: "daemon.write_pidfile_test_blocked",
403
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
404
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
405
+ });
406
+ return;
407
+ }
408
+ try {
409
+ const pids = [process.pid, ...extraPids].filter(Boolean);
410
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
411
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
412
+ }
413
+ catch { /* best effort */ }
414
+ }
415
+ function readSocketIdentity(socketPath) {
416
+ try {
417
+ const stats = fs.lstatSync(socketPath);
418
+ return {
419
+ dev: stats.dev,
420
+ ino: stats.ino,
421
+ ctimeMs: stats.ctimeMs,
422
+ };
423
+ }
424
+ catch {
425
+ return null;
426
+ }
427
+ }
428
+ function sameSocketIdentity(left, right) {
429
+ if (!left || !right)
430
+ return false;
431
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
432
+ }
433
+ function buildWorkerRows(snapshots) {
434
+ return snapshots.map((snapshot) => ({
435
+ agent: snapshot.name,
436
+ worker: snapshot.channel,
437
+ autoStart: snapshot.autoStart ?? true,
438
+ status: snapshot.status,
439
+ pid: snapshot.pid,
440
+ restartCount: snapshot.restartCount,
441
+ startedAt: snapshot.startedAt,
442
+ lastExitCode: snapshot.lastExitCode ?? null,
443
+ lastSignal: snapshot.lastSignal ?? null,
444
+ errorReason: snapshot.errorReason ?? null,
445
+ fixHint: snapshot.fixHint ?? null,
446
+ }));
447
+ }
448
+ function unhealthySenseRows(senses) {
449
+ return senses.filter((row) => {
450
+ if (!row.enabled)
451
+ return false;
452
+ if (row.status === "disabled" || row.status === "not_attached")
453
+ return false;
454
+ if (row.status === "interactive" || row.status === "running")
455
+ return false;
456
+ return true;
457
+ });
458
+ }
459
+ function isParkedWorker(row) {
460
+ return row.autoStart === false && row.status === "stopped";
461
+ }
462
+ function unhealthyWorkerRows(workers) {
463
+ return workers.filter((row) => !isParkedWorker(row) && row.status !== "running");
464
+ }
465
+ function unhealthyHealthChecks(healthChecks) {
466
+ return healthChecks.filter((row) => row.status !== "ok");
467
+ }
468
+ function overviewHealth(workers, senses, healthChecks = []) {
469
+ if (unhealthyWorkerRows(workers).length > 0)
470
+ return "warn";
471
+ if (unhealthySenseRows(senses).length > 0)
472
+ return "warn";
473
+ if (unhealthyHealthChecks(healthChecks).length > 0)
474
+ return "warn";
475
+ return "ok";
476
+ }
477
+ function formatStatusSummary(payload) {
478
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
44
479
  return "no managed agents";
45
- return snapshots
46
- .map((snapshot) => {
47
- return `${snapshot.name}\t${snapshot.channel}\t${snapshot.status}\tpid=${snapshot.pid ?? "none"}\trestarts=${snapshot.restartCount}`;
48
- })
49
- .join("\n");
480
+ }
481
+ const degraded = [
482
+ ...unhealthyWorkerRows(payload.workers)
483
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
484
+ ...unhealthySenseRows(payload.senses)
485
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
486
+ ...(payload.healthChecks ?? [])
487
+ .filter((row) => row.status !== "ok")
488
+ .map((row) => `health-check:${row.name}:${row.status}`),
489
+ ];
490
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
491
+ if (!detail) {
492
+ const rows = [
493
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
494
+ ...payload.senses
495
+ .filter((row) => row.enabled)
496
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
497
+ ];
498
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
499
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
500
+ }
501
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
50
502
  }
51
503
  function parseIncomingCommand(raw) {
52
504
  let parsed;
@@ -65,21 +517,240 @@ function parseIncomingCommand(raw) {
65
517
  }
66
518
  return parsed;
67
519
  }
520
+ function isValidSenseReviveCommand(command) {
521
+ return typeof command.agent === "string"
522
+ && typeof command.sense === "string"
523
+ && typeof command.reason === "string";
524
+ }
525
+ function isValidTaskPokeCommand(command) {
526
+ return typeof command.agent === "string"
527
+ && command.agent.trim().length > 0
528
+ && typeof command.taskId === "string"
529
+ && command.taskId.trim().length > 0;
530
+ }
531
+ function isValidHabitPokeCommand(command) {
532
+ return typeof command.agent === "string"
533
+ && command.agent.trim().length > 0
534
+ && typeof command.habitName === "string"
535
+ && command.habitName.trim().length > 0;
536
+ }
537
+ function isValidHabitProbeCommand(command) {
538
+ return typeof command.agent === "string"
539
+ && command.agent.trim().length > 0
540
+ && typeof command.habitName === "string"
541
+ && command.habitName.trim().length > 0
542
+ && (command.noSend === undefined || command.noSend === true);
543
+ }
544
+ function taskIdFromTaskPokePrivateWakeCommand(command) {
545
+ if (command.kind !== "private.wake" || command.triggerSource !== "task-poke")
546
+ return null;
547
+ const taskRef = command.originRefs?.find((ref) => ref.kind === "task" && typeof ref.id === "string");
548
+ if (!taskRef || typeof taskRef.id !== "string")
549
+ return null;
550
+ const trimmed = taskRef.id.trim();
551
+ return trimmed.length > 0 ? trimmed : null;
552
+ }
553
+ /**
554
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
555
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
556
+ * restarts the daemon process (fresh module cache).
557
+ */
558
+ async function handleAgentSenseTurn(command, runtime) {
559
+ try {
560
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
561
+ setAgentName(command.agent);
562
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
563
+ const result = await runSenseTurn({
564
+ agentName: command.agent,
565
+ channel: command.channel,
566
+ sessionKey: command.sessionKey,
567
+ friendId: command.friendId,
568
+ userMessage: command.message,
569
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
570
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
571
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
572
+ // turn for a different agent cannot inherit these servers.
573
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
574
+ });
575
+ return {
576
+ ok: true,
577
+ message: result.response,
578
+ data: { ponderDeferred: result.ponderDeferred },
579
+ };
580
+ }
581
+ catch (error) {
582
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
583
+ const errorMessage = error instanceof Error ? error.message : String(error);
584
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
585
+ }
586
+ }
587
+ async function handleAgentAskTurn(command, runtime) {
588
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
589
+ const question = typeof command.question === "string" ? command.question : "";
590
+ if (!question.trim())
591
+ return { ok: false, error: "Missing required parameter: question" };
592
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
593
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
594
+ ? command.sessionKey.trim()
595
+ : `agent-ask:${command.friendId}`;
596
+ /* v8 ignore stop */
597
+ return handleAgentSenseTurn({
598
+ kind: "agent.senseTurn",
599
+ agent: command.agent,
600
+ friendId: command.friendId,
601
+ channel,
602
+ sessionKey,
603
+ message: question,
604
+ }, runtime);
605
+ }
68
606
  class OuroDaemon {
69
607
  socketPath;
70
608
  processManager;
71
609
  scheduler;
72
610
  healthMonitor;
73
611
  router;
612
+ senseManager;
74
613
  bundlesRoot;
614
+ mode;
75
615
  server = null;
616
+ mailboxServer = null;
617
+ socketIdentity = null;
618
+ senseAutostartTimer = null;
619
+ externalEventReconcileTimer = null;
620
+ externalEventReconcileRunning = false;
621
+ constructedAtMs = Date.now();
622
+ mailboxServerFactory;
623
+ privateRuntimePolicyDeps;
624
+ onStopCommandComplete;
625
+ externalEventRoot;
626
+ privilegedEventSpoolRoot;
627
+ privilegedEventScanner;
628
+ rsvpHabitRunner;
629
+ nativeHabitRunner;
630
+ nativeHabitMatch;
631
+ nativeHabitClaims = new Set();
632
+ authenticatedSchedulerPokes = new WeakMap();
633
+ schedulerFireVerifier;
634
+ schedulerFireConsumer;
635
+ orphanStartupDrain;
636
+ externalEventSourceReadiness;
76
637
  constructor(options) {
77
638
  this.socketPath = options.socketPath;
78
639
  this.processManager = options.processManager;
79
640
  this.scheduler = options.scheduler;
80
641
  this.healthMonitor = options.healthMonitor;
81
642
  this.router = options.router;
643
+ this.senseManager = options.senseManager ?? null;
82
644
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
645
+ this.mode = options.mode ?? "production";
646
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
647
+ this.privateRuntimePolicyDeps = options.privateRuntimePolicyDeps ?? {};
648
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
649
+ this.externalEventRoot = options.externalEventRoot ?? null;
650
+ this.privilegedEventSpoolRoot = options.privilegedEventSpoolRoot ?? "/run/ouro-events";
651
+ this.privilegedEventScanner = options.privilegedEventScanner ?? router_1.scanPrivilegedEventSpool;
652
+ this.rsvpHabitRunner = options.rsvpHabitRunner;
653
+ this.nativeHabitRunner = options.nativeHabitRunner;
654
+ this.nativeHabitMatch = options.nativeHabitMatch;
655
+ this.schedulerFireVerifier = options.schedulerFireVerifier;
656
+ this.schedulerFireConsumer = options.schedulerFireConsumer;
657
+ this.orphanStartupDrain = options.orphanStartupDrain ?? drainOrphanProcessesBeforeStartup;
658
+ this.externalEventSourceReadiness = options.externalEventSourceReadiness ?? (async (agent, source) => {
659
+ const { ensureSanctuarySourceRuntimeReady } = await Promise.resolve().then(() => __importStar(require("../../senses/sanctuary-runtime")));
660
+ await ensureSanctuarySourceRuntimeReady(agent, source);
661
+ });
662
+ }
663
+ /* v8 ignore start -- default mailbox server wiring: production-only path, tests inject mailboxServerFactory stub instead. startMailboxHttpServer itself has full coverage in mailbox-http.test.ts @preserve */
664
+ createDefaultMailboxServer() {
665
+ return (0, mailbox_http_1.startMailboxHttpServer)({
666
+ host: "127.0.0.1",
667
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
668
+ bundlesRoot: this.bundlesRoot,
669
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
670
+ readMachineView: ({ machine }) => {
671
+ const overview = this.buildStatusPayload().overview;
672
+ return (0, mailbox_view_1.buildMailboxMachineView)({
673
+ machine,
674
+ daemon: {
675
+ status: overview.daemon,
676
+ health: overview.health,
677
+ mode: overview.mode,
678
+ socketPath: overview.socketPath,
679
+ mailboxUrl: overview.mailboxUrl,
680
+ entryPath: overview.entryPath,
681
+ workerCount: overview.workerCount,
682
+ senseCount: overview.senseCount,
683
+ },
684
+ });
685
+ },
686
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
687
+ readAgentView: (agentName) => {
688
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
689
+ return (0, mailbox_view_1.buildMailboxAgentView)({
690
+ agent,
691
+ viewer: { kind: "human" },
692
+ });
693
+ },
694
+ });
695
+ }
696
+ /* v8 ignore stop */
697
+ buildStatusPayload() {
698
+ const snapshots = this.processManager.listAgentSnapshots();
699
+ const workers = buildWorkerRows(snapshots);
700
+ const senses = this.senseManager?.listSenseRows() ?? [];
701
+ const healthChecks = this.overlaySchedulerHealth(this.healthMonitor.getLastResults?.() ?? []);
702
+ const repoRoot = (0, identity_1.getRepoRoot)();
703
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
704
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
705
+ const providerAgents = (0, agent_discovery_1.listEnabledBundleAgents)({ bundlesRoot: this.bundlesRoot });
706
+ const providers = providerAgents.flatMap((agentName) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
707
+ agentName,
708
+ agentRoot: path.join(this.bundlesRoot, `${agentName}.ouro`),
709
+ })));
710
+ const externalEvents = (0, router_1.listExternalEventStatus)(this.externalEventRoot ?? (0, router_1.getExternalEventRoot)());
711
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
712
+ return {
713
+ overview: {
714
+ daemon: "running",
715
+ health: overviewHealth(workers, senses, healthChecks),
716
+ socketPath: this.socketPath,
717
+ mailboxUrl,
718
+ outlookUrl: mailboxUrl,
719
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
720
+ workerCount: workers.length,
721
+ senseCount: senses.length,
722
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
723
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
724
+ },
725
+ workers,
726
+ senses,
727
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
728
+ sync,
729
+ agents,
730
+ ...(providers.length > 0 ? { providers } : {}),
731
+ ...(externalEvents.length > 0 ? { externalEvents } : {}),
732
+ };
733
+ }
734
+ overlaySchedulerHealth(healthChecks) {
735
+ const degradedJobs = this.scheduler.listDegradedJobs?.() ?? [];
736
+ if (degradedJobs.length === 0)
737
+ return healthChecks;
738
+ const cronHealth = {
739
+ name: "cron-health",
740
+ status: "warn",
741
+ message: `cron jobs degraded; timer fallback active: ${degradedJobs
742
+ .map((job) => `${job.id} (${job.reason})`)
743
+ .join(", ")}`,
744
+ };
745
+ const next = healthChecks.map((check) => ({ ...check }));
746
+ const existingIndex = next.findIndex((check) => check.name === "cron-health");
747
+ if (existingIndex === -1) {
748
+ next.push(cronHealth);
749
+ }
750
+ else {
751
+ next[existingIndex] = cronHealth;
752
+ }
753
+ return next;
83
754
  }
84
755
  async start() {
85
756
  if (this.server)
@@ -90,22 +761,186 @@ class OuroDaemon {
90
761
  message: "starting daemon server",
91
762
  meta: { socketPath: this.socketPath },
92
763
  });
93
- await this.processManager.startAutoStartAgents();
764
+ try {
765
+ await this.startInner();
766
+ }
767
+ catch (err) {
768
+ // Emit a paired terminating event (`_error`) so the nerves audit's
769
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
770
+ // and `stop()` (which emits `server_end`) is never called.
771
+ (0, runtime_1.emitNervesEvent)({
772
+ level: "error",
773
+ component: "daemon",
774
+ event: "daemon.server_error",
775
+ message: "daemon start failed",
776
+ meta: {
777
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
778
+ },
779
+ });
780
+ throw err;
781
+ }
782
+ }
783
+ async startInner() {
784
+ const containerPolicy = (0, container_runtime_1.readContainerRuntimePolicy)();
785
+ // Register update hooks and apply pending updates before starting agents
786
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
787
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
788
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
789
+ if (containerPolicy?.updates !== "disabled")
790
+ await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
791
+ // Start periodic update checker (polls npm registry every 30 minutes)
792
+ // Skip in dev mode — dev builds should not auto-update from npm
793
+ if (this.mode === "dev" || containerPolicy?.updates === "disabled") {
794
+ (0, runtime_1.emitNervesEvent)({
795
+ component: "daemon",
796
+ event: "daemon.update_checker_skip",
797
+ message: "skipping update checker in dev mode",
798
+ meta: { reason: this.mode === "dev" ? "dev mode" : "container policy" },
799
+ });
800
+ }
801
+ else {
802
+ (0, update_checker_1.startUpdateChecker)({
803
+ currentVersion,
804
+ deps: {
805
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
806
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
807
+ fetchRegistryJson: async () => {
808
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
809
+ return res.json();
810
+ },
811
+ /* v8 ignore stop */
812
+ },
813
+ });
814
+ }
815
+ // MCP connections are lazily initialized per-agent during senseTurn
816
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
817
+ await this.orphanStartupDrain(this.socketPath);
818
+ await this.openCommandSocket();
819
+ await this.reconcileExternalEvents();
820
+ this.externalEventReconcileTimer = setInterval(() => {
821
+ void this.reconcileExternalEvents();
822
+ }, 1_000);
823
+ this.externalEventReconcileTimer.unref?.();
824
+ this.triggerAutoStartAgents();
825
+ this.triggerAutoStartSensesWhenAgentsSettled();
826
+ // Write all managed PIDs to disk so the next daemon can clean up
827
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
828
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
829
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
830
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
831
+ /* v8 ignore stop */
94
832
  this.scheduler.start?.();
95
833
  await this.scheduler.reconcile?.();
96
834
  await this.drainPendingBundleMessages();
835
+ await this.drainPendingSenseMessages();
836
+ // startInner is only reachable when this.server is null (guarded in
837
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
838
+ // so mailboxServer is guaranteed unset here — no need for a guard.
839
+ try {
840
+ this.mailboxServer = await this.mailboxServerFactory();
841
+ }
842
+ catch (error) {
843
+ (0, runtime_1.emitNervesEvent)({
844
+ level: "warn",
845
+ component: "daemon",
846
+ event: "daemon.mailbox_start_failed",
847
+ message: `Mailbox server failed to start: ${String(error)}`,
848
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
849
+ });
850
+ }
851
+ }
852
+ triggerAutoStartAgents() {
853
+ if (this.processManager.triggerAutoStartAgents) {
854
+ this.processManager.triggerAutoStartAgents();
855
+ return;
856
+ }
857
+ void this.processManager.startAutoStartAgents().catch((error) => {
858
+ (0, runtime_1.emitNervesEvent)({
859
+ level: "error",
860
+ component: "daemon",
861
+ event: "daemon.agent_autostart_error",
862
+ message: "agent autostart failed after daemon socket opened",
863
+ meta: { error: error instanceof Error ? error.message : String(error) },
864
+ });
865
+ });
866
+ }
867
+ triggerAutoStartSenses() {
868
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
869
+ if (!this.senseManager)
870
+ return;
871
+ if (this.senseManager.triggerAutoStartSenses) {
872
+ this.senseManager.triggerAutoStartSenses();
873
+ return;
874
+ }
875
+ void this.senseManager.startAutoStartSenses().catch((error) => {
876
+ (0, runtime_1.emitNervesEvent)({
877
+ level: "error",
878
+ component: "daemon",
879
+ event: "daemon.sense_autostart_error",
880
+ message: "sense autostart failed after daemon socket opened",
881
+ meta: { error: error instanceof Error ? error.message : String(error) },
882
+ });
883
+ });
884
+ }
885
+ triggerAutoStartSensesWhenAgentsSettled() {
886
+ if (!this.senseManager)
887
+ return;
888
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
889
+ .some((snapshot) => snapshot.status === "starting");
890
+ if (!waitingOnAgents) {
891
+ this.triggerAutoStartSenses();
892
+ return;
893
+ }
894
+ this.senseAutostartTimer = setTimeout(() => {
895
+ this.senseAutostartTimer = null;
896
+ this.triggerAutoStartSensesWhenAgentsSettled();
897
+ }, 250);
898
+ }
899
+ async openCommandSocket() {
97
900
  if (fs.existsSync(this.socketPath)) {
98
901
  fs.unlinkSync(this.socketPath);
99
902
  }
100
- this.server = net.createServer((connection) => {
903
+ // allowHalfOpen: true lets the server keep its writable side open after
904
+ // the client sends FIN. Without this, when a client calls `client.end()`
905
+ // after writing a command, node closes the server's writable side
906
+ // automatically — so a long-running response (like an agent.senseTurn
907
+ // LLM turn that takes 5+ seconds) never reaches the client. The
908
+ // socket-client fix in #303/#334 also removed client.end() on the
909
+ // sending side, but this option is defense in depth: even if a future
910
+ // caller half-closes, the server still writes its response correctly.
911
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
101
912
  let raw = "";
102
913
  let responded = false;
914
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
915
+ connection.on("error", (err) => {
916
+ (0, runtime_1.emitNervesEvent)({
917
+ level: "warn",
918
+ component: "daemon",
919
+ event: "daemon.connection_error",
920
+ message: "socket connection error",
921
+ meta: { error: err.message, code: err.code ?? null },
922
+ });
923
+ });
924
+ /* v8 ignore stop */
103
925
  const flushResponse = async () => {
104
926
  if (responded)
105
927
  return;
106
928
  responded = true;
107
929
  const response = await this.handleRawPayload(raw);
108
- connection.end(response);
930
+ try {
931
+ connection.end(response);
932
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
933
+ }
934
+ catch (err) {
935
+ (0, runtime_1.emitNervesEvent)({
936
+ level: "warn",
937
+ component: "daemon",
938
+ event: "daemon.connection_end_error",
939
+ message: "failed to send response to client (EPIPE)",
940
+ meta: { error: err instanceof Error ? err.message : String(err) },
941
+ });
942
+ }
943
+ /* v8 ignore stop */
109
944
  };
110
945
  connection.on("data", (chunk) => {
111
946
  raw += chunk.toString("utf-8");
@@ -118,7 +953,23 @@ class OuroDaemon {
118
953
  const server = this.server;
119
954
  await new Promise((resolve, reject) => {
120
955
  server.once("error", reject);
121
- server.listen(this.socketPath, () => resolve());
956
+ server.listen(this.socketPath, () => {
957
+ // Replace the one-time error listener with a persistent one after successful listen
958
+ server.removeAllListeners("error");
959
+ this.socketIdentity = readSocketIdentity(this.socketPath);
960
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
961
+ server.on("error", (err) => {
962
+ (0, runtime_1.emitNervesEvent)({
963
+ level: "error",
964
+ component: "daemon",
965
+ event: "daemon.server_error",
966
+ message: "daemon server error after listen",
967
+ meta: { error: err.message, code: err.code ?? null },
968
+ });
969
+ });
970
+ /* v8 ignore stop */
971
+ resolve();
972
+ });
122
973
  });
123
974
  }
124
975
  async drainPendingBundleMessages() {
@@ -169,24 +1020,196 @@ class OuroDaemon {
169
1020
  fs.writeFileSync(pendingPath, next, "utf-8");
170
1021
  }
171
1022
  }
1023
+ /** Drains per-sense pending dirs for always-on senses across all agents. */
1024
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
1025
+ async drainPendingSenseMessages() {
1026
+ if (!fs.existsSync(this.bundlesRoot))
1027
+ return;
1028
+ let bundleDirs;
1029
+ try {
1030
+ bundleDirs = fs.readdirSync(this.bundlesRoot, { withFileTypes: true });
1031
+ }
1032
+ catch {
1033
+ return;
1034
+ }
1035
+ for (const bundleDir of bundleDirs) {
1036
+ if (!bundleDir.isDirectory() || !bundleDir.name.endsWith(".ouro"))
1037
+ continue;
1038
+ const agentName = bundleDir.name.replace(/\.ouro$/, "");
1039
+ const pendingRoot = path.join(this.bundlesRoot, bundleDir.name, "state", "pending");
1040
+ if (!fs.existsSync(pendingRoot))
1041
+ continue;
1042
+ let friendDirs;
1043
+ try {
1044
+ friendDirs = fs.readdirSync(pendingRoot, { withFileTypes: true });
1045
+ }
1046
+ catch {
1047
+ continue;
1048
+ }
1049
+ for (const friendDir of friendDirs) {
1050
+ if (!friendDir.isDirectory())
1051
+ continue;
1052
+ const friendPath = path.join(pendingRoot, friendDir.name);
1053
+ let channelDirs;
1054
+ try {
1055
+ channelDirs = fs.readdirSync(friendPath, { withFileTypes: true });
1056
+ }
1057
+ catch {
1058
+ continue;
1059
+ }
1060
+ for (const channelDir of channelDirs) {
1061
+ if (!channelDir.isDirectory())
1062
+ continue;
1063
+ if (!OuroDaemon.ALWAYS_ON_SENSES.has(channelDir.name))
1064
+ continue;
1065
+ const channelPath = path.join(friendPath, channelDir.name);
1066
+ let keyDirs;
1067
+ try {
1068
+ keyDirs = fs.readdirSync(channelPath, { withFileTypes: true });
1069
+ }
1070
+ catch {
1071
+ continue;
1072
+ }
1073
+ for (const keyDir of keyDirs) {
1074
+ if (!keyDir.isDirectory())
1075
+ continue;
1076
+ const leafDir = path.join(channelPath, keyDir.name);
1077
+ const messages = (0, pending_1.drainPending)(leafDir);
1078
+ for (const msg of messages) {
1079
+ try {
1080
+ await this.router.send({
1081
+ from: msg.from,
1082
+ to: agentName,
1083
+ content: msg.content,
1084
+ priority: "normal",
1085
+ });
1086
+ }
1087
+ catch {
1088
+ // Best-effort delivery — log and continue
1089
+ }
1090
+ }
1091
+ if (messages.length > 0) {
1092
+ (0, runtime_1.emitNervesEvent)({
1093
+ component: "daemon",
1094
+ event: "daemon.startup_sense_drain",
1095
+ message: "drained pending sense messages on startup",
1096
+ meta: {
1097
+ agent: agentName,
1098
+ channel: channelDir.name,
1099
+ friendId: friendDir.name,
1100
+ key: keyDir.name,
1101
+ count: messages.length,
1102
+ },
1103
+ });
1104
+ }
1105
+ }
1106
+ }
1107
+ }
1108
+ }
1109
+ }
172
1110
  async stop() {
1111
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
1112
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
1113
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
173
1114
  (0, runtime_1.emitNervesEvent)({
174
1115
  component: "daemon",
175
- event: "daemon.server_stop",
1116
+ event: "daemon.server_end",
176
1117
  message: "stopping daemon server",
177
1118
  meta: { socketPath: this.socketPath },
178
1119
  });
1120
+ (0, update_checker_1.stopUpdateChecker)();
1121
+ (0, mcp_manager_1.shutdownSharedMcpManager)();
179
1122
  this.scheduler.stop?.();
180
- await this.processManager.stopAll();
1123
+ this.healthMonitor.stopPeriodicChecks?.();
1124
+ if (this.senseAutostartTimer) {
1125
+ clearTimeout(this.senseAutostartTimer);
1126
+ this.senseAutostartTimer = null;
1127
+ }
1128
+ if (this.externalEventReconcileTimer) {
1129
+ clearInterval(this.externalEventReconcileTimer);
1130
+ this.externalEventReconcileTimer = null;
1131
+ }
1132
+ const workerStopTasks = [Promise.resolve().then(() => this.processManager.stopAll())];
1133
+ if (this.senseManager) {
1134
+ workerStopTasks.push(Promise.resolve().then(() => this.senseManager.stopAll()));
1135
+ }
1136
+ const workerStopResults = await Promise.allSettled(workerStopTasks);
1137
+ const workerStopFailures = workerStopResults.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
181
1138
  if (this.server) {
182
- await new Promise((resolve) => {
183
- this.server?.close(() => resolve());
184
- });
1139
+ // DO NOT `await` server.close() here. server.close() resolves only
1140
+ // after every open connection has closed. When stop() is invoked
1141
+ // from the daemon.stop command handler, the calling client's
1142
+ // connection is STILL open — its flushResponse() is currently
1143
+ // awaiting THIS function. Awaiting close() creates a deadlock:
1144
+ //
1145
+ // client → flushResponse → handleRawPayload → daemon.stop case
1146
+ // → stop() → await server.close() (waits for client's connection)
1147
+ // → client's connection waits for flushResponse to call
1148
+ // connection.end() → DEADLOCK
1149
+ //
1150
+ // Both processes sit in kevent forever. Verified live on
1151
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
1152
+ // line for 5+ minutes after a client sent daemon.stop, while the
1153
+ // client (alpha.270 ouro up) hung waiting for the response.
1154
+ //
1155
+ // This regressed when #303/#334/#339 stopped half-closing the
1156
+ // client socket and switched the server to allowHalfOpen: true.
1157
+ // Previously, the client called .end() after writing its command,
1158
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
1159
+ // the server's writable side — incidentally unblocking
1160
+ // server.close() before the response was sent. The half-close
1161
+ // breakage masked this deadlock; the fix exposed it.
1162
+ //
1163
+ // Solution: fire close() and let it complete asynchronously. Once
1164
+ // stop() returns, the daemon.stop case returns its response,
1165
+ // flushResponse() calls connection.end(response), the connection
1166
+ // closes, and server.close()'s pending callback fires. The event
1167
+ // loop drains and the daemon exits cleanly.
1168
+ this.server.close();
185
1169
  this.server = null;
186
1170
  }
187
- if (fs.existsSync(this.socketPath)) {
1171
+ if (this.mailboxServer) {
1172
+ await this.mailboxServer.stop();
1173
+ this.mailboxServer = null;
1174
+ }
1175
+ const socketPathExists = fs.existsSync(this.socketPath);
1176
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1177
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
188
1178
  fs.unlinkSync(this.socketPath);
189
1179
  }
1180
+ else if (socketPathExists) {
1181
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1182
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1183
+ (0, runtime_1.emitNervesEvent)({
1184
+ level: "warn",
1185
+ component: "daemon",
1186
+ event: "daemon.socket_cleanup_skipped",
1187
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1188
+ meta: {
1189
+ socketPath: this.socketPath,
1190
+ expectedDev: expectedSocketIdentity.dev,
1191
+ expectedIno: expectedSocketIdentity.ino,
1192
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1193
+ actualDev: actualSocketIdentity.dev,
1194
+ actualIno: actualSocketIdentity.ino,
1195
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1196
+ },
1197
+ });
1198
+ }
1199
+ this.socketIdentity = null;
1200
+ if (workerStopFailures.length > 0) {
1201
+ const errorReason = `daemon shutdown could not drain ${workerStopFailures.length} managed worker group(s)`;
1202
+ (0, runtime_1.emitNervesEvent)({
1203
+ level: "error",
1204
+ component: "daemon",
1205
+ event: "daemon.worker_shutdown_error",
1206
+ message: errorReason,
1207
+ meta: {
1208
+ failures: workerStopFailures.map((error) => error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error rejection @preserve */ String(error)),
1209
+ },
1210
+ });
1211
+ throw new AggregateError(workerStopFailures, errorReason);
1212
+ }
190
1213
  }
191
1214
  async handleRawPayload(raw) {
192
1215
  try {
@@ -208,19 +1231,658 @@ class OuroDaemon {
208
1231
  message: "handling daemon command",
209
1232
  meta: { kind: command.kind },
210
1233
  });
1234
+ try {
1235
+ return await this.handleCommandInner(command);
1236
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1237
+ }
1238
+ catch (error) {
1239
+ (0, runtime_1.emitNervesEvent)({
1240
+ level: "error",
1241
+ component: "daemon",
1242
+ event: "daemon.command_error",
1243
+ message: "unexpected error handling daemon command",
1244
+ meta: {
1245
+ kind: command.kind,
1246
+ error: error instanceof Error ? error.message : String(error),
1247
+ stack: error instanceof Error ? error.stack ?? null : null,
1248
+ },
1249
+ });
1250
+ throw error;
1251
+ }
1252
+ /* v8 ignore stop */
1253
+ }
1254
+ hasManagedPrivateRuntime(agent) {
1255
+ return this.processManager.listAgentSnapshots().some((snapshot) => snapshot.name === agent && snapshot.channel === "private-runtime");
1256
+ }
1257
+ buildPrivateRuntimeWakeRequest(command) {
1258
+ if (command.kind === "inner.wake") {
1259
+ return {
1260
+ agent: command.agent,
1261
+ origin: "daemon.private.wake",
1262
+ reason: "legacy inner.wake compatibility alias",
1263
+ providerLane: "inner",
1264
+ triggerSource: "legacy",
1265
+ budgetClass: "interactive",
1266
+ originRefs: [{ kind: "daemon-command", id: "inner.wake" }],
1267
+ };
1268
+ }
1269
+ const hasNoSendCapability = command.originRefs?.some((ref) => ref.kind === "capability" && ref.id === "no-send") ?? false;
1270
+ if ((command.noSend === true) !== hasNoSendCapability) {
1271
+ throw new Error("private-runtime no-send capability does not match its bound origin reference");
1272
+ }
1273
+ return {
1274
+ agent: command.agent,
1275
+ origin: "daemon.private.wake",
1276
+ reason: command.reason ?? "manual private-runtime wake",
1277
+ providerLane: "inner",
1278
+ triggerSource: command.triggerSource ?? "manual",
1279
+ budgetClass: command.budgetClass ?? "interactive",
1280
+ ...(command.idempotencyKey ? { idempotencyKey: command.idempotencyKey } : {}),
1281
+ originRefs: command.originRefs ?? [{ kind: "daemon-command", id: "private.wake" }],
1282
+ };
1283
+ }
1284
+ buildAwaitPrivateWakeCommand(command) {
1285
+ return (0, await_private_wake_1.buildAwaitPrivateWakeCommand)({
1286
+ agent: command.agent,
1287
+ awaitName: command.awaitName,
1288
+ triggerSource: "await-poke",
1289
+ });
1290
+ }
1291
+ buildTaskPokePrivateWakeCommand(command, receiptId) {
1292
+ return {
1293
+ kind: "private.wake",
1294
+ agent: command.agent,
1295
+ reason: `task poke ${command.taskId}`,
1296
+ triggerSource: "task-poke",
1297
+ budgetClass: "scheduled",
1298
+ idempotencyKey: `task-poke:${command.agent}:${command.taskId}:${receiptId}`,
1299
+ originRefs: [
1300
+ { kind: "task", id: command.taskId },
1301
+ { kind: "queue-receipt", id: receiptId },
1302
+ { kind: "daemon-command", id: "task.poke" },
1303
+ ],
1304
+ };
1305
+ }
1306
+ buildExternalEventPrivateWakeCommand(command, receiptId, generation, attemptCount) {
1307
+ return {
1308
+ kind: "private.wake",
1309
+ agent: command.agent,
1310
+ reason: `external event ${command.source}/${command.eventType}`,
1311
+ triggerSource: "external-event",
1312
+ budgetClass: "interactive",
1313
+ idempotencyKey: `external-event:${command.agent}:${command.source}:${command.eventId}:generation:${generation}:attempt:${attemptCount}`,
1314
+ originRefs: [
1315
+ { kind: "external-event", id: command.eventId, source: command.source, eventType: command.eventType },
1316
+ { kind: "queue-receipt", id: receiptId },
1317
+ { kind: "daemon-command", id: "external.event.submit" },
1318
+ ],
1319
+ };
1320
+ }
1321
+ resolveHabitDispatch(options) {
1322
+ const agentRoot = path.join(this.bundlesRoot, `${options.agent}.ouro`);
1323
+ const habitPath = path.join(agentRoot, "habits", `${options.habitName}.md`);
1324
+ const isRsvp = (0, habit_policy_1.isRsvpHabitName)(options.habitName);
1325
+ let readFailure = null;
1326
+ let habit;
1327
+ if (!fs.existsSync(habitPath)) {
1328
+ readFailure = "missing";
1329
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", "habit file not found");
1330
+ }
1331
+ else {
1332
+ try {
1333
+ habit = (0, habit_runtime_state_1.applyHabitRuntimeState)(agentRoot, (0, habit_parser_1.parseHabitFile)(fs.readFileSync(habitPath, "utf-8"), habitPath));
1334
+ }
1335
+ catch (error) {
1336
+ readFailure = "read";
1337
+ habit = (0, habit_parser_1.createDegradedHabitFile)(habitPath, "read_error", "", messageFromHabitPokeError(error));
1338
+ }
1339
+ }
1340
+ if (habit.status !== "active") {
1341
+ let skipReason = `habit status ${habit.status} is non-executable`;
1342
+ if (isRsvp && habit.status === "degraded") {
1343
+ if (readFailure === "missing") {
1344
+ skipReason = "RSVP habit file not found";
1345
+ }
1346
+ else {
1347
+ skipReason = `RSVP habit metadata invalid: ${habit.degradedDetail ?? habit.degradedReason}`;
1348
+ }
1349
+ }
1350
+ else if (readFailure === "missing"
1351
+ && options.source === "habit-poke"
1352
+ && options.trigger !== "manual"
1353
+ && options.trigger !== "poke") {
1354
+ skipReason = "habit file not found";
1355
+ }
1356
+ return { kind: "skipped", habit, skipReason };
1357
+ }
1358
+ if (isRsvp && !habit.rsvp) {
1359
+ return {
1360
+ kind: "skipped",
1361
+ habit,
1362
+ skipReason: "RSVP habit metadata is required before private runtime wake",
1363
+ };
1364
+ }
1365
+ if (options.trigger === "poke" || options.trigger === "manual") {
1366
+ return { kind: "ready", habit };
1367
+ }
1368
+ if (typeof options.occurrenceId === "string" && options.occurrenceId.trim().length > 0) {
1369
+ return { kind: "ready", habit, occurrenceId: options.occurrenceId.trim() };
1370
+ }
1371
+ if (habit.cadence === null) {
1372
+ return { kind: "skipped", habit, skipReason: "habit has no cadence" };
1373
+ }
1374
+ if (habit.lastRun === null) {
1375
+ return { kind: "ready", habit, occurrenceId: `${options.trigger}:first-run:${habit.cadence}` };
1376
+ }
1377
+ return {
1378
+ kind: "ready",
1379
+ habit,
1380
+ occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}`,
1381
+ };
1382
+ }
1383
+ emitHabitDispatchSkipped(options) {
1384
+ (0, runtime_1.emitNervesEvent)({
1385
+ level: "warn",
1386
+ component: "daemon",
1387
+ event: "daemon.habit_dispatch_skipped",
1388
+ message: "habit dispatch rejected by current lifecycle state",
1389
+ meta: {
1390
+ agent: options.agent,
1391
+ habitName: options.habitName,
1392
+ trigger: options.trigger,
1393
+ status: options.resolution.habit.status,
1394
+ degradedReason: options.resolution.habit.status === "degraded"
1395
+ ? options.resolution.habit.degradedReason
1396
+ : null,
1397
+ detail: options.resolution.habit.status === "degraded"
1398
+ ? options.resolution.habit.degradedDetail
1399
+ : null,
1400
+ reason: options.resolution.skipReason,
1401
+ },
1402
+ });
1403
+ }
1404
+ emitHabitDispatchReady(options) {
1405
+ (0, runtime_1.emitNervesEvent)({
1406
+ component: "daemon",
1407
+ event: "daemon.habit_dispatch_ready",
1408
+ message: "habit dispatch accepted by current lifecycle state",
1409
+ meta: {
1410
+ agent: options.agent,
1411
+ habitName: options.habitName,
1412
+ trigger: options.trigger,
1413
+ status: options.resolution.habit.status,
1414
+ occurrenceId: options.resolution.occurrenceId ?? null,
1415
+ },
1416
+ });
1417
+ }
1418
+ skippedHabitDispatchResponse(options) {
1419
+ return {
1420
+ ok: true,
1421
+ message: `skipped scheduled habit ${options.habitName} for ${options.agent}: ${options.skipReason}`,
1422
+ };
1423
+ }
1424
+ async runNativeRsvpHabit(command, trigger, occurrenceId, noSend = false) {
1425
+ const runner = this.rsvpHabitRunner ?? (async (input) => {
1426
+ const { runNativeRsvpHabit } = await Promise.resolve().then(() => __importStar(require("../../rsvp/native-habit-runner")));
1427
+ return runNativeRsvpHabit(input);
1428
+ });
1429
+ const result = await runner({
1430
+ agent: command.agent,
1431
+ bundlesRoot: this.bundlesRoot,
1432
+ habitName: command.habitName,
1433
+ trigger,
1434
+ ...(occurrenceId ? { occurrenceId } : {}),
1435
+ ...(noSend ? { noSend: true } : {}),
1436
+ });
1437
+ if (noSend) {
1438
+ const payload = result.payload;
1439
+ const status = payload?.status;
1440
+ const transportInvocationCount = payload?.transportInvocationCount;
1441
+ const contractError = "native RSVP habit probe violated the immutable no-send result contract";
1442
+ if (!result.ok) {
1443
+ return {
1444
+ ok: false,
1445
+ error: result.message,
1446
+ data: {
1447
+ ok: false,
1448
+ noSend: true,
1449
+ status: typeof status === "string" ? status : "degraded",
1450
+ transportInvocationCount: null,
1451
+ error: result.message,
1452
+ },
1453
+ };
1454
+ }
1455
+ if (payload?.noSend !== true
1456
+ || typeof status !== "string"
1457
+ || typeof transportInvocationCount !== "number"
1458
+ || transportInvocationCount !== 0) {
1459
+ return {
1460
+ ok: false,
1461
+ error: contractError,
1462
+ data: {
1463
+ ok: false,
1464
+ noSend: true,
1465
+ status: typeof status === "string" ? status : "degraded",
1466
+ transportInvocationCount: null,
1467
+ error: contractError,
1468
+ },
1469
+ };
1470
+ }
1471
+ return {
1472
+ ok: true,
1473
+ message: result.message,
1474
+ data: { noSend: true, status, transportInvocationCount: 0 },
1475
+ };
1476
+ }
1477
+ return {
1478
+ ok: result.ok,
1479
+ message: result.message,
1480
+ data: result,
1481
+ };
1482
+ }
1483
+ buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent) {
1484
+ const awaitName = (0, await_private_wake_1.awaitNameFromPrivateWakeCommand)(command);
1485
+ if (awaitName) {
1486
+ return {
1487
+ type: "await",
1488
+ awaitName,
1489
+ privateTurnDecision: decision,
1490
+ };
1491
+ }
1492
+ const taskId = taskIdFromTaskPokePrivateWakeCommand(command);
1493
+ if (taskId) {
1494
+ return {
1495
+ type: "poke",
1496
+ taskId,
1497
+ privateTurnDecision: decision,
1498
+ };
1499
+ }
1500
+ const habitMessage = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1501
+ if (habitMessage) {
1502
+ return {
1503
+ type: "habit",
1504
+ habitName: habitMessage.habitName,
1505
+ trigger: habitMessage.trigger,
1506
+ ...(habitMessage.noSend ? { noSend: true } : {}),
1507
+ privateTurnDecision: decision,
1508
+ };
1509
+ }
1510
+ return { type: "message", privateTurnDecision: decision, ...(externalEvent ? { externalEvent } : {}) };
1511
+ }
1512
+ queueOperatorCliMessageForPrivateRuntime(command) {
1513
+ if (command.kind !== "private.wake" || command.triggerSource !== "operator-cli")
1514
+ return;
1515
+ const receiptId = command.originRefs?.find((ref) => ref.kind === "daemon-receipt")?.id;
1516
+ if (!receiptId)
1517
+ return;
1518
+ const messages = this.router.peekInbox?.(command.agent) ?? [];
1519
+ const routed = messages.find((message) => message.id === receiptId);
1520
+ if (!routed)
1521
+ return;
1522
+ const pendingDir = path.join(this.bundlesRoot, `${command.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1523
+ const queuedAtMs = Date.parse(routed.queuedAt);
1524
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1525
+ from: routed.from,
1526
+ content: routed.content,
1527
+ timestamp: Number.isFinite(queuedAtMs) ? queuedAtMs : Date.now(),
1528
+ mode: "relay",
1529
+ requestId: routed.id,
1530
+ packetId: `operator-cli:${command.agent}:${routed.id}`,
1531
+ });
1532
+ }
1533
+ queueExternalEventForPrivateRuntime(record, quiet = false) {
1534
+ const pendingDir = path.join(this.bundlesRoot, `${record.agent}.ouro`, "state", "pending", pending_1.PRIVATE_RUNTIME_PENDING.friendId, pending_1.PRIVATE_RUNTIME_PENDING.channel, pending_1.PRIVATE_RUNTIME_PENDING.key);
1535
+ const originKey = `${record.source}:${record.eventId}`;
1536
+ const parsedReceivedAt = Date.parse(record.receivedAt);
1537
+ (0, pending_1.queuePendingMessageOnce)(pendingDir, {
1538
+ from: "ouro-external-event",
1539
+ friendId: "ouro-external-event",
1540
+ channel: "external-event",
1541
+ key: originKey,
1542
+ content: (0, router_1.buildExternalEventMessage)(record),
1543
+ timestamp: Number.isFinite(parsedReceivedAt) ? parsedReceivedAt : Date.now(),
1544
+ delegatedFrom: {
1545
+ friendId: "ouro-external-event",
1546
+ channel: "external-event",
1547
+ key: originKey,
1548
+ },
1549
+ obligationStatus: "pending",
1550
+ mode: "relay",
1551
+ packetId: `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount}`,
1552
+ });
1553
+ if (!quiet) {
1554
+ (0, runtime_1.emitNervesEvent)({
1555
+ component: "daemon",
1556
+ event: "daemon.external_event_private_runtime_queued",
1557
+ message: "queued external event for private-runtime attention",
1558
+ meta: {
1559
+ agent: record.agent,
1560
+ source: record.source,
1561
+ eventType: record.eventType,
1562
+ eventId: record.eventId,
1563
+ pendingDir,
1564
+ },
1565
+ });
1566
+ }
1567
+ }
1568
+ externalEventRootPath() {
1569
+ return this.externalEventRoot ?? (0, router_1.getExternalEventRoot)();
1570
+ }
1571
+ externalEventLease(record) {
1572
+ /* v8 ignore next -- dispatcher calls this only with the record returned by claimExternalEvent @preserve */
1573
+ if (!record.claimOwner)
1574
+ throw new Error("External event dispatch requires a claimed receipt");
1575
+ return {
1576
+ schemaVersion: 1,
1577
+ recordPath: record.recordPath,
1578
+ agent: record.agent,
1579
+ source: record.source,
1580
+ eventId: record.eventId,
1581
+ generation: record.generation,
1582
+ observationRevision: record.observationRevision,
1583
+ claimOwner: record.claimOwner,
1584
+ };
1585
+ }
1586
+ async dispatchExternalEvents(records) {
1587
+ const claimed = [];
1588
+ let failureClass;
1589
+ try {
1590
+ for (const key of new Set(records.map((record) => `${record.agent}\0${record.source}`))) {
1591
+ const [agent, source] = key.split("\0");
1592
+ await this.externalEventSourceReadiness(agent, source);
1593
+ }
1594
+ for (const record of records) {
1595
+ const owner = `external-event:${record.agent}:${record.source}:${record.eventId}:generation:${record.generation}:attempt:${record.attemptCount + 1}`;
1596
+ claimed.push((0, router_1.claimExternalEvent)(record.recordPath, { owner, expectedVersion: record.version, expectedGeneration: record.generation }));
1597
+ }
1598
+ const primary = claimed[0];
1599
+ const [primaryLease, ...relatedEvents] = claimed.map((record) => this.externalEventLease(record));
1600
+ const lease = { ...primaryLease, ...(relatedEvents.length > 0 ? { relatedEvents } : {}) };
1601
+ const receipt = {
1602
+ id: `external-event:${primary.agent}:${primary.source}:${primary.eventId}:generation:${primary.generation}:attempt:${primary.attemptCount}`,
1603
+ queuedAt: primary.updatedAt,
1604
+ };
1605
+ const wake = await this.handlePrivateRuntimeWake(this.buildExternalEventPrivateWakeCommand({
1606
+ kind: "external.event.submit",
1607
+ agent: primary.agent,
1608
+ source: primary.source,
1609
+ eventType: primary.eventType,
1610
+ eventId: primary.eventId,
1611
+ }, receipt.id, primary.generation, primary.attemptCount), () => {
1612
+ const batched = claimed.length > 1;
1613
+ for (const record of claimed)
1614
+ this.queueExternalEventForPrivateRuntime(record, batched);
1615
+ if (batched) {
1616
+ (0, runtime_1.emitNervesEvent)({
1617
+ component: "daemon",
1618
+ event: "daemon.external_event_private_runtime_batch_queued",
1619
+ message: "queued an external-event batch for private-runtime attention",
1620
+ meta: { agent: primary.agent, source: primary.source, eventCount: claimed.length },
1621
+ });
1622
+ }
1623
+ }, lease);
1624
+ failureClass = wake.denialCode === "managed_runtime_unavailable"
1625
+ ? "managed_runtime_unavailable"
1626
+ : wake.data?.decision?.denialCode === "provider_lane_unavailable"
1627
+ ? "provider_lane_unavailable"
1628
+ : undefined;
1629
+ const denied = !wake.ok || wake.data?.decision?.executable === false;
1630
+ if (denied)
1631
+ throw new Error(wake.error ?? wake.message ?? /* v8 ignore next -- daemon wake responses always carry an error or message @preserve */ "external-event private turn was denied");
1632
+ return { events: claimed, event: primary, receipt, wake };
1633
+ }
1634
+ catch (error) {
1635
+ for (const record of claimed) {
1636
+ (0, router_1.settleExternalEventFailureIfOwned)(record.recordPath, {
1637
+ owner: record.claimOwner, expectedGeneration: record.generation,
1638
+ error: failureClass ? `external-event private-runtime dispatch failed: ${failureClass}` : "external-event private-runtime dispatch failed",
1639
+ ...(failureClass ? { failureClass } : {}),
1640
+ });
1641
+ }
1642
+ throw error;
1643
+ }
1644
+ }
1645
+ dispatchExternalEvent(record) {
1646
+ return this.dispatchExternalEvents([record]);
1647
+ }
1648
+ async reconcileExternalEvents() {
1649
+ /* v8 ignore next -- re-entrancy guard is exercised only by overlapping real timer callbacks @preserve */
1650
+ if (this.externalEventReconcileRunning)
1651
+ return;
1652
+ this.externalEventReconcileRunning = true;
1653
+ try {
1654
+ const now = new Date().toISOString();
1655
+ if (fs.existsSync(this.privilegedEventSpoolRoot)) {
1656
+ this.privilegedEventScanner({ spoolRoot: this.privilegedEventSpoolRoot, eventRoot: this.externalEventRootPath() });
1657
+ }
1658
+ const statuses = (0, router_1.listExternalEventStatus)(this.externalEventRootPath());
1659
+ const readinessKeys = new Set();
1660
+ for (const status of statuses) {
1661
+ if (status.corrupt)
1662
+ continue;
1663
+ const candidate = (0, router_1.readExternalEventRecord)(status.recordPath);
1664
+ if (candidate.dispatchEnabled === false)
1665
+ continue;
1666
+ const retryDue = candidate.executionState === "retry_wait" && candidate.nextAttemptAt !== null && Date.parse(candidate.nextAttemptAt) <= Date.parse(now);
1667
+ const leaseExpired = candidate.executionState === "running" && candidate.claimExpiresAt !== null && Date.parse(candidate.claimExpiresAt) <= Date.parse(now);
1668
+ const recoverableDeadLetter = candidate.executionState === "dead_letter"
1669
+ && (0, router_1.externalEventRecoveryFailure)(candidate) !== null
1670
+ && candidate.recoveryGrant?.generation !== candidate.generation;
1671
+ const dispatchable = candidate.executionState === "received" || candidate.executionState === "queued" || retryDue || leaseExpired || recoverableDeadLetter;
1672
+ if (dispatchable && (candidate.source === "sanctuary-health" || candidate.source === "sanctuary-usenet"))
1673
+ readinessKeys.add(`${candidate.agent}\0${candidate.source}`);
1674
+ }
1675
+ const blockedReadinessKeys = new Set();
1676
+ for (const key of readinessKeys) {
1677
+ const [agent, source] = key.split("\0");
1678
+ try {
1679
+ await this.externalEventSourceReadiness(agent, source);
1680
+ }
1681
+ catch (error) {
1682
+ blockedReadinessKeys.add(key);
1683
+ (0, runtime_1.emitNervesEvent)({
1684
+ level: "warn",
1685
+ component: "daemon",
1686
+ event: "daemon.external_event_readiness_blocked",
1687
+ message: "external-event reconciliation is waiting for source runtime readiness",
1688
+ meta: { agent, source, error: (error instanceof Error ? error.message : String(error)).slice(0, 1_000) },
1689
+ });
1690
+ }
1691
+ }
1692
+ const dueRecords = [];
1693
+ const providerEvidenceByAgent = new Map();
1694
+ const runtimeEvidenceByAgent = new Map();
1695
+ const recoveredByClass = new Map();
1696
+ for (const status of statuses) {
1697
+ if (status.corrupt)
1698
+ continue;
1699
+ let record = (0, router_1.readExternalEventRecord)(status.recordPath);
1700
+ if (record.dispatchEnabled === false)
1701
+ continue;
1702
+ if (blockedReadinessKeys.has(`${record.agent}\0${record.source}`))
1703
+ continue;
1704
+ if (record.executionState === "dead_letter") {
1705
+ const failure = (0, router_1.externalEventRecoveryFailure)(record);
1706
+ if (!failure || record.recoveryGrant?.generation === record.generation)
1707
+ continue;
1708
+ let evidence = null;
1709
+ try {
1710
+ if (failure.class === "provider_lane_unavailable") {
1711
+ if (!providerEvidenceByAgent.has(record.agent)) {
1712
+ providerEvidenceByAgent.set(record.agent, null);
1713
+ const binding = (0, provider_binding_resolver_1.resolveEffectiveProviderBinding)({
1714
+ agentName: record.agent,
1715
+ agentRoot: path.join(this.bundlesRoot, `${record.agent}.ouro`),
1716
+ lane: "inner",
1717
+ });
1718
+ providerEvidenceByAgent.set(record.agent, binding.ok && binding.binding.credential.status === "present"
1719
+ && binding.binding.readiness.status === "ready" && binding.binding.readiness.checkedAt
1720
+ ? { observedAt: binding.binding.readiness.checkedAt }
1721
+ : null);
1722
+ }
1723
+ const current = providerEvidenceByAgent.get(record.agent);
1724
+ const readinessIsCurrentBoot = current && Date.parse(current.observedAt) >= this.constructedAtMs;
1725
+ if (current && ((0, router_1.isExactLegacyProviderRecoveryFailure)(record)
1726
+ ? readinessIsCurrentBoot
1727
+ : Date.parse(current.observedAt) > Date.parse(failure.failedAt))) {
1728
+ evidence = { class: failure.class, observedAt: current.observedAt };
1729
+ }
1730
+ }
1731
+ else if (failure.class === "execution_lease_expired") {
1732
+ if (!runtimeEvidenceByAgent.has(record.agent)) {
1733
+ const snapshot = this.processManager.listAgentSnapshots().find((candidate) => candidate.name === record.agent && candidate.channel === "private-runtime"
1734
+ && candidate.status === "running" && candidate.pid !== null && candidate.startedAt !== null);
1735
+ runtimeEvidenceByAgent.set(record.agent, snapshot?.startedAt ? { observedAt: snapshot.startedAt } : null);
1736
+ }
1737
+ const current = runtimeEvidenceByAgent.get(record.agent);
1738
+ if (current && Date.parse(current.observedAt) > Date.parse(failure.failedAt)) {
1739
+ evidence = { class: failure.class, observedAt: current.observedAt };
1740
+ }
1741
+ }
1742
+ else if (this.hasManagedPrivateRuntime(record.agent) && Date.parse(now) > Date.parse(failure.failedAt)) {
1743
+ evidence = { class: failure.class, observedAt: now };
1744
+ }
1745
+ if (!evidence)
1746
+ continue;
1747
+ const revival = (0, router_1.reviveExternalEventAfterRecovery)(record.recordPath, { expectedVersion: record.version, expectedGeneration: record.generation, evidence, now: () => now, quiet: true });
1748
+ record = revival.record;
1749
+ recoveredByClass.set(failure.class, (recoveredByClass.get(failure.class) ?? 0) + 1);
1750
+ }
1751
+ catch (error) {
1752
+ (0, runtime_1.emitNervesEvent)({
1753
+ level: "warn",
1754
+ component: "daemon",
1755
+ event: "daemon.external_event_recovery_error",
1756
+ message: "external event dead-letter recovery check failed",
1757
+ meta: { agent: record.agent, source: record.source, eventId: record.eventId, generation: record.generation, error: error instanceof Error ? error.message : String(error) },
1758
+ });
1759
+ continue;
1760
+ }
1761
+ }
1762
+ if (record.executionState === "running" && record.claimExpiresAt && Date.parse(record.claimExpiresAt) <= Date.parse(now)) {
1763
+ record = (0, router_1.reconcileExternalEvent)(record.recordPath);
1764
+ }
1765
+ const due = record.executionState === "received"
1766
+ || record.executionState === "queued"
1767
+ || (record.executionState === "retry_wait" && record.nextAttemptAt !== null && Date.parse(record.nextAttemptAt) <= Date.parse(now));
1768
+ if (due)
1769
+ dueRecords.push(record);
1770
+ }
1771
+ if (recoveredByClass.size > 0) {
1772
+ (0, runtime_1.emitNervesEvent)({
1773
+ component: "daemon",
1774
+ event: "daemon.external_event_recovery_batch",
1775
+ message: "requeued external events after cached infrastructure recovery evidence",
1776
+ meta: { recovered: Object.fromEntries(recoveredByClass) },
1777
+ });
1778
+ }
1779
+ const batches = new Map();
1780
+ for (const record of dueRecords) {
1781
+ const key = `${record.agent}\0${record.source}`;
1782
+ const batch = batches.get(key) ?? [];
1783
+ batch.push(record);
1784
+ batches.set(key, batch);
1785
+ }
1786
+ for (const records of batches.values()) {
1787
+ for (let offset = 0; offset < records.length; offset += 32) {
1788
+ const batch = records.slice(offset, offset + 32);
1789
+ try {
1790
+ await this.dispatchExternalEvents(batch);
1791
+ }
1792
+ catch (error) {
1793
+ (0, runtime_1.emitNervesEvent)({
1794
+ level: "warn",
1795
+ component: "daemon",
1796
+ event: "daemon.external_event_dispatch_error",
1797
+ message: "external event dispatch failed",
1798
+ meta: { recordPath: batch[0].recordPath, batchSize: batch.length, error: error instanceof Error ? error.message : /* v8 ignore next -- dispatch failures are Error objects @preserve */ String(error) },
1799
+ });
1800
+ }
1801
+ }
1802
+ }
1803
+ }
1804
+ finally {
1805
+ this.externalEventReconcileRunning = false;
1806
+ }
1807
+ }
1808
+ async handlePrivateRuntimeWake(command, beforeDispatch, externalEvent) {
1809
+ if (!this.hasManagedPrivateRuntime(command.agent)) {
1810
+ return {
1811
+ ok: false,
1812
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
1813
+ denialCode: "managed_runtime_unavailable",
1814
+ };
1815
+ }
1816
+ const decision = await (0, private_runtime_1.requestPrivateTurnDecision)(this.buildPrivateRuntimeWakeRequest(command), {
1817
+ bundlesRoot: this.bundlesRoot,
1818
+ ...this.privateRuntimePolicyDeps,
1819
+ });
1820
+ if (!decision.executable) {
1821
+ return {
1822
+ ok: true,
1823
+ message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
1824
+ ...(decision.denialCode ? { denialCode: decision.denialCode } : {}),
1825
+ data: { decision },
1826
+ };
1827
+ }
1828
+ this.queueOperatorCliMessageForPrivateRuntime(command);
1829
+ await beforeDispatch?.(decision);
1830
+ await this.processManager.startAgent(command.agent);
1831
+ const message = this.buildPrivateRuntimeWorkerWakeMessage(command, decision, externalEvent);
1832
+ if (this.processManager.dispatchToAgent)
1833
+ await this.processManager.dispatchToAgent(command.agent, message);
1834
+ else
1835
+ this.processManager.sendToAgent?.(command.agent, message);
1836
+ return {
1837
+ ok: true,
1838
+ message: `woke private runtime for ${command.agent}`,
1839
+ data: { decision },
1840
+ };
1841
+ }
1842
+ async handleCommandInner(command) {
211
1843
  switch (command.kind) {
212
1844
  case "daemon.start":
213
1845
  await this.start();
214
1846
  return { ok: true, message: "daemon started" };
215
1847
  case "daemon.stop":
216
- await this.stop();
1848
+ try {
1849
+ await this.stop();
1850
+ }
1851
+ finally {
1852
+ await this.onStopCommandComplete?.();
1853
+ }
217
1854
  return { ok: true, message: "daemon stopped" };
1855
+ case "daemon.restart": {
1856
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1857
+ // policy the process is auto-restarted on exit, so daemon.restart and
1858
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1859
+ // the process simply exits — same observable behavior as daemon.stop.
1860
+ (0, runtime_1.emitNervesEvent)({
1861
+ component: "daemon",
1862
+ event: "daemon.restart_requested",
1863
+ message: "daemon restart requested",
1864
+ meta: {
1865
+ reason: command.reason ?? null,
1866
+ requestedBy: command.requestedBy ?? null,
1867
+ },
1868
+ });
1869
+ try {
1870
+ await this.stop();
1871
+ }
1872
+ finally {
1873
+ await this.onStopCommandComplete?.();
1874
+ }
1875
+ return {
1876
+ ok: true,
1877
+ message: "daemon restarting — launchctl will respawn",
1878
+ };
1879
+ }
218
1880
  case "daemon.status": {
219
- const snapshots = this.processManager.listAgentSnapshots();
1881
+ const data = this.buildStatusPayload();
220
1882
  return {
221
1883
  ok: true,
222
- summary: formatStatusSummary(snapshots),
223
- data: snapshots,
1884
+ summary: formatStatusSummary(data),
1885
+ data,
224
1886
  };
225
1887
  }
226
1888
  case "daemon.health": {
@@ -233,17 +1895,114 @@ class OuroDaemon {
233
1895
  ok: true,
234
1896
  summary: "logs: use `ouro logs` to tail daemon and agent output",
235
1897
  message: "log streaming available via ouro logs",
236
- data: { logDir: "~/.agentstate/daemon/logs" },
1898
+ data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
237
1899
  };
1900
+ case "daemon.sense_revive": {
1901
+ if (!isValidSenseReviveCommand(command)) {
1902
+ return {
1903
+ ok: false,
1904
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
1905
+ };
1906
+ }
1907
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
1908
+ if (revivedSenseRow) {
1909
+ return {
1910
+ ok: true,
1911
+ message: `revived ${command.agent}/${command.sense}`,
1912
+ data: revivedSenseRow,
1913
+ };
1914
+ }
1915
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
1916
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
1917
+ if (managedSenseSnapshots.length === 0) {
1918
+ return {
1919
+ ok: false,
1920
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
1921
+ };
1922
+ }
1923
+ const exactTargetName = `${command.agent}:${command.sense}`;
1924
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
1925
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
1926
+ if (!target) {
1927
+ return {
1928
+ ok: false,
1929
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
1930
+ };
1931
+ }
1932
+ this.processManager.resetAgentFailureState(target.name);
1933
+ await this.processManager.startAgent(target.name);
1934
+ const freshSnapshot = this.processManager.listAgentSnapshots()
1935
+ .find((snapshot) => snapshot.name === target.name) ?? target;
1936
+ return {
1937
+ ok: true,
1938
+ message: `revived ${command.agent}/${command.sense}`,
1939
+ data: freshSnapshot,
1940
+ };
1941
+ }
238
1942
  case "agent.start":
239
1943
  await this.processManager.startAgent(command.agent);
240
1944
  return { ok: true, message: `started ${command.agent}` };
241
1945
  case "agent.stop":
242
1946
  await this.processManager.stopAgent?.(command.agent);
243
1947
  return { ok: true, message: `stopped ${command.agent}` };
244
- case "agent.restart":
245
- await this.processManager.restartAgent?.(command.agent);
246
- return { ok: true, message: `restarted ${command.agent}` };
1948
+ case "agent.restart": {
1949
+ if (!this.processManager.restartAgent) {
1950
+ return { ok: false, error: "Managed agent restart is not available." };
1951
+ }
1952
+ const managedSnapshot = this.processManager.listAgentSnapshots()
1953
+ .find((snapshot) => snapshot.name === command.agent);
1954
+ if (!managedSnapshot) {
1955
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
1956
+ }
1957
+ if (managedSnapshot.autoStart === false && managedSnapshot.status === "stopped") {
1958
+ return { ok: true, message: `restart skipped for parked non-autostart agent '${command.agent}'` };
1959
+ }
1960
+ const restartWork = command.skipConfigCheck === true
1961
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
1962
+ : this.processManager.restartAgent(command.agent);
1963
+ void restartWork.catch((error) => {
1964
+ (0, runtime_1.emitNervesEvent)({
1965
+ level: "error",
1966
+ component: "daemon",
1967
+ event: "daemon.agent_restart_request_error",
1968
+ message: "managed agent restart failed after request acknowledgement",
1969
+ meta: {
1970
+ agent: command.agent,
1971
+ error: error instanceof Error ? error.message : String(error),
1972
+ },
1973
+ });
1974
+ });
1975
+ return { ok: true, message: `restart requested for ${command.agent}` };
1976
+ }
1977
+ case "agent.ask":
1978
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
1979
+ case "agent.status":
1980
+ return (0, agent_service_1.handleAgentStatus)(command);
1981
+ case "agent.catchup":
1982
+ return (0, agent_service_1.handleAgentCatchup)(command);
1983
+ case "agent.delegate":
1984
+ return (0, agent_service_1.handleAgentDelegate)(command);
1985
+ case "agent.getContext":
1986
+ return (0, agent_service_1.handleAgentGetContext)(command);
1987
+ case "agent.searchFacts":
1988
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
1989
+ case "agent.getTask":
1990
+ return (0, agent_service_1.handleAgentGetTask)(command);
1991
+ case "agent.checkScope":
1992
+ return (0, agent_service_1.handleAgentCheckScope)(command);
1993
+ case "agent.requestDecision":
1994
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
1995
+ case "agent.checkGuidance":
1996
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
1997
+ case "agent.reportProgress":
1998
+ return (0, agent_service_1.handleAgentReportProgress)(command);
1999
+ case "agent.reportBlocker":
2000
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
2001
+ case "agent.reportComplete":
2002
+ return (0, agent_service_1.handleAgentReportComplete)(command);
2003
+ case "agent.senseTurn":
2004
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
2005
+ /* v8 ignore stop */
247
2006
  case "cron.list": {
248
2007
  const jobs = this.scheduler.listJobs();
249
2008
  const summary = jobs.length === 0
@@ -252,10 +2011,28 @@ class OuroDaemon {
252
2011
  return { ok: true, summary, data: jobs };
253
2012
  }
254
2013
  case "cron.trigger": {
2014
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
2015
+ if (habitResult?.ok) {
2016
+ return { ok: true, message: habitResult.message };
2017
+ }
255
2018
  const result = await this.scheduler.triggerJob(command.jobId);
256
2019
  return { ok: result.ok, message: result.message };
257
2020
  }
258
2021
  case "message.send": {
2022
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
2023
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
2024
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
2025
+ // events to avoid waking the agent on every tool call. The hook's
2026
+ // intent was completely defeated by this handler calling
2027
+ // `sendToAgent({type: "message"})`, which woke the private runtime
2028
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
2029
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
2030
+ //
2031
+ // Callers that want immediate processing must send `private.wake`
2032
+ // explicitly after message.send. The CLI `ouro msg` does so
2033
+ // (lifecycle-boundary delivery should wake); the hook does so
2034
+ // only on session-start / stop, not per tool-use; the API does
2035
+ // not (notifications go to the queue).
259
2036
  const receipt = await this.router.send({
260
2037
  from: command.from,
261
2038
  to: command.to,
@@ -264,7 +2041,6 @@ class OuroDaemon {
264
2041
  sessionId: command.sessionId,
265
2042
  taskRef: command.taskRef,
266
2043
  });
267
- this.processManager.sendToAgent?.(command.to, { type: "message" });
268
2044
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
269
2045
  }
270
2046
  case "message.poll": {
@@ -275,6 +2051,127 @@ class OuroDaemon {
275
2051
  data: messages,
276
2052
  };
277
2053
  }
2054
+ case "external.event.submit": {
2055
+ const record = (0, router_1.recordExternalEvent)({
2056
+ agent: command.agent,
2057
+ source: command.source,
2058
+ eventType: command.eventType,
2059
+ eventId: command.eventId,
2060
+ summary: command.summary,
2061
+ evidence: command.evidence,
2062
+ payloadPath: command.payloadPath,
2063
+ priority: command.priority,
2064
+ observationRevision: command.observationRevision,
2065
+ transition: command.transition,
2066
+ }, {
2067
+ ...(this.externalEventRoot ? { root: this.externalEventRoot } : {}),
2068
+ dispatchEnabled: command.wake !== false,
2069
+ });
2070
+ if (!record.shouldWake || command.wake === false) {
2071
+ return {
2072
+ ok: true,
2073
+ message: `updated external event ${record.source}/${record.eventId} without wake`,
2074
+ data: { event: record, receipt: null, wake: null },
2075
+ };
2076
+ }
2077
+ const dispatched = await this.dispatchExternalEvent(record);
2078
+ return {
2079
+ ok: true,
2080
+ message: `queued external event ${record.source}/${record.eventId} as ${dispatched.receipt.id}; ${dispatched.wake.message ?? "wake skipped"}`,
2081
+ data: dispatched,
2082
+ };
2083
+ }
2084
+ case "external.event.repair": {
2085
+ if (this.externalEventReconcileRunning)
2086
+ return { ok: false, error: "external event reconciliation is already active; repair made no changes" };
2087
+ this.externalEventReconcileRunning = true;
2088
+ try {
2089
+ try {
2090
+ const result = (0, router_1.repairExternalEventsFromManifest)(command.manifestPath, { root: this.externalEventRootPath() });
2091
+ return { ok: result.failed.length === 0, message: `external event repair applied=${result.applied.length} alreadyApplied=${result.alreadyApplied.length} failed=${result.failed.length} pending=${result.pending.length}`, data: result };
2092
+ }
2093
+ catch (error) {
2094
+ const message = (error instanceof Error ? error.message : /* v8 ignore next -- defensive: repair parser and filesystem dependencies throw Error instances @preserve */ String(error)).slice(0, 1_000);
2095
+ const result = { applied: [], alreadyApplied: [], failed: [{ identity: "<manifest>", error: message }], pending: [] };
2096
+ (0, runtime_1.emitNervesEvent)({ level: "error", component: "daemon", event: "daemon.external_event_repair", message: "rejected external event repair manifest", meta: { applied: 0, alreadyApplied: 0, failed: 1, pending: 0 } });
2097
+ return { ok: false, error: `external event repair rejected: ${message}`, data: result };
2098
+ }
2099
+ }
2100
+ finally {
2101
+ this.externalEventReconcileRunning = false;
2102
+ }
2103
+ }
2104
+ case "private.decisions": {
2105
+ const requestedLimit = Number.isInteger(command.limit) && command.limit && command.limit > 0 ? command.limit : 20;
2106
+ const limit = Math.min(requestedLimit, 1000);
2107
+ const ledgerPath = (0, private_runtime_1.privateTurnLedgerPath)(command.agent, { bundlesRoot: this.bundlesRoot });
2108
+ const ledgerExists = fs.existsSync(ledgerPath);
2109
+ let decisions;
2110
+ try {
2111
+ decisions = ledgerExists ? (0, private_runtime_1.readPrivateTurnLedger)(ledgerPath) : [];
2112
+ }
2113
+ catch {
2114
+ return {
2115
+ ok: false,
2116
+ error: `private-runtime decision ledger is malformed: ${ledgerPath}; repair or remove malformed JSONL rows before reading decisions`,
2117
+ };
2118
+ }
2119
+ const guidance = ledgerExists
2120
+ ? undefined
2121
+ : `No private-runtime decision ledger exists for ${command.agent}; run an explicit private-runtime trigger or check ${path.dirname(ledgerPath)}.`;
2122
+ const payload = (0, private_runtime_1.buildPrivateDecisionReadPayload)({
2123
+ agent: command.agent,
2124
+ ledgerPath,
2125
+ decisions,
2126
+ limit,
2127
+ ...(guidance ? { guidance } : {}),
2128
+ });
2129
+ return {
2130
+ ok: true,
2131
+ summary: (0, private_runtime_1.privateDecisionCountSummary)(payload.decisions.length),
2132
+ ...(guidance ? { message: guidance } : {}),
2133
+ data: payload,
2134
+ };
2135
+ }
2136
+ case "inner.wake":
2137
+ return this.handlePrivateRuntimeWake(command);
2138
+ case "private.wake": {
2139
+ const scheduledHabit = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
2140
+ if (!scheduledHabit || !this.hasManagedPrivateRuntime(command.agent)) {
2141
+ return this.handlePrivateRuntimeWake(command);
2142
+ }
2143
+ const occurrenceRef = command.originRefs?.find((ref) => ref.kind === "habit-occurrence");
2144
+ const occurrenceId = typeof occurrenceRef?.id === "string" && occurrenceRef.id.trim().length > 0
2145
+ ? occurrenceRef.id.trim()
2146
+ : undefined;
2147
+ const resolution = this.resolveHabitDispatch({
2148
+ agent: command.agent,
2149
+ habitName: scheduledHabit.habitName,
2150
+ trigger: scheduledHabit.trigger,
2151
+ source: "private-wake",
2152
+ ...(occurrenceId ? { occurrenceId } : {}),
2153
+ });
2154
+ if (resolution.kind === "skipped") {
2155
+ this.emitHabitDispatchSkipped({
2156
+ agent: command.agent,
2157
+ habitName: scheduledHabit.habitName,
2158
+ trigger: scheduledHabit.trigger,
2159
+ resolution,
2160
+ });
2161
+ return this.skippedHabitDispatchResponse({
2162
+ agent: command.agent,
2163
+ habitName: scheduledHabit.habitName,
2164
+ skipReason: resolution.skipReason,
2165
+ });
2166
+ }
2167
+ this.emitHabitDispatchReady({
2168
+ agent: command.agent,
2169
+ habitName: scheduledHabit.habitName,
2170
+ trigger: scheduledHabit.trigger,
2171
+ resolution,
2172
+ });
2173
+ return this.handlePrivateRuntimeWake(command);
2174
+ }
278
2175
  case "chat.connect":
279
2176
  await this.processManager.startAgent(command.agent);
280
2177
  return {
@@ -282,6 +2179,12 @@ class OuroDaemon {
282
2179
  message: `connected to ${command.agent}`,
283
2180
  };
284
2181
  case "task.poke": {
2182
+ if (!isValidTaskPokeCommand(command)) {
2183
+ return {
2184
+ ok: false,
2185
+ error: "Invalid task.poke payload: expected non-empty string fields 'agent' and 'taskId'.",
2186
+ };
2187
+ }
285
2188
  const receipt = await this.router.send({
286
2189
  from: "ouro-poke",
287
2190
  to: command.agent,
@@ -290,17 +2193,242 @@ class OuroDaemon {
290
2193
  taskRef: command.taskId,
291
2194
  });
292
2195
  await this.scheduler.recordTaskRun?.(command.agent, command.taskId);
293
- this.processManager.sendToAgent?.(command.agent, { type: "poke", taskId: command.taskId });
2196
+ await this.handlePrivateRuntimeWake(this.buildTaskPokePrivateWakeCommand(command, receipt.id));
294
2197
  return {
295
2198
  ok: true,
296
2199
  message: `queued poke ${receipt.id}`,
297
2200
  data: receipt,
298
2201
  };
299
2202
  }
2203
+ case "habit.scheduler-fire": {
2204
+ if (!this.schedulerFireVerifier || !this.schedulerFireConsumer)
2205
+ return { ok: false, error: "authenticated scheduler fire is unavailable" };
2206
+ let origin;
2207
+ try {
2208
+ origin = this.schedulerFireVerifier(command);
2209
+ this.schedulerFireConsumer(origin);
2210
+ }
2211
+ catch (error) {
2212
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2213
+ }
2214
+ const poke = { kind: "habit.poke", agent: command.agent, habitName: command.habitName, trigger: "cron", occurrenceId: origin.occurrenceId };
2215
+ this.authenticatedSchedulerPokes.set(poke, origin);
2216
+ try {
2217
+ return await this.handleCommand(poke);
2218
+ }
2219
+ finally {
2220
+ this.authenticatedSchedulerPokes.delete(poke);
2221
+ }
2222
+ }
2223
+ case "habit.poke": {
2224
+ if (!isValidHabitPokeCommand(command)) {
2225
+ return {
2226
+ ok: false,
2227
+ error: "Invalid habit.poke payload: expected non-empty string fields 'agent' and 'habitName'.",
2228
+ };
2229
+ }
2230
+ const trigger = command.trigger ?? "poke";
2231
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
2232
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
2233
+ }
2234
+ const schedulerOrigin = this.authenticatedSchedulerPokes.get(command);
2235
+ if (command.agent === "sanctuary" && command.habitName === "sanctuary-health" && trigger === "cron" && !schedulerOrigin) {
2236
+ return { ok: false, error: "Sanctuary cron habit requires authenticated Supercronic provenance" };
2237
+ }
2238
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2239
+ return {
2240
+ ok: false,
2241
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2242
+ };
2243
+ }
2244
+ const resolution = this.resolveHabitDispatch({
2245
+ agent: command.agent,
2246
+ habitName: command.habitName,
2247
+ trigger,
2248
+ source: "habit-poke",
2249
+ ...(command.occurrenceId ? { occurrenceId: command.occurrenceId } : {}),
2250
+ });
2251
+ if (resolution.kind === "skipped") {
2252
+ this.emitHabitDispatchSkipped({
2253
+ agent: command.agent,
2254
+ habitName: command.habitName,
2255
+ trigger,
2256
+ resolution,
2257
+ });
2258
+ return this.skippedHabitDispatchResponse({
2259
+ agent: command.agent,
2260
+ habitName: command.habitName,
2261
+ skipReason: resolution.skipReason,
2262
+ });
2263
+ }
2264
+ this.emitHabitDispatchReady({
2265
+ agent: command.agent,
2266
+ habitName: command.habitName,
2267
+ trigger,
2268
+ resolution,
2269
+ });
2270
+ if (this.nativeHabitRunner && this.nativeHabitMatch?.(command.agent, command.habitName)) {
2271
+ const occurrenceId = resolution.occurrenceId ?? `${trigger}:${command.agent}:${command.habitName}`;
2272
+ const claimKey = `${command.agent}:${command.habitName}`;
2273
+ if (this.nativeHabitClaims.has(claimKey)) {
2274
+ return { ok: true, message: `skipped overlapping native habit occurrence ${occurrenceId}` };
2275
+ }
2276
+ this.nativeHabitClaims.add(claimKey);
2277
+ const startedAt = new Date().toISOString();
2278
+ const runnerId = (0, node_crypto_1.randomUUID)();
2279
+ let nativeResult;
2280
+ try {
2281
+ nativeResult = await this.nativeHabitRunner({
2282
+ agent: command.agent,
2283
+ habitName: command.habitName,
2284
+ trigger,
2285
+ occurrenceId,
2286
+ runnerId,
2287
+ ...(schedulerOrigin ? { schedulerOrigin } : {}),
2288
+ }) ?? { ok: false, error: "native habit runner declined a matched habit" };
2289
+ }
2290
+ catch (error) {
2291
+ nativeResult = { ok: false, error: error instanceof Error ? error.message : String(error) };
2292
+ }
2293
+ const endedAt = new Date().toISOString();
2294
+ let completion;
2295
+ try {
2296
+ completion = (0, habit_session_1.completeHabitRun)({
2297
+ agentRoot: path.join(this.bundlesRoot, `${command.agent}.ouro`),
2298
+ habit: resolution.habit,
2299
+ runId: runnerId,
2300
+ trigger,
2301
+ startedAt,
2302
+ endedAt,
2303
+ operationId: occurrenceId,
2304
+ permissionEnvelope: { schemaVersion: 1, canMessageOutward: true, returnRoutes: [], deniedTools: [], warnings: [] },
2305
+ toolPolicy: { requestedTools: null, grantedTools: [], deniedTools: [], outwardMessagingAllowed: true },
2306
+ ...(nativeResult.ok ? {} : { errors: [nativeResult.error ?? nativeResult.message ?? "native habit failed"] }),
2307
+ });
2308
+ }
2309
+ finally {
2310
+ this.nativeHabitClaims.delete(claimKey);
2311
+ }
2312
+ if (!completion.receiptWritten || !completion.runtimeStateRecorded) {
2313
+ return { ok: false, error: "native habit completed but its durable receipt or cursor could not be recorded", data: nativeResult };
2314
+ }
2315
+ return nativeResult;
2316
+ }
2317
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2318
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId);
2319
+ }
2320
+ return this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2321
+ agent: command.agent,
2322
+ habitName: command.habitName,
2323
+ trigger,
2324
+ sourceRef: { kind: "daemon-command", id: "habit.poke" },
2325
+ occurrenceId: resolution.occurrenceId,
2326
+ }));
2327
+ }
2328
+ case "habit.probe": {
2329
+ if (!isValidHabitProbeCommand(command)) {
2330
+ return {
2331
+ ok: false,
2332
+ error: "Invalid habit.probe payload: expected non-empty agent/habitName and noSend=true.",
2333
+ };
2334
+ }
2335
+ const trigger = "manual";
2336
+ if (!(0, habit_policy_1.isRsvpHabitName)(command.habitName) && !this.hasManagedPrivateRuntime(command.agent)) {
2337
+ return {
2338
+ ok: false,
2339
+ error: `No managed agent '${command.agent}' is registered with daemon-managed private runtime.`,
2340
+ };
2341
+ }
2342
+ const resolution = this.resolveHabitDispatch({
2343
+ agent: command.agent,
2344
+ habitName: command.habitName,
2345
+ trigger,
2346
+ source: "habit-probe",
2347
+ });
2348
+ if (resolution.kind === "skipped") {
2349
+ this.emitHabitDispatchSkipped({
2350
+ agent: command.agent,
2351
+ habitName: command.habitName,
2352
+ trigger,
2353
+ resolution,
2354
+ });
2355
+ return {
2356
+ ok: true,
2357
+ message: `habit probe rejected by lifecycle: status=${resolution.habit.status}`,
2358
+ data: {
2359
+ noSend: true,
2360
+ status: resolution.habit.status,
2361
+ transportInvocationCount: 0,
2362
+ },
2363
+ };
2364
+ }
2365
+ this.emitHabitDispatchReady({
2366
+ agent: command.agent,
2367
+ habitName: command.habitName,
2368
+ trigger,
2369
+ resolution,
2370
+ });
2371
+ if ((0, habit_policy_1.isRsvpHabitName)(command.habitName)) {
2372
+ return this.runNativeRsvpHabit(command, trigger, resolution.occurrenceId, true);
2373
+ }
2374
+ const wake = await this.handlePrivateRuntimeWake((0, habit_private_wake_1.buildHabitPrivateWakeCommand)({
2375
+ agent: command.agent,
2376
+ habitName: command.habitName,
2377
+ trigger,
2378
+ sourceRef: { kind: "daemon-command", id: "habit.probe" },
2379
+ occurrenceId: resolution.occurrenceId,
2380
+ noSend: true,
2381
+ }));
2382
+ if (!wake.ok)
2383
+ return wake;
2384
+ const denied = wake.data
2385
+ ?.decision?.executable === false;
2386
+ const error = denied
2387
+ ? "non-RSVP habit probe was not executed because private-runtime policy denied execution"
2388
+ : "non-RSVP habit probe completion is asynchronous; zero-transport evidence is unverified";
2389
+ return {
2390
+ ok: false,
2391
+ error,
2392
+ data: {
2393
+ ok: false,
2394
+ noSend: true,
2395
+ status: resolution.habit.status,
2396
+ transportInvocationCount: null,
2397
+ error,
2398
+ },
2399
+ };
2400
+ }
2401
+ case "await.poke": {
2402
+ return this.handlePrivateRuntimeWake(this.buildAwaitPrivateWakeCommand(command));
2403
+ }
2404
+ case "mcp.list": {
2405
+ (0, identity_1.setAgentName)(command.agent ?? "default");
2406
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
2407
+ if (!mcpManager) {
2408
+ return { ok: true, data: [], message: "no MCP servers configured" };
2409
+ }
2410
+ return { ok: true, data: mcpManager.listAllTools() };
2411
+ }
2412
+ case "mcp.call": {
2413
+ (0, identity_1.setAgentName)(command.agent ?? "default");
2414
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
2415
+ if (!mcpCallManager) {
2416
+ return { ok: false, error: "no MCP servers configured" };
2417
+ }
2418
+ try {
2419
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
2420
+ const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
2421
+ return { ok: true, data: result };
2422
+ }
2423
+ catch (error) {
2424
+ /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
2425
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
2426
+ }
2427
+ }
300
2428
  case "hatch.start":
301
2429
  return {
302
2430
  ok: true,
303
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
2431
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
304
2432
  };
305
2433
  default:
306
2434
  return {