@ouro.bot/cli 0.1.0-alpha.28 → 0.1.0-alpha.280

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 (267) hide show
  1. package/README.md +187 -191
  2. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/agent.json +3 -2
  3. package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/SOUL.md +1 -1
  4. package/changelog.json +1696 -0
  5. package/dist/arc/attention-types.js +8 -0
  6. package/dist/arc/cares.js +140 -0
  7. package/dist/arc/episodes.js +117 -0
  8. package/dist/arc/intentions.js +133 -0
  9. package/dist/arc/json-store.js +117 -0
  10. package/dist/arc/obligations.js +237 -0
  11. package/dist/arc/presence.js +185 -0
  12. package/dist/heart/active-work.js +832 -0
  13. package/dist/heart/agent-entry.js +37 -2
  14. package/dist/heart/auth/auth-flow.js +456 -0
  15. package/dist/heart/bridges/manager.js +358 -0
  16. package/dist/heart/bridges/state-machine.js +135 -0
  17. package/dist/heart/bridges/store.js +123 -0
  18. package/dist/heart/commitments.js +111 -0
  19. package/dist/heart/config-registry.js +304 -0
  20. package/dist/heart/config.js +63 -30
  21. package/dist/heart/core.js +644 -196
  22. package/dist/heart/cross-chat-delivery.js +131 -0
  23. package/dist/heart/daemon/agent-config-check.js +149 -0
  24. package/dist/heart/daemon/agent-discovery.js +79 -3
  25. package/dist/heart/daemon/agent-service.js +360 -0
  26. package/dist/heart/daemon/cadence.js +70 -0
  27. package/dist/heart/daemon/cli-defaults.js +574 -0
  28. package/dist/heart/daemon/cli-exec.js +1932 -0
  29. package/dist/heart/daemon/cli-parse.js +762 -0
  30. package/dist/heart/daemon/cli-render.js +503 -0
  31. package/dist/heart/daemon/cli-types.js +8 -0
  32. package/dist/heart/daemon/daemon-cli.js +29 -1155
  33. package/dist/heart/daemon/daemon-entry.js +234 -3
  34. package/dist/heart/daemon/daemon-health.js +136 -0
  35. package/dist/heart/daemon/daemon-runtime-sync.js +153 -12
  36. package/dist/heart/daemon/daemon-tombstone.js +236 -0
  37. package/dist/heart/daemon/daemon.js +702 -57
  38. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  39. package/dist/heart/daemon/hooks/bundle-meta.js +115 -1
  40. package/dist/heart/daemon/inner-status.js +89 -0
  41. package/dist/heart/daemon/launchd.js +46 -9
  42. package/dist/heart/daemon/log-tailer.js +82 -12
  43. package/dist/heart/daemon/logs-prune.js +105 -0
  44. package/dist/heart/daemon/message-router.js +17 -8
  45. package/dist/heart/daemon/os-cron-deps.js +134 -0
  46. package/dist/heart/daemon/ouro-bot-entry.js +1 -1
  47. package/dist/heart/daemon/process-manager.js +180 -0
  48. package/dist/heart/daemon/pulse.js +463 -0
  49. package/dist/heart/daemon/run-hooks.js +2 -0
  50. package/dist/heart/daemon/runtime-logging.js +67 -16
  51. package/dist/heart/daemon/runtime-metadata.js +101 -0
  52. package/dist/heart/daemon/runtime-mode.js +67 -0
  53. package/dist/heart/daemon/safe-mode.js +161 -0
  54. package/dist/heart/daemon/sense-manager.js +72 -3
  55. package/dist/heart/daemon/session-id-resolver.js +131 -0
  56. package/dist/heart/daemon/skill-management-installer.js +94 -0
  57. package/dist/heart/daemon/socket-client.js +307 -0
  58. package/dist/heart/daemon/task-scheduler.js +3 -25
  59. package/dist/heart/daemon/thoughts.js +510 -0
  60. package/dist/heart/delegation.js +62 -0
  61. package/dist/heart/habits/habit-migration.js +181 -0
  62. package/dist/heart/habits/habit-parser.js +119 -0
  63. package/dist/heart/habits/habit-scheduler.js +371 -0
  64. package/dist/heart/{daemon → hatch}/hatch-flow.js +30 -120
  65. package/dist/heart/{daemon → hatch}/hatch-specialist.js +3 -3
  66. package/dist/heart/{daemon → hatch}/specialist-prompt.js +10 -7
  67. package/dist/heart/{daemon → hatch}/specialist-tools.js +49 -3
  68. package/dist/heart/identity.js +163 -60
  69. package/dist/heart/kicks.js +2 -20
  70. package/dist/heart/mcp/mcp-server.js +653 -0
  71. package/dist/heart/migrate-config.js +127 -0
  72. package/dist/heart/model-capabilities.js +59 -0
  73. package/dist/heart/outlook/outlook-http.js +439 -0
  74. package/dist/heart/outlook/outlook-read.js +1618 -0
  75. package/dist/heart/outlook/outlook-render.js +1032 -0
  76. package/dist/heart/outlook/outlook-types.js +7 -0
  77. package/dist/heart/outlook/outlook-view.js +194 -0
  78. package/dist/heart/progress-story.js +42 -0
  79. package/dist/heart/provider-failover.js +88 -0
  80. package/dist/heart/provider-ping.js +162 -0
  81. package/dist/heart/providers/anthropic-token.js +163 -0
  82. package/dist/heart/providers/anthropic.js +169 -46
  83. package/dist/heart/providers/azure.js +98 -11
  84. package/dist/heart/providers/error-classification.js +63 -0
  85. package/dist/heart/providers/github-copilot.js +136 -0
  86. package/dist/heart/providers/minimax-vlm.js +189 -0
  87. package/dist/heart/providers/minimax.js +23 -5
  88. package/dist/heart/providers/openai-codex.js +33 -22
  89. package/dist/heart/session-activity.js +172 -0
  90. package/dist/heart/session-recall.js +216 -0
  91. package/dist/heart/start-of-turn-packet.js +330 -0
  92. package/dist/heart/streaming.js +36 -27
  93. package/dist/heart/sync.js +277 -0
  94. package/dist/heart/target-resolution.js +127 -0
  95. package/dist/heart/tempo.js +93 -0
  96. package/dist/heart/temporal-view.js +41 -0
  97. package/dist/heart/tool-activity-callbacks.js +36 -0
  98. package/dist/heart/tool-description.js +135 -0
  99. package/dist/heart/tool-loop.js +200 -0
  100. package/dist/heart/turn-context.js +358 -0
  101. package/dist/heart/turn-coordinator.js +28 -0
  102. package/dist/heart/versioning/ouro-bot-global-installer.js +128 -0
  103. package/dist/heart/{daemon → versioning}/ouro-bot-wrapper.js +1 -1
  104. package/dist/heart/{daemon → versioning}/ouro-path-installer.js +78 -35
  105. package/dist/heart/versioning/ouro-version-manager.js +295 -0
  106. package/dist/heart/{daemon → versioning}/staged-restart.js +40 -8
  107. package/dist/heart/{daemon → versioning}/update-checker.js +12 -2
  108. package/dist/heart/{daemon → versioning}/update-hooks.js +63 -59
  109. package/dist/mind/associative-recall.js +126 -66
  110. package/dist/mind/bundle-manifest.js +8 -1
  111. package/dist/mind/context.js +125 -14
  112. package/dist/mind/{memory.js → diary.js} +68 -96
  113. package/dist/mind/embedding-provider.js +60 -0
  114. package/dist/mind/file-state.js +179 -0
  115. package/dist/mind/first-impressions.js +14 -1
  116. package/dist/mind/friends/channel.js +56 -0
  117. package/dist/mind/friends/group-context.js +144 -0
  118. package/dist/mind/friends/resolver.js +37 -0
  119. package/dist/mind/friends/store-file.js +58 -3
  120. package/dist/mind/friends/trust-explanation.js +74 -0
  121. package/dist/mind/friends/types.js +8 -0
  122. package/dist/mind/journal-index.js +161 -0
  123. package/dist/mind/obligation-steering.js +221 -0
  124. package/dist/mind/pending.js +76 -9
  125. package/dist/mind/prompt.js +874 -109
  126. package/dist/mind/scrutiny.js +173 -0
  127. package/dist/mind/token-estimate.js +8 -12
  128. package/dist/nerves/cli-logging.js +7 -1
  129. package/dist/nerves/coverage/audit.js +1 -1
  130. package/dist/nerves/coverage/file-completeness.js +50 -5
  131. package/dist/nerves/coverage/run-artifacts.js +1 -1
  132. package/dist/nerves/event-buffer.js +111 -0
  133. package/dist/nerves/index.js +220 -4
  134. package/dist/nerves/observation.js +20 -0
  135. package/dist/nerves/runtime.js +5 -1
  136. package/dist/outlook-ui/assets/index-Ck8agNeO.js +61 -0
  137. package/dist/outlook-ui/assets/index-LwChZTgL.css +1 -0
  138. package/dist/outlook-ui/index.html +15 -0
  139. package/dist/repertoire/ado-client.js +15 -56
  140. package/dist/repertoire/ado-semantic.js +11 -10
  141. package/dist/repertoire/api-client.js +97 -0
  142. package/dist/repertoire/bitwarden-store.js +319 -0
  143. package/dist/repertoire/bw-installer.js +79 -0
  144. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  145. package/dist/repertoire/coding/context-pack.js +330 -0
  146. package/dist/repertoire/coding/feedback.js +197 -30
  147. package/dist/repertoire/coding/manager.js +149 -2
  148. package/dist/repertoire/coding/spawner.js +55 -9
  149. package/dist/repertoire/coding/tools.js +170 -7
  150. package/dist/repertoire/commerce-errors.js +109 -0
  151. package/dist/repertoire/commerce-self-test.js +156 -0
  152. package/dist/repertoire/credential-access.js +515 -0
  153. package/dist/repertoire/duffel-client.js +185 -0
  154. package/dist/repertoire/github-client.js +14 -55
  155. package/dist/repertoire/graph-client.js +11 -52
  156. package/dist/repertoire/guardrails.js +369 -0
  157. package/dist/repertoire/mcp-client.js +255 -0
  158. package/dist/repertoire/mcp-manager.js +305 -0
  159. package/dist/repertoire/mcp-tools.js +63 -0
  160. package/dist/repertoire/shell-sessions.js +133 -0
  161. package/dist/repertoire/skills.js +14 -23
  162. package/dist/repertoire/stripe-client.js +131 -0
  163. package/dist/repertoire/tasks/board.js +43 -5
  164. package/dist/repertoire/tasks/fix.js +182 -0
  165. package/dist/repertoire/tasks/index.js +28 -10
  166. package/dist/repertoire/tasks/lifecycle.js +2 -2
  167. package/dist/repertoire/tasks/parser.js +3 -2
  168. package/dist/repertoire/tasks/scanner.js +194 -37
  169. package/dist/repertoire/tasks/transitions.js +11 -28
  170. package/dist/repertoire/tools-base.js +43 -771
  171. package/dist/repertoire/tools-bluebubbles.js +201 -0
  172. package/dist/repertoire/tools-bridge.js +141 -0
  173. package/dist/repertoire/tools-config.js +185 -0
  174. package/dist/repertoire/tools-continuity.js +248 -0
  175. package/dist/repertoire/tools-credential.js +182 -0
  176. package/dist/repertoire/tools-files.js +342 -0
  177. package/dist/repertoire/tools-flight.js +224 -0
  178. package/dist/repertoire/tools-flow.js +62 -0
  179. package/dist/repertoire/tools-github.js +1 -7
  180. package/dist/repertoire/tools-memory.js +347 -0
  181. package/dist/repertoire/tools-session.js +739 -0
  182. package/dist/repertoire/tools-shell.js +120 -0
  183. package/dist/repertoire/tools-stripe.js +180 -0
  184. package/dist/repertoire/tools-surface.js +243 -0
  185. package/dist/repertoire/tools-teams.js +12 -62
  186. package/dist/repertoire/tools-travel.js +125 -0
  187. package/dist/repertoire/tools-user-profile.js +144 -0
  188. package/dist/repertoire/tools-vault.js +110 -0
  189. package/dist/repertoire/tools.js +155 -130
  190. package/dist/repertoire/travel-api-client.js +360 -0
  191. package/dist/repertoire/user-profile.js +118 -0
  192. package/dist/repertoire/vault-setup.js +241 -0
  193. package/dist/scripts/claude-code-hook.js +41 -0
  194. package/dist/scripts/claude-code-stop-hook.js +47 -0
  195. package/dist/senses/attention-queue.js +97 -0
  196. package/dist/senses/bluebubbles/attachment-cache.js +53 -0
  197. package/dist/senses/{bluebubbles-client.js → bluebubbles/client.js} +143 -9
  198. package/dist/senses/bluebubbles/entry.js +13 -0
  199. package/dist/senses/bluebubbles/inbound-log.js +110 -0
  200. package/dist/senses/bluebubbles/index.js +1410 -0
  201. package/dist/senses/{bluebubbles-media.js → bluebubbles/media.js} +140 -23
  202. package/dist/senses/{bluebubbles-model.js → bluebubbles/model.js} +20 -5
  203. package/dist/senses/{bluebubbles-mutation-log.js → bluebubbles/mutation-log.js} +46 -6
  204. package/dist/senses/bluebubbles/runtime-state.js +109 -0
  205. package/dist/senses/bluebubbles/session-cleanup.js +72 -0
  206. package/dist/senses/cli/bracketed-paste.js +82 -0
  207. package/dist/senses/cli/image-paste.js +211 -0
  208. package/dist/senses/cli/image-ref-navigation.js +75 -0
  209. package/dist/senses/cli/ink-app.js +156 -0
  210. package/dist/senses/cli/inline-diff.js +64 -0
  211. package/dist/senses/cli/input-keys.js +174 -0
  212. package/dist/senses/cli/kill-ring.js +86 -0
  213. package/dist/senses/cli/message-list.js +51 -0
  214. package/dist/senses/cli/ouro-tui.js +595 -0
  215. package/dist/senses/cli/spinner-imperative.js +135 -0
  216. package/dist/senses/cli/spinner.js +101 -0
  217. package/dist/senses/cli/status-line.js +60 -0
  218. package/dist/senses/cli/streaming-markdown.js +526 -0
  219. package/dist/senses/cli/tool-display.js +83 -0
  220. package/dist/senses/cli/tool-render.js +85 -0
  221. package/dist/senses/cli/tui-store.js +240 -0
  222. package/dist/senses/cli/virtual-list.js +35 -0
  223. package/dist/senses/cli-entry.js +1 -1
  224. package/dist/senses/cli-layout.js +187 -0
  225. package/dist/senses/cli.js +569 -246
  226. package/dist/senses/commands.js +65 -1
  227. package/dist/senses/continuity.js +94 -0
  228. package/dist/senses/habit-turn-message.js +108 -0
  229. package/dist/senses/inner-dialog-worker.js +112 -19
  230. package/dist/senses/inner-dialog.js +593 -85
  231. package/dist/senses/pipeline.js +552 -0
  232. package/dist/senses/shared-turn.js +199 -0
  233. package/dist/senses/surface-tool.js +68 -0
  234. package/dist/senses/teams.js +664 -165
  235. package/dist/senses/trust-gate.js +112 -2
  236. package/package.json +14 -7
  237. package/skills/agent-commerce.md +106 -0
  238. package/skills/browser-navigation.md +110 -0
  239. package/skills/commerce-setup-guide.md +116 -0
  240. package/skills/commerce-setup.md +84 -0
  241. package/skills/configure-dev-tools.md +81 -0
  242. package/skills/travel-planning.md +138 -0
  243. package/dist/heart/daemon/subagent-installer.js +0 -134
  244. package/dist/senses/bluebubbles-entry.js +0 -11
  245. package/dist/senses/bluebubbles.js +0 -421
  246. package/dist/senses/debug-activity.js +0 -108
  247. package/subagents/README.md +0 -73
  248. package/subagents/work-doer.md +0 -235
  249. package/subagents/work-merger.md +0 -618
  250. package/subagents/work-planner.md +0 -382
  251. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/basilisk.md +0 -0
  252. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jafar.md +0 -0
  253. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/jormungandr.md +0 -0
  254. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/kaa.md +0 -0
  255. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/medusa.md +0 -0
  256. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/monty.md +0 -0
  257. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/nagini.md +0 -0
  258. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/ouroboros.md +0 -0
  259. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/python.md +0 -0
  260. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/quetzalcoatl.md +0 -0
  261. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/sir-hiss.md +0 -0
  262. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-serpent.md +0 -0
  263. /package/{AdoptionSpecialist.ouro → SerpentGuide.ouro}/psyche/identities/the-snake.md +0 -0
  264. /package/dist/heart/{daemon → hatch}/hatch-animation.js +0 -0
  265. /package/dist/heart/{daemon → hatch}/specialist-orchestrator.js +0 -0
  266. /package/dist/heart/{daemon → versioning}/ouro-uti.js +0 -0
  267. /package/dist/heart/{daemon → versioning}/wrapper-publish-guard.js +0 -0
@@ -34,18 +34,243 @@ 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.killOrphanProcesses = killOrphanProcesses;
40
+ exports.writePidfile = writePidfile;
41
+ exports.handleAgentSenseTurn = handleAgentSenseTurn;
37
42
  const fs = __importStar(require("fs"));
38
43
  const net = __importStar(require("net"));
44
+ const os = __importStar(require("os"));
39
45
  const path = __importStar(require("path"));
40
46
  const identity_1 = require("../identity");
47
+ const agent_discovery_1 = require("./agent-discovery");
41
48
  const runtime_1 = require("../../nerves/runtime");
42
49
  const runtime_metadata_1 = require("./runtime-metadata");
43
- const update_hooks_1 = require("./update-hooks");
50
+ const runtime_mode_1 = require("./runtime-mode");
51
+ const update_hooks_1 = require("../versioning/update-hooks");
44
52
  const bundle_meta_1 = require("./hooks/bundle-meta");
53
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
45
54
  const bundle_manifest_1 = require("../../mind/bundle-manifest");
46
- const update_checker_1 = require("./update-checker");
47
- const staged_restart_1 = require("./staged-restart");
55
+ const update_checker_1 = require("../versioning/update-checker");
56
+ const staged_restart_1 = require("../versioning/staged-restart");
57
+ const ouro_version_manager_1 = require("../versioning/ouro-version-manager");
48
58
  const child_process_1 = require("child_process");
59
+ const pending_1 = require("../../mind/pending");
60
+ const agent_service_1 = require("./agent-service");
61
+ const channel_1 = require("../../mind/friends/channel");
62
+ const mcp_manager_1 = require("../../repertoire/mcp-manager");
63
+ const outlook_http_1 = require("../outlook/outlook-http");
64
+ const outlook_types_1 = require("../outlook/outlook-types");
65
+ const outlook_read_1 = require("../outlook/outlook-read");
66
+ const outlook_view_1 = require("../outlook/outlook-view");
67
+ const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
68
+ /**
69
+ * Defense-in-depth: detect if we're running under vitest. The pidfile lives
70
+ * at a hardcoded path under the user's real ~/.ouro-cli/ — there's no DI
71
+ * seam to redirect it. So when a test creates a real OuroDaemon and calls
72
+ * start(), the daemon's killOrphanProcesses() reads the REAL pidfile,
73
+ * ps-verifies the PIDs, and SIGTERMs the production daemon. We saw this
74
+ * cause an outage on 2026-04-08 (alpha.265 daemon killed 93s after startup
75
+ * by a vitest test that called daemon.start()).
76
+ *
77
+ * Both killOrphanProcesses() and writePidfile() short-circuit under vitest
78
+ * to make the production pidfile sacred. Tests that need to verify these
79
+ * functions' behavior should use the extracted pure helpers
80
+ * (parseOrphanPidsFromPs, filterPidfilePidsToActualOrphans).
81
+ */
82
+ function isVitestProcess() {
83
+ /* v8 ignore next -- defensive: process and process.argv always exist in node @preserve */
84
+ if (typeof process === "undefined" || !Array.isArray(process.argv))
85
+ return false;
86
+ return process.argv.some((arg) => typeof arg === "string" && arg.includes("vitest"));
87
+ }
88
+ /**
89
+ * Scan `ps -eo pid,ppid,command` output for daemon-owned entry points whose
90
+ * parent has died (PPID reparented to init/PID 1). Returns the list of PIDs
91
+ * that are safe to SIGTERM — true orphans, not children of live sibling
92
+ * daemons running from worktrees, test suites, or other users of the harness.
93
+ *
94
+ * Exported so unit tests can exercise the filter without shelling out.
95
+ */
96
+ function parseOrphanPidsFromPs(psOutput, selfPid) {
97
+ const orphans = [];
98
+ for (const line of psOutput.split("\n")) {
99
+ // Explicitly exclude MCP server processes — they share a harness entry
100
+ // point but are not daemon children and must never be killed.
101
+ if (line.includes("mcp-serve") || line.includes("mcp serve"))
102
+ continue;
103
+ // Match only daemon-owned JS entry points.
104
+ if (!line.includes("agent-entry.js")
105
+ && !line.includes("daemon-entry.js")
106
+ && !line.includes("bluebubbles/entry.js")
107
+ && !line.includes("teams-entry.js"))
108
+ continue;
109
+ // Parse `<pid> <ppid> <command...>`. ps pads these with leading spaces.
110
+ // Regex guarantees both groups are \d+ so parseInt can't produce NaN.
111
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s/);
112
+ if (!match)
113
+ continue;
114
+ const pid = parseInt(match[1], 10);
115
+ const ppid = parseInt(match[2], 10);
116
+ if (pid === selfPid)
117
+ continue;
118
+ // CRITICAL: only kill processes whose parent is init (PID 1). A live
119
+ // PPID means the process belongs to another daemon instance (parallel
120
+ // test run, sibling worktree, another user of /tmp/ouroboros-daemon.sock).
121
+ // Killing those will crash unrelated harnesses — we saw this in B6
122
+ // when a vitest worker's daemon killed slugger's production children.
123
+ if (ppid !== 1)
124
+ continue;
125
+ orphans.push(pid);
126
+ }
127
+ return orphans;
128
+ }
129
+ /**
130
+ * Given a list of PIDs from the pidfile, return only those that are actual
131
+ * orphans (PPID reparented to init/PID 1). Protects against a polluted
132
+ * pidfile killing a PID that the OS has reassigned to an unrelated process.
133
+ *
134
+ * Implementation: shells out to `ps -p <csv> -o pid,ppid` for a batch lookup.
135
+ * Returns the empty list if ps fails — safer to skip cleanup than to
136
+ * wildcard-kill on a bad read.
137
+ *
138
+ * Exported for direct unit coverage.
139
+ */
140
+ function filterPidfilePidsToActualOrphans(candidatePids, psRunner = runPsCheck) {
141
+ if (candidatePids.length === 0)
142
+ return [];
143
+ const psOutput = psRunner(candidatePids);
144
+ if (psOutput === null)
145
+ return [];
146
+ const survivingOrphans = [];
147
+ // `ps -p x,y,z -o pid,ppid` emits a header line then one row per found PID.
148
+ // PIDs not found (already exited) are silently omitted — which is the
149
+ // correct behavior for us: we only want to kill live orphans.
150
+ for (const line of psOutput.split("\n")) {
151
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
152
+ if (!match)
153
+ continue;
154
+ const pid = parseInt(match[1], 10);
155
+ const ppid = parseInt(match[2], 10);
156
+ if (ppid !== 1)
157
+ continue;
158
+ if (!candidatePids.includes(pid))
159
+ continue;
160
+ survivingOrphans.push(pid);
161
+ }
162
+ return survivingOrphans;
163
+ }
164
+ /* v8 ignore start -- shells out to ps; covered by filterPidfilePidsToActualOrphans unit tests via injected runner @preserve */
165
+ function runPsCheck(pids) {
166
+ try {
167
+ const csv = pids.join(",");
168
+ return (0, child_process_1.execSync)(`ps -p ${csv} -o pid=,ppid=`, { encoding: "utf-8", timeout: 5000 });
169
+ }
170
+ catch {
171
+ // ps returns non-zero when none of the requested PIDs exist. Treat as
172
+ // "no survivors" rather than an error.
173
+ return "";
174
+ }
175
+ }
176
+ /* v8 ignore stop */
177
+ /**
178
+ * Kill all ouro processes from the previous daemon instance using the pidfile.
179
+ * On startup, reads PIDs from ~/.ouro-cli/daemon.pids, kills them all, then
180
+ * deletes the file. The new daemon writes its own PIDs after spawning.
181
+ *
182
+ * Safety: pidfile contents are verified before being killed — each PID must
183
+ * be an actual orphan (PPID reparented to init/PID 1) via
184
+ * `filterPidfilePidsToActualOrphans`. Otherwise a polluted pidfile (written
185
+ * by a test, or a crashed daemon whose PIDs have since been reused by the
186
+ * OS) could SIGTERM unrelated processes.
187
+ *
188
+ * Falls back to ps-based scanning scoped to true orphans (PPID=1) if the
189
+ * pidfile doesn't exist (first run, previous daemon crashed before writing,
190
+ * manual cleanup). The scope is narrow on purpose — see parseOrphanPidsFromPs.
191
+ */
192
+ /* v8 ignore start -- process lifecycle: uses kill/ps, tested via deployment @preserve */
193
+ function killOrphanProcesses() {
194
+ if (isVitestProcess()) {
195
+ (0, runtime_1.emitNervesEvent)({
196
+ level: "warn",
197
+ component: "daemon",
198
+ event: "daemon.orphan_cleanup_test_blocked",
199
+ message: "blocked killOrphanProcesses from touching real pidfile under vitest",
200
+ meta: { pidfilePath: PIDFILE_PATH },
201
+ });
202
+ return;
203
+ }
204
+ try {
205
+ let pidsToKill = [];
206
+ // Primary: read pidfile from previous daemon
207
+ try {
208
+ const raw = fs.readFileSync(PIDFILE_PATH, "utf-8");
209
+ const candidates = raw.split("\n")
210
+ .map((s) => parseInt(s.trim(), 10))
211
+ .filter((n) => !isNaN(n) && n !== process.pid);
212
+ // Verify each candidate is an actual live orphan before killing. See
213
+ // docstring above for why this matters.
214
+ pidsToKill = filterPidfilePidsToActualOrphans(candidates);
215
+ fs.unlinkSync(PIDFILE_PATH);
216
+ }
217
+ catch {
218
+ // No pidfile — fall back to ps scan (scoped to orphans with PPID=1).
219
+ }
220
+ if (pidsToKill.length === 0) {
221
+ try {
222
+ const result = (0, child_process_1.execSync)("ps -eo pid,ppid,command", { encoding: "utf-8", timeout: 5000 });
223
+ pidsToKill = parseOrphanPidsFromPs(result, process.pid);
224
+ }
225
+ catch { /* ps failed — best effort */ }
226
+ }
227
+ if (pidsToKill.length > 0) {
228
+ for (const pid of pidsToKill) {
229
+ try {
230
+ process.kill(pid, "SIGTERM");
231
+ }
232
+ catch { /* already exited */ }
233
+ }
234
+ (0, runtime_1.emitNervesEvent)({
235
+ component: "daemon",
236
+ event: "daemon.orphan_cleanup",
237
+ message: `killed ${pidsToKill.length} orphaned ouro processes`,
238
+ meta: { pids: pidsToKill },
239
+ });
240
+ }
241
+ }
242
+ catch (error) {
243
+ (0, runtime_1.emitNervesEvent)({
244
+ level: "warn",
245
+ component: "daemon",
246
+ event: "daemon.orphan_cleanup_error",
247
+ message: "failed to clean up orphaned ouro processes",
248
+ meta: { error: error instanceof Error ? error.message : String(error) },
249
+ });
250
+ }
251
+ }
252
+ /**
253
+ * Write all managed PIDs (daemon + children) to the pidfile.
254
+ * Called after all agents and senses are spawned.
255
+ */
256
+ function writePidfile(extraPids = []) {
257
+ if (isVitestProcess()) {
258
+ (0, runtime_1.emitNervesEvent)({
259
+ level: "warn",
260
+ component: "daemon",
261
+ event: "daemon.write_pidfile_test_blocked",
262
+ message: "blocked writePidfile from clobbering real pidfile under vitest",
263
+ meta: { pidfilePath: PIDFILE_PATH, attemptedPids: extraPids.length },
264
+ });
265
+ return;
266
+ }
267
+ try {
268
+ const pids = [process.pid, ...extraPids].filter(Boolean);
269
+ fs.mkdirSync(path.dirname(PIDFILE_PATH), { recursive: true });
270
+ fs.writeFileSync(PIDFILE_PATH, pids.join("\n") + "\n", "utf-8");
271
+ }
272
+ catch { /* best effort */ }
273
+ }
49
274
  function buildWorkerRows(snapshots) {
50
275
  return snapshots.map((snapshot) => ({
51
276
  agent: snapshot.name,
@@ -54,6 +279,8 @@ function buildWorkerRows(snapshots) {
54
279
  pid: snapshot.pid,
55
280
  restartCount: snapshot.restartCount,
56
281
  startedAt: snapshot.startedAt,
282
+ lastExitCode: snapshot.lastExitCode ?? null,
283
+ lastSignal: snapshot.lastSignal ?? null,
57
284
  }));
58
285
  }
59
286
  function formatStatusSummary(payload) {
@@ -86,6 +313,35 @@ function parseIncomingCommand(raw) {
86
313
  }
87
314
  return parsed;
88
315
  }
316
+ /**
317
+ * Handle agent.senseTurn command: runs a full agent turn via the daemon process.
318
+ * Dynamic import lazy-loads shared-turn. Hot-reload works because ouro dev
319
+ * restarts the daemon process (fresh module cache).
320
+ */
321
+ async function handleAgentSenseTurn(command) {
322
+ try {
323
+ const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
324
+ setAgentName(command.agent);
325
+ const { runSenseTurn } = await Promise.resolve().then(() => __importStar(require("../../senses/shared-turn")));
326
+ const result = await runSenseTurn({
327
+ agentName: command.agent,
328
+ channel: command.channel,
329
+ sessionKey: command.sessionKey,
330
+ friendId: command.friendId,
331
+ userMessage: command.message,
332
+ });
333
+ return {
334
+ ok: true,
335
+ message: result.response,
336
+ data: { ponderDeferred: result.ponderDeferred },
337
+ };
338
+ }
339
+ catch (error) {
340
+ /* v8 ignore next -- branch: String(error) fallback only for non-Error throws @preserve */
341
+ const errorMessage = error instanceof Error ? error.message : String(error);
342
+ return { ok: false, error: `sense turn failed: ${errorMessage}` };
343
+ }
344
+ }
89
345
  class OuroDaemon {
90
346
  socketPath;
91
347
  processManager;
@@ -94,7 +350,9 @@ class OuroDaemon {
94
350
  router;
95
351
  senseManager;
96
352
  bundlesRoot;
353
+ mode;
97
354
  server = null;
355
+ outlookServer = null;
98
356
  constructor(options) {
99
357
  this.socketPath = options.socketPath;
100
358
  this.processManager = options.processManager;
@@ -103,6 +361,32 @@ class OuroDaemon {
103
361
  this.router = options.router;
104
362
  this.senseManager = options.senseManager ?? null;
105
363
  this.bundlesRoot = options.bundlesRoot ?? (0, identity_1.getAgentBundlesRoot)();
364
+ this.mode = options.mode ?? "production";
365
+ }
366
+ buildStatusPayload() {
367
+ const snapshots = this.processManager.listAgentSnapshots();
368
+ const workers = buildWorkerRows(snapshots);
369
+ const senses = this.senseManager?.listSenseRows() ?? [];
370
+ const repoRoot = (0, identity_1.getRepoRoot)();
371
+ const sync = (0, agent_discovery_1.listBundleSyncRows)({ bundlesRoot: this.bundlesRoot });
372
+ const agents = (0, agent_discovery_1.listAllBundleAgents)({ bundlesRoot: this.bundlesRoot });
373
+ return {
374
+ overview: {
375
+ daemon: "running",
376
+ health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
377
+ socketPath: this.socketPath,
378
+ outlookUrl: this.outlookServer?.origin ?? "http://127.0.0.1:0",
379
+ ...(0, runtime_metadata_1.getRuntimeMetadata)(),
380
+ workerCount: workers.length,
381
+ senseCount: senses.length,
382
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
383
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
384
+ },
385
+ workers,
386
+ senses,
387
+ sync,
388
+ agents,
389
+ };
106
390
  }
107
391
  async start() {
108
392
  if (this.server)
@@ -113,61 +397,211 @@ class OuroDaemon {
113
397
  message: "starting daemon server",
114
398
  meta: { socketPath: this.socketPath },
115
399
  });
400
+ try {
401
+ await this.startInner();
402
+ }
403
+ catch (err) {
404
+ // Emit a paired terminating event (`_error`) so the nerves audit's
405
+ // start_end_pairing rule is satisfied when startup throws mid-sequence
406
+ // and `stop()` (which emits `server_end`) is never called.
407
+ (0, runtime_1.emitNervesEvent)({
408
+ level: "error",
409
+ component: "daemon",
410
+ event: "daemon.server_error",
411
+ message: "daemon start failed",
412
+ meta: {
413
+ error: err instanceof Error ? err.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(err),
414
+ },
415
+ });
416
+ throw err;
417
+ }
418
+ }
419
+ async startInner() {
116
420
  // Register update hooks and apply pending updates before starting agents
117
421
  (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
422
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
118
423
  const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
119
424
  await (0, update_hooks_1.applyPendingUpdates)(this.bundlesRoot, currentVersion);
120
425
  // Start periodic update checker (polls npm registry every 30 minutes)
426
+ // Skip in dev mode — dev builds should not auto-update from npm
121
427
  const bundlesRoot = this.bundlesRoot;
122
- const daemon = this;
123
- (0, update_checker_1.startUpdateChecker)({
124
- currentVersion,
125
- deps: {
126
- distTag: "alpha",
127
- fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
128
- const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
129
- return res.json();
130
- },
131
- },
132
- onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
133
- if (!result.latestVersion)
134
- return;
135
- await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
136
- execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
137
- spawnSync: child_process_1.spawnSync,
138
- resolveNewCodePath: (_version) => {
139
- try {
140
- const resolved = (0, child_process_1.execSync)(`node -e "console.log(require.resolve('@ouro.bot/cli/package.json'))"`, { encoding: "utf-8" }).trim();
141
- return resolved ? path.dirname(resolved) : null;
142
- }
143
- catch {
144
- return null;
145
- }
428
+ const daemonSocketPath = this.socketPath;
429
+ if (this.mode === "dev") {
430
+ (0, runtime_1.emitNervesEvent)({
431
+ component: "daemon",
432
+ event: "daemon.update_checker_skip",
433
+ message: "skipping update checker in dev mode",
434
+ meta: { reason: "dev mode" },
435
+ });
436
+ }
437
+ else {
438
+ const daemon = this;
439
+ (0, update_checker_1.startUpdateChecker)({
440
+ currentVersion,
441
+ deps: {
442
+ distTag: "alpha",
443
+ fetchRegistryJson: /* v8 ignore next -- integration: real HTTP fetch @preserve */ async () => {
444
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
445
+ return res.json();
146
446
  },
147
- gracefulShutdown: () => daemon.stop(),
148
- nodePath: process.execPath,
149
- bundlesRoot,
150
- });
151
- },
152
- /* v8 ignore stop */
153
- });
447
+ },
448
+ onUpdate: /* v8 ignore start -- integration: real npm install + process spawn @preserve */ async (result) => {
449
+ if (!result.latestVersion)
450
+ return;
451
+ // Install via the version manager (NOT `npm install -g`). The
452
+ // global install path doesn't end up on the daemon process's
453
+ // NODE_PATH, so the previous `require.resolve('@ouro.bot/cli')`
454
+ // -based path lookup always returned null and the staged restart
455
+ // never actually completed. Verified live on 2026-04-08:
456
+ // alpha.268 daemon detected alpha.270 was available, ran the
457
+ // staged restart, and bailed at `staged_restart_path_failed` —
458
+ // meaning the daemon could never auto-update itself and required
459
+ // manual `ouro up` to pick up new versions.
460
+ //
461
+ // Switch to the version-managed layout the CLI itself uses:
462
+ // installVersion(version) puts files at
463
+ // ~/.ouro-cli/versions/{version}/node_modules/@ouro.bot/cli
464
+ // which is a known path we can compute deterministically.
465
+ // Then activateVersion(version) flips the CurrentVersion symlink
466
+ // so the next `ouro up` from the user sees the same version
467
+ // the daemon is running.
468
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
469
+ await (0, staged_restart_1.performStagedRestart)(result.latestVersion, {
470
+ execSync: (cmd) => (0, child_process_1.execSync)(cmd, { stdio: "inherit" }),
471
+ spawnSync: child_process_1.spawnSync,
472
+ installNewVersion: (version) => {
473
+ (0, ouro_version_manager_1.installVersion)(version, {});
474
+ (0, ouro_version_manager_1.activateVersion)(version, {});
475
+ },
476
+ resolveNewCodePath: (version) => {
477
+ const versionPath = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli");
478
+ return fs.existsSync(versionPath) ? versionPath : null;
479
+ },
480
+ gracefulShutdown: () => daemon.stop(),
481
+ spawnNewDaemon: (entryPath, sock) => {
482
+ const outFd = fs.openSync(os.devNull, "w");
483
+ const errFd = fs.openSync(os.devNull, "w");
484
+ const child = (0, child_process_1.spawn)(process.execPath, [entryPath, "--socket", sock], {
485
+ detached: true,
486
+ stdio: ["ignore", outFd, errFd],
487
+ });
488
+ child.unref();
489
+ return { pid: child.pid ?? null };
490
+ },
491
+ nodePath: process.execPath,
492
+ bundlesRoot,
493
+ socketPath: daemonSocketPath,
494
+ });
495
+ },
496
+ /* v8 ignore stop */
497
+ });
498
+ }
499
+ // MCP connections are lazily initialized per-agent during senseTurn
500
+ // (daemon manages multiple agents; agent identity must be set before loading MCP config)
501
+ /* v8 ignore start -- orphan cleanup + pidfile: calls process management functions @preserve */
502
+ killOrphanProcesses();
503
+ /* v8 ignore stop */
154
504
  await this.processManager.startAutoStartAgents();
155
505
  await this.senseManager?.startAutoStartSenses();
506
+ // Write all managed PIDs to disk so the next daemon can clean up
507
+ /* v8 ignore start -- pidfile write: collects PIDs from process managers @preserve */
508
+ const agentPids = this.processManager.listAgentSnapshots().map((s) => s.pid).filter((p) => p !== null);
509
+ const sensePids = this.senseManager?.listManagedPids?.() ?? [];
510
+ writePidfile([...agentPids, ...sensePids]);
511
+ /* v8 ignore stop */
156
512
  this.scheduler.start?.();
157
513
  await this.scheduler.reconcile?.();
158
514
  await this.drainPendingBundleMessages();
515
+ await this.drainPendingSenseMessages();
516
+ /* v8 ignore start — Outlook server startup, tested via outlook-http.test.ts */
517
+ if (!this.outlookServer) {
518
+ try {
519
+ this.outlookServer = await (0, outlook_http_1.startOutlookHttpServer)({
520
+ host: "127.0.0.1",
521
+ port: outlook_types_1.OUTLOOK_DEFAULT_PORT,
522
+ bundlesRoot: this.bundlesRoot,
523
+ readMachineState: () => (0, outlook_read_1.readOutlookMachineState)({ bundlesRoot: this.bundlesRoot }),
524
+ readMachineView: ({ machine }) => {
525
+ const overview = this.buildStatusPayload().overview;
526
+ return (0, outlook_view_1.buildOutlookMachineView)({
527
+ machine,
528
+ daemon: {
529
+ status: overview.daemon,
530
+ health: overview.health,
531
+ mode: overview.mode,
532
+ socketPath: overview.socketPath,
533
+ outlookUrl: overview.outlookUrl,
534
+ entryPath: overview.entryPath,
535
+ workerCount: overview.workerCount,
536
+ senseCount: overview.senseCount,
537
+ },
538
+ });
539
+ },
540
+ readAgentState: (agentName) => (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot }),
541
+ readAgentView: (agentName) => {
542
+ const agent = (0, outlook_read_1.readOutlookAgentState)(agentName, { bundlesRoot: this.bundlesRoot });
543
+ return (0, outlook_view_1.buildOutlookAgentView)({
544
+ agent,
545
+ viewer: { kind: "human" },
546
+ });
547
+ },
548
+ });
549
+ }
550
+ catch (error) {
551
+ (0, runtime_1.emitNervesEvent)({
552
+ level: "warn",
553
+ component: "daemon",
554
+ event: "daemon.outlook_start_failed",
555
+ message: `Outlook server failed to start: ${String(error)}`,
556
+ meta: { port: outlook_types_1.OUTLOOK_DEFAULT_PORT },
557
+ });
558
+ }
559
+ }
560
+ /* v8 ignore stop */
159
561
  if (fs.existsSync(this.socketPath)) {
160
562
  fs.unlinkSync(this.socketPath);
161
563
  }
162
- this.server = net.createServer((connection) => {
564
+ // allowHalfOpen: true lets the server keep its writable side open after
565
+ // the client sends FIN. Without this, when a client calls `client.end()`
566
+ // after writing a command, node closes the server's writable side
567
+ // automatically — so a long-running response (like an agent.senseTurn
568
+ // LLM turn that takes 5+ seconds) never reaches the client. The
569
+ // socket-client fix in #303/#334 also removed client.end() on the
570
+ // sending side, but this option is defense in depth: even if a future
571
+ // caller half-closes, the server still writes its response correctly.
572
+ this.server = net.createServer({ allowHalfOpen: true }, (connection) => {
163
573
  let raw = "";
164
574
  let responded = false;
575
+ /* v8 ignore start — connection error handler requires real socket error @preserve */
576
+ connection.on("error", (err) => {
577
+ (0, runtime_1.emitNervesEvent)({
578
+ level: "warn",
579
+ component: "daemon",
580
+ event: "daemon.connection_error",
581
+ message: "socket connection error",
582
+ meta: { error: err.message, code: err.code ?? null },
583
+ });
584
+ });
585
+ /* v8 ignore stop */
165
586
  const flushResponse = async () => {
166
587
  if (responded)
167
588
  return;
168
589
  responded = true;
169
590
  const response = await this.handleRawPayload(raw);
170
- connection.end(response);
591
+ try {
592
+ connection.end(response);
593
+ /* v8 ignore start — EPIPE catch requires real socket disconnect @preserve */
594
+ }
595
+ catch (err) {
596
+ (0, runtime_1.emitNervesEvent)({
597
+ level: "warn",
598
+ component: "daemon",
599
+ event: "daemon.connection_end_error",
600
+ message: "failed to send response to client (EPIPE)",
601
+ meta: { error: err instanceof Error ? err.message : String(err) },
602
+ });
603
+ }
604
+ /* v8 ignore stop */
171
605
  };
172
606
  connection.on("data", (chunk) => {
173
607
  raw += chunk.toString("utf-8");
@@ -180,7 +614,22 @@ class OuroDaemon {
180
614
  const server = this.server;
181
615
  await new Promise((resolve, reject) => {
182
616
  server.once("error", reject);
183
- server.listen(this.socketPath, () => resolve());
617
+ server.listen(this.socketPath, () => {
618
+ // Replace the one-time error listener with a persistent one after successful listen
619
+ server.removeAllListeners("error");
620
+ /* v8 ignore start — server error after listen requires real socket race condition @preserve */
621
+ server.on("error", (err) => {
622
+ (0, runtime_1.emitNervesEvent)({
623
+ level: "error",
624
+ component: "daemon",
625
+ event: "daemon.server_error",
626
+ message: "daemon server error after listen",
627
+ meta: { error: err.message, code: err.code ?? null },
628
+ });
629
+ });
630
+ /* v8 ignore stop */
631
+ resolve();
632
+ });
184
633
  });
185
634
  }
186
635
  async drainPendingBundleMessages() {
@@ -231,23 +680,147 @@ class OuroDaemon {
231
680
  fs.writeFileSync(pendingPath, next, "utf-8");
232
681
  }
233
682
  }
683
+ /** Drains per-sense pending dirs for always-on senses across all agents. */
684
+ static ALWAYS_ON_SENSES = new Set((0, channel_1.getAlwaysOnSenseNames)());
685
+ async drainPendingSenseMessages() {
686
+ if (!fs.existsSync(this.bundlesRoot))
687
+ return;
688
+ let bundleDirs;
689
+ try {
690
+ bundleDirs = fs.readdirSync(this.bundlesRoot, { withFileTypes: true });
691
+ }
692
+ catch {
693
+ return;
694
+ }
695
+ for (const bundleDir of bundleDirs) {
696
+ if (!bundleDir.isDirectory() || !bundleDir.name.endsWith(".ouro"))
697
+ continue;
698
+ const agentName = bundleDir.name.replace(/\.ouro$/, "");
699
+ const pendingRoot = path.join(this.bundlesRoot, bundleDir.name, "state", "pending");
700
+ if (!fs.existsSync(pendingRoot))
701
+ continue;
702
+ let friendDirs;
703
+ try {
704
+ friendDirs = fs.readdirSync(pendingRoot, { withFileTypes: true });
705
+ }
706
+ catch {
707
+ continue;
708
+ }
709
+ for (const friendDir of friendDirs) {
710
+ if (!friendDir.isDirectory())
711
+ continue;
712
+ const friendPath = path.join(pendingRoot, friendDir.name);
713
+ let channelDirs;
714
+ try {
715
+ channelDirs = fs.readdirSync(friendPath, { withFileTypes: true });
716
+ }
717
+ catch {
718
+ continue;
719
+ }
720
+ for (const channelDir of channelDirs) {
721
+ if (!channelDir.isDirectory())
722
+ continue;
723
+ if (!OuroDaemon.ALWAYS_ON_SENSES.has(channelDir.name))
724
+ continue;
725
+ const channelPath = path.join(friendPath, channelDir.name);
726
+ let keyDirs;
727
+ try {
728
+ keyDirs = fs.readdirSync(channelPath, { withFileTypes: true });
729
+ }
730
+ catch {
731
+ continue;
732
+ }
733
+ for (const keyDir of keyDirs) {
734
+ if (!keyDir.isDirectory())
735
+ continue;
736
+ const leafDir = path.join(channelPath, keyDir.name);
737
+ const messages = (0, pending_1.drainPending)(leafDir);
738
+ for (const msg of messages) {
739
+ try {
740
+ await this.router.send({
741
+ from: msg.from,
742
+ to: agentName,
743
+ content: msg.content,
744
+ priority: "normal",
745
+ });
746
+ }
747
+ catch {
748
+ // Best-effort delivery — log and continue
749
+ }
750
+ }
751
+ if (messages.length > 0) {
752
+ (0, runtime_1.emitNervesEvent)({
753
+ component: "daemon",
754
+ event: "daemon.startup_sense_drain",
755
+ message: "drained pending sense messages on startup",
756
+ meta: {
757
+ agent: agentName,
758
+ channel: channelDir.name,
759
+ friendId: friendDir.name,
760
+ key: keyDir.name,
761
+ count: messages.length,
762
+ },
763
+ });
764
+ }
765
+ }
766
+ }
767
+ }
768
+ }
769
+ }
234
770
  async stop() {
771
+ // Must be named `_end` (not `_stop`) to satisfy the nerves audit's
772
+ // start/end pairing rule — see src/nerves/coverage/audit-rules.ts.
773
+ // This is the counterpart to `daemon.server_start` emitted at line 480.
235
774
  (0, runtime_1.emitNervesEvent)({
236
775
  component: "daemon",
237
- event: "daemon.server_stop",
776
+ event: "daemon.server_end",
238
777
  message: "stopping daemon server",
239
778
  meta: { socketPath: this.socketPath },
240
779
  });
241
780
  (0, update_checker_1.stopUpdateChecker)();
781
+ (0, mcp_manager_1.shutdownSharedMcpManager)();
242
782
  this.scheduler.stop?.();
243
783
  await this.processManager.stopAll();
244
784
  await this.senseManager?.stopAll();
245
785
  if (this.server) {
246
- await new Promise((resolve) => {
247
- this.server?.close(() => resolve());
248
- });
786
+ // DO NOT `await` server.close() here. server.close() resolves only
787
+ // after every open connection has closed. When stop() is invoked
788
+ // from the daemon.stop command handler, the calling client's
789
+ // connection is STILL open — its flushResponse() is currently
790
+ // awaiting THIS function. Awaiting close() creates a deadlock:
791
+ //
792
+ // client → flushResponse → handleRawPayload → daemon.stop case
793
+ // → stop() → await server.close() (waits for client's connection)
794
+ // → client's connection waits for flushResponse to call
795
+ // connection.end() → DEADLOCK
796
+ //
797
+ // Both processes sit in kevent forever. Verified live on
798
+ // 2026-04-08: alpha.268 daemon hung at `daemon.server_end` log
799
+ // line for 5+ minutes after a client sent daemon.stop, while the
800
+ // client (alpha.270 ouro up) hung waiting for the response.
801
+ //
802
+ // This regressed when #303/#334/#339 stopped half-closing the
803
+ // client socket and switched the server to allowHalfOpen: true.
804
+ // Previously, the client called .end() after writing its command,
805
+ // which (with allowHalfOpen: false) caused node to auto-tear-down
806
+ // the server's writable side — incidentally unblocking
807
+ // server.close() before the response was sent. The half-close
808
+ // breakage masked this deadlock; the fix exposed it.
809
+ //
810
+ // Solution: fire close() and let it complete asynchronously. Once
811
+ // stop() returns, the daemon.stop case returns its response,
812
+ // flushResponse() calls connection.end(response), the connection
813
+ // closes, and server.close()'s pending callback fires. The event
814
+ // loop drains and the daemon exits cleanly.
815
+ this.server.close();
249
816
  this.server = null;
250
817
  }
818
+ /* v8 ignore start -- outlookServer stop: only reachable when the outlook HTTP server successfully bound to port 6876 during start(). Coverage fluctuates locally because a running production daemon holds the port and tests get EADDRINUSE, leaving outlookServer null. In CI the port is free and this block runs. Not worth fighting port contention to cover two trivial lines. @preserve */
819
+ if (this.outlookServer) {
820
+ await this.outlookServer.stop();
821
+ this.outlookServer = null;
822
+ }
823
+ /* v8 ignore stop */
251
824
  if (fs.existsSync(this.socketPath)) {
252
825
  fs.unlinkSync(this.socketPath);
253
826
  }
@@ -272,6 +845,27 @@ class OuroDaemon {
272
845
  message: "handling daemon command",
273
846
  meta: { kind: command.kind },
274
847
  });
848
+ try {
849
+ return await this.handleCommandInner(command);
850
+ /* v8 ignore start — command error catch tested in daemon-command-error.test; instanceof branches defensive @preserve */
851
+ }
852
+ catch (error) {
853
+ (0, runtime_1.emitNervesEvent)({
854
+ level: "error",
855
+ component: "daemon",
856
+ event: "daemon.command_error",
857
+ message: "unexpected error handling daemon command",
858
+ meta: {
859
+ kind: command.kind,
860
+ error: error instanceof Error ? error.message : String(error),
861
+ stack: error instanceof Error ? error.stack ?? null : null,
862
+ },
863
+ });
864
+ throw error;
865
+ }
866
+ /* v8 ignore stop */
867
+ }
868
+ async handleCommandInner(command) {
275
869
  switch (command.kind) {
276
870
  case "daemon.start":
277
871
  await this.start();
@@ -280,21 +874,7 @@ class OuroDaemon {
280
874
  await this.stop();
281
875
  return { ok: true, message: "daemon stopped" };
282
876
  case "daemon.status": {
283
- const snapshots = this.processManager.listAgentSnapshots();
284
- const workers = buildWorkerRows(snapshots);
285
- const senses = this.senseManager?.listSenseRows() ?? [];
286
- const data = {
287
- overview: {
288
- daemon: "running",
289
- health: workers.every((worker) => worker.status === "running") ? "ok" : "warn",
290
- socketPath: this.socketPath,
291
- ...(0, runtime_metadata_1.getRuntimeMetadata)(),
292
- workerCount: workers.length,
293
- senseCount: senses.length,
294
- },
295
- workers,
296
- senses,
297
- };
877
+ const data = this.buildStatusPayload();
298
878
  return {
299
879
  ok: true,
300
880
  summary: formatStatusSummary(data),
@@ -311,7 +891,7 @@ class OuroDaemon {
311
891
  ok: true,
312
892
  summary: "logs: use `ouro logs` to tail daemon and agent output",
313
893
  message: "log streaming available via ouro logs",
314
- data: { logDir: "~/.agentstate/daemon/logs" },
894
+ data: { logDir: "~/AgentBundles/<agent>.ouro/state/daemon/logs" },
315
895
  };
316
896
  case "agent.start":
317
897
  await this.processManager.startAgent(command.agent);
@@ -322,6 +902,35 @@ class OuroDaemon {
322
902
  case "agent.restart":
323
903
  await this.processManager.restartAgent?.(command.agent);
324
904
  return { ok: true, message: `restarted ${command.agent}` };
905
+ case "agent.ask":
906
+ return (0, agent_service_1.handleAgentAsk)(command);
907
+ case "agent.status":
908
+ return (0, agent_service_1.handleAgentStatus)(command);
909
+ case "agent.catchup":
910
+ return (0, agent_service_1.handleAgentCatchup)(command);
911
+ case "agent.delegate":
912
+ return (0, agent_service_1.handleAgentDelegate)(command);
913
+ case "agent.getContext":
914
+ return (0, agent_service_1.handleAgentGetContext)(command);
915
+ case "agent.searchMemory":
916
+ return (0, agent_service_1.handleAgentSearchMemory)(command);
917
+ case "agent.getTask":
918
+ return (0, agent_service_1.handleAgentGetTask)(command);
919
+ case "agent.checkScope":
920
+ return (0, agent_service_1.handleAgentCheckScope)(command);
921
+ case "agent.requestDecision":
922
+ return (0, agent_service_1.handleAgentRequestDecision)(command);
923
+ case "agent.checkGuidance":
924
+ return (0, agent_service_1.handleAgentCheckGuidance)(command);
925
+ case "agent.reportProgress":
926
+ return (0, agent_service_1.handleAgentReportProgress)(command);
927
+ case "agent.reportBlocker":
928
+ return (0, agent_service_1.handleAgentReportBlocker)(command);
929
+ case "agent.reportComplete":
930
+ return (0, agent_service_1.handleAgentReportComplete)(command);
931
+ case "agent.senseTurn":
932
+ return handleAgentSenseTurn(command);
933
+ /* v8 ignore stop */
325
934
  case "cron.list": {
326
935
  const jobs = this.scheduler.listJobs();
327
936
  const summary = jobs.length === 0
@@ -353,6 +962,13 @@ class OuroDaemon {
353
962
  data: messages,
354
963
  };
355
964
  }
965
+ case "inner.wake":
966
+ await this.processManager.startAgent(command.agent);
967
+ this.processManager.sendToAgent?.(command.agent, { type: "message" });
968
+ return {
969
+ ok: true,
970
+ message: `woke inner dialog for ${command.agent}`,
971
+ };
356
972
  case "chat.connect":
357
973
  await this.processManager.startAgent(command.agent);
358
974
  return {
@@ -375,6 +991,35 @@ class OuroDaemon {
375
991
  data: receipt,
376
992
  };
377
993
  }
994
+ case "habit.poke": {
995
+ this.processManager.sendToAgent?.(command.agent, { type: "habit", habitName: command.habitName });
996
+ return {
997
+ ok: true,
998
+ message: `poked habit ${command.habitName} for ${command.agent}`,
999
+ };
1000
+ }
1001
+ case "mcp.list": {
1002
+ const mcpManager = await (0, mcp_manager_1.getSharedMcpManager)();
1003
+ if (!mcpManager) {
1004
+ return { ok: true, data: [], message: "no MCP servers configured" };
1005
+ }
1006
+ return { ok: true, data: mcpManager.listAllTools() };
1007
+ }
1008
+ case "mcp.call": {
1009
+ const mcpCallManager = await (0, mcp_manager_1.getSharedMcpManager)();
1010
+ if (!mcpCallManager) {
1011
+ return { ok: false, error: "no MCP servers configured" };
1012
+ }
1013
+ try {
1014
+ const parsedArgs = command.args ? JSON.parse(command.args) : {};
1015
+ const result = await mcpCallManager.callTool(command.server, command.tool, parsedArgs);
1016
+ return { ok: true, data: result };
1017
+ }
1018
+ catch (error) {
1019
+ /* v8 ignore next -- defensive: callTool errors are always Error instances @preserve */
1020
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
1021
+ }
1022
+ }
378
1023
  case "hatch.start":
379
1024
  return {
380
1025
  ok: true,