@ouro.bot/cli 0.1.0-alpha.75 → 0.1.0-alpha.750

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