@ouro.bot/cli 0.1.0-alpha.67 → 0.1.0-alpha.671

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 (457) hide show
  1. package/README.md +127 -23
  2. package/RepairGuide.ouro/agent.json +5 -0
  3. package/RepairGuide.ouro/psyche/IDENTITY.md +19 -0
  4. package/RepairGuide.ouro/psyche/SOUL.md +55 -0
  5. package/RepairGuide.ouro/skills/diagnose-broken-remote.md +63 -0
  6. package/RepairGuide.ouro/skills/diagnose-stacked-typed-issues.md +35 -0
  7. package/RepairGuide.ouro/skills/diagnose-sync-blocked.md +54 -0
  8. package/RepairGuide.ouro/skills/diagnose-vault-expired.md +60 -0
  9. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +4 -2
  10. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +2 -2
  11. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +1 -1
  12. package/changelog.json +4277 -16
  13. package/dist/a2a/card.js +56 -0
  14. package/dist/a2a/client.js +143 -0
  15. package/dist/a2a/config.js +50 -0
  16. package/dist/a2a/onboarding.js +83 -0
  17. package/dist/a2a/server.js +498 -0
  18. package/dist/a2a/task-store.js +69 -0
  19. package/dist/a2a/types.js +3 -0
  20. package/dist/arc/attention-types.js +8 -0
  21. package/dist/arc/cares.js +144 -0
  22. package/dist/arc/episodes.js +118 -0
  23. package/dist/arc/evolution.js +487 -0
  24. package/dist/arc/flight-recorder.js +810 -0
  25. package/dist/arc/intentions.js +134 -0
  26. package/dist/arc/json-store.js +117 -0
  27. package/dist/arc/obligations.js +326 -0
  28. package/dist/arc/packets.js +288 -0
  29. package/dist/arc/presence.js +185 -0
  30. package/dist/arc/task-lifecycle.js +57 -0
  31. package/dist/commerce/store.js +755 -0
  32. package/dist/commerce/types.js +3 -0
  33. package/dist/heart/active-work.js +860 -43
  34. package/dist/heart/agent-entry.js +69 -3
  35. package/dist/heart/attachments/image-normalize.js +194 -0
  36. package/dist/heart/attachments/materialize.js +97 -0
  37. package/dist/heart/attachments/originals.js +88 -0
  38. package/dist/heart/attachments/render.js +29 -0
  39. package/dist/heart/attachments/sources/bluebubbles.js +156 -0
  40. package/dist/heart/attachments/sources/cli-local-file.js +78 -0
  41. package/dist/heart/attachments/sources/index.js +16 -0
  42. package/dist/heart/attachments/store.js +103 -0
  43. package/dist/heart/attachments/types.js +93 -0
  44. package/dist/heart/auth/auth-flow.js +479 -0
  45. package/dist/heart/awaiting/await-alert.js +146 -0
  46. package/dist/heart/awaiting/await-expiry.js +108 -0
  47. package/dist/heart/awaiting/await-loader.js +91 -0
  48. package/dist/heart/awaiting/await-parser.js +141 -0
  49. package/dist/heart/awaiting/await-runtime-state.js +100 -0
  50. package/dist/heart/awaiting/await-scheduler.js +378 -0
  51. package/dist/heart/background-operations.js +281 -0
  52. package/dist/heart/bridges/manager.js +137 -17
  53. package/dist/heart/bridges/store.js +14 -2
  54. package/dist/heart/bundle-state.js +168 -0
  55. package/dist/heart/commitments.js +135 -0
  56. package/dist/heart/config-registry.js +331 -0
  57. package/dist/heart/config.js +118 -119
  58. package/dist/heart/context-loss-gauntlet.js +354 -0
  59. package/dist/heart/context-loss-sentinel.js +907 -0
  60. package/dist/heart/core.js +1288 -249
  61. package/dist/heart/cross-chat-delivery.js +8 -22
  62. package/dist/heart/daemon/agent-config-check.js +427 -0
  63. package/dist/heart/daemon/agent-discovery.js +102 -3
  64. package/dist/heart/daemon/agent-service.js +523 -0
  65. package/dist/heart/daemon/agentic-repair.js +547 -0
  66. package/dist/heart/daemon/bluebubbles-health-diagnostics.js +122 -0
  67. package/dist/heart/daemon/boot-sync-probe.js +197 -0
  68. package/dist/heart/daemon/cadence.js +70 -0
  69. package/dist/heart/daemon/cli-defaults.js +780 -0
  70. package/dist/heart/daemon/cli-desk.js +322 -0
  71. package/dist/heart/daemon/cli-exec.js +7940 -0
  72. package/dist/heart/daemon/cli-help.js +576 -0
  73. package/dist/heart/daemon/cli-parse.js +1850 -0
  74. package/dist/heart/daemon/cli-render-doctor.js +57 -0
  75. package/dist/heart/daemon/cli-render.js +763 -0
  76. package/dist/heart/daemon/cli-types.js +8 -0
  77. package/dist/heart/daemon/connect-bay.js +323 -0
  78. package/dist/heart/daemon/daemon-cli.js +29 -1750
  79. package/dist/heart/daemon/daemon-entry.js +533 -3
  80. package/dist/heart/daemon/daemon-health.js +176 -0
  81. package/dist/heart/daemon/daemon-rollup.js +57 -0
  82. package/dist/heart/daemon/daemon-runtime-sync.js +88 -13
  83. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  84. package/dist/heart/daemon/daemon.js +950 -76
  85. package/dist/heart/daemon/dns-workflow.js +394 -0
  86. package/dist/heart/daemon/doctor-types.js +8 -0
  87. package/dist/heart/daemon/doctor.js +873 -0
  88. package/dist/heart/daemon/health-monitor.js +125 -1
  89. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  90. package/dist/heart/daemon/hooks/bundle-meta.js +135 -1
  91. package/dist/heart/daemon/http-health-probe.js +80 -0
  92. package/dist/heart/daemon/human-command-screens.js +234 -0
  93. package/dist/heart/daemon/human-readiness.js +114 -0
  94. package/dist/heart/daemon/inner-status.js +78 -0
  95. package/dist/heart/daemon/interactive-repair.js +394 -0
  96. package/dist/heart/daemon/launchd.js +37 -8
  97. package/dist/heart/daemon/log-tailer.js +79 -10
  98. package/dist/heart/daemon/logs-prune.js +110 -0
  99. package/dist/heart/daemon/mcp-canary.js +297 -0
  100. package/dist/heart/daemon/message-router.js +6 -2
  101. package/dist/heart/daemon/migrate-to-desk.js +848 -0
  102. package/dist/heart/daemon/os-cron-deps.js +135 -0
  103. package/dist/heart/daemon/os-cron.js +14 -12
  104. package/dist/heart/daemon/ouro-bot-entry.js +4 -2
  105. package/dist/heart/daemon/ouro-entry.js +3 -1
  106. package/dist/heart/daemon/plugin-cli.js +432 -0
  107. package/dist/heart/daemon/process-manager.js +511 -40
  108. package/dist/heart/daemon/provider-discovery.js +137 -0
  109. package/dist/heart/daemon/provider-ping-progress.js +83 -0
  110. package/dist/heart/daemon/pulse.js +475 -0
  111. package/dist/heart/daemon/readiness-repair.js +365 -0
  112. package/dist/heart/daemon/run-hooks.js +2 -0
  113. package/dist/heart/daemon/runtime-logging.js +41 -14
  114. package/dist/heart/daemon/runtime-metadata.js +2 -30
  115. package/dist/heart/daemon/safe-mode.js +161 -0
  116. package/dist/heart/daemon/sense-manager.js +564 -38
  117. package/dist/heart/daemon/session-id-resolver.js +131 -0
  118. package/dist/heart/daemon/skill-management-installer.js +1 -1
  119. package/dist/heart/daemon/socket-client.js +158 -11
  120. package/dist/heart/daemon/stale-bundle-prune.js +96 -0
  121. package/dist/heart/daemon/startup-tui.js +330 -0
  122. package/dist/heart/daemon/task-scheduler.js +117 -39
  123. package/dist/heart/daemon/terminal-ui.js +499 -0
  124. package/dist/heart/daemon/thoughts.js +229 -17
  125. package/dist/heart/daemon/up-progress.js +366 -0
  126. package/dist/heart/daemon/vault-items.js +56 -0
  127. package/dist/heart/delegation.js +1 -4
  128. package/dist/heart/habits/habit-migration.js +189 -0
  129. package/dist/heart/habits/habit-parser.js +211 -0
  130. package/dist/heart/habits/habit-runtime-state.js +114 -0
  131. package/dist/heart/habits/habit-scheduler.js +391 -0
  132. package/dist/heart/habits/habit-session-summary.js +318 -0
  133. package/dist/heart/habits/habit-session.js +618 -0
  134. package/dist/heart/{daemon → hatch}/hatch-flow.js +42 -56
  135. package/dist/heart/{daemon → hatch}/hatch-specialist.js +6 -8
  136. package/dist/heart/{daemon → hatch}/specialist-prompt.js +12 -9
  137. package/dist/heart/{daemon → hatch}/specialist-tools.js +45 -18
  138. package/dist/heart/identity.js +174 -57
  139. package/dist/heart/kept-notes.js +289 -0
  140. package/dist/heart/kicks.js +1 -1
  141. package/dist/heart/machine-identity.js +161 -0
  142. package/dist/heart/mail-import-discovery.js +353 -0
  143. package/dist/heart/mailbox/mailbox-http-hooks.js +96 -0
  144. package/dist/heart/mailbox/mailbox-http-response.js +7 -0
  145. package/dist/heart/mailbox/mailbox-http-routes.js +375 -0
  146. package/dist/heart/mailbox/mailbox-http-static.js +103 -0
  147. package/dist/heart/mailbox/mailbox-http-transport.js +116 -0
  148. package/dist/heart/mailbox/mailbox-http.js +99 -0
  149. package/dist/heart/mailbox/mailbox-read.js +37 -0
  150. package/dist/heart/mailbox/mailbox-types.js +27 -0
  151. package/dist/heart/mailbox/mailbox-view.js +197 -0
  152. package/dist/heart/mailbox/readers/agent-machine.js +428 -0
  153. package/dist/heart/mailbox/readers/continuity-readers.js +329 -0
  154. package/dist/heart/mailbox/readers/mail.js +375 -0
  155. package/dist/heart/mailbox/readers/runtime-readers.js +815 -0
  156. package/dist/heart/mailbox/readers/sessions.js +232 -0
  157. package/dist/heart/mailbox/readers/shared.js +111 -0
  158. package/dist/heart/mcp/mcp-server.js +696 -0
  159. package/dist/heart/migrate-config.js +100 -0
  160. package/dist/heart/model-capabilities.js +19 -0
  161. package/dist/heart/orientation-frame.js +217 -0
  162. package/dist/heart/platform.js +81 -0
  163. package/dist/heart/provider-attempt.js +134 -0
  164. package/dist/heart/provider-binding-resolver.js +273 -0
  165. package/dist/heart/provider-credentials.js +425 -0
  166. package/dist/heart/provider-failover.js +311 -0
  167. package/dist/heart/provider-models.js +81 -0
  168. package/dist/heart/provider-ping.js +262 -0
  169. package/dist/heart/provider-readiness-cache.js +119 -0
  170. package/dist/heart/provider-visibility.js +188 -0
  171. package/dist/heart/providers/anthropic-token.js +131 -0
  172. package/dist/heart/providers/anthropic.js +139 -52
  173. package/dist/heart/providers/azure.js +23 -11
  174. package/dist/heart/providers/error-classification.js +127 -0
  175. package/dist/heart/providers/github-copilot.js +145 -0
  176. package/dist/heart/providers/minimax-vlm.js +189 -0
  177. package/dist/heart/providers/minimax.js +26 -8
  178. package/dist/heart/providers/openai-codex-token.js +349 -0
  179. package/dist/heart/providers/openai-codex.js +55 -40
  180. package/dist/heart/runtime-capability-check.js +170 -0
  181. package/dist/heart/runtime-credentials.js +367 -0
  182. package/dist/heart/runtime-cwd.js +87 -0
  183. package/dist/heart/sense-truth.js +17 -4
  184. package/dist/heart/session-activity.js +48 -24
  185. package/dist/heart/session-events.js +1133 -0
  186. package/dist/heart/session-playback-cli-main.js +5 -0
  187. package/dist/heart/session-playback-cli.js +36 -0
  188. package/dist/heart/session-playback.js +231 -0
  189. package/dist/heart/session-stats-cli-main.js +5 -0
  190. package/dist/heart/session-stats.js +182 -0
  191. package/dist/heart/session-transcript.js +133 -0
  192. package/dist/heart/start-of-turn-packet.js +357 -0
  193. package/dist/heart/streaming.js +44 -27
  194. package/dist/heart/structured-output.js +196 -0
  195. package/dist/heart/sync-classification.js +176 -0
  196. package/dist/heart/sync.js +449 -0
  197. package/dist/heart/target-resolution.js +11 -7
  198. package/dist/heart/tempo.js +93 -0
  199. package/dist/heart/temporal-view.js +41 -0
  200. package/dist/heart/timeouts.js +101 -0
  201. package/dist/heart/tool-activity-callbacks.js +59 -0
  202. package/dist/heart/tool-description.js +155 -0
  203. package/dist/heart/tool-friction.js +55 -0
  204. package/dist/heart/tool-loop.js +200 -0
  205. package/dist/heart/turn-context.js +450 -0
  206. package/dist/heart/{daemon → versioning}/ouro-bot-global-installer.js +6 -5
  207. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  208. package/dist/heart/versioning/ouro-path-installer.js +426 -0
  209. package/dist/heart/versioning/ouro-version-manager.js +409 -0
  210. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  211. package/dist/heart/{daemon → versioning}/update-checker.js +6 -1
  212. package/dist/heart/versioning/update-hooks.js +154 -0
  213. package/dist/heart/work-card.js +390 -0
  214. package/dist/mailbox-ui/assets/index-CaTIFDmv.js +1 -0
  215. package/dist/mailbox-ui/assets/index-Du_9G9WO.css +1 -0
  216. package/dist/mailbox-ui/assets/vendor-CcN1XpQ9.js +61 -0
  217. package/dist/mailbox-ui/index.html +16 -0
  218. package/dist/mailroom/attention.js +167 -0
  219. package/dist/mailroom/autonomy.js +209 -0
  220. package/dist/mailroom/blob-store.js +715 -0
  221. package/dist/mailroom/body-cache.js +61 -0
  222. package/dist/mailroom/core.js +788 -0
  223. package/dist/mailroom/entry.js +160 -0
  224. package/dist/mailroom/file-store.js +568 -0
  225. package/dist/mailroom/mbox-import.js +393 -0
  226. package/dist/mailroom/migration.js +164 -0
  227. package/dist/mailroom/outbound.js +380 -0
  228. package/dist/mailroom/policy.js +263 -0
  229. package/dist/mailroom/reader.js +233 -0
  230. package/dist/mailroom/search-cache.js +334 -0
  231. package/dist/mailroom/search-relevance.js +319 -0
  232. package/dist/mailroom/smtp-ingress.js +176 -0
  233. package/dist/mailroom/source-state.js +176 -0
  234. package/dist/mailroom/thread.js +109 -0
  235. package/dist/mailroom/travel-extract.js +89 -0
  236. package/dist/mind/bundle-manifest.js +24 -2
  237. package/dist/mind/context.js +250 -101
  238. package/dist/mind/desk-section.js +362 -0
  239. package/dist/mind/diary-integrity.js +60 -0
  240. package/dist/mind/{memory.js → diary.js} +68 -77
  241. package/dist/mind/embedding-provider.js +60 -0
  242. package/dist/mind/file-state.js +179 -0
  243. package/dist/mind/{associative-recall.js → note-search.js} +47 -58
  244. package/dist/mind/obligation-steering.js +221 -0
  245. package/dist/mind/pending.js +6 -1
  246. package/dist/mind/prompt-refresh.js +3 -2
  247. package/dist/mind/prompt.js +1020 -148
  248. package/dist/mind/provenance-trust.js +26 -0
  249. package/dist/mind/record-paths.js +312 -0
  250. package/dist/mind/scrutiny.js +173 -0
  251. package/dist/nerves/cli-logging.js +7 -1
  252. package/dist/nerves/coverage/audit-rules.js +15 -6
  253. package/dist/nerves/coverage/audit.js +28 -2
  254. package/dist/nerves/coverage/cli.js +1 -1
  255. package/dist/nerves/coverage/contract.js +5 -5
  256. package/dist/nerves/coverage/file-completeness.js +139 -5
  257. package/dist/nerves/event-buffer.js +111 -0
  258. package/dist/nerves/index.js +224 -4
  259. package/dist/nerves/observation.js +20 -0
  260. package/dist/nerves/redact.js +79 -0
  261. package/dist/nerves/review/cli-main.js +5 -0
  262. package/dist/nerves/review/cli.js +156 -0
  263. package/dist/nerves/review/core.js +152 -0
  264. package/dist/nerves/runtime.js +5 -1
  265. package/dist/repertoire/ado-client.js +15 -56
  266. package/dist/repertoire/ado-semantic.js +16 -10
  267. package/dist/repertoire/api-client.js +97 -0
  268. package/dist/repertoire/bitwarden-store.js +1042 -0
  269. package/dist/repertoire/bundle-templates.js +71 -0
  270. package/dist/repertoire/bw-installer.js +180 -0
  271. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  272. package/dist/repertoire/coding/context-pack.js +331 -0
  273. package/dist/repertoire/coding/feedback.js +197 -30
  274. package/dist/repertoire/coding/manager.js +166 -10
  275. package/dist/repertoire/coding/spawner.js +55 -9
  276. package/dist/repertoire/coding/tools.js +219 -7
  277. package/dist/repertoire/commerce-errors.js +109 -0
  278. package/dist/repertoire/commerce-self-test.js +156 -0
  279. package/dist/repertoire/credential-access.js +178 -0
  280. package/dist/repertoire/desk/classifier.js +362 -0
  281. package/dist/repertoire/duffel-client.js +185 -0
  282. package/dist/repertoire/github-client.js +14 -55
  283. package/dist/repertoire/graph-client.js +11 -52
  284. package/dist/repertoire/guardrails.js +161 -27
  285. package/dist/repertoire/mcp-client.js +295 -0
  286. package/dist/repertoire/mcp-manager.js +434 -0
  287. package/dist/repertoire/mcp-tools.js +83 -0
  288. package/dist/repertoire/plugin-mcp.js +175 -0
  289. package/dist/repertoire/plugins.js +253 -0
  290. package/dist/repertoire/shell-sessions.js +133 -0
  291. package/dist/repertoire/skills.js +48 -4
  292. package/dist/repertoire/stripe-client.js +131 -0
  293. package/dist/repertoire/tool-results.js +29 -0
  294. package/dist/repertoire/tools-a2a.js +282 -0
  295. package/dist/repertoire/tools-attachments.js +317 -0
  296. package/dist/repertoire/tools-awaiting.js +372 -0
  297. package/dist/repertoire/tools-base.js +63 -1082
  298. package/dist/repertoire/tools-bluebubbles.js +2 -0
  299. package/dist/repertoire/tools-bridge.js +144 -0
  300. package/dist/repertoire/tools-bundle.js +993 -0
  301. package/dist/repertoire/tools-commerce.js +253 -0
  302. package/dist/repertoire/tools-config.js +186 -0
  303. package/dist/repertoire/tools-continuity.js +252 -0
  304. package/dist/repertoire/tools-credential.js +383 -0
  305. package/dist/repertoire/tools-evolution.js +527 -0
  306. package/dist/repertoire/tools-files.js +344 -0
  307. package/dist/repertoire/tools-flight.js +290 -0
  308. package/dist/repertoire/tools-flow.js +119 -0
  309. package/dist/repertoire/tools-github.js +3 -8
  310. package/dist/repertoire/tools-mail.js +1975 -0
  311. package/dist/repertoire/tools-notes.js +459 -0
  312. package/dist/repertoire/tools-obligations.js +143 -0
  313. package/dist/repertoire/tools-orientation.js +31 -0
  314. package/dist/repertoire/tools-record.js +482 -0
  315. package/dist/repertoire/tools-runtime.js +150 -0
  316. package/dist/repertoire/tools-session.js +906 -0
  317. package/dist/repertoire/tools-shell.js +120 -0
  318. package/dist/repertoire/tools-stripe.js +224 -0
  319. package/dist/repertoire/tools-surface.js +355 -0
  320. package/dist/repertoire/tools-teams.js +12 -39
  321. package/dist/repertoire/tools-travel.js +125 -0
  322. package/dist/repertoire/tools-trip.js +982 -0
  323. package/dist/repertoire/tools-user-profile.js +146 -0
  324. package/dist/repertoire/tools-vault.js +40 -0
  325. package/dist/repertoire/tools-voice.js +145 -0
  326. package/dist/repertoire/tools.js +250 -79
  327. package/dist/repertoire/travel-api-client.js +360 -0
  328. package/dist/repertoire/user-profile.js +131 -0
  329. package/dist/repertoire/vault-setup.js +246 -0
  330. package/dist/repertoire/vault-unlock.js +594 -0
  331. package/dist/scripts/claude-code-hook.js +41 -0
  332. package/dist/scripts/claude-code-stop-hook.js +47 -0
  333. package/dist/senses/a2a-entry.js +78 -0
  334. package/dist/senses/attention-queue.js +186 -0
  335. package/dist/senses/await-turn-message.js +58 -0
  336. package/dist/senses/bluebubbles/active-turns.js +216 -0
  337. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  338. package/dist/senses/bluebubbles/attachment-download.js +137 -0
  339. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +219 -18
  340. package/dist/senses/bluebubbles/entry.js +77 -0
  341. package/dist/senses/{bluebubbles-inbound-log.js → bluebubbles/inbound-log.js} +20 -3
  342. package/dist/senses/bluebubbles/index.js +2732 -0
  343. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +121 -71
  344. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +33 -12
  345. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +3 -3
  346. package/dist/senses/bluebubbles/processed-log.js +133 -0
  347. package/dist/senses/bluebubbles/replay.js +137 -0
  348. package/dist/senses/{bluebubbles-runtime-state.js → bluebubbles/runtime-state.js} +30 -2
  349. package/dist/senses/{bluebubbles-session-cleanup.js → bluebubbles/session-cleanup.js} +1 -1
  350. package/dist/senses/bluebubbles-meta-guard.js +40 -0
  351. package/dist/senses/cli/bracketed-paste.js +82 -0
  352. package/dist/senses/cli/image-paste.js +287 -0
  353. package/dist/senses/cli/image-ref-navigation.js +75 -0
  354. package/dist/senses/cli/ink-app.js +156 -0
  355. package/dist/senses/cli/inline-diff.js +64 -0
  356. package/dist/senses/cli/input-keys.js +174 -0
  357. package/dist/senses/cli/kill-ring.js +86 -0
  358. package/dist/senses/cli/message-list.js +51 -0
  359. package/dist/senses/cli/ouro-tui.js +607 -0
  360. package/dist/senses/cli/spinner-imperative.js +135 -0
  361. package/dist/senses/cli/spinner.js +101 -0
  362. package/dist/senses/cli/status-line.js +60 -0
  363. package/dist/senses/cli/streaming-markdown.js +526 -0
  364. package/dist/senses/cli/tool-display.js +85 -0
  365. package/dist/senses/cli/tool-render.js +85 -0
  366. package/dist/senses/cli/tui-store.js +240 -0
  367. package/dist/senses/cli/virtual-list.js +35 -0
  368. package/dist/senses/cli-entry.js +60 -8
  369. package/dist/senses/cli-layout.js +100 -0
  370. package/dist/senses/cli.js +522 -212
  371. package/dist/senses/commands.js +66 -3
  372. package/dist/senses/habit-turn-message.js +160 -0
  373. package/dist/senses/inner-dialog-worker.js +499 -22
  374. package/dist/senses/inner-dialog.js +544 -47
  375. package/dist/senses/mail-entry.js +66 -0
  376. package/dist/senses/mail.js +379 -0
  377. package/dist/senses/pipeline.js +870 -179
  378. package/dist/senses/proactive-content-guard.js +51 -0
  379. package/dist/senses/shared-turn.js +416 -0
  380. package/dist/senses/surface-tool.js +109 -0
  381. package/dist/senses/teams-entry.js +60 -8
  382. package/dist/senses/teams.js +400 -112
  383. package/dist/senses/trust-gate.js +102 -7
  384. package/dist/senses/voice/audio-playback.js +237 -0
  385. package/dist/senses/voice/audio-routing.js +119 -0
  386. package/dist/senses/voice/elevenlabs.js +202 -0
  387. package/dist/senses/voice/floor-control.js +431 -0
  388. package/dist/senses/voice/floor-controller.js +115 -0
  389. package/dist/senses/voice/golden-path.js +116 -0
  390. package/dist/senses/voice/index.js +29 -0
  391. package/dist/senses/voice/meeting.js +113 -0
  392. package/dist/senses/voice/outbound.js +190 -0
  393. package/dist/senses/voice/phone.js +33 -0
  394. package/dist/senses/voice/playback.js +139 -0
  395. package/dist/senses/voice/realtime-eval.js +496 -0
  396. package/dist/senses/voice/realtime-trace.js +531 -0
  397. package/dist/senses/voice/transcript.js +70 -0
  398. package/dist/senses/voice/turn.js +191 -0
  399. package/dist/senses/voice/twilio-phone-runtime.js +807 -0
  400. package/dist/senses/voice/twilio-phone.js +5077 -0
  401. package/dist/senses/voice/types.js +2 -0
  402. package/dist/senses/voice/whisper.js +161 -0
  403. package/dist/senses/voice-entry.js +81 -0
  404. package/dist/senses/voice-realtime-eval-command.js +99 -0
  405. package/dist/senses/voice-realtime-eval-entry.js +21 -0
  406. package/dist/senses/voice-twilio-entry.js +87 -0
  407. package/dist/trips/core.js +138 -0
  408. package/dist/trips/store.js +265 -0
  409. package/dist/util/frontmatter.js +69 -0
  410. package/package.json +57 -12
  411. package/skills/agent-commerce.md +113 -0
  412. package/skills/browser-navigation.md +117 -0
  413. package/skills/commerce-setup-guide.md +116 -0
  414. package/skills/commerce-setup.md +84 -0
  415. package/skills/configure-dev-tools.md +99 -0
  416. package/skills/travel-planning.md +138 -0
  417. package/dist/heart/daemon/auth-flow.js +0 -351
  418. package/dist/heart/daemon/ouro-path-installer.js +0 -178
  419. package/dist/heart/daemon/update-hooks.js +0 -138
  420. package/dist/heart/safe-workspace.js +0 -228
  421. package/dist/heart/session-recall.js +0 -116
  422. package/dist/mind/friends/channel.js +0 -84
  423. package/dist/mind/friends/group-context.js +0 -144
  424. package/dist/mind/friends/resolver.js +0 -84
  425. package/dist/mind/friends/store-file.js +0 -190
  426. package/dist/mind/friends/store.js +0 -4
  427. package/dist/mind/friends/tokens.js +0 -26
  428. package/dist/mind/friends/trust-explanation.js +0 -74
  429. package/dist/mind/friends/types.js +0 -29
  430. package/dist/repertoire/tasks/board.js +0 -134
  431. package/dist/repertoire/tasks/index.js +0 -224
  432. package/dist/repertoire/tasks/lifecycle.js +0 -80
  433. package/dist/repertoire/tasks/middleware.js +0 -65
  434. package/dist/repertoire/tasks/parser.js +0 -173
  435. package/dist/repertoire/tasks/scanner.js +0 -132
  436. package/dist/repertoire/tasks/transitions.js +0 -144
  437. package/dist/senses/bluebubbles-entry.js +0 -13
  438. package/dist/senses/bluebubbles.js +0 -1177
  439. package/dist/senses/debug-activity.js +0 -148
  440. package/subagents/README.md +0 -7
  441. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  442. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  443. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  444. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  445. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  446. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  447. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  448. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  449. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  450. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  451. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  452. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  453. /package/dist/{repertoire/tasks/types.js → heart/attachments/sources/adapter.js} +0 -0
  454. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  455. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  456. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  457. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,21 +34,342 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.OuroDaemon = void 0;
37
+ exports.parseOrphanPidsFromPs = parseOrphanPidsFromPs;
38
+ exports.filterPidfilePidsToActualOrphans = filterPidfilePidsToActualOrphans;
39
+ exports.mergeUniqueOrphanPids = mergeUniqueOrphanPids;
40
+ exports.waitForOrphanProcessesToSettle = waitForOrphanProcessesToSettle;
41
+ exports.killOrphanProcesses = killOrphanProcesses;
42
+ exports.writePidfile = writePidfile;
43
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
44
+ exports.handleAgentAskTurn = handleAgentAskTurn;
37
45
  const fs = __importStar(require("fs"));
38
46
  const net = __importStar(require("net"));
47
+ const os = __importStar(require("os"));
39
48
  const path = __importStar(require("path"));
40
49
  const identity_1 = require("../identity");
50
+ const agent_discovery_1 = require("./agent-discovery");
41
51
  const runtime_1 = require("../../nerves/runtime");
42
52
  const runtime_metadata_1 = require("./runtime-metadata");
43
53
  const runtime_mode_1 = require("./runtime-mode");
44
- const update_hooks_1 = require("./update-hooks");
54
+ const update_hooks_1 = require("../versioning/update-hooks");
45
55
  const bundle_meta_1 = require("./hooks/bundle-meta");
56
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
46
57
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
47
- const update_checker_1 = require("./update-checker");
48
- const staged_restart_1 = require("./staged-restart");
58
+ const update_checker_1 = require("../versioning/update-checker");
49
59
  const child_process_1 = require("child_process");
50
60
  const pending_1 = require("../../mind/pending");
51
- const channel_1 = require("../../mind/friends/channel");
61
+ const agent_service_1 = require("./agent-service");
62
+ const friends_1 = require("@ouro.bot/friends");
63
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
64
+ const mailbox_http_1 = require("../mailbox/mailbox-http");
65
+ const mailbox_types_1 = require("../mailbox/mailbox-types");
66
+ const mailbox_read_1 = require("../mailbox/mailbox-read");
67
+ const mailbox_view_1 = require("../mailbox/mailbox-view");
68
+ const provider_visibility_1 = require("../provider-visibility");
69
+ const socket_client_1 = require("./socket-client");
70
+ const flight_recorder_1 = require("../../arc/flight-recorder");
71
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
72
+ /**
73
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
74
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
75
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
76
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
77
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
78
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
79
+ * by a vitest test that called daemon.start()).
80
+ *
81
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
82
+ * to make the production pidfile sacred. Tests that need to verify these
83
+ * functions' behavior should use the extracted pure helpers
84
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
85
+ */
86
+ function isVitestProcess() {
87
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
88
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
89
+ return false;
90
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
91
+ }
92
+ /**
93
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
94
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
95
+ * that are safe to SIGTERM — true orphans, not children of live sibling
96
+ * daemons running from worktrees, test suites, or other users of the harness.
97
+ *
98
+ * Exported so unit tests can exercise the filter without shelling out.
99
+ */
100
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
101
+ const orphans = [];
102
+ for (const line of psOutput.split("\n")) {
103
+ // Explicitly exclude MCP server processes — they share a harness entry
104
+ // point but are not daemon children and must never be killed.
105
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
106
+ continue;
107
+ // Match only daemon-owned JS entry points.
108
+ if (!line.includes("agent-entry.js")
109
+ && !line.includes("daemon-entry.js")
110
+ && !line.includes("bluebubbles/entry.js")
111
+ && !line.includes("mail-entry.js")
112
+ && !line.includes("teams-entry.js")
113
+ && !line.includes("a2a-entry.js"))
114
+ continue;
115
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
116
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
117
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
118
+ if (!match)
119
+ continue;
120
+ const pid = parseInt(match[1], 10);
121
+ const ppid = parseInt(match[2], 10);
122
+ if (pid === selfPid)
123
+ continue;
124
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
125
+ // PPID means the process belongs to another daemon instance (parallel
126
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
127
+ // Killing those will crash unrelated harnesses — we saw this in B6
128
+ // when a vitest worker's daemon killed a production agent's children.
129
+ if (ppid !== 1)
130
+ continue;
131
+ orphans.push(pid);
132
+ }
133
+ return orphans;
134
+ }
135
+ /**
136
+ * Given a list of PIDs from the pidfile, return only those that are actual
137
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
138
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
139
+ *
140
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
141
+ * Returns the empty list if ps fails — safer to skip cleanup than to
142
+ * wildcard-kill on a bad read.
143
+ *
144
+ * Exported for direct unit coverage.
145
+ */
146
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
147
+ if (candidatePids.length === 0)
148
+ return [];
149
+ const psOutput = psRunner(candidatePids);
150
+ if (psOutput === null)
151
+ return [];
152
+ const survivingOrphans = [];
153
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
154
+ // PIDs not found (already exited) are silently omitted — which is the
155
+ // correct behavior for us: we only want to kill live orphans.
156
+ for (const line of psOutput.split("\n")) {
157
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
158
+ if (!match)
159
+ continue;
160
+ const pid = parseInt(match[1], 10);
161
+ const ppid = parseInt(match[2], 10);
162
+ if (ppid !== 1)
163
+ continue;
164
+ if (!candidatePids.includes(pid))
165
+ continue;
166
+ survivingOrphans.push(pid);
167
+ }
168
+ return survivingOrphans;
169
+ }
170
+ function mergeUniqueOrphanPids(...sources) {
171
+ const merged = [];
172
+ const seen = new Set();
173
+ for (const source of sources) {
174
+ for (const pid of source) {
175
+ if (seen.has(pid))
176
+ continue;
177
+ seen.add(pid);
178
+ merged.push(pid);
179
+ }
180
+ }
181
+ return merged;
182
+ }
183
+ const ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS = 5_000;
184
+ const ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS = 50;
185
+ /* v8 ignore start -- process liveness probe; pure wait behavior covered via injected deps @preserve */
186
+ function defaultIsPidAlive(pid) {
187
+ try {
188
+ process.kill(pid, 0);
189
+ return true;
190
+ }
191
+ catch (error) {
192
+ return error.code === "EPERM";
193
+ }
194
+ }
195
+ /* v8 ignore stop */
196
+ /* v8 ignore start -- real timer wiring; wait behavior covered via injected sleep @preserve */
197
+ async function defaultSettleSleep(ms) {
198
+ await new Promise((resolve) => setTimeout(resolve, ms));
199
+ }
200
+ /* v8 ignore stop */
201
+ async function waitForOrphanProcessesToSettle(pids, deps = {}) {
202
+ if (pids.length === 0)
203
+ return [];
204
+ const isPidAlive = deps.isPidAlive ?? defaultIsPidAlive;
205
+ const now = deps.now ?? Date.now;
206
+ const sleep = deps.sleep ?? defaultSettleSleep;
207
+ const timeoutMs = deps.timeoutMs ?? ORPHAN_CLEANUP_SETTLE_TIMEOUT_MS;
208
+ const pollIntervalMs = deps.pollIntervalMs ?? ORPHAN_CLEANUP_SETTLE_POLL_INTERVAL_MS;
209
+ const deadline = now() + timeoutMs;
210
+ let survivors = pids.filter(isPidAlive);
211
+ while (survivors.length > 0 && now() < deadline) {
212
+ await sleep(pollIntervalMs);
213
+ survivors = pids.filter(isPidAlive);
214
+ }
215
+ return survivors;
216
+ }
217
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
218
+ function runPsCheck(pids) {
219
+ try {
220
+ const csv = pids.join(",");
221
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
222
+ }
223
+ catch {
224
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
225
+ // "no survivors" rather than an error.
226
+ return "";
227
+ }
228
+ }
229
+ /* v8 ignore stop */
230
+ /**
231
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
232
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
233
+ * deletes the file. The new daemon writes its own PIDs after spawning.
234
+ *
235
+ * Safety: pidfile contents are verified before being killed — each PID must
236
+ * be an actual orphan (PPID reparented to init/PID 1) via
237
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
238
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
239
+ * OS) could SIGTERM unrelated processes.
240
+ *
241
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
242
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
243
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
244
+ */
245
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
246
+ function isProductionDaemonSocketPath(socketPath) {
247
+ return socketPath === socket_client_1.DEFAULT_DAEMON_SOCKET_PATH;
248
+ }
249
+ function killOrphanProcesses(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
250
+ if (!isProductionDaemonSocketPath(socketPath)) {
251
+ (0, runtime_1.emitNervesEvent)({
252
+ level: "warn",
253
+ component: "daemon",
254
+ event: "daemon.orphan_cleanup_nonproduction_blocked",
255
+ message: "blocked orphan cleanup for non-production daemon socket",
256
+ meta: { socketPath, pidfilePath: PIDFILE_PATH },
257
+ });
258
+ return [];
259
+ }
260
+ if (isVitestProcess()) {
261
+ (0, runtime_1.emitNervesEvent)({
262
+ level: "warn",
263
+ component: "daemon",
264
+ event: "daemon.orphan_cleanup_test_blocked",
265
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
266
+ meta: { pidfilePath: PIDFILE_PATH },
267
+ });
268
+ return [];
269
+ }
270
+ try {
271
+ let pidfileOrphans = [];
272
+ let scanOrphans = [];
273
+ // Primary: read pidfile from previous daemon
274
+ try {
275
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
276
+ const candidates = raw.split("\n")
277
+ .map((s) => parseInt(s.trim(), 10))
278
+ .filter((n) => !isNaN(n) && n !== process.pid);
279
+ // Verify each candidate is an actual live orphan before killing. See
280
+ // docstring above for why this matters.
281
+ pidfileOrphans = filterPidfilePidsToActualOrphans(candidates);
282
+ fs.unlinkSync(PIDFILE_PATH);
283
+ }
284
+ catch {
285
+ // No pidfile — the ps scan below still covers true orphans.
286
+ }
287
+ // Always supplement the pidfile with the scoped ps scan. A stale or
288
+ // partial pidfile can otherwise kill one old daemon while leaving a
289
+ // sibling PPID=1 daemon alive without a socket.
290
+ try {
291
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
292
+ scanOrphans = parseOrphanPidsFromPs(result, process.pid);
293
+ }
294
+ catch { /* ps failed — best effort */ }
295
+ const pidsToKill = mergeUniqueOrphanPids(pidfileOrphans, scanOrphans);
296
+ if (pidsToKill.length > 0) {
297
+ for (const pid of pidsToKill) {
298
+ try {
299
+ process.kill(pid, "SIGTERM");
300
+ }
301
+ catch { /* already exited */ }
302
+ }
303
+ (0, runtime_1.emitNervesEvent)({
304
+ component: "daemon",
305
+ event: "daemon.orphan_cleanup",
306
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
307
+ meta: { pids: pidsToKill },
308
+ });
309
+ }
310
+ return pidsToKill;
311
+ }
312
+ catch (error) {
313
+ (0, runtime_1.emitNervesEvent)({
314
+ level: "warn",
315
+ component: "daemon",
316
+ event: "daemon.orphan_cleanup_error",
317
+ message: "failed to clean up orphaned ouro processes",
318
+ meta: { error: error instanceof Error ? error.message : String(error) },
319
+ });
320
+ return [];
321
+ }
322
+ }
323
+ /**
324
+ * Write all managed PIDs (daemon + children) to the pidfile.
325
+ * Called after all agents and senses are spawned.
326
+ */
327
+ function writePidfile(extraPids = [], socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
328
+ if (!isProductionDaemonSocketPath(socketPath)) {
329
+ (0, runtime_1.emitNervesEvent)({
330
+ level: "warn",
331
+ component: "daemon",
332
+ event: "daemon.write_pidfile_nonproduction_blocked",
333
+ message: "blocked production pidfile write for non-production daemon socket",
334
+ meta: { socketPath, pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
335
+ });
336
+ return;
337
+ }
338
+ if (isVitestProcess()) {
339
+ (0, runtime_1.emitNervesEvent)({
340
+ level: "warn",
341
+ component: "daemon",
342
+ event: "daemon.write_pidfile_test_blocked",
343
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
344
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
345
+ });
346
+ return;
347
+ }
348
+ try {
349
+ const pids = [process.pid, ...extraPids].filter(Boolean);
350
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
351
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
352
+ }
353
+ catch { /* best effort */ }
354
+ }
355
+ function readSocketIdentity(socketPath) {
356
+ try {
357
+ const stats = fs.lstatSync(socketPath);
358
+ return {
359
+ dev: stats.dev,
360
+ ino: stats.ino,
361
+ ctimeMs: stats.ctimeMs,
362
+ };
363
+ }
364
+ catch {
365
+ return null;
366
+ }
367
+ }
368
+ function sameSocketIdentity(left, right) {
369
+ if (!left || !right)
370
+ return false;
371
+ return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
372
+ }
52
373
  function buildWorkerRows(snapshots) {
53
374
  return snapshots.map((snapshot) => ({
54
375
  agent: snapshot.name,
@@ -57,19 +378,60 @@ function buildWorkerRows(snapshots) {
57
378
  pid: snapshot.pid,
58
379
  restartCount: snapshot.restartCount,
59
380
  startedAt: snapshot.startedAt,
381
+ lastExitCode: snapshot.lastExitCode ?? null,
382
+ lastSignal: snapshot.lastSignal ?? null,
383
+ errorReason: snapshot.errorReason ?? null,
384
+ fixHint: snapshot.fixHint ?? null,
60
385
  }));
61
386
  }
387
+ function unhealthySenseRows(senses) {
388
+ return senses.filter((row) => {
389
+ if (!row.enabled)
390
+ return false;
391
+ if (row.status === "disabled" || row.status === "not_attached")
392
+ return false;
393
+ if (row.status === "interactive" || row.status === "running")
394
+ return false;
395
+ return true;
396
+ });
397
+ }
398
+ function unhealthyHealthChecks(healthChecks) {
399
+ return healthChecks.filter((row) => row.status !== "ok");
400
+ }
401
+ function overviewHealth(workers, senses, healthChecks = []) {
402
+ if (!workers.every((worker) => worker.status === "running"))
403
+ return "warn";
404
+ if (unhealthySenseRows(senses).length > 0)
405
+ return "warn";
406
+ if (unhealthyHealthChecks(healthChecks).length > 0)
407
+ return "warn";
408
+ return "ok";
409
+ }
62
410
  function formatStatusSummary(payload) {
63
- if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0) {
411
+ if (payload.overview.workerCount === 0 && payload.overview.senseCount === 0 && (payload.healthChecks ?? []).length === 0) {
64
412
  return "no managed agents";
65
413
  }
66
- const rows = [
67
- ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
68
- ...payload.senses
69
- .filter((row) => row.enabled)
70
- .map((row) => `${row.agent}/${row.sense}:${row.status}`),
414
+ const degraded = [
415
+ ...payload.workers
416
+ .filter((row) => row.status !== "running")
417
+ .map((row) => `worker:${row.agent}/${row.worker}:${row.status}`),
418
+ ...unhealthySenseRows(payload.senses)
419
+ .map((row) => `sense:${row.agent}/${row.sense}:${row.status}`),
420
+ ...(payload.healthChecks ?? [])
421
+ .filter((row) => row.status !== "ok")
422
+ .map((row) => `health-check:${row.name}:${row.status}`),
71
423
  ];
72
- const detail = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
424
+ const detail = degraded.length > 0 ? `\tdegraded=${degraded.join(",")}` : "";
425
+ if (!detail) {
426
+ const rows = [
427
+ ...payload.workers.map((row) => `${row.agent}/${row.worker}:${row.status}`),
428
+ ...payload.senses
429
+ .filter((row) => row.enabled)
430
+ .map((row) => `${row.agent}/${row.sense}:${row.status}`),
431
+ ];
432
+ const items = rows.length > 0 ? `\titems=${rows.join(",")}` : "";
433
+ return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${items}`;
434
+ }
73
435
  return `daemon=${payload.overview.daemon}\tworkers=${payload.overview.workerCount}\tsenses=${payload.overview.senseCount}\thealth=${payload.overview.health}${detail}`;
74
436
  }
75
437
  function parseIncomingCommand(raw) {
@@ -89,6 +451,64 @@ function parseIncomingCommand(raw) {
89
451
  }
90
452
  return parsed;
91
453
  }
454
+ function isValidSenseReviveCommand(command) {
455
+ return typeof command.agent === "string"
456
+ && typeof command.sense === "string"
457
+ && typeof command.reason === "string";
458
+ }
459
+ /**
460
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
461
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
462
+ * restarts the daemon process (fresh module cache).
463
+ */
464
+ async function handleAgentSenseTurn(command, runtime) {
465
+ try {
466
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
467
+ setAgentName(command.agent);
468
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
469
+ const result = await runSenseTurn({
470
+ agentName: command.agent,
471
+ channel: command.channel,
472
+ sessionKey: command.sessionKey,
473
+ friendId: command.friendId,
474
+ userMessage: command.message,
475
+ ...(runtime?.socketPath ? { toolContext: { daemonSocketPath: runtime.socketPath } } : {}),
476
+ // Per-turn, per-agent runtime MCP injection (e.g. Workbench's ouro_workbench).
477
+ // Scoped to THIS turn only — never stored as module state, so a concurrent
478
+ // turn for a different agent cannot inherit these servers.
479
+ ...(command.runtimeMcp ? { runtimeMcpServers: command.runtimeMcp } : {}),
480
+ });
481
+ return {
482
+ ok: true,
483
+ message: result.response,
484
+ data: { ponderDeferred: result.ponderDeferred },
485
+ };
486
+ }
487
+ catch (error) {
488
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
489
+ const errorMessage = error instanceof Error ? error.message : String(error);
490
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
491
+ }
492
+ }
493
+ async function handleAgentAskTurn(command, runtime) {
494
+ /* v8 ignore start -- ask command parameter defaults are legacy MCP compatibility; send_message shares the primary path @preserve */
495
+ const question = typeof command.question === "string" ? command.question : "";
496
+ if (!question.trim())
497
+ return { ok: false, error: "Missing required parameter: question" };
498
+ const channel = typeof command.channel === "string" && command.channel.trim() ? command.channel.trim() : "mcp";
499
+ const sessionKey = typeof command.sessionKey === "string" && command.sessionKey.trim()
500
+ ? command.sessionKey.trim()
501
+ : `agent-ask:${command.friendId}`;
502
+ /* v8 ignore stop */
503
+ return handleAgentSenseTurn({
504
+ kind: "agent.senseTurn",
505
+ agent: command.agent,
506
+ friendId: command.friendId,
507
+ channel,
508
+ sessionKey,
509
+ message: question,
510
+ }, runtime);
511
+ }
92
512
  class OuroDaemon {
93
513
  socketPath;
94
514
  processManager;
@@ -97,7 +517,13 @@ class OuroDaemon {
97
517
  router;
98
518
  senseManager;
99
519
  bundlesRoot;
520
+ mode;
100
521
  server = null;
522
+ mailboxServer = null;
523
+ socketIdentity = null;
524
+ senseAutostartTimer = null;
525
+ mailboxServerFactory;
526
+ onStopCommandComplete;
101
527
  constructor(options) {
102
528
  this.socketPath = options.socketPath;
103
529
  this.processManager = options.processManager;
@@ -106,6 +532,77 @@ class OuroDaemon {
106
532
  this.router = options.router;
107
533
  this.senseManager = options.senseManager ?? null;
108
534
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
535
+ this.mode = options.mode ?? "production";
536
+ this.mailboxServerFactory = options.mailboxServerFactory ?? this.createDefaultMailboxServer.bind(this);
537
+ this.onStopCommandComplete = options.onStopCommandComplete ?? null;
538
+ }
539
+ /* 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 */
540
+ createDefaultMailboxServer() {
541
+ return (0, mailbox_http_1.startMailboxHttpServer)({
542
+ host: "127.0.0.1",
543
+ port: mailbox_types_1.MAILBOX_DEFAULT_PORT,
544
+ bundlesRoot: this.bundlesRoot,
545
+ readMachineState: () => (0, mailbox_read_1.readMailboxMachineState)({ bundlesRoot: this.bundlesRoot }),
546
+ readMachineView: ({ machine }) => {
547
+ const overview = this.buildStatusPayload().overview;
548
+ return (0, mailbox_view_1.buildMailboxMachineView)({
549
+ machine,
550
+ daemon: {
551
+ status: overview.daemon,
552
+ health: overview.health,
553
+ mode: overview.mode,
554
+ socketPath: overview.socketPath,
555
+ mailboxUrl: overview.mailboxUrl,
556
+ entryPath: overview.entryPath,
557
+ workerCount: overview.workerCount,
558
+ senseCount: overview.senseCount,
559
+ },
560
+ });
561
+ },
562
+ readAgentState: (agentName) => (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
563
+ readAgentView: (agentName) => {
564
+ const agent = (0, mailbox_read_1.readMailboxAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
565
+ return (0, mailbox_view_1.buildMailboxAgentView)({
566
+ agent,
567
+ viewer: { kind: "human" },
568
+ });
569
+ },
570
+ });
571
+ }
572
+ /* v8 ignore stop */
573
+ buildStatusPayload() {
574
+ const snapshots = this.processManager.listAgentSnapshots();
575
+ const workers = buildWorkerRows(snapshots);
576
+ const senses = this.senseManager?.listSenseRows() ?? [];
577
+ const healthChecks = this.healthMonitor.getLastResults?.() ?? [];
578
+ const repoRoot = (0, identity_1.getRepoRoot)();
579
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
580
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
581
+ const providers = agents.flatMap((agent) => (0, provider_visibility_1.providerVisibilityStatusRows)((0, provider_visibility_1.buildAgentProviderVisibility)({
582
+ agentName: agent.name,
583
+ agentRoot: path.join(this.bundlesRoot, `${agent.name}.ouro`),
584
+ })));
585
+ const mailboxUrl = this.mailboxServer?.origin ?? "http://127.0.0.1:0";
586
+ return {
587
+ overview: {
588
+ daemon: "running",
589
+ health: overviewHealth(workers, senses, healthChecks),
590
+ socketPath: this.socketPath,
591
+ mailboxUrl,
592
+ outlookUrl: mailboxUrl,
593
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
594
+ workerCount: workers.length,
595
+ senseCount: senses.length,
596
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
597
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
598
+ },
599
+ workers,
600
+ senses,
601
+ ...(healthChecks.length > 0 ? { healthChecks } : {}),
602
+ sync,
603
+ agents,
604
+ ...(providers.length > 0 ? { providers } : {}),
605
+ };
109
606
  }
110
607
  async start() {
111
608
  if (this.server)
@@ -116,62 +613,182 @@ class OuroDaemon {
116
613
  message: "starting daemon server",
117
614
  meta: { socketPath: this.socketPath },
118
615
  });
616
+ try {
617
+ await this.startInner();
618
+ }
619
+ catch (err) {
620
+ // Emit a paired terminating event (`_error`) so the nerves audit's
621
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
622
+ // and `stop()` (which emits `server_end`) is never called.
623
+ (0, runtime_1.emitNervesEvent)({
624
+ level: "error",
625
+ component: "daemon",
626
+ event: "daemon.server_error",
627
+ message: "daemon start failed",
628
+ meta: {
629
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
630
+ },
631
+ });
632
+ throw err;
633
+ }
634
+ }
635
+ async startInner() {
119
636
  // Register update hooks and apply pending updates before starting agents
120
637
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
638
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
121
639
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
122
640
  await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
123
641
  // Start periodic update checker (polls npm registry every 30 minutes)
124
- const bundlesRoot = this.bundlesRoot;
125
- const daemon = this;
126
- (0, update_checker_1.startUpdateChecker)({
127
- currentVersion,
128
- deps: {
129
- distTag: "alpha",
130
- fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
131
- const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
132
- return res.json();
133
- },
134
- },
135
- onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
136
- if (!result.latestVersion)
137
- return;
138
- await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
139
- execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
140
- spawnSync: child_process_1.spawnSync,
141
- resolveNewCodePath: (_version) => {
142
- try {
143
- const resolved = (0, child_process_1.execSync)(`node -e "console.log(require.resolve('@ouro.bot/cli/package.json'))"`, { encoding: "utf-8" }).trim();
144
- return resolved ? path.dirname(resolved) : null;
145
- }
146
- catch {
147
- return null;
148
- }
642
+ // Skip in dev mode — dev builds should not auto-update from npm
643
+ if (this.mode === "dev") {
644
+ (0, runtime_1.emitNervesEvent)({
645
+ component: "daemon",
646
+ event: "daemon.update_checker_skip",
647
+ message: "skipping update checker in dev mode",
648
+ meta: { reason: "dev mode" },
649
+ });
650
+ }
651
+ else {
652
+ (0, update_checker_1.startUpdateChecker)({
653
+ currentVersion,
654
+ deps: {
655
+ distTag: update_checker_1.CLI_UPDATE_DIST_TAG,
656
+ /* v8 ignore start -- integration: real HTTP fetch @preserve */
657
+ fetchRegistryJson: async () => {
658
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
659
+ return res.json();
149
660
  },
150
- gracefulShutdown: () => daemon.stop(),
151
- nodePath: process.execPath,
152
- bundlesRoot,
153
- });
154
- },
155
- /* v8 ignore stop */
156
- });
157
- await this.processManager.startAutoStartAgents();
158
- await this.senseManager?.startAutoStartSenses();
661
+ /* v8 ignore stop */
662
+ },
663
+ });
664
+ }
665
+ // MCP connections are lazily initialized per-agent during senseTurn
666
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
667
+ /* v8 ignore start -- orphan cleanup + pidfile: calls process management functions @preserve */
668
+ const killedOrphanPids = killOrphanProcesses(this.socketPath);
669
+ await waitForOrphanProcessesToSettle(killedOrphanPids);
670
+ /* v8 ignore stop */
671
+ await this.openCommandSocket();
672
+ this.triggerAutoStartAgents();
673
+ this.triggerAutoStartSensesWhenAgentsSettled();
674
+ // Write all managed PIDs to disk so the next daemon can clean up
675
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
676
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
677
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
678
+ writePidfile([...agentPids, ...sensePids], this.socketPath);
679
+ /* v8 ignore stop */
159
680
  this.scheduler.start?.();
160
681
  await this.scheduler.reconcile?.();
161
682
  await this.drainPendingBundleMessages();
162
683
  await this.drainPendingSenseMessages();
684
+ // startInner is only reachable when this.server is null (guarded in
685
+ // start()), and stop() nulls out this.mailboxServer alongside this.server,
686
+ // so mailboxServer is guaranteed unset here — no need for a guard.
687
+ try {
688
+ this.mailboxServer = await this.mailboxServerFactory();
689
+ }
690
+ catch (error) {
691
+ (0, runtime_1.emitNervesEvent)({
692
+ level: "warn",
693
+ component: "daemon",
694
+ event: "daemon.mailbox_start_failed",
695
+ message: `Mailbox server failed to start: ${String(error)}`,
696
+ meta: { port: mailbox_types_1.MAILBOX_DEFAULT_PORT },
697
+ });
698
+ }
699
+ }
700
+ triggerAutoStartAgents() {
701
+ if (this.processManager.triggerAutoStartAgents) {
702
+ this.processManager.triggerAutoStartAgents();
703
+ return;
704
+ }
705
+ void this.processManager.startAutoStartAgents().catch((error) => {
706
+ (0, runtime_1.emitNervesEvent)({
707
+ level: "error",
708
+ component: "daemon",
709
+ event: "daemon.agent_autostart_error",
710
+ message: "agent autostart failed after daemon socket opened",
711
+ meta: { error: error instanceof Error ? error.message : String(error) },
712
+ });
713
+ });
714
+ }
715
+ triggerAutoStartSenses() {
716
+ /* v8 ignore next -- defensive: callers already check senseManager before delegating here @preserve */
717
+ if (!this.senseManager)
718
+ return;
719
+ if (this.senseManager.triggerAutoStartSenses) {
720
+ this.senseManager.triggerAutoStartSenses();
721
+ return;
722
+ }
723
+ void this.senseManager.startAutoStartSenses().catch((error) => {
724
+ (0, runtime_1.emitNervesEvent)({
725
+ level: "error",
726
+ component: "daemon",
727
+ event: "daemon.sense_autostart_error",
728
+ message: "sense autostart failed after daemon socket opened",
729
+ meta: { error: error instanceof Error ? error.message : String(error) },
730
+ });
731
+ });
732
+ }
733
+ triggerAutoStartSensesWhenAgentsSettled() {
734
+ if (!this.senseManager)
735
+ return;
736
+ const waitingOnAgents = this.processManager.listAgentSnapshots()
737
+ .some((snapshot) => snapshot.status === "starting");
738
+ if (!waitingOnAgents) {
739
+ this.triggerAutoStartSenses();
740
+ return;
741
+ }
742
+ this.senseAutostartTimer = setTimeout(() => {
743
+ this.senseAutostartTimer = null;
744
+ this.triggerAutoStartSensesWhenAgentsSettled();
745
+ }, 250);
746
+ }
747
+ async openCommandSocket() {
163
748
  if (fs.existsSync(this.socketPath)) {
164
749
  fs.unlinkSync(this.socketPath);
165
750
  }
166
- this.server = net.createServer((connection) => {
751
+ // allowHalfOpen: true lets the server keep its writable side open after
752
+ // the client sends FIN. Without this, when a client calls `client.end()`
753
+ // after writing a command, node closes the server's writable side
754
+ // automatically — so a long-running response (like an agent.senseTurn
755
+ // LLM turn that takes 5+ seconds) never reaches the client. The
756
+ // socket-client fix in #303/#334 also removed client.end() on the
757
+ // sending side, but this option is defense in depth: even if a future
758
+ // caller half-closes, the server still writes its response correctly.
759
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
167
760
  let raw = "";
168
761
  let responded = false;
762
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
763
+ connection.on("error", (err) => {
764
+ (0, runtime_1.emitNervesEvent)({
765
+ level: "warn",
766
+ component: "daemon",
767
+ event: "daemon.connection_error",
768
+ message: "socket connection error",
769
+ meta: { error: err.message, code: err.code ?? null },
770
+ });
771
+ });
772
+ /* v8 ignore stop */
169
773
  const flushResponse = async () => {
170
774
  if (responded)
171
775
  return;
172
776
  responded = true;
173
777
  const response = await this.handleRawPayload(raw);
174
- connection.end(response);
778
+ try {
779
+ connection.end(response);
780
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
781
+ }
782
+ catch (err) {
783
+ (0, runtime_1.emitNervesEvent)({
784
+ level: "warn",
785
+ component: "daemon",
786
+ event: "daemon.connection_end_error",
787
+ message: "failed to send response to client (EPIPE)",
788
+ meta: { error: err instanceof Error ? err.message : String(err) },
789
+ });
790
+ }
791
+ /* v8 ignore stop */
175
792
  };
176
793
  connection.on("data", (chunk) => {
177
794
  raw += chunk.toString("utf-8");
@@ -184,7 +801,23 @@ class OuroDaemon {
184
801
  const server = this.server;
185
802
  await new Promise((resolve, reject) => {
186
803
  server.once("error", reject);
187
- server.listen(this.socketPath, () => resolve());
804
+ server.listen(this.socketPath, () => {
805
+ // Replace the one-time error listener with a persistent one after successful listen
806
+ server.removeAllListeners("error");
807
+ this.socketIdentity = readSocketIdentity(this.socketPath);
808
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
809
+ server.on("error", (err) => {
810
+ (0, runtime_1.emitNervesEvent)({
811
+ level: "error",
812
+ component: "daemon",
813
+ event: "daemon.server_error",
814
+ message: "daemon server error after listen",
815
+ meta: { error: err.message, code: err.code ?? null },
816
+ });
817
+ });
818
+ /* v8 ignore stop */
819
+ resolve();
820
+ });
188
821
  });
189
822
  }
190
823
  async drainPendingBundleMessages() {
@@ -236,7 +869,7 @@ class OuroDaemon {
236
869
  }
237
870
  }
238
871
  /** Drains per-sense pending dirs for always-on senses across all agents. */
239
- static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
872
+ static ALWAYS_ON_SENSES = new Set((0, friends_1.getAlwaysOnSenseNames)());
240
873
  async drainPendingSenseMessages() {
241
874
  if (!fs.existsSync(this.bundlesRoot))
242
875
  return;
@@ -323,25 +956,87 @@ class OuroDaemon {
323
956
  }
324
957
  }
325
958
  async stop() {
959
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
960
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
961
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
326
962
  (0, runtime_1.emitNervesEvent)({
327
963
  component: "daemon",
328
- event: "daemon.server_stop",
964
+ event: "daemon.server_end",
329
965
  message: "stopping daemon server",
330
966
  meta: { socketPath: this.socketPath },
331
967
  });
332
968
  (0, update_checker_1.stopUpdateChecker)();
969
+ (0, mcp_manager_1.shutdownSharedMcpManager)();
333
970
  this.scheduler.stop?.();
971
+ this.healthMonitor.stopPeriodicChecks?.();
972
+ if (this.senseAutostartTimer) {
973
+ clearTimeout(this.senseAutostartTimer);
974
+ this.senseAutostartTimer = null;
975
+ }
334
976
  await this.processManager.stopAll();
335
977
  await this.senseManager?.stopAll();
336
978
  if (this.server) {
337
- await new Promise((resolve) => {
338
- this.server?.close(() => resolve());
339
- });
979
+ // DO NOT `await` server.close() here. server.close() resolves only
980
+ // after every open connection has closed. When stop() is invoked
981
+ // from the daemon.stop command handler, the calling client's
982
+ // connection is STILL open — its flushResponse() is currently
983
+ // awaiting THIS function. Awaiting close() creates a deadlock:
984
+ //
985
+ // client → flushResponse → handleRawPayload → daemon.stop case
986
+ // → stop() → await server.close() (waits for client's connection)
987
+ // → client's connection waits for flushResponse to call
988
+ // connection.end() → DEADLOCK
989
+ //
990
+ // Both processes sit in kevent forever. Verified live on
991
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
992
+ // line for 5+ minutes after a client sent daemon.stop, while the
993
+ // client (alpha.270 ouro up) hung waiting for the response.
994
+ //
995
+ // This regressed when #303/#334/#339 stopped half-closing the
996
+ // client socket and switched the server to allowHalfOpen: true.
997
+ // Previously, the client called .end() after writing its command,
998
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
999
+ // the server's writable side — incidentally unblocking
1000
+ // server.close() before the response was sent. The half-close
1001
+ // breakage masked this deadlock; the fix exposed it.
1002
+ //
1003
+ // Solution: fire close() and let it complete asynchronously. Once
1004
+ // stop() returns, the daemon.stop case returns its response,
1005
+ // flushResponse() calls connection.end(response), the connection
1006
+ // closes, and server.close()'s pending callback fires. The event
1007
+ // loop drains and the daemon exits cleanly.
1008
+ this.server.close();
340
1009
  this.server = null;
341
1010
  }
342
- if (fs.existsSync(this.socketPath)) {
1011
+ if (this.mailboxServer) {
1012
+ await this.mailboxServer.stop();
1013
+ this.mailboxServer = null;
1014
+ }
1015
+ const socketPathExists = fs.existsSync(this.socketPath);
1016
+ const currentSocketIdentity = socketPathExists ? readSocketIdentity(this.socketPath) : null;
1017
+ if (sameSocketIdentity(this.socketIdentity, currentSocketIdentity)) {
343
1018
  fs.unlinkSync(this.socketPath);
344
1019
  }
1020
+ else if (socketPathExists) {
1021
+ const expectedSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...this.socketIdentity };
1022
+ const actualSocketIdentity = { dev: null, ino: null, ctimeMs: null, ...currentSocketIdentity };
1023
+ (0, runtime_1.emitNervesEvent)({
1024
+ level: "warn",
1025
+ component: "daemon",
1026
+ event: "daemon.socket_cleanup_skipped",
1027
+ message: "skipped daemon socket cleanup because the socket path no longer belongs to this daemon",
1028
+ meta: {
1029
+ socketPath: this.socketPath,
1030
+ expectedDev: expectedSocketIdentity.dev,
1031
+ expectedIno: expectedSocketIdentity.ino,
1032
+ expectedCtimeMs: expectedSocketIdentity.ctimeMs,
1033
+ actualDev: actualSocketIdentity.dev,
1034
+ actualIno: actualSocketIdentity.ino,
1035
+ actualCtimeMs: actualSocketIdentity.ctimeMs,
1036
+ },
1037
+ });
1038
+ }
1039
+ this.socketIdentity = null;
345
1040
  }
346
1041
  async handleRawPayload(raw) {
347
1042
  try {
@@ -363,32 +1058,58 @@ class OuroDaemon {
363
1058
  message: "handling daemon command",
364
1059
  meta: { kind: command.kind },
365
1060
  });
1061
+ try {
1062
+ return await this.handleCommandInner(command);
1063
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
1064
+ }
1065
+ catch (error) {
1066
+ (0, runtime_1.emitNervesEvent)({
1067
+ level: "error",
1068
+ component: "daemon",
1069
+ event: "daemon.command_error",
1070
+ message: "unexpected error handling daemon command",
1071
+ meta: {
1072
+ kind: command.kind,
1073
+ error: error instanceof Error ? error.message : String(error),
1074
+ stack: error instanceof Error ? error.stack ?? null : null,
1075
+ },
1076
+ });
1077
+ throw error;
1078
+ }
1079
+ /* v8 ignore stop */
1080
+ }
1081
+ async handleCommandInner(command) {
366
1082
  switch (command.kind) {
367
1083
  case "daemon.start":
368
1084
  await this.start();
369
1085
  return { ok: true, message: "daemon started" };
370
1086
  case "daemon.stop":
371
1087
  await this.stop();
1088
+ this.onStopCommandComplete?.();
372
1089
  return { ok: true, message: "daemon stopped" };
373
- case "daemon.status": {
374
- const snapshots = this.processManager.listAgentSnapshots();
375
- const workers = buildWorkerRows(snapshots);
376
- const senses = this.senseManager?.listSenseRows() ?? [];
377
- const repoRoot = (0, identity_1.getRepoRoot)();
378
- const data = {
379
- overview: {
380
- daemon: "running",
381
- health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
382
- socketPath: this.socketPath,
383
- ...(0, runtime_metadata_1.getRuntimeMetadata)(),
384
- workerCount: workers.length,
385
- senseCount: senses.length,
386
- entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
387
- mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
1090
+ case "daemon.restart": {
1091
+ // Restart is "stop + let launchctl respawn." Under launchctl's KeepAlive
1092
+ // policy the process is auto-restarted on exit, so daemon.restart and
1093
+ // daemon.stop differ only in intent + audit trail. In dev (no launchctl),
1094
+ // the process simply exits — same observable behavior as daemon.stop.
1095
+ (0, runtime_1.emitNervesEvent)({
1096
+ component: "daemon",
1097
+ event: "daemon.restart_requested",
1098
+ message: "daemon restart requested",
1099
+ meta: {
1100
+ reason: command.reason ?? null,
1101
+ requestedBy: command.requestedBy ?? null,
388
1102
  },
389
- workers,
390
- senses,
1103
+ });
1104
+ await this.stop();
1105
+ this.onStopCommandComplete?.();
1106
+ return {
1107
+ ok: true,
1108
+ message: "daemon restarting — launchctl will respawn",
391
1109
  };
1110
+ }
1111
+ case "daemon.status": {
1112
+ const data = this.buildStatusPayload();
392
1113
  return {
393
1114
  ok: true,
394
1115
  summary: formatStatusSummary(data),
@@ -407,15 +1128,109 @@ class OuroDaemon {
407
1128
  message: "log streaming available via ouro logs",
408
1129
  data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
409
1130
  };
1131
+ case "daemon.sense_revive": {
1132
+ if (!isValidSenseReviveCommand(command)) {
1133
+ return {
1134
+ ok: false,
1135
+ error: "Invalid daemon.sense_revive payload: expected string fields 'agent', 'sense', and 'reason'.",
1136
+ };
1137
+ }
1138
+ const revivedSenseRow = await this.senseManager?.reviveSense?.(command.agent, command.sense);
1139
+ if (revivedSenseRow) {
1140
+ return {
1141
+ ok: true,
1142
+ message: `revived ${command.agent}/${command.sense}`,
1143
+ data: revivedSenseRow,
1144
+ };
1145
+ }
1146
+ const managedSenseSnapshots = this.processManager.listAgentSnapshots()
1147
+ .filter((snapshot) => snapshot.name.startsWith(`${command.agent}:`));
1148
+ if (managedSenseSnapshots.length === 0) {
1149
+ return {
1150
+ ok: false,
1151
+ error: `No managed agent '${command.agent}' is registered with daemon-managed senses.`,
1152
+ };
1153
+ }
1154
+ const exactTargetName = `${command.agent}:${command.sense}`;
1155
+ const target = managedSenseSnapshots.find((snapshot) => snapshot.name === exactTargetName)
1156
+ ?? managedSenseSnapshots.find((snapshot) => snapshot.channel === command.sense);
1157
+ if (!target) {
1158
+ return {
1159
+ ok: false,
1160
+ error: `No managed sense '${command.sense}' is registered for agent '${command.agent}'.`,
1161
+ };
1162
+ }
1163
+ this.processManager.resetAgentFailureState(target.name);
1164
+ await this.processManager.startAgent(target.name);
1165
+ const freshSnapshot = this.processManager.listAgentSnapshots()
1166
+ .find((snapshot) => snapshot.name === target.name) ?? target;
1167
+ return {
1168
+ ok: true,
1169
+ message: `revived ${command.agent}/${command.sense}`,
1170
+ data: freshSnapshot,
1171
+ };
1172
+ }
410
1173
  case "agent.start":
411
1174
  await this.processManager.startAgent(command.agent);
412
1175
  return { ok: true, message: `started ${command.agent}` };
413
1176
  case "agent.stop":
414
1177
  await this.processManager.stopAgent?.(command.agent);
415
1178
  return { ok: true, message: `stopped ${command.agent}` };
416
- case "agent.restart":
417
- await this.processManager.restartAgent?.(command.agent);
418
- return { ok: true, message: `restarted ${command.agent}` };
1179
+ case "agent.restart": {
1180
+ if (!this.processManager.restartAgent) {
1181
+ return { ok: false, error: "Managed agent restart is not available." };
1182
+ }
1183
+ const managed = this.processManager.listAgentSnapshots()
1184
+ .some((snapshot) => snapshot.name === command.agent);
1185
+ if (!managed) {
1186
+ return { ok: false, error: `Unknown managed agent '${command.agent}'.` };
1187
+ }
1188
+ const restartWork = command.skipConfigCheck === true
1189
+ ? this.processManager.restartAgent(command.agent, { skipConfigCheck: true })
1190
+ : this.processManager.restartAgent(command.agent);
1191
+ void restartWork.catch((error) => {
1192
+ (0, runtime_1.emitNervesEvent)({
1193
+ level: "error",
1194
+ component: "daemon",
1195
+ event: "daemon.agent_restart_request_error",
1196
+ message: "managed agent restart failed after request acknowledgement",
1197
+ meta: {
1198
+ agent: command.agent,
1199
+ error: error instanceof Error ? error.message : String(error),
1200
+ },
1201
+ });
1202
+ });
1203
+ return { ok: true, message: `restart requested for ${command.agent}` };
1204
+ }
1205
+ case "agent.ask":
1206
+ return handleAgentAskTurn(command, { socketPath: this.socketPath });
1207
+ case "agent.status":
1208
+ return (0, agent_service_1.handleAgentStatus)(command);
1209
+ case "agent.catchup":
1210
+ return (0, agent_service_1.handleAgentCatchup)(command);
1211
+ case "agent.delegate":
1212
+ return (0, agent_service_1.handleAgentDelegate)(command);
1213
+ case "agent.getContext":
1214
+ return (0, agent_service_1.handleAgentGetContext)(command);
1215
+ case "agent.searchFacts":
1216
+ return (0, agent_service_1.handleAgentSearchFacts)(command);
1217
+ case "agent.getTask":
1218
+ return (0, agent_service_1.handleAgentGetTask)(command);
1219
+ case "agent.checkScope":
1220
+ return (0, agent_service_1.handleAgentCheckScope)(command);
1221
+ case "agent.requestDecision":
1222
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
1223
+ case "agent.checkGuidance":
1224
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
1225
+ case "agent.reportProgress":
1226
+ return (0, agent_service_1.handleAgentReportProgress)(command);
1227
+ case "agent.reportBlocker":
1228
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
1229
+ case "agent.reportComplete":
1230
+ return (0, agent_service_1.handleAgentReportComplete)(command);
1231
+ case "agent.senseTurn":
1232
+ return handleAgentSenseTurn(command, { socketPath: this.socketPath });
1233
+ /* v8 ignore stop */
419
1234
  case "cron.list": {
420
1235
  const jobs = this.scheduler.listJobs();
421
1236
  const summary = jobs.length === 0
@@ -424,10 +1239,28 @@ class OuroDaemon {
424
1239
  return { ok: true, summary, data: jobs };
425
1240
  }
426
1241
  case "cron.trigger": {
1242
+ const habitResult = await this.scheduler.triggerHabitJob?.(command.jobId);
1243
+ if (habitResult?.ok) {
1244
+ return { ok: true, message: habitResult.message };
1245
+ }
427
1246
  const result = await this.scheduler.triggerJob(command.jobId);
428
1247
  return { ok: result.ok, message: result.message };
429
1248
  }
430
1249
  case "message.send": {
1250
+ // Pure queue-only delivery. We DO NOT wake the recipient — that was
1251
+ // the 2026-05-11 $50 bleed. The Claude Code post-tool-use hook
1252
+ // (cli-exec.ts) intentionally sends only message.send for tool-use
1253
+ // events to avoid waking the agent on every tool call. The hook's
1254
+ // intent was completely defeated by this handler calling
1255
+ // `sendToAgent({type: "message"})`, which woke the inner-dialog
1256
+ // worker on EVERY message.send anyway. ~30 message.send/min × the
1257
+ // 3-turn instinct-loop cap = ~90 turns/min sustained for hours.
1258
+ //
1259
+ // Callers that want immediate processing must send `inner.wake`
1260
+ // explicitly after message.send. The CLI `ouro msg` does so
1261
+ // (lifecycle-boundary delivery should wake); the hook does so
1262
+ // only on session-start / stop, not per tool-use; the API does
1263
+ // not (notifications go to the queue).
431
1264
  const receipt = await this.router.send({
432
1265
  from: command.from,
433
1266
  to: command.to,
@@ -436,7 +1269,6 @@ class OuroDaemon {
436
1269
  sessionId: command.sessionId,
437
1270
  taskRef: command.taskRef,
438
1271
  });
439
- this.processManager.sendToAgent?.(command.to, { type: "message" });
440
1272
  return { ok: true, message: `queued message ${receipt.id}`, data: receipt };
441
1273
  }
442
1274
  case "message.poll": {
@@ -476,10 +1308,52 @@ class OuroDaemon {
476
1308
  data: receipt,
477
1309
  };
478
1310
  }
1311
+ case "habit.poke": {
1312
+ const trigger = command.trigger ?? "poke";
1313
+ if (!(0, flight_recorder_1.isHabitRunTrigger)(trigger)) {
1314
+ return { ok: false, error: `invalid habit trigger: ${String(trigger)}` };
1315
+ }
1316
+ this.processManager.sendToAgent?.(command.agent, { type: "habit", habitName: command.habitName, trigger });
1317
+ return {
1318
+ ok: true,
1319
+ message: `poked habit ${command.habitName} for ${command.agent}`,
1320
+ };
1321
+ }
1322
+ case "await.poke": {
1323
+ this.processManager.sendToAgent?.(command.agent, { type: "await", awaitName: command.awaitName });
1324
+ return {
1325
+ ok: true,
1326
+ message: `poked await ${command.awaitName} for ${command.agent}`,
1327
+ };
1328
+ }
1329
+ case "mcp.list": {
1330
+ (0, identity_1.setAgentName)(command.agent ?? "default");
1331
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
1332
+ if (!mcpManager) {
1333
+ return { ok: true, data: [], message: "no MCP servers configured" };
1334
+ }
1335
+ return { ok: true, data: mcpManager.listAllTools() };
1336
+ }
1337
+ case "mcp.call": {
1338
+ (0, identity_1.setAgentName)(command.agent ?? "default");
1339
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
1340
+ if (!mcpCallManager) {
1341
+ return { ok: false, error: "no MCP servers configured" };
1342
+ }
1343
+ try {
1344
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
1345
+ const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
1346
+ return { ok: true, data: result };
1347
+ }
1348
+ catch (error) {
1349
+ /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
1350
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
1351
+ }
1352
+ }
479
1353
  case "hatch.start":
480
1354
  return {
481
1355
  ok: true,
482
- message: "hatch flow is stubbed in Gate 3 and completed in Gate 6",
1356
+ message: "hatch flow is stubbed; the interactive implementation lands in a later milestone",
483
1357
  };
484
1358
  default:
485
1359
  return {