@ouro.bot/cli 0.1.0-alpha.83 → 0.1.0-alpha.831

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