@ouro.bot/cli 0.1.0-alpha.17 → 0.1.0-alpha.171

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 (168) hide show
  1. package/AdoptionSpecialist.ouro/agent.json +3 -2
  2. package/AdoptionSpecialist.ouro/psyche/SOUL.md +3 -3
  3. package/AdoptionSpecialist.ouro/psyche/identities/monty.md +2 -2
  4. package/README.md +187 -191
  5. package/changelog.json +1152 -0
  6. package/dist/heart/active-work.js +633 -0
  7. package/dist/heart/bridges/manager.js +358 -0
  8. package/dist/heart/bridges/state-machine.js +135 -0
  9. package/dist/heart/bridges/store.js +123 -0
  10. package/dist/heart/commitments.js +105 -0
  11. package/dist/heart/config.js +40 -30
  12. package/dist/heart/core.js +608 -123
  13. package/dist/heart/cross-chat-delivery.js +146 -0
  14. package/dist/heart/daemon/agent-discovery.js +81 -0
  15. package/dist/heart/daemon/agent-service.js +360 -0
  16. package/dist/heart/daemon/auth-flow.js +477 -0
  17. package/dist/heart/daemon/cadence.js +70 -0
  18. package/dist/heart/daemon/daemon-cli.js +2473 -206
  19. package/dist/heart/daemon/daemon-entry.js +140 -4
  20. package/dist/heart/daemon/daemon-health.js +136 -0
  21. package/dist/heart/daemon/daemon-runtime-sync.js +212 -0
  22. package/dist/heart/daemon/daemon-tombstone.js +123 -0
  23. package/dist/heart/daemon/daemon.js +446 -17
  24. package/dist/heart/daemon/habit-migration.js +181 -0
  25. package/dist/heart/daemon/habit-parser.js +119 -0
  26. package/dist/heart/daemon/habit-scheduler.js +369 -0
  27. package/dist/heart/daemon/hatch-animation.js +10 -3
  28. package/dist/heart/daemon/hatch-flow.js +30 -111
  29. package/dist/heart/daemon/hooks/agent-config-v2.js +33 -0
  30. package/dist/heart/daemon/hooks/bundle-meta.js +92 -0
  31. package/dist/heart/daemon/inner-status.js +89 -0
  32. package/dist/heart/daemon/launchd.js +161 -0
  33. package/dist/heart/daemon/log-tailer.js +4 -3
  34. package/dist/heart/daemon/mcp-server.js +591 -0
  35. package/dist/heart/daemon/message-router.js +17 -8
  36. package/dist/heart/daemon/os-cron-deps.js +134 -0
  37. package/dist/heart/daemon/ouro-bot-global-installer.js +128 -0
  38. package/dist/heart/daemon/ouro-path-installer.js +78 -34
  39. package/dist/heart/daemon/ouro-version-manager.js +171 -0
  40. package/dist/heart/daemon/outlook-http.js +399 -0
  41. package/dist/heart/daemon/outlook-read.js +1291 -0
  42. package/dist/heart/daemon/outlook-render.js +1032 -0
  43. package/dist/heart/daemon/outlook-types.js +7 -0
  44. package/dist/heart/daemon/outlook-view.js +194 -0
  45. package/dist/heart/daemon/process-manager.js +75 -0
  46. package/dist/heart/daemon/run-hooks.js +39 -0
  47. package/dist/heart/daemon/runtime-logging.js +58 -15
  48. package/dist/heart/daemon/runtime-metadata.js +219 -0
  49. package/dist/heart/daemon/runtime-mode.js +67 -0
  50. package/dist/heart/daemon/safe-mode.js +161 -0
  51. package/dist/heart/daemon/sense-manager.js +50 -2
  52. package/dist/heart/daemon/session-id-resolver.js +131 -0
  53. package/dist/heart/daemon/skill-management-installer.js +94 -0
  54. package/dist/heart/daemon/socket-client.js +202 -0
  55. package/dist/heart/daemon/specialist-orchestrator.js +2 -2
  56. package/dist/heart/daemon/specialist-prompt.js +13 -8
  57. package/dist/heart/daemon/specialist-tools.js +53 -4
  58. package/dist/heart/daemon/staged-restart.js +114 -0
  59. package/dist/heart/daemon/task-scheduler.js +3 -25
  60. package/dist/heart/daemon/thoughts.js +507 -0
  61. package/dist/heart/daemon/update-checker.js +111 -0
  62. package/dist/heart/daemon/update-hooks.js +138 -0
  63. package/dist/heart/daemon/wrapper-publish-guard.js +86 -0
  64. package/dist/heart/delegation.js +62 -0
  65. package/dist/heart/identity.js +136 -55
  66. package/dist/heart/kicks.js +2 -20
  67. package/dist/heart/migrate-config.js +127 -0
  68. package/dist/heart/model-capabilities.js +48 -0
  69. package/dist/heart/obligations.js +197 -0
  70. package/dist/heart/progress-story.js +42 -0
  71. package/dist/heart/provider-failover.js +88 -0
  72. package/dist/heart/provider-ping.js +172 -0
  73. package/dist/heart/providers/anthropic-token.js +163 -0
  74. package/dist/heart/providers/anthropic.js +196 -36
  75. package/dist/heart/providers/azure.js +116 -10
  76. package/dist/heart/providers/github-copilot.js +157 -0
  77. package/dist/heart/providers/minimax.js +33 -3
  78. package/dist/heart/providers/openai-codex.js +51 -16
  79. package/dist/heart/session-activity.js +172 -0
  80. package/dist/heart/session-recall.js +216 -0
  81. package/dist/heart/streaming.js +62 -32
  82. package/dist/heart/target-resolution.js +127 -0
  83. package/dist/heart/tool-activity-callbacks.js +36 -0
  84. package/dist/heart/tool-description.js +135 -0
  85. package/dist/heart/tool-loop.js +200 -0
  86. package/dist/heart/turn-coordinator.js +28 -0
  87. package/dist/mind/associative-recall.js +122 -32
  88. package/dist/mind/bundle-manifest.js +14 -0
  89. package/dist/mind/context.js +125 -14
  90. package/dist/mind/{memory.js → diary.js} +70 -56
  91. package/dist/mind/first-impressions.js +16 -2
  92. package/dist/mind/friends/channel.js +56 -0
  93. package/dist/mind/friends/group-context.js +144 -0
  94. package/dist/mind/friends/store-file.js +19 -0
  95. package/dist/mind/friends/trust-explanation.js +74 -0
  96. package/dist/mind/friends/types.js +8 -0
  97. package/dist/mind/journal-index.js +161 -0
  98. package/dist/mind/obligation-steering.js +221 -0
  99. package/dist/mind/obligations.js +134 -0
  100. package/dist/mind/pending.js +76 -9
  101. package/dist/mind/phrases.js +1 -0
  102. package/dist/mind/prompt.js +649 -89
  103. package/dist/mind/token-estimate.js +8 -12
  104. package/dist/nerves/cli-logging.js +15 -2
  105. package/dist/nerves/coverage/run-artifacts.js +1 -1
  106. package/dist/nerves/event-buffer.js +111 -0
  107. package/dist/nerves/index.js +63 -3
  108. package/dist/nerves/observation.js +20 -0
  109. package/dist/nerves/runtime.js +5 -1
  110. package/dist/outlook-ui/assets/index-CBueh0d3.css +1 -0
  111. package/dist/outlook-ui/assets/index-rMPfWjDm.js +61 -0
  112. package/dist/outlook-ui/index.html +15 -0
  113. package/dist/repertoire/ado-semantic.js +6 -0
  114. package/dist/repertoire/coding/codex-jsonl.js +64 -0
  115. package/dist/repertoire/coding/context-pack.js +254 -0
  116. package/dist/repertoire/coding/feedback.js +197 -30
  117. package/dist/repertoire/coding/manager.js +149 -2
  118. package/dist/repertoire/coding/spawner.js +55 -9
  119. package/dist/repertoire/coding/tools.js +135 -2
  120. package/dist/repertoire/guardrails.js +291 -0
  121. package/dist/repertoire/mcp-client.js +254 -0
  122. package/dist/repertoire/mcp-manager.js +198 -0
  123. package/dist/repertoire/skills.js +14 -23
  124. package/dist/repertoire/tasks/board.js +43 -5
  125. package/dist/repertoire/tasks/fix.js +182 -0
  126. package/dist/repertoire/tasks/index.js +28 -10
  127. package/dist/repertoire/tasks/lifecycle.js +2 -2
  128. package/dist/repertoire/tasks/parser.js +3 -2
  129. package/dist/repertoire/tasks/scanner.js +194 -37
  130. package/dist/repertoire/tasks/transitions.js +11 -28
  131. package/dist/repertoire/tools-base.js +991 -272
  132. package/dist/repertoire/tools-bluebubbles.js +94 -0
  133. package/dist/repertoire/tools-github.js +1 -6
  134. package/dist/repertoire/tools-teams.js +12 -59
  135. package/dist/repertoire/tools.js +281 -122
  136. package/dist/scripts/claude-code-hook.js +41 -0
  137. package/dist/scripts/claude-code-stop-hook.js +47 -0
  138. package/dist/senses/attention-queue.js +97 -0
  139. package/dist/senses/bluebubbles-client.js +102 -3
  140. package/dist/senses/bluebubbles-entry.js +2 -0
  141. package/dist/senses/bluebubbles-inbound-log.js +109 -0
  142. package/dist/senses/bluebubbles-media.js +118 -23
  143. package/dist/senses/bluebubbles-model.js +12 -4
  144. package/dist/senses/bluebubbles-mutation-log.js +45 -5
  145. package/dist/senses/bluebubbles-runtime-state.js +109 -0
  146. package/dist/senses/bluebubbles-session-cleanup.js +72 -0
  147. package/dist/senses/bluebubbles.js +1008 -102
  148. package/dist/senses/cli-entry.js +1 -1
  149. package/dist/senses/cli-layout.js +187 -0
  150. package/dist/senses/cli.js +419 -152
  151. package/dist/senses/commands.js +38 -1
  152. package/dist/senses/continuity.js +94 -0
  153. package/dist/senses/habit-turn-message.js +108 -0
  154. package/dist/senses/inner-dialog-worker.js +112 -19
  155. package/dist/senses/inner-dialog.js +592 -84
  156. package/dist/senses/pipeline.js +502 -0
  157. package/dist/senses/shared-turn.js +196 -0
  158. package/dist/senses/surface-tool.js +95 -0
  159. package/dist/senses/teams.js +667 -120
  160. package/dist/senses/trust-gate.js +112 -2
  161. package/package.json +13 -5
  162. package/skills/configure-dev-tools.md +81 -0
  163. package/subagents/README.md +4 -70
  164. package/dist/heart/daemon/subagent-installer.js +0 -134
  165. package/dist/senses/debug-activity.js +0 -107
  166. package/subagents/work-doer.md +0 -235
  167. package/subagents/work-merger.md +0 -618
  168. package/subagents/work-planner.md +0 -382
@@ -34,26 +34,48 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ensureDaemonRunning = ensureDaemonRunning;
37
+ exports.listGithubCopilotModels = listGithubCopilotModels;
38
+ exports.pingGithubCopilotModel = pingGithubCopilotModel;
37
39
  exports.parseOuroCommand = parseOuroCommand;
40
+ exports.readFirstBundleMetaVersion = readFirstBundleMetaVersion;
38
41
  exports.discoverExistingCredentials = discoverExistingCredentials;
39
42
  exports.createDefaultOuroCliDeps = createDefaultOuroCliDeps;
40
43
  exports.runOuroCli = runOuroCli;
41
44
  const child_process_1 = require("child_process");
45
+ const crypto_1 = require("crypto");
42
46
  const fs = __importStar(require("fs"));
43
- const net = __importStar(require("net"));
44
47
  const os = __importStar(require("os"));
45
48
  const path = __importStar(require("path"));
49
+ const semver = __importStar(require("semver"));
46
50
  const identity_1 = require("../identity");
47
51
  const runtime_1 = require("../../nerves/runtime");
48
52
  const store_file_1 = require("../../mind/friends/store-file");
49
53
  const types_1 = require("../../mind/friends/types");
50
54
  const ouro_uti_1 = require("./ouro-uti");
51
55
  const ouro_path_installer_1 = require("./ouro-path-installer");
52
- const subagent_installer_1 = require("./subagent-installer");
56
+ const ouro_version_manager_1 = require("./ouro-version-manager");
57
+ const skill_management_installer_1 = require("./skill-management-installer");
53
58
  const hatch_flow_1 = require("./hatch-flow");
54
59
  const specialist_orchestrator_1 = require("./specialist-orchestrator");
55
60
  const specialist_prompt_1 = require("./specialist-prompt");
56
61
  const specialist_tools_1 = require("./specialist-tools");
62
+ const runtime_metadata_1 = require("./runtime-metadata");
63
+ const runtime_mode_1 = require("./runtime-mode");
64
+ const daemon_runtime_sync_1 = require("./daemon-runtime-sync");
65
+ const agent_discovery_1 = require("./agent-discovery");
66
+ const update_hooks_1 = require("./update-hooks");
67
+ const bundle_meta_1 = require("./hooks/bundle-meta");
68
+ const agent_config_v2_1 = require("./hooks/agent-config-v2");
69
+ const bundle_manifest_1 = require("../../mind/bundle-manifest");
70
+ const tasks_1 = require("../../repertoire/tasks");
71
+ const thoughts_1 = require("./thoughts");
72
+ const ouro_bot_global_installer_1 = require("./ouro-bot-global-installer");
73
+ const launchd_1 = require("./launchd");
74
+ const socket_client_1 = require("./socket-client");
75
+ const daemon_tombstone_1 = require("./daemon-tombstone");
76
+ const daemon_health_1 = require("./daemon-health");
77
+ const session_activity_1 = require("../session-activity");
78
+ const auth_flow_1 = require("./auth-flow");
57
79
  function stringField(value) {
58
80
  return typeof value === "string" ? value : null;
59
81
  }
@@ -78,8 +100,15 @@ function parseStatusPayload(data) {
78
100
  daemon: stringField(overview.daemon) ?? "unknown",
79
101
  health: stringField(overview.health) ?? "unknown",
80
102
  socketPath: stringField(overview.socketPath) ?? "unknown",
103
+ outlookUrl: stringField(overview.outlookUrl) ?? "unavailable",
104
+ version: stringField(overview.version) ?? "unknown",
105
+ lastUpdated: stringField(overview.lastUpdated) ?? "unknown",
106
+ repoRoot: stringField(overview.repoRoot) ?? "unknown",
107
+ configFingerprint: stringField(overview.configFingerprint) ?? "unknown",
81
108
  workerCount: numberField(overview.workerCount) ?? 0,
82
109
  senseCount: numberField(overview.senseCount) ?? 0,
110
+ entryPath: stringField(overview.entryPath) ?? "unknown",
111
+ mode: stringField(overview.mode) ?? "unknown",
83
112
  };
84
113
  const parsedSenses = senses.map((entry) => {
85
114
  if (!entry || typeof entry !== "object" || Array.isArray(entry))
@@ -120,6 +149,8 @@ function parseStatusPayload(data) {
120
149
  status,
121
150
  pid,
122
151
  restartCount,
152
+ lastExitCode: numberField(row.lastExitCode) ?? null,
153
+ lastSignal: stringField(row.lastSignal) ?? null,
123
154
  };
124
155
  });
125
156
  if (parsedSenses.some((row) => row === null) || parsedWorkers.some((row) => row === null))
@@ -143,7 +174,9 @@ function humanizeSenseName(sense, label) {
143
174
  }
144
175
  function formatTable(headers, rows) {
145
176
  const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => row[index].length)));
146
- const renderRow = (row) => `| ${row.map((cell, index) => cell.padEnd(widths[index])).join(" | ")} |`;
177
+ const renderRow = (row) => `| ${row.map((cell, index) => (index === row.length - 1
178
+ ? cell
179
+ : cell.padEnd(widths[index]))).join(" | ")} |`;
147
180
  const divider = `|-${widths.map((width) => "-".repeat(width)).join("-|-")}-|`;
148
181
  return [
149
182
  renderRow(headers),
@@ -158,6 +191,11 @@ function formatDaemonStatusOutput(response, fallback) {
158
191
  const overviewRows = [
159
192
  ["Daemon", payload.overview.daemon],
160
193
  ["Socket", payload.overview.socketPath],
194
+ ["Version", payload.overview.version],
195
+ ["Last Updated", payload.overview.lastUpdated],
196
+ ["Outlook", payload.overview.outlookUrl],
197
+ ["Entry Path", payload.overview.entryPath],
198
+ ["Mode", payload.overview.mode],
161
199
  ["Workers", String(payload.overview.workerCount)],
162
200
  ["Senses", String(payload.overview.senseCount)],
163
201
  ["Health", payload.overview.health],
@@ -169,13 +207,23 @@ function formatDaemonStatusOutput(response, fallback) {
169
207
  row.status,
170
208
  row.detail,
171
209
  ]);
172
- const workerRows = payload.workers.map((row) => [
173
- row.agent,
174
- row.worker,
175
- row.status,
176
- row.pid === null ? "n/a" : String(row.pid),
177
- String(row.restartCount),
178
- ]);
210
+ const workerRows = payload.workers.map((row) => {
211
+ /* v8 ignore start — exit info branches tested via daemon-crash-context; v8 misreports conditional chains @preserve */
212
+ let exitInfo = "n/a";
213
+ if (row.lastExitCode !== null)
214
+ exitInfo = `code=${row.lastExitCode}`;
215
+ if (row.lastSignal !== null)
216
+ exitInfo = row.lastExitCode !== null ? `code=${row.lastExitCode} sig=${row.lastSignal}` : `sig=${row.lastSignal}`;
217
+ /* v8 ignore stop */
218
+ return [
219
+ row.agent,
220
+ row.worker,
221
+ row.status,
222
+ row.pid === null ? "n/a" : String(row.pid),
223
+ String(row.restartCount),
224
+ exitInfo,
225
+ ];
226
+ });
179
227
  return [
180
228
  "Overview",
181
229
  formatTable(["Item", "Value"], overviewRows),
@@ -184,16 +232,41 @@ function formatDaemonStatusOutput(response, fallback) {
184
232
  formatTable(["Agent", "Sense", "Enabled", "State", "Detail"], senseRows),
185
233
  "",
186
234
  "Workers",
187
- formatTable(["Agent", "Worker", "State", "PID", "Restarts"], workerRows),
235
+ formatTable(["Agent", "Worker", "State", "PID", "Restarts", "Last Exit"], workerRows),
188
236
  ].join("\n");
189
237
  }
190
238
  async function ensureDaemonRunning(deps) {
191
239
  const alive = await deps.checkSocketAlive(deps.socketPath);
192
240
  if (alive) {
193
- return {
194
- alreadyRunning: true,
195
- message: `daemon already running (${deps.socketPath})`,
241
+ const localRuntime = (0, runtime_metadata_1.getRuntimeMetadata)();
242
+ let runningRuntimePromise = null;
243
+ const fetchRunningRuntimeMetadata = async () => {
244
+ runningRuntimePromise ??= (async () => {
245
+ const status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
246
+ const payload = parseStatusPayload(status.data);
247
+ return {
248
+ version: payload?.overview.version ?? "unknown",
249
+ lastUpdated: payload?.overview.lastUpdated ?? "unknown",
250
+ repoRoot: payload?.overview.repoRoot ?? "unknown",
251
+ configFingerprint: payload?.overview.configFingerprint ?? "unknown",
252
+ };
253
+ })();
254
+ return runningRuntimePromise;
196
255
  };
256
+ return (0, daemon_runtime_sync_1.ensureCurrentDaemonRuntime)({
257
+ socketPath: deps.socketPath,
258
+ localVersion: localRuntime.version,
259
+ localLastUpdated: localRuntime.lastUpdated,
260
+ localRepoRoot: localRuntime.repoRoot,
261
+ localConfigFingerprint: localRuntime.configFingerprint,
262
+ fetchRunningVersion: async () => (await fetchRunningRuntimeMetadata()).version,
263
+ fetchRunningRuntimeMetadata,
264
+ stopDaemon: async () => {
265
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
266
+ },
267
+ cleanupStaleSocket: deps.cleanupStaleSocket,
268
+ startDaemonProcess: deps.startDaemonProcess,
269
+ });
197
270
  }
198
271
  deps.cleanupStaleSocket(deps.socketPath);
199
272
  const started = await deps.startDaemonProcess(deps.socketPath);
@@ -202,17 +275,137 @@ async function ensureDaemonRunning(deps) {
202
275
  message: `daemon started (pid ${started.pid ?? "unknown"})`,
203
276
  };
204
277
  }
278
+ /**
279
+ * Extract `--agent <name>` from an args array, returning the agent name and
280
+ * the remaining args with the flag pair removed.
281
+ */
282
+ function extractAgentFlag(args) {
283
+ const idx = args.indexOf("--agent");
284
+ if (idx === -1 || idx + 1 >= args.length)
285
+ return { rest: args };
286
+ const agent = args[idx + 1];
287
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
288
+ return { agent, rest };
289
+ }
205
290
  function usage() {
206
291
  return [
207
292
  "Usage:",
208
293
  " ouro [up]",
209
- " ouro stop|status|logs|hatch",
294
+ " ouro dev [--repo-path <path>] [--clone [--clone-path <path>]]",
295
+ " ouro stop|down|status|logs|hatch",
296
+ " ouro outlook [--json]",
297
+ " ouro -v|--version",
298
+ " ouro config model --agent <name> <model-name>",
299
+ " ouro config models --agent <name>",
300
+ " ouro auth --agent <name> [--provider <provider>]",
301
+ " ouro auth verify --agent <name> [--provider <provider>]",
302
+ " ouro auth switch --agent <name> --provider <provider>",
210
303
  " ouro chat <agent>",
211
304
  " ouro msg --to <agent> [--session <id>] [--task <ref>] <message>",
212
305
  " ouro poke <agent> --task <task-id>",
306
+ " ouro poke <agent> --habit <name>",
307
+ " ouro habit list [--agent <name>]",
308
+ " ouro habit create [--agent <name>] <name> [--cadence <interval>]",
213
309
  " ouro link <agent> --friend <id> --provider <provider> --external-id <external-id>",
310
+ " ouro task board [<status>] [--agent <name>]",
311
+ " ouro task create <title> [--type <type>] [--agent <name>]",
312
+ " ouro task update <id> <status> [--agent <name>]",
313
+ " ouro task show <id> [--agent <name>]",
314
+ " ouro task fix [--safe|--all] [<id> [--option <N>]] [--agent <name>]",
315
+ " ouro task actionable|deps|sessions [--agent <name>]",
316
+ " ouro reminder create <title> --body <body> [--at <iso>] [--cadence <interval>] [--category <category>] [--agent <name>]",
317
+ " ouro friend list [--agent <name>]",
318
+ " ouro friend show <id> [--agent <name>]",
319
+ " ouro friend create --name <name> [--trust <level>] [--agent <name>]",
320
+ " ouro friend update <id> --trust <level> [--agent <name>]",
321
+ " ouro thoughts [--last <n>] [--json] [--follow] [--agent <name>]",
322
+ " ouro inner [--agent <name>]",
323
+ " ouro friend link <agent> --friend <id> --provider <p> --external-id <eid>",
324
+ " ouro friend unlink <agent> --friend <id> --provider <p> --external-id <eid>",
325
+ " ouro whoami [--agent <name>]",
326
+ " ouro session list [--agent <name>]",
327
+ " ouro mcp list",
328
+ " ouro mcp call <server> <tool> [--args '{...}']",
329
+ " ouro rollback [<version>]",
330
+ " ouro versions",
214
331
  ].join("\n");
215
332
  }
333
+ function formatVersionOutput() {
334
+ const version = (0, runtime_metadata_1.getRuntimeMetadata)().version;
335
+ const mode = (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)());
336
+ /* v8 ignore start — cosmetic display toggle; dev mode always true in test env */
337
+ return mode === "dev" ? `${version} (dev)` : version;
338
+ /* v8 ignore stop */
339
+ }
340
+ function buildStoppedStatusPayload(socketPath) {
341
+ const metadata = (0, runtime_metadata_1.getRuntimeMetadata)();
342
+ const repoRoot = (0, identity_1.getRepoRoot)();
343
+ return {
344
+ overview: {
345
+ daemon: "stopped",
346
+ health: "warn",
347
+ socketPath,
348
+ outlookUrl: "unavailable",
349
+ version: metadata.version,
350
+ lastUpdated: metadata.lastUpdated,
351
+ repoRoot: metadata.repoRoot,
352
+ configFingerprint: metadata.configFingerprint,
353
+ workerCount: 0,
354
+ senseCount: 0,
355
+ entryPath: path.join(repoRoot, "dist", "heart", "daemon", "daemon-entry.js"),
356
+ mode: (0, runtime_mode_1.detectRuntimeMode)(repoRoot),
357
+ },
358
+ senses: [],
359
+ workers: [],
360
+ };
361
+ }
362
+ function daemonUnavailableStatusOutput(socketPath, healthFilePath) {
363
+ /* v8 ignore start — tombstone read tested in daemon-status-tombstone.test; branch misreported @preserve */
364
+ const tombstone = (0, daemon_tombstone_1.readDaemonTombstone)();
365
+ const deathLine = tombstone
366
+ ? `Last death: ${tombstone.timestamp} -- ${tombstone.reason}: ${tombstone.message}`
367
+ : null;
368
+ /* v8 ignore stop */
369
+ const lines = [
370
+ formatDaemonStatusOutput({
371
+ ok: true,
372
+ summary: "daemon not running",
373
+ data: buildStoppedStatusPayload(socketPath),
374
+ }, "daemon not running"),
375
+ "",
376
+ ];
377
+ /* v8 ignore start — tombstone presence requires real daemon crash @preserve */
378
+ if (deathLine) {
379
+ lines.push(deathLine);
380
+ lines.push("");
381
+ /* v8 ignore stop */
382
+ }
383
+ // Read health file for last-known state (best-effort)
384
+ const resolvedHealthPath = healthFilePath ?? (0, daemon_health_1.getDefaultHealthPath)();
385
+ const health = (0, daemon_health_1.readHealth)(resolvedHealthPath);
386
+ if (health) {
387
+ lines.push(`Last known status: ${health.status} (pid ${health.pid}, uptime ${health.uptimeSeconds}s)`);
388
+ if (health.safeMode?.active) {
389
+ lines.push(`SAFE MODE: ${health.safeMode.reason}`);
390
+ }
391
+ if (health.degraded.length > 0) {
392
+ lines.push("");
393
+ lines.push("Degraded:");
394
+ for (const d of health.degraded) {
395
+ lines.push(` ${d.component}: ${d.reason} (since ${d.since})`);
396
+ }
397
+ }
398
+ lines.push("");
399
+ }
400
+ lines.push("daemon not running; run `ouro up`");
401
+ return lines.join("\n");
402
+ }
403
+ function isDaemonUnavailableError(error) {
404
+ const code = typeof error === "object" && error !== null && "code" in error
405
+ ? String(error.code ?? "")
406
+ : "";
407
+ return code === "ENOENT" || code === "ECONNREFUSED";
408
+ }
216
409
  function parseMessageCommand(args) {
217
410
  let to;
218
411
  let sessionId;
@@ -254,17 +447,56 @@ function parsePokeCommand(args) {
254
447
  if (!agent)
255
448
  throw new Error(`Usage\n${usage()}`);
256
449
  let taskId;
450
+ let habitName;
257
451
  for (let i = 1; i < args.length; i += 1) {
258
452
  if (args[i] === "--task") {
259
453
  taskId = args[i + 1];
260
454
  i += 1;
261
455
  }
456
+ if (args[i] === "--habit") {
457
+ habitName = args[i + 1];
458
+ i += 1;
459
+ }
262
460
  }
461
+ // --habit takes priority over --task
462
+ if (habitName)
463
+ return { kind: "habit.poke", agent, habitName };
263
464
  if (!taskId)
264
465
  throw new Error(`Usage\n${usage()}`);
265
466
  return { kind: "task.poke", agent, taskId };
266
467
  }
267
- function parseLinkCommand(args) {
468
+ function parseHabitCommand(args) {
469
+ const { agent, rest } = extractAgentFlag(args);
470
+ const sub = rest[0];
471
+ if (sub === "list") {
472
+ return { kind: "habit.list", ...(agent ? { agent } : {}) };
473
+ }
474
+ if (sub === "create") {
475
+ const nameArgs = rest.slice(1);
476
+ let name;
477
+ let cadence;
478
+ const positional = [];
479
+ for (let i = 0; i < nameArgs.length; i++) {
480
+ if (nameArgs[i] === "--cadence" && nameArgs[i + 1]) {
481
+ cadence = nameArgs[++i];
482
+ continue;
483
+ }
484
+ /* v8 ignore start -- defensive: --agent already extracted by extractAgentFlag; guard prevents regression if parsing flow changes @preserve */
485
+ if (nameArgs[i] === "--agent" && nameArgs[i + 1]) {
486
+ i++; // skip --agent value (already extracted)
487
+ continue;
488
+ }
489
+ /* v8 ignore stop */
490
+ positional.push(nameArgs[i]);
491
+ }
492
+ name = positional[0];
493
+ if (!name)
494
+ throw new Error(`Usage\n${usage()}`);
495
+ return { kind: "habit.create", name, ...(agent ? { agent } : {}), ...(cadence ? { cadence } : {}) };
496
+ }
497
+ throw new Error(`Usage\n${usage()}`);
498
+ }
499
+ function parseLinkCommand(args, kind = "friend.link") {
268
500
  const agent = args[0];
269
501
  if (!agent)
270
502
  throw new Error(`Usage\n${usage()}`);
@@ -296,7 +528,7 @@ function parseLinkCommand(args) {
296
528
  throw new Error(`Unknown identity provider '${providerRaw}'. Use aad|local|teams-conversation.`);
297
529
  }
298
530
  return {
299
- kind: "friend.link",
531
+ kind,
300
532
  agent,
301
533
  friendId,
302
534
  provider: providerRaw,
@@ -304,7 +536,102 @@ function parseLinkCommand(args) {
304
536
  };
305
537
  }
306
538
  function isAgentProvider(value) {
307
- return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex";
539
+ return value === "azure" || value === "anthropic" || value === "minimax" || value === "openai-codex" || value === "github-copilot";
540
+ }
541
+ /* v8 ignore start -- hasStoredCredentials: per-provider branches tested via auth switch tests @preserve */
542
+ function hasStoredCredentials(provider, providerSecrets) {
543
+ if (provider === "anthropic")
544
+ return !!providerSecrets.setupToken;
545
+ if (provider === "openai-codex")
546
+ return !!providerSecrets.oauthAccessToken;
547
+ if (provider === "github-copilot")
548
+ return !!providerSecrets.githubToken;
549
+ if (provider === "minimax")
550
+ return !!providerSecrets.apiKey;
551
+ // azure
552
+ return !!providerSecrets.endpoint && !!providerSecrets.apiKey;
553
+ }
554
+ /* v8 ignore stop */
555
+ /* v8 ignore start -- verifyProviderCredentials: delegates to pingProvider @preserve */
556
+ async function verifyProviderCredentials(provider, providers) {
557
+ const config = providers[provider];
558
+ if (!config)
559
+ return "not configured";
560
+ try {
561
+ const { pingProvider } = await Promise.resolve().then(() => __importStar(require("../../heart/provider-ping")));
562
+ const result = await pingProvider(provider, config);
563
+ return result.ok ? "ok" : `failed (${result.message})`;
564
+ }
565
+ catch (error) {
566
+ return `failed (${error instanceof Error ? error.message : String(error)})`;
567
+ }
568
+ }
569
+ async function listGithubCopilotModels(baseUrl, token, fetchImpl = fetch) {
570
+ const url = `${baseUrl.replace(/\/+$/, "")}/models`;
571
+ const response = await fetchImpl(url, {
572
+ headers: { Authorization: `Bearer ${token}` },
573
+ });
574
+ if (!response.ok) {
575
+ throw new Error(`model listing failed (HTTP ${response.status})`);
576
+ }
577
+ const body = await response.json();
578
+ /* v8 ignore start -- response shape handling: tested via config-models.test.ts @preserve */
579
+ const items = Array.isArray(body) ? body : (body?.data ?? []);
580
+ return items.map((item) => {
581
+ const rec = item;
582
+ const capabilities = Array.isArray(rec.capabilities)
583
+ ? rec.capabilities.filter((c) => typeof c === "string")
584
+ : undefined;
585
+ return {
586
+ id: String(rec.id ?? rec.name ?? ""),
587
+ name: String(rec.name ?? rec.id ?? ""),
588
+ ...(capabilities ? { capabilities } : {}),
589
+ };
590
+ });
591
+ /* v8 ignore stop */
592
+ }
593
+ async function pingGithubCopilotModel(baseUrl, token, model, fetchImpl = fetch) {
594
+ const base = baseUrl.replace(/\/+$/, "");
595
+ const isClaude = model.startsWith("claude");
596
+ const url = isClaude ? `${base}/chat/completions` : `${base}/responses`;
597
+ const body = isClaude
598
+ ? JSON.stringify({ model, messages: [{ role: "user", content: "ping" }], max_tokens: 1 })
599
+ : JSON.stringify({ model, input: "ping", max_output_tokens: 16 });
600
+ try {
601
+ const response = await fetchImpl(url, {
602
+ method: "POST",
603
+ headers: {
604
+ Authorization: `Bearer ${token}`,
605
+ "Content-Type": "application/json",
606
+ },
607
+ body,
608
+ });
609
+ if (response.ok)
610
+ return { ok: true };
611
+ let detail = `HTTP ${response.status}`;
612
+ try {
613
+ const json = await response.json();
614
+ /* v8 ignore start -- error format parsing: all branches tested via config-models.test.ts @preserve */
615
+ if (typeof json.error === "string")
616
+ detail = json.error;
617
+ else if (typeof json.error === "object" && json.error !== null) {
618
+ const errObj = json.error;
619
+ if (typeof errObj.message === "string")
620
+ detail = errObj.message;
621
+ }
622
+ else if (typeof json.message === "string")
623
+ detail = json.message;
624
+ /* v8 ignore stop */
625
+ }
626
+ catch {
627
+ // response body not JSON — keep HTTP status
628
+ }
629
+ return { ok: false, error: detail };
630
+ }
631
+ catch (err) {
632
+ /* v8 ignore next -- defensive: fetch errors are always Error instances @preserve */
633
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
634
+ }
308
635
  }
309
636
  function parseHatchCommand(args) {
310
637
  let agentName;
@@ -361,7 +688,7 @@ function parseHatchCommand(args) {
361
688
  }
362
689
  }
363
690
  if (providerRaw && !isAgentProvider(providerRaw)) {
364
- throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex.");
691
+ throw new Error("Unknown provider. Use azure|anthropic|minimax|openai-codex|github-copilot.");
365
692
  }
366
693
  const provider = providerRaw && isAgentProvider(providerRaw) ? providerRaw : undefined;
367
694
  return {
@@ -373,20 +700,480 @@ function parseHatchCommand(args) {
373
700
  migrationPath,
374
701
  };
375
702
  }
703
+ function parseTaskCommand(args) {
704
+ const { agent, rest: cleaned } = extractAgentFlag(args);
705
+ const [sub, ...rest] = cleaned;
706
+ if (!sub)
707
+ throw new Error(`Usage\n${usage()}`);
708
+ if (sub === "board") {
709
+ const status = rest[0];
710
+ return status
711
+ ? { kind: "task.board", status, ...(agent ? { agent } : {}) }
712
+ : { kind: "task.board", ...(agent ? { agent } : {}) };
713
+ }
714
+ if (sub === "create") {
715
+ const title = rest[0];
716
+ if (!title)
717
+ throw new Error(`Usage\n${usage()}`);
718
+ let type;
719
+ for (let i = 1; i < rest.length; i++) {
720
+ if (rest[i] === "--type" && rest[i + 1]) {
721
+ type = rest[i + 1];
722
+ i += 1;
723
+ }
724
+ }
725
+ return type
726
+ ? { kind: "task.create", title, type, ...(agent ? { agent } : {}) }
727
+ : { kind: "task.create", title, ...(agent ? { agent } : {}) };
728
+ }
729
+ if (sub === "update") {
730
+ const id = rest[0];
731
+ const status = rest[1];
732
+ if (!id || !status)
733
+ throw new Error(`Usage\n${usage()}`);
734
+ return { kind: "task.update", id, status, ...(agent ? { agent } : {}) };
735
+ }
736
+ if (sub === "show") {
737
+ const id = rest[0];
738
+ if (!id)
739
+ throw new Error(`Usage\n${usage()}`);
740
+ return { kind: "task.show", id, ...(agent ? { agent } : {}) };
741
+ }
742
+ if (sub === "actionable")
743
+ return { kind: "task.actionable", ...(agent ? { agent } : {}) };
744
+ if (sub === "deps")
745
+ return { kind: "task.deps", ...(agent ? { agent } : {}) };
746
+ if (sub === "sessions")
747
+ return { kind: "task.sessions", ...(agent ? { agent } : {}) };
748
+ if (sub === "fix") {
749
+ // fix --safe | fix --all | fix <id> [--option N] | fix (dry-run)
750
+ if (rest.length === 0)
751
+ return { kind: "task.fix", mode: "dry-run", ...(agent ? { agent } : {}) };
752
+ const first = rest[0];
753
+ if (first === "--safe" || first === "--all") {
754
+ return { kind: "task.fix", mode: "safe", ...(agent ? { agent } : {}) };
755
+ }
756
+ // first arg is an issue ID (contains a colon, e.g. schema-missing-kind:one-shots/foo.md)
757
+ const issueId = first;
758
+ let option;
759
+ for (let i = 1; i < rest.length; i++) {
760
+ if (rest[i] === "--option" && rest[i + 1]) {
761
+ option = parseInt(rest[i + 1], 10);
762
+ i += 1;
763
+ }
764
+ }
765
+ return {
766
+ kind: "task.fix",
767
+ mode: "single",
768
+ issueId,
769
+ ...(option !== undefined ? { option } : {}),
770
+ ...(agent ? { agent } : {}),
771
+ };
772
+ }
773
+ throw new Error(`Usage\n${usage()}`);
774
+ }
775
+ function extractFacingFlag(args) {
776
+ const idx = args.indexOf("--facing");
777
+ if (idx === -1 || idx + 1 >= args.length)
778
+ return { rest: args };
779
+ const value = args[idx + 1];
780
+ if (value !== "human" && value !== "agent") {
781
+ throw new Error(`--facing must be 'human' or 'agent'`);
782
+ }
783
+ const rest = [...args.slice(0, idx), ...args.slice(idx + 2)];
784
+ return { facing: value, rest };
785
+ }
786
+ function parseAuthCommand(args) {
787
+ const first = args[0];
788
+ // Support both positional (`auth switch`) and flag (`auth --switch`) forms
789
+ if (first === "verify" || first === "switch" || first === "--verify" || first === "--switch") {
790
+ const subcommand = first.replace(/^--/, "");
791
+ const { agent, rest: afterAgent } = extractAgentFlag(args.slice(1));
792
+ const { facing, rest } = extractFacingFlag(afterAgent);
793
+ let provider;
794
+ /* v8 ignore start -- provider flag parsing: branches tested via CLI parsing tests @preserve */
795
+ for (let i = 0; i < rest.length; i += 1) {
796
+ if (rest[i] === "--provider") {
797
+ const value = rest[i + 1];
798
+ if (!isAgentProvider(value))
799
+ throw new Error(`Usage\n${usage()}`);
800
+ provider = value;
801
+ i += 1;
802
+ continue;
803
+ }
804
+ }
805
+ /* v8 ignore stop */
806
+ /* v8 ignore next -- defensive: agent always provided in tests @preserve */
807
+ if (!agent)
808
+ throw new Error(`Usage\n${usage()}`);
809
+ if (subcommand === "switch") {
810
+ if (!provider)
811
+ throw new Error(`auth switch requires --provider.\n${usage()}`);
812
+ return facing ? { kind: "auth.switch", agent, provider, facing } : { kind: "auth.switch", agent, provider };
813
+ }
814
+ return provider ? { kind: "auth.verify", agent, provider } : { kind: "auth.verify", agent };
815
+ }
816
+ const { agent, rest } = extractAgentFlag(args);
817
+ let provider;
818
+ for (let i = 0; i < rest.length; i += 1) {
819
+ if (rest[i] === "--provider") {
820
+ const value = rest[i + 1];
821
+ if (!isAgentProvider(value))
822
+ throw new Error(`Usage\n${usage()}`);
823
+ provider = value;
824
+ i += 1;
825
+ continue;
826
+ }
827
+ }
828
+ if (!agent) {
829
+ throw new Error([
830
+ "Usage:",
831
+ " ouro auth --agent <name> [--provider <provider>] Set up credentials",
832
+ " ouro auth verify --agent <name> [--provider <p>] Verify credentials work",
833
+ " ouro auth switch --agent <name> --provider <p> Switch active provider",
834
+ ].join("\n"));
835
+ }
836
+ return provider ? { kind: "auth.run", agent, provider } : { kind: "auth.run", agent };
837
+ }
838
+ function parseReminderCommand(args) {
839
+ const { agent, rest: cleaned } = extractAgentFlag(args);
840
+ const [sub, ...rest] = cleaned;
841
+ if (!sub)
842
+ throw new Error(`Usage\n${usage()}`);
843
+ if (sub === "create") {
844
+ const title = rest[0];
845
+ if (!title)
846
+ throw new Error(`Usage\n${usage()}`);
847
+ let body;
848
+ let scheduledAt;
849
+ let cadence;
850
+ let category;
851
+ let requester;
852
+ for (let i = 1; i < rest.length; i++) {
853
+ if (rest[i] === "--body" && rest[i + 1]) {
854
+ body = rest[i + 1];
855
+ i += 1;
856
+ }
857
+ else if (rest[i] === "--at" && rest[i + 1]) {
858
+ scheduledAt = rest[i + 1];
859
+ i += 1;
860
+ }
861
+ else if (rest[i] === "--cadence" && rest[i + 1]) {
862
+ cadence = rest[i + 1];
863
+ i += 1;
864
+ }
865
+ else if (rest[i] === "--category" && rest[i + 1]) {
866
+ category = rest[i + 1];
867
+ i += 1;
868
+ }
869
+ else if (rest[i] === "--requester" && rest[i + 1]) {
870
+ requester = rest[i + 1];
871
+ i += 1;
872
+ }
873
+ }
874
+ if (!body)
875
+ throw new Error(`Usage\n${usage()}`);
876
+ if (!scheduledAt && !cadence)
877
+ throw new Error(`Usage\n${usage()}`);
878
+ return {
879
+ kind: "reminder.create",
880
+ title,
881
+ body,
882
+ ...(scheduledAt ? { scheduledAt } : {}),
883
+ ...(cadence ? { cadence } : {}),
884
+ ...(category ? { category } : {}),
885
+ ...(requester ? { requester } : {}),
886
+ ...(agent ? { agent } : {}),
887
+ };
888
+ }
889
+ throw new Error(`Usage\n${usage()}`);
890
+ }
891
+ function parseSessionCommand(args) {
892
+ const { agent, rest: cleaned } = extractAgentFlag(args);
893
+ const [sub] = cleaned;
894
+ if (!sub)
895
+ throw new Error(`Usage\n${usage()}`);
896
+ if (sub === "list")
897
+ return { kind: "session.list", ...(agent ? { agent } : {}) };
898
+ throw new Error(`Usage\n${usage()}`);
899
+ }
900
+ function parseAttentionCommand(args) {
901
+ const { agent, rest: cleaned } = extractAgentFlag(args);
902
+ const sub = cleaned[0];
903
+ if (sub === "show" && cleaned[1]) {
904
+ return { kind: "attention.show", id: cleaned[1], ...(agent ? { agent } : {}) };
905
+ }
906
+ if (sub === "history") {
907
+ return { kind: "attention.history", ...(agent ? { agent } : {}) };
908
+ }
909
+ return { kind: "attention.list", ...(agent ? { agent } : {}) };
910
+ }
911
+ function parseThoughtsCommand(args) {
912
+ const { agent, rest: cleaned } = extractAgentFlag(args);
913
+ let last;
914
+ let json = false;
915
+ let follow = false;
916
+ for (let i = 0; i < cleaned.length; i++) {
917
+ if (cleaned[i] === "--last" && i + 1 < cleaned.length) {
918
+ last = Number.parseInt(cleaned[i + 1], 10);
919
+ i++;
920
+ }
921
+ if (cleaned[i] === "--json")
922
+ json = true;
923
+ if (cleaned[i] === "--follow" || cleaned[i] === "-f")
924
+ follow = true;
925
+ }
926
+ return { kind: "thoughts", ...(agent ? { agent } : {}), ...(last ? { last } : {}), ...(json ? { json } : {}), ...(follow ? { follow } : {}) };
927
+ }
928
+ function parseFriendCommand(args) {
929
+ const { agent, rest: cleaned } = extractAgentFlag(args);
930
+ const [sub, ...rest] = cleaned;
931
+ if (!sub)
932
+ throw new Error(`Usage\n${usage()}`);
933
+ if (sub === "list")
934
+ return { kind: "friend.list", ...(agent ? { agent } : {}) };
935
+ if (sub === "show") {
936
+ const friendId = rest[0];
937
+ if (!friendId)
938
+ throw new Error(`Usage\n${usage()}`);
939
+ return { kind: "friend.show", friendId, ...(agent ? { agent } : {}) };
940
+ }
941
+ if (sub === "create") {
942
+ let name;
943
+ let trustLevel;
944
+ for (let i = 0; i < rest.length; i++) {
945
+ if (rest[i] === "--name" && rest[i + 1]) {
946
+ name = rest[i + 1];
947
+ i += 1;
948
+ }
949
+ else if (rest[i] === "--trust" && rest[i + 1]) {
950
+ trustLevel = rest[i + 1];
951
+ i += 1;
952
+ }
953
+ }
954
+ if (!name)
955
+ throw new Error(`Usage\n${usage()}`);
956
+ return {
957
+ kind: "friend.create",
958
+ name,
959
+ ...(trustLevel ? { trustLevel } : {}),
960
+ ...(agent ? { agent } : {}),
961
+ };
962
+ }
963
+ if (sub === "update") {
964
+ const friendId = rest[0];
965
+ if (!friendId)
966
+ throw new Error(`Usage: ouro friend update <id> --trust <level>`);
967
+ let trustLevel;
968
+ /* v8 ignore start -- flag parsing loop: tested via CLI parsing tests @preserve */
969
+ for (let i = 1; i < rest.length; i++) {
970
+ if (rest[i] === "--trust" && rest[i + 1]) {
971
+ trustLevel = rest[i + 1];
972
+ i += 1;
973
+ }
974
+ }
975
+ /* v8 ignore stop */
976
+ const VALID_TRUST_LEVELS = new Set(["stranger", "acquaintance", "friend", "family"]);
977
+ if (!trustLevel || !VALID_TRUST_LEVELS.has(trustLevel)) {
978
+ throw new Error(`Usage: ouro friend update <id> --trust <stranger|acquaintance|friend|family>`);
979
+ }
980
+ return {
981
+ kind: "friend.update",
982
+ friendId,
983
+ trustLevel: trustLevel,
984
+ ...(agent ? { agent } : {}),
985
+ };
986
+ }
987
+ if (sub === "link")
988
+ return parseLinkCommand(rest, "friend.link");
989
+ if (sub === "unlink")
990
+ return parseLinkCommand(rest, "friend.unlink");
991
+ throw new Error(`Usage\n${usage()}`);
992
+ }
993
+ function parseConfigCommand(args) {
994
+ const { agent, rest: afterAgent } = extractAgentFlag(args);
995
+ const { facing, rest: cleaned } = extractFacingFlag(afterAgent);
996
+ const [sub, ...rest] = cleaned;
997
+ if (!sub)
998
+ throw new Error(`Usage\n${usage()}`);
999
+ if (sub === "model") {
1000
+ if (!agent)
1001
+ throw new Error("--agent is required for config model");
1002
+ const modelName = rest[0];
1003
+ if (!modelName)
1004
+ throw new Error(`Usage: ouro config model --agent <name> <model-name>`);
1005
+ return facing ? { kind: "config.model", agent, modelName, facing } : { kind: "config.model", agent, modelName };
1006
+ }
1007
+ if (sub === "models") {
1008
+ if (!agent)
1009
+ throw new Error("--agent is required for config models");
1010
+ return { kind: "config.models", agent };
1011
+ }
1012
+ throw new Error(`Usage\n${usage()}`);
1013
+ }
1014
+ function parseMcpCommand(args) {
1015
+ const [sub, ...rest] = args;
1016
+ if (!sub)
1017
+ throw new Error(`Usage\n${usage()}`);
1018
+ if (sub === "list")
1019
+ return { kind: "mcp.list" };
1020
+ if (sub === "call") {
1021
+ const server = rest[0];
1022
+ const tool = rest[1];
1023
+ if (!server || !tool)
1024
+ throw new Error(`Usage\n${usage()}`);
1025
+ const argsIdx = rest.indexOf("--args");
1026
+ const mcpArgs = argsIdx !== -1 && rest[argsIdx + 1] ? rest[argsIdx + 1] : undefined;
1027
+ return { kind: "mcp.call", server, tool, ...(mcpArgs ? { args: mcpArgs } : {}) };
1028
+ }
1029
+ throw new Error(`Usage\n${usage()}`);
1030
+ }
1031
+ function parseMcpServeCommand(args) {
1032
+ let agent;
1033
+ let friendId;
1034
+ let socketOverride;
1035
+ for (let i = 0; i < args.length; i++) {
1036
+ if (args[i] === "--agent" && args[i + 1]) {
1037
+ agent = args[++i];
1038
+ continue;
1039
+ }
1040
+ if (args[i] === "--friend" && args[i + 1]) {
1041
+ friendId = args[++i];
1042
+ continue;
1043
+ }
1044
+ if (args[i] === "--socket" && args[i + 1]) {
1045
+ socketOverride = args[++i];
1046
+ continue;
1047
+ }
1048
+ }
1049
+ if (!agent)
1050
+ throw new Error("mcp-serve requires --agent <name>");
1051
+ return { kind: "mcp-serve", agent, ...(friendId ? { friendId } : {}), ...(socketOverride ? { socketOverride } : {}) };
1052
+ }
1053
+ function parseSetupCommand(args) {
1054
+ let tool;
1055
+ let agent;
1056
+ for (let i = 0; i < args.length; i++) {
1057
+ if (args[i] === "--tool" && args[i + 1]) {
1058
+ tool = args[++i];
1059
+ continue;
1060
+ }
1061
+ if (args[i] === "--agent" && args[i + 1]) {
1062
+ agent = args[++i];
1063
+ continue;
1064
+ }
1065
+ }
1066
+ if (!tool)
1067
+ throw new Error("setup requires --tool (claude-code | codex)");
1068
+ if (tool !== "claude-code" && tool !== "codex")
1069
+ throw new Error(`Unknown tool: ${tool}. Supported: claude-code, codex`);
1070
+ if (!agent)
1071
+ throw new Error("setup requires --agent <name>");
1072
+ return { kind: "setup", tool, agent };
1073
+ }
376
1074
  function parseOuroCommand(args) {
377
1075
  const [head, second] = args;
378
1076
  if (!head)
379
1077
  return { kind: "daemon.up" };
1078
+ if (head === "--agent" && second) {
1079
+ return parseOuroCommand(args.slice(2));
1080
+ }
1081
+ if (head === "hook") {
1082
+ const hookArgs = args.slice(1);
1083
+ let event;
1084
+ let hookAgent;
1085
+ for (let i = 0; i < hookArgs.length; i++) {
1086
+ if (hookArgs[i] === "--agent" && hookArgs[i + 1]) {
1087
+ hookAgent = hookArgs[++i];
1088
+ continue;
1089
+ }
1090
+ /* v8 ignore start -- false branch: extra positional args after event are ignored */
1091
+ if (!event) {
1092
+ event = hookArgs[i];
1093
+ }
1094
+ /* v8 ignore stop */
1095
+ }
1096
+ if (!event)
1097
+ throw new Error("hook requires an event name (session-start, stop, post-tool-use)");
1098
+ if (!hookAgent)
1099
+ throw new Error("hook requires --agent <name>");
1100
+ return { kind: "hook", event, agent: hookAgent };
1101
+ }
380
1102
  if (head === "up")
381
1103
  return { kind: "daemon.up" };
382
- if (head === "stop")
1104
+ if (head === "dev") {
1105
+ const devArgs = args.slice(1);
1106
+ let repoPath;
1107
+ let clone = false;
1108
+ let clonePath;
1109
+ for (let i = 0; i < devArgs.length; i++) {
1110
+ if (devArgs[i] === "--repo-path" && devArgs[i + 1]) {
1111
+ repoPath = devArgs[++i];
1112
+ continue;
1113
+ }
1114
+ if (devArgs[i] === "--clone") {
1115
+ clone = true;
1116
+ continue;
1117
+ }
1118
+ if (devArgs[i] === "--clone-path" && devArgs[i + 1]) {
1119
+ clonePath = devArgs[++i];
1120
+ continue;
1121
+ }
1122
+ }
1123
+ return { kind: "daemon.dev", repoPath, clone, clonePath };
1124
+ }
1125
+ if (head === "rollback")
1126
+ return { kind: "rollback", ...(second ? { version: second } : {}) };
1127
+ if (head === "versions")
1128
+ return { kind: "versions" };
1129
+ if (head === "stop" || head === "down")
383
1130
  return { kind: "daemon.stop" };
384
1131
  if (head === "status")
385
1132
  return { kind: "daemon.status" };
386
1133
  if (head === "logs")
387
1134
  return { kind: "daemon.logs" };
1135
+ if (head === "outlook")
1136
+ return { kind: "outlook", ...(args.includes("--json") ? { json: true } : {}) };
388
1137
  if (head === "hatch")
389
1138
  return parseHatchCommand(args.slice(1));
1139
+ if (head === "auth")
1140
+ return parseAuthCommand(args.slice(1));
1141
+ if (head === "task")
1142
+ return parseTaskCommand(args.slice(1));
1143
+ if (head === "reminder")
1144
+ return parseReminderCommand(args.slice(1));
1145
+ if (head === "habit")
1146
+ return parseHabitCommand(args.slice(1));
1147
+ if (head === "friend")
1148
+ return parseFriendCommand(args.slice(1));
1149
+ if (head === "config")
1150
+ return parseConfigCommand(args.slice(1));
1151
+ if (head === "mcp")
1152
+ return parseMcpCommand(args.slice(1));
1153
+ if (head === "whoami") {
1154
+ const { agent } = extractAgentFlag(args.slice(1));
1155
+ return { kind: "whoami", ...(agent ? { agent } : {}) };
1156
+ }
1157
+ if (head === "session")
1158
+ return parseSessionCommand(args.slice(1));
1159
+ if (head === "changelog") {
1160
+ const sliced = args.slice(1);
1161
+ const { agent, rest: remaining } = extractAgentFlag(sliced);
1162
+ let from;
1163
+ const fromIdx = remaining.indexOf("--from");
1164
+ if (fromIdx !== -1 && remaining[fromIdx + 1]) {
1165
+ from = remaining[fromIdx + 1];
1166
+ }
1167
+ return { kind: "changelog", ...(from ? { from } : {}), ...(agent ? { agent } : {}) };
1168
+ }
1169
+ if (head === "thoughts")
1170
+ return parseThoughtsCommand(args.slice(1));
1171
+ if (head === "attention")
1172
+ return parseAttentionCommand(args.slice(1));
1173
+ if (head === "inner") {
1174
+ const { agent } = extractAgentFlag(args.slice(1));
1175
+ return { kind: "inner.status", ...(agent ? { agent } : {}) };
1176
+ }
390
1177
  if (head === "chat") {
391
1178
  if (!second)
392
1179
  throw new Error(`Usage\n${usage()}`);
@@ -398,92 +1185,56 @@ function parseOuroCommand(args) {
398
1185
  return parsePokeCommand(args.slice(1));
399
1186
  if (head === "link")
400
1187
  return parseLinkCommand(args.slice(1));
1188
+ if (head === "mcp-serve")
1189
+ return parseMcpServeCommand(args.slice(1));
1190
+ if (head === "setup")
1191
+ return parseSetupCommand(args.slice(1));
401
1192
  throw new Error(`Unknown command '${args.join(" ")}'.\n${usage()}`);
402
1193
  }
403
- function defaultSendCommand(socketPath, command) {
404
- return new Promise((resolve, reject) => {
405
- const client = net.createConnection(socketPath);
406
- let raw = "";
407
- client.on("connect", () => {
408
- client.write(JSON.stringify(command));
409
- client.end();
410
- });
411
- client.on("data", (chunk) => {
412
- raw += chunk.toString("utf-8");
413
- });
414
- client.on("error", reject);
415
- client.on("end", () => {
416
- const trimmed = raw.trim();
417
- if (trimmed.length === 0 && command.kind === "daemon.stop") {
418
- resolve({ ok: true, message: "daemon stopped" });
419
- return;
420
- }
421
- if (trimmed.length === 0) {
422
- reject(new Error("Daemon returned empty response."));
423
- return;
424
- }
425
- try {
426
- const parsed = JSON.parse(trimmed);
427
- resolve(parsed);
428
- }
429
- catch (error) {
430
- reject(error);
431
- }
432
- });
433
- });
434
- }
435
1194
  function defaultStartDaemonProcess(socketPath) {
436
1195
  const entry = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
1196
+ // Redirect stdio to /dev/null via file descriptors — using 'ignore' causes EPIPE
1197
+ // when the daemon's logging system writes to stderr after the parent exits.
1198
+ const outFd = fs.openSync(os.devNull, "w");
1199
+ const errFd = fs.openSync(os.devNull, "w");
437
1200
  const child = (0, child_process_1.spawn)("node", [entry, "--socket", socketPath], {
438
1201
  detached: true,
439
- stdio: "ignore",
1202
+ stdio: ["ignore", outFd, errFd],
440
1203
  });
441
1204
  child.unref();
1205
+ // Don't close fds — the child process needs them. They'll be cleaned up when the parent exits.
442
1206
  return Promise.resolve({ pid: child.pid ?? null });
443
1207
  }
444
1208
  function defaultWriteStdout(text) {
445
1209
  // eslint-disable-next-line no-console -- terminal UX: CLI command output
446
1210
  console.log(text);
447
1211
  }
448
- function defaultCheckSocketAlive(socketPath) {
449
- return new Promise((resolve) => {
450
- const client = net.createConnection(socketPath);
451
- let raw = "";
452
- let done = false;
453
- const finalize = (alive) => {
454
- if (done)
455
- return;
456
- done = true;
457
- resolve(alive);
458
- };
459
- if ("setTimeout" in client && typeof client.setTimeout === "function") {
460
- client.setTimeout(800, () => {
461
- client.destroy();
462
- finalize(false);
463
- });
1212
+ /**
1213
+ * Read the runtimeVersion from the first .ouro bundle's bundle-meta.json.
1214
+ * Returns undefined if none found or unreadable.
1215
+ */
1216
+ function readFirstBundleMetaVersion(bundlesRoot) {
1217
+ try {
1218
+ if (!fs.existsSync(bundlesRoot))
1219
+ return undefined;
1220
+ const entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
1221
+ for (const entry of entries) {
1222
+ /* v8 ignore next -- skip non-.ouro dirs: tested via version-detect tests @preserve */
1223
+ if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
1224
+ continue;
1225
+ const metaPath = path.join(bundlesRoot, entry.name, "bundle-meta.json");
1226
+ if (!fs.existsSync(metaPath))
1227
+ continue;
1228
+ const raw = fs.readFileSync(metaPath, "utf-8");
1229
+ const meta = JSON.parse(raw);
1230
+ if (meta.runtimeVersion)
1231
+ return meta.runtimeVersion;
464
1232
  }
465
- client.on("connect", () => {
466
- client.write(JSON.stringify({ kind: "daemon.status" }));
467
- client.end();
468
- });
469
- client.on("data", (chunk) => {
470
- raw += chunk.toString("utf-8");
471
- });
472
- client.on("error", () => finalize(false));
473
- client.on("end", () => {
474
- if (raw.trim().length === 0) {
475
- finalize(false);
476
- return;
477
- }
478
- try {
479
- JSON.parse(raw);
480
- finalize(true);
481
- }
482
- catch {
483
- finalize(false);
484
- }
485
- });
486
- });
1233
+ }
1234
+ catch {
1235
+ // Best effort — return undefined on any error
1236
+ }
1237
+ return undefined;
487
1238
  }
488
1239
  function defaultCleanupStaleSocket(socketPath) {
489
1240
  if (fs.existsSync(socketPath)) {
@@ -519,9 +1270,38 @@ function defaultFallbackPendingMessage(command) {
519
1270
  });
520
1271
  return pendingPath;
521
1272
  }
522
- async function defaultInstallSubagents() {
523
- return (0, subagent_installer_1.installSubagentsForAvailableCli)({
524
- repoRoot: (0, identity_1.getRepoRoot)(),
1273
+ function defaultEnsureDaemonBootPersistence(socketPath) {
1274
+ if (process.platform !== "darwin") {
1275
+ return;
1276
+ }
1277
+ const homeDir = os.homedir();
1278
+ const launchdDeps = {
1279
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd, { stdio: "ignore" }); },
1280
+ writeFile: (filePath, content) => fs.writeFileSync(filePath, content, "utf-8"),
1281
+ removeFile: (filePath) => fs.rmSync(filePath, { force: true }),
1282
+ existsFile: (filePath) => fs.existsSync(filePath),
1283
+ mkdirp: (dir) => fs.mkdirSync(dir, { recursive: true }),
1284
+ homeDir,
1285
+ userUid: process.getuid?.() ?? 0,
1286
+ };
1287
+ const entryPath = path.join((0, identity_1.getRepoRoot)(), "dist", "heart", "daemon", "daemon-entry.js");
1288
+ /* v8 ignore next -- covered via mock in daemon-cli-defaults.test.ts; v8 on CI attributes the real fs.existsSync branch to the non-mock load @preserve */
1289
+ if (!fs.existsSync(entryPath)) {
1290
+ (0, runtime_1.emitNervesEvent)({
1291
+ level: "warn",
1292
+ component: "daemon",
1293
+ event: "daemon.entry_path_missing",
1294
+ message: "entryPath does not exist on disk — plist may point to a stale location. Run 'ouro daemon install' from the correct location.",
1295
+ meta: { entryPath },
1296
+ });
1297
+ }
1298
+ const logDir = (0, identity_1.getAgentDaemonLogsDir)();
1299
+ (0, launchd_1.installLaunchAgent)(launchdDeps, {
1300
+ nodePath: process.execPath,
1301
+ entryPath,
1302
+ socketPath,
1303
+ logDir,
1304
+ envPath: process.env.PATH,
525
1305
  });
526
1306
  }
527
1307
  async function defaultPromptInput(question) {
@@ -539,62 +1319,11 @@ async function defaultPromptInput(question) {
539
1319
  }
540
1320
  }
541
1321
  function defaultListDiscoveredAgents() {
542
- const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
543
- let entries;
544
- try {
545
- entries = fs.readdirSync(bundlesRoot, { withFileTypes: true });
546
- }
547
- catch {
548
- return [];
549
- }
550
- const discovered = [];
551
- for (const entry of entries) {
552
- if (!entry.isDirectory() || !entry.name.endsWith(".ouro"))
553
- continue;
554
- const agentName = entry.name.slice(0, -5);
555
- const configPath = path.join(bundlesRoot, entry.name, "agent.json");
556
- let enabled = true;
557
- try {
558
- const raw = fs.readFileSync(configPath, "utf-8");
559
- const parsed = JSON.parse(raw);
560
- if (typeof parsed.enabled === "boolean") {
561
- enabled = parsed.enabled;
562
- }
563
- }
564
- catch {
565
- continue;
566
- }
567
- if (enabled) {
568
- discovered.push(agentName);
569
- }
570
- }
571
- return discovered.sort((left, right) => left.localeCompare(right));
572
- }
573
- async function defaultLinkFriendIdentity(command) {
574
- const fp = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`, "friends");
575
- const friendStore = new store_file_1.FileFriendStore(fp);
576
- const current = await friendStore.get(command.friendId);
577
- if (!current) {
578
- return `friend not found: ${command.friendId}`;
579
- }
580
- const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
581
- if (alreadyLinked) {
582
- return `identity already linked: ${command.provider}:${command.externalId}`;
583
- }
584
- const now = new Date().toISOString();
585
- await friendStore.put(command.friendId, {
586
- ...current,
587
- externalIds: [
588
- ...current.externalIds,
589
- {
590
- provider: command.provider,
591
- externalId: command.externalId,
592
- linkedAt: now,
593
- },
594
- ],
595
- updatedAt: now,
1322
+ return (0, agent_discovery_1.listEnabledBundleAgents)({
1323
+ bundlesRoot: (0, identity_1.getAgentBundlesRoot)(),
1324
+ readdirSync: fs.readdirSync,
1325
+ readFileSync: fs.readFileSync,
596
1326
  });
597
- return `linked ${command.provider}:${command.externalId} to ${command.friendId}`;
598
1327
  }
599
1328
  function discoverExistingCredentials(secretsRoot) {
600
1329
  const found = [];
@@ -627,16 +1356,16 @@ function discoverExistingCredentials(secretsRoot) {
627
1356
  continue;
628
1357
  for (const [provName, provConfig] of Object.entries(parsed.providers)) {
629
1358
  if (provName === "anthropic" && provConfig.setupToken) {
630
- found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken } });
1359
+ found.push({ agentName: entry.name, provider: "anthropic", credentials: { setupToken: provConfig.setupToken }, providerConfig: { ...provConfig } });
631
1360
  }
632
1361
  else if (provName === "openai-codex" && provConfig.oauthAccessToken) {
633
- found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken } });
1362
+ found.push({ agentName: entry.name, provider: "openai-codex", credentials: { oauthAccessToken: provConfig.oauthAccessToken }, providerConfig: { ...provConfig } });
634
1363
  }
635
1364
  else if (provName === "minimax" && provConfig.apiKey) {
636
- found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey } });
1365
+ found.push({ agentName: entry.name, provider: "minimax", credentials: { apiKey: provConfig.apiKey }, providerConfig: { ...provConfig } });
637
1366
  }
638
1367
  else if (provName === "azure" && provConfig.apiKey && provConfig.endpoint && provConfig.deployment) {
639
- found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment } });
1368
+ found.push({ agentName: entry.name, provider: "azure", credentials: { apiKey: provConfig.apiKey, endpoint: provConfig.endpoint, deployment: provConfig.deployment }, providerConfig: { ...provConfig } });
640
1369
  }
641
1370
  }
642
1371
  }
@@ -654,7 +1383,7 @@ function discoverExistingCredentials(secretsRoot) {
654
1383
  async function defaultRunAdoptionSpecialist() {
655
1384
  const { runCliSession } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
656
1385
  const { patchRuntimeConfig } = await Promise.resolve().then(() => __importStar(require("../config")));
657
- const { setAgentName } = await Promise.resolve().then(() => __importStar(require("../identity")));
1386
+ const { setAgentName, setAgentConfigOverride } = await Promise.resolve().then(() => __importStar(require("../identity")));
658
1387
  const readlinePromises = await Promise.resolve().then(() => __importStar(require("readline/promises")));
659
1388
  const crypto = await Promise.resolve().then(() => __importStar(require("crypto")));
660
1389
  // Phase 1: cold CLI — collect provider/credentials with a simple readline
@@ -665,16 +1394,29 @@ async function defaultRunAdoptionSpecialist() {
665
1394
  };
666
1395
  let providerRaw;
667
1396
  let credentials = {};
1397
+ let providerConfig = {};
668
1398
  const tempDir = path.join(os.tmpdir(), `ouro-hatch-${crypto.randomUUID()}`);
669
1399
  try {
670
1400
  const secretsRoot = path.join(os.homedir(), ".agentsecrets");
671
1401
  const discovered = discoverExistingCredentials(secretsRoot);
1402
+ const existingBundleCount = (0, specialist_orchestrator_1.listExistingBundles)((0, identity_1.getAgentBundlesRoot)()).length;
1403
+ const hatchVerb = existingBundleCount > 0 ? "let's hatch a new agent." : "let's hatch your first agent.";
1404
+ // Default models per provider (used when entering new credentials)
1405
+ const defaultModels = {
1406
+ anthropic: "claude-opus-4-6",
1407
+ minimax: "MiniMax-M2.7",
1408
+ "openai-codex": "gpt-5.4",
1409
+ "github-copilot": "claude-sonnet-4.6",
1410
+ azure: "",
1411
+ };
672
1412
  if (discovered.length > 0) {
673
- process.stdout.write("\n\ud83d\udc0d welcome to ouro! let's hatch your first agent.\n");
1413
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
674
1414
  process.stdout.write("i found existing API credentials:\n\n");
675
1415
  const unique = [...new Map(discovered.map((d) => [`${d.provider}`, d])).values()];
676
1416
  for (let i = 0; i < unique.length; i++) {
677
- process.stdout.write(` ${i + 1}. ${unique[i].provider} (from ${unique[i].agentName})\n`);
1417
+ const model = unique[i].providerConfig.model || unique[i].providerConfig.deployment || "";
1418
+ const modelLabel = model ? `, ${model}` : "";
1419
+ process.stdout.write(` ${i + 1}. ${unique[i].provider}${modelLabel} (from ${unique[i].agentName})\n`);
678
1420
  }
679
1421
  process.stdout.write("\n");
680
1422
  const choice = await coldPrompt("use one of these? enter number, or 'new' for a different key: ");
@@ -682,15 +1424,17 @@ async function defaultRunAdoptionSpecialist() {
682
1424
  if (idx >= 0 && idx < unique.length) {
683
1425
  providerRaw = unique[idx].provider;
684
1426
  credentials = unique[idx].credentials;
1427
+ providerConfig = unique[idx].providerConfig;
685
1428
  }
686
1429
  else {
687
- const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
1430
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
688
1431
  if (!isAgentProvider(pRaw)) {
689
1432
  process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
690
1433
  coldRl.close();
691
1434
  return null;
692
1435
  }
693
1436
  providerRaw = pRaw;
1437
+ providerConfig = { model: defaultModels[providerRaw] };
694
1438
  if (providerRaw === "anthropic")
695
1439
  credentials.setupToken = await coldPrompt("API key: ");
696
1440
  if (providerRaw === "openai-codex")
@@ -705,15 +1449,16 @@ async function defaultRunAdoptionSpecialist() {
705
1449
  }
706
1450
  }
707
1451
  else {
708
- process.stdout.write("\n\ud83d\udc0d welcome to ouro! let's hatch your first agent.\n");
1452
+ process.stdout.write(`\n\ud83d\udc0d welcome to ouroboros! ${hatchVerb}\n`);
709
1453
  process.stdout.write("i need an API key to power our conversation.\n\n");
710
- const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex): ");
1454
+ const pRaw = await coldPrompt("provider (anthropic/azure/minimax/openai-codex/github-copilot): ");
711
1455
  if (!isAgentProvider(pRaw)) {
712
1456
  process.stdout.write("unknown provider. run `ouro hatch` to try again.\n");
713
1457
  coldRl.close();
714
1458
  return null;
715
1459
  }
716
1460
  providerRaw = pRaw;
1461
+ providerConfig = { model: defaultModels[providerRaw] };
717
1462
  if (providerRaw === "anthropic")
718
1463
  credentials.setupToken = await coldPrompt("API key: ");
719
1464
  if (providerRaw === "openai-codex")
@@ -732,21 +1477,38 @@ async function defaultRunAdoptionSpecialist() {
732
1477
  const bundleSourceDir = path.resolve(__dirname, "..", "..", "..", "AdoptionSpecialist.ouro");
733
1478
  const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
734
1479
  const secretsRoot2 = path.join(os.homedir(), ".agentsecrets");
735
- // Configure provider credentials in runtime config
736
- patchRuntimeConfig({
737
- providers: {
738
- [providerRaw]: credentials,
739
- },
740
- });
1480
+ // Suppress non-critical log noise during adoption (no secrets.json, etc.)
1481
+ const { setRuntimeLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
1482
+ const { createLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves")));
1483
+ setRuntimeLogger(createLogger({ level: "error" }));
1484
+ // Configure runtime: set agent identity + config override so runAgent
1485
+ // doesn't try to read from ~/AgentBundles/AdoptionSpecialist.ouro/
741
1486
  setAgentName("AdoptionSpecialist");
742
1487
  // Build specialist system prompt
743
1488
  const soulText = (0, specialist_orchestrator_1.loadSoulText)(bundleSourceDir);
744
1489
  const identitiesDir = path.join(bundleSourceDir, "psyche", "identities");
745
1490
  const identity = (0, specialist_orchestrator_1.pickRandomIdentity)(identitiesDir);
1491
+ // Load identity-specific spinner phrases (falls back to DEFAULT_AGENT_PHRASES)
1492
+ const { loadIdentityPhrases } = await Promise.resolve().then(() => __importStar(require("./specialist-orchestrator")));
1493
+ const phrases = loadIdentityPhrases(bundleSourceDir, identity.fileName);
1494
+ setAgentConfigOverride({
1495
+ version: 2,
1496
+ enabled: true,
1497
+ provider: providerRaw,
1498
+ humanFacing: { provider: providerRaw, model: "" },
1499
+ agentFacing: { provider: providerRaw, model: "" },
1500
+ phrases,
1501
+ });
1502
+ patchRuntimeConfig({
1503
+ providers: {
1504
+ [providerRaw]: { ...providerConfig, ...credentials },
1505
+ },
1506
+ });
746
1507
  const existingBundles = (0, specialist_orchestrator_1.listExistingBundles)(bundlesRoot);
747
1508
  const systemPrompt = (0, specialist_prompt_1.buildSpecialistSystemPrompt)(soulText, identity.content, existingBundles, {
748
1509
  tempDir,
749
1510
  provider: providerRaw,
1511
+ model: providerConfig.model ?? "",
750
1512
  });
751
1513
  // Build specialist tools
752
1514
  const specialistTools = (0, specialist_tools_1.getSpecialistTools)();
@@ -764,6 +1526,10 @@ async function defaultRunAdoptionSpecialist() {
764
1526
  tools: specialistTools,
765
1527
  execTool: specialistExecTool,
766
1528
  exitOnToolCall: "complete_adoption",
1529
+ autoFirstTurn: true,
1530
+ banner: false,
1531
+ disableCommands: true,
1532
+ skipSystemPromptRefresh: true,
767
1533
  messages: [
768
1534
  { role: "system", content: systemPrompt },
769
1535
  { role: "user", content: "hi" },
@@ -777,11 +1543,21 @@ async function defaultRunAdoptionSpecialist() {
777
1543
  }
778
1544
  return null;
779
1545
  }
780
- catch {
1546
+ catch (err) {
1547
+ process.stderr.write(`\nouro adoption error: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
781
1548
  coldRl.close();
782
1549
  return null;
783
1550
  }
784
1551
  finally {
1552
+ // Clear specialist config/identity so the hatched agent gets its own
1553
+ setAgentConfigOverride(null);
1554
+ const { resetProviderRuntime } = await Promise.resolve().then(() => __importStar(require("../core")));
1555
+ resetProviderRuntime();
1556
+ const { resetConfigCache } = await Promise.resolve().then(() => __importStar(require("../config")));
1557
+ resetConfigCache();
1558
+ // Restore default logging
1559
+ const { setRuntimeLogger: restoreLogger } = await Promise.resolve().then(() => __importStar(require("../../nerves/runtime")));
1560
+ restoreLogger(null);
785
1561
  // Clean up temp dir if it still exists
786
1562
  try {
787
1563
  if (fs.existsSync(tempDir)) {
@@ -794,30 +1570,118 @@ async function defaultRunAdoptionSpecialist() {
794
1570
  }
795
1571
  }
796
1572
  /* v8 ignore stop */
797
- function createDefaultOuroCliDeps(socketPath = "/tmp/ouroboros-daemon.sock") {
1573
+ function createDefaultOuroCliDeps(socketPath = socket_client_1.DEFAULT_DAEMON_SOCKET_PATH) {
798
1574
  return {
799
1575
  socketPath,
800
- sendCommand: defaultSendCommand,
1576
+ sendCommand: socket_client_1.sendDaemonCommand,
801
1577
  startDaemonProcess: defaultStartDaemonProcess,
802
1578
  writeStdout: defaultWriteStdout,
803
- checkSocketAlive: defaultCheckSocketAlive,
1579
+ checkSocketAlive: socket_client_1.checkDaemonSocketAlive,
804
1580
  cleanupStaleSocket: defaultCleanupStaleSocket,
805
1581
  fallbackPendingMessage: defaultFallbackPendingMessage,
806
- installSubagents: defaultInstallSubagents,
807
- linkFriendIdentity: defaultLinkFriendIdentity,
808
1582
  listDiscoveredAgents: defaultListDiscoveredAgents,
809
1583
  runHatchFlow: hatch_flow_1.runHatchFlow,
810
1584
  promptInput: defaultPromptInput,
811
1585
  runAdoptionSpecialist: defaultRunAdoptionSpecialist,
1586
+ runAuthFlow: auth_flow_1.runRuntimeAuthFlow,
812
1587
  registerOuroBundleType: ouro_uti_1.registerOuroBundleUti,
813
1588
  installOuroCommand: ouro_path_installer_1.installOuroCommand,
1589
+ /* v8 ignore start -- self-healing: ensures active symlink matches running runtime version @preserve */
1590
+ ensureCurrentVersionInstalled: () => {
1591
+ const linkedVersion = (0, ouro_version_manager_1.getCurrentVersion)({});
1592
+ const version = (0, bundle_manifest_1.getPackageVersion)();
1593
+ if (linkedVersion === version)
1594
+ return;
1595
+ (0, ouro_version_manager_1.ensureLayout)({});
1596
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
1597
+ const versionEntry = path.join(cliHome, "versions", version, "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
1598
+ if (!fs.existsSync(versionEntry)) {
1599
+ (0, ouro_version_manager_1.installVersion)(version, {});
1600
+ }
1601
+ (0, ouro_version_manager_1.activateVersion)(version, {});
1602
+ },
1603
+ /* v8 ignore stop */
1604
+ /* v8 ignore start -- CLI version management defaults: integration code @preserve */
1605
+ checkForCliUpdate: async () => {
1606
+ const { checkForUpdate } = await Promise.resolve().then(() => __importStar(require("./update-checker")));
1607
+ return checkForUpdate((0, bundle_manifest_1.getPackageVersion)(), {
1608
+ fetchRegistryJson: async () => {
1609
+ const res = await fetch("https://registry.npmjs.org/@ouro.bot/cli");
1610
+ return res.json();
1611
+ },
1612
+ distTag: "alpha",
1613
+ });
1614
+ },
1615
+ installCliVersion: async (version) => { (0, ouro_version_manager_1.installVersion)(version, {}); },
1616
+ activateCliVersion: (version) => { (0, ouro_version_manager_1.activateVersion)(version, {}); },
1617
+ getCurrentCliVersion: () => (0, ouro_version_manager_1.getCurrentVersion)({}),
1618
+ getPreviousCliVersion: () => (0, ouro_version_manager_1.getPreviousVersion)({}),
1619
+ listCliVersions: () => (0, ouro_version_manager_1.listInstalledVersions)({}),
1620
+ reExecFromNewVersion: (reArgs) => {
1621
+ const entry = path.join((0, ouro_version_manager_1.getOuroCliHome)(), "CurrentVersion", "node_modules", "@ouro.bot", "cli", "dist", "heart", "daemon", "ouro-entry.js");
1622
+ require("child_process").execFileSync("node", [entry, ...reArgs], { stdio: "inherit" });
1623
+ process.exit(0);
1624
+ },
1625
+ /* v8 ignore stop */
1626
+ syncGlobalOuroBotWrapper: ouro_bot_global_installer_1.syncGlobalOuroBotWrapper,
1627
+ ensureSkillManagement: skill_management_installer_1.ensureSkillManagement,
1628
+ ensureDaemonBootPersistence: defaultEnsureDaemonBootPersistence,
1629
+ /* v8 ignore start -- dev-mode defaults: tests inject mocks for mode detection and binary resolution @preserve */
1630
+ detectMode: () => (0, runtime_mode_1.detectRuntimeMode)((0, identity_1.getRepoRoot)()),
1631
+ getInstalledBinaryPath: () => {
1632
+ const cliHome = (0, ouro_version_manager_1.getOuroCliHome)();
1633
+ const binaryPath = path.join(cliHome, "bin", "ouro");
1634
+ return fs.existsSync(binaryPath) ? binaryPath : null;
1635
+ },
1636
+ execInstalledBinary: (binaryPath, binArgs) => {
1637
+ const { execFileSync } = require("child_process");
1638
+ execFileSync(binaryPath, binArgs, { stdio: "inherit" });
1639
+ process.exit(0);
1640
+ },
1641
+ /* v8 ignore stop */
814
1642
  /* v8 ignore next 3 -- integration: launches interactive CLI session @preserve */
815
1643
  startChat: async (agentName) => {
816
1644
  const { main } = await Promise.resolve().then(() => __importStar(require("../../senses/cli")));
817
1645
  await main(agentName);
818
1646
  },
1647
+ scanSessions: async () => {
1648
+ const agentName = (0, identity_1.getAgentName)();
1649
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
1650
+ return (0, session_activity_1.listSessionActivity)({
1651
+ sessionsDir: path.join(agentRoot, "state", "sessions"),
1652
+ friendsDir: path.join(agentRoot, "friends"),
1653
+ agentName,
1654
+ }).map((entry) => ({
1655
+ friendId: entry.friendId,
1656
+ friendName: entry.friendName,
1657
+ channel: entry.channel,
1658
+ lastActivity: entry.lastActivityAt,
1659
+ }));
1660
+ },
819
1661
  };
820
1662
  }
1663
+ function formatMcpResponse(command, response) {
1664
+ if (command.kind === "mcp.list") {
1665
+ const allTools = response.data;
1666
+ if (!allTools || allTools.length === 0) {
1667
+ return response.message ?? "no tools available from connected MCP servers";
1668
+ }
1669
+ const lines = [];
1670
+ for (const entry of allTools) {
1671
+ lines.push(`[${entry.server}]`);
1672
+ for (const tool of entry.tools) {
1673
+ lines.push(` ${tool.name}: ${tool.description}`);
1674
+ }
1675
+ }
1676
+ return lines.join("\n");
1677
+ }
1678
+ // mcp.call
1679
+ const result = response.data;
1680
+ if (!result) {
1681
+ return response.message ?? "no result";
1682
+ }
1683
+ return result.content.map((c) => c.text).join("\n");
1684
+ }
821
1685
  function toDaemonCommand(command) {
822
1686
  return command;
823
1687
  }
@@ -825,28 +1689,17 @@ async function resolveHatchInput(command, deps) {
825
1689
  const prompt = deps.promptInput;
826
1690
  const agentName = command.agentName ?? (prompt ? await prompt("Hatchling name: ") : "");
827
1691
  const humanName = command.humanName ?? (prompt ? await prompt("Your name: ") : os.userInfo().username);
828
- const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex): ") : "");
1692
+ const providerRaw = command.provider ?? (prompt ? await prompt("Provider (azure|anthropic|minimax|openai-codex|github-copilot): ") : "");
829
1693
  if (!agentName || !humanName || !isAgentProvider(providerRaw)) {
830
1694
  throw new Error(`Usage\n${usage()}`);
831
1695
  }
832
- const credentials = { ...(command.credentials ?? {}) };
833
- if (providerRaw === "anthropic" && !credentials.setupToken && prompt) {
834
- credentials.setupToken = await prompt("Anthropic setup-token: ");
835
- }
836
- if (providerRaw === "openai-codex" && !credentials.oauthAccessToken && prompt) {
837
- credentials.oauthAccessToken = await prompt("OpenAI Codex OAuth token: ");
838
- }
839
- if (providerRaw === "minimax" && !credentials.apiKey && prompt) {
840
- credentials.apiKey = await prompt("MiniMax API key: ");
841
- }
842
- if (providerRaw === "azure") {
843
- if (!credentials.apiKey && prompt)
844
- credentials.apiKey = await prompt("Azure API key: ");
845
- if (!credentials.endpoint && prompt)
846
- credentials.endpoint = await prompt("Azure endpoint: ");
847
- if (!credentials.deployment && prompt)
848
- credentials.deployment = await prompt("Azure deployment: ");
849
- }
1696
+ const credentials = await (0, auth_flow_1.resolveHatchCredentials)({
1697
+ agentName,
1698
+ provider: providerRaw,
1699
+ credentials: command.credentials,
1700
+ promptInput: prompt,
1701
+ runAuthFlow: deps.runAuthFlow,
1702
+ });
850
1703
  return {
851
1704
  agentName,
852
1705
  humanName,
@@ -876,7 +1729,11 @@ async function performSystemSetup(deps) {
876
1729
  // Install ouro command to PATH (non-blocking)
877
1730
  if (deps.installOuroCommand) {
878
1731
  try {
879
- deps.installOuroCommand();
1732
+ const installResult = deps.installOuroCommand();
1733
+ /* v8 ignore next -- old-launcher repair hint: fires when stale ~/.local/bin/ouro is fixed @preserve */
1734
+ if (installResult.repairedOldLauncher) {
1735
+ deps.writeStdout("repaired stale ouro launcher at ~/.local/bin/ouro");
1736
+ }
880
1737
  }
881
1738
  catch (error) {
882
1739
  (0, runtime_1.emitNervesEvent)({
@@ -888,28 +1745,391 @@ async function performSystemSetup(deps) {
888
1745
  });
889
1746
  }
890
1747
  }
891
- // Install subagents (claude/codex skills)
892
- try {
893
- await deps.installSubagents();
1748
+ // Self-healing: ensure current version is installed in ~/.ouro-cli/ layout.
1749
+ // Handles the case where the wrapper exists but CurrentVersion is missing
1750
+ // (e.g., first run after migration from old npx wrapper).
1751
+ if (deps.ensureCurrentVersionInstalled) {
1752
+ try {
1753
+ deps.ensureCurrentVersionInstalled();
1754
+ }
1755
+ catch (error) {
1756
+ (0, runtime_1.emitNervesEvent)({
1757
+ level: "warn",
1758
+ component: "daemon",
1759
+ event: "daemon.system_setup_version_install_error",
1760
+ message: "failed to ensure current version installed",
1761
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive @preserve */ String(error) },
1762
+ });
1763
+ }
894
1764
  }
895
- catch (error) {
896
- (0, runtime_1.emitNervesEvent)({
897
- level: "warn",
898
- component: "daemon",
899
- event: "daemon.subagent_install_error",
900
- message: "subagent auto-install failed",
901
- meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
902
- });
1765
+ if (deps.syncGlobalOuroBotWrapper) {
1766
+ try {
1767
+ await Promise.resolve(deps.syncGlobalOuroBotWrapper());
1768
+ }
1769
+ catch (error) {
1770
+ (0, runtime_1.emitNervesEvent)({
1771
+ level: "warn",
1772
+ component: "daemon",
1773
+ event: "daemon.system_setup_ouro_bot_wrapper_error",
1774
+ message: "failed to sync global ouro.bot wrapper",
1775
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
1776
+ });
1777
+ }
1778
+ }
1779
+ // Ensure skill-management skill is available
1780
+ if (deps.ensureSkillManagement) {
1781
+ try {
1782
+ await deps.ensureSkillManagement();
1783
+ /* v8 ignore start -- defensive: ensureSkillManagement handles its own errors internally @preserve */
1784
+ }
1785
+ catch (error) {
1786
+ (0, runtime_1.emitNervesEvent)({
1787
+ level: "warn",
1788
+ component: "daemon",
1789
+ event: "daemon.system_setup_skill_management_error",
1790
+ message: "failed to ensure skill-management skill",
1791
+ meta: { error: error instanceof Error ? error.message : String(error) },
1792
+ });
1793
+ }
1794
+ /* v8 ignore stop */
903
1795
  }
904
1796
  // Register .ouro bundle type (UTI on macOS)
905
1797
  await registerOuroBundleTypeNonBlocking(deps);
906
1798
  }
1799
+ function executeTaskCommand(command, taskMod) {
1800
+ if (command.kind === "task.board") {
1801
+ if (command.status) {
1802
+ const lines = taskMod.boardStatus(command.status);
1803
+ return lines.length > 0 ? lines.join("\n") : "no tasks in that status";
1804
+ }
1805
+ const board = taskMod.getBoard();
1806
+ return board.full || board.compact || "no tasks found";
1807
+ }
1808
+ if (command.kind === "task.create") {
1809
+ try {
1810
+ const created = taskMod.createTask({
1811
+ title: command.title,
1812
+ type: command.type ?? "one-shot",
1813
+ category: "general",
1814
+ body: "",
1815
+ });
1816
+ return `created: ${created}`;
1817
+ }
1818
+ catch (error) {
1819
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1820
+ }
1821
+ }
1822
+ if (command.kind === "task.update") {
1823
+ const result = taskMod.updateStatus(command.id, command.status);
1824
+ if (!result.ok) {
1825
+ return `error: ${result.reason ?? "status update failed"}`;
1826
+ }
1827
+ const archivedSuffix = result.archived && result.archived.length > 0
1828
+ ? ` | archived: ${result.archived.join(", ")}`
1829
+ : "";
1830
+ return `updated: ${command.id} -> ${result.to}${archivedSuffix}`;
1831
+ }
1832
+ if (command.kind === "task.show") {
1833
+ const task = taskMod.getTask(command.id);
1834
+ if (!task)
1835
+ return `task not found: ${command.id}`;
1836
+ return [
1837
+ `title: ${task.title}`,
1838
+ `type: ${task.type}`,
1839
+ `status: ${task.status}`,
1840
+ `category: ${task.category}`,
1841
+ `created: ${task.created}`,
1842
+ `updated: ${task.updated}`,
1843
+ `path: ${task.path}`,
1844
+ task.body ? `\n${task.body}` : "",
1845
+ ].filter(Boolean).join("\n");
1846
+ }
1847
+ if (command.kind === "task.actionable") {
1848
+ const lines = taskMod.boardAction();
1849
+ return lines.length > 0 ? lines.join("\n") : "no action required";
1850
+ }
1851
+ if (command.kind === "task.deps") {
1852
+ const lines = taskMod.boardDeps();
1853
+ return lines.length > 0 ? lines.join("\n") : "no unresolved dependencies";
1854
+ }
1855
+ if (command.kind === "task.fix") {
1856
+ try {
1857
+ const fixOptions = {
1858
+ mode: command.mode,
1859
+ ...(command.issueId ? { issueId: command.issueId } : {}),
1860
+ ...(command.option !== undefined ? { option: command.option } : {}),
1861
+ };
1862
+ const result = taskMod.fix(fixOptions);
1863
+ if (command.mode === "dry-run") {
1864
+ if (result.remaining.length === 0) {
1865
+ return `task health: clean`;
1866
+ }
1867
+ const safeIssues = result.remaining.filter((i) => i.confidence === "safe");
1868
+ const reviewIssues = result.remaining.filter((i) => i.confidence === "needs_review");
1869
+ const lines = [`${result.remaining.length} issues found`];
1870
+ if (safeIssues.length > 0) {
1871
+ lines.push("", `safe fixes (${safeIssues.length}):`);
1872
+ for (const issue of safeIssues) {
1873
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1874
+ }
1875
+ }
1876
+ if (reviewIssues.length > 0) {
1877
+ lines.push("", `needs review (${reviewIssues.length}):`);
1878
+ for (const issue of reviewIssues) {
1879
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1880
+ }
1881
+ }
1882
+ lines.push("", `task health: ${result.health}`);
1883
+ return lines.join("\n");
1884
+ }
1885
+ // safe, single, or --all modes: show what was done
1886
+ const lines = [];
1887
+ if (result.applied.length > 0) {
1888
+ lines.push(`${result.applied.length} applied:`);
1889
+ for (const issue of result.applied) {
1890
+ lines.push(` ${issue.code}:${issue.target}`);
1891
+ }
1892
+ }
1893
+ if (result.remaining.length > 0) {
1894
+ lines.push(`${result.remaining.length} remaining:`);
1895
+ for (const issue of result.remaining) {
1896
+ lines.push(` ${issue.code}:${issue.target} -- ${issue.description}`);
1897
+ }
1898
+ }
1899
+ if (result.applied.length === 0 && result.remaining.length === 0) {
1900
+ lines.push("no issues");
1901
+ }
1902
+ lines.push(`task health: ${result.health}`);
1903
+ return lines.join("\n");
1904
+ }
1905
+ catch (error) {
1906
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
1907
+ }
1908
+ }
1909
+ // command.kind === "task.sessions"
1910
+ const lines = taskMod.boardSessions();
1911
+ return lines.length > 0 ? lines.join("\n") : "no active sessions";
1912
+ }
1913
+ const TRUST_RANK = { family: 4, friend: 3, acquaintance: 2, stranger: 1 };
1914
+ /* v8 ignore start -- defensive: ?? fallbacks are unreachable when inputs are valid TrustLevel values @preserve */
1915
+ function higherTrust(a, b) {
1916
+ const rankA = TRUST_RANK[a ?? "stranger"] ?? 1;
1917
+ const rankB = TRUST_RANK[b ?? "stranger"] ?? 1;
1918
+ return rankA >= rankB ? (a ?? "stranger") : (b ?? "stranger");
1919
+ }
1920
+ /* v8 ignore stop */
1921
+ async function executeFriendCommand(command, store) {
1922
+ if (command.kind === "friend.list") {
1923
+ const listAll = store.listAll;
1924
+ if (!listAll)
1925
+ return "friend store does not support listing";
1926
+ const friends = await listAll.call(store);
1927
+ if (friends.length === 0)
1928
+ return "no friends found";
1929
+ const lines = friends.map((f) => {
1930
+ const trust = f.trustLevel ?? "unknown";
1931
+ return `${f.id} ${f.name} ${trust}`;
1932
+ });
1933
+ return lines.join("\n");
1934
+ }
1935
+ if (command.kind === "friend.show") {
1936
+ const record = await store.get(command.friendId);
1937
+ if (!record)
1938
+ return `friend not found: ${command.friendId}`;
1939
+ return JSON.stringify(record, null, 2);
1940
+ }
1941
+ if (command.kind === "friend.create") {
1942
+ const now = new Date().toISOString();
1943
+ const id = (0, crypto_1.randomUUID)();
1944
+ const trustLevel = (command.trustLevel ?? "acquaintance");
1945
+ await store.put(id, {
1946
+ id,
1947
+ name: command.name,
1948
+ trustLevel,
1949
+ externalIds: [],
1950
+ tenantMemberships: [],
1951
+ toolPreferences: {},
1952
+ notes: {},
1953
+ totalTokens: 0,
1954
+ createdAt: now,
1955
+ updatedAt: now,
1956
+ schemaVersion: 1,
1957
+ });
1958
+ return `created: ${id} (${command.name}, ${trustLevel})`;
1959
+ }
1960
+ if (command.kind === "friend.update") {
1961
+ const current = await store.get(command.friendId);
1962
+ if (!current)
1963
+ return `friend not found: ${command.friendId}`;
1964
+ const now = new Date().toISOString();
1965
+ await store.put(command.friendId, {
1966
+ ...current,
1967
+ trustLevel: command.trustLevel,
1968
+ role: command.trustLevel,
1969
+ updatedAt: now,
1970
+ });
1971
+ return `updated: ${command.friendId} → trust=${command.trustLevel}`;
1972
+ }
1973
+ if (command.kind === "friend.link") {
1974
+ const current = await store.get(command.friendId);
1975
+ if (!current)
1976
+ return `friend not found: ${command.friendId}`;
1977
+ const alreadyLinked = current.externalIds.some((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
1978
+ if (alreadyLinked)
1979
+ return `identity already linked: ${command.provider}:${command.externalId}`;
1980
+ const now = new Date().toISOString();
1981
+ const newExternalIds = [
1982
+ ...current.externalIds,
1983
+ { provider: command.provider, externalId: command.externalId, linkedAt: now },
1984
+ ];
1985
+ // Orphan cleanup: check if another friend has this externalId
1986
+ const orphan = await store.findByExternalId(command.provider, command.externalId);
1987
+ let mergeMessage = "";
1988
+ let mergedNotes = { ...current.notes };
1989
+ let mergedTrust = current.trustLevel;
1990
+ let orphanExternalIds = [];
1991
+ if (orphan && orphan.id !== command.friendId) {
1992
+ // Merge orphan's notes (target's notes take priority)
1993
+ mergedNotes = { ...orphan.notes, ...current.notes };
1994
+ // Keep higher trust level
1995
+ mergedTrust = higherTrust(current.trustLevel, orphan.trustLevel);
1996
+ // Collect orphan's other externalIds (excluding the one being linked)
1997
+ orphanExternalIds = orphan.externalIds.filter((ext) => !(ext.provider === command.provider && ext.externalId === command.externalId));
1998
+ await store.delete(orphan.id);
1999
+ mergeMessage = ` (merged orphan ${orphan.id})`;
2000
+ }
2001
+ await store.put(command.friendId, {
2002
+ ...current,
2003
+ externalIds: [...newExternalIds, ...orphanExternalIds],
2004
+ notes: mergedNotes,
2005
+ trustLevel: mergedTrust,
2006
+ updatedAt: now,
2007
+ });
2008
+ return `linked ${command.provider}:${command.externalId} to ${command.friendId}${mergeMessage}`;
2009
+ }
2010
+ // command.kind === "friend.unlink"
2011
+ const current = await store.get(command.friendId);
2012
+ if (!current)
2013
+ return `friend not found: ${command.friendId}`;
2014
+ const idx = current.externalIds.findIndex((ext) => ext.provider === command.provider && ext.externalId === command.externalId);
2015
+ if (idx === -1)
2016
+ return `identity not linked: ${command.provider}:${command.externalId}`;
2017
+ const now = new Date().toISOString();
2018
+ const filtered = current.externalIds.filter((_, i) => i !== idx);
2019
+ await store.put(command.friendId, { ...current, externalIds: filtered, updatedAt: now });
2020
+ return `unlinked ${command.provider}:${command.externalId} from ${command.friendId}`;
2021
+ }
2022
+ function executeReminderCommand(command, taskMod) {
2023
+ try {
2024
+ const created = taskMod.createTask({
2025
+ title: command.title,
2026
+ type: command.cadence ? "ongoing" : "one-shot",
2027
+ category: command.category ?? "reminder",
2028
+ body: command.body,
2029
+ scheduledAt: command.scheduledAt,
2030
+ cadence: command.cadence,
2031
+ requester: command.requester,
2032
+ });
2033
+ return `created: ${created}`;
2034
+ }
2035
+ catch (error) {
2036
+ return `error: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
2037
+ }
2038
+ }
2039
+ /* v8 ignore start -- repo resolution for ouro dev: repoPath branch tested via daemon-cli-dev; clone requires real git/npm @preserve */
2040
+ function getDevConfigPath() {
2041
+ return path.join((0, ouro_version_manager_1.getOuroCliHome)(), "dev-config.json");
2042
+ }
2043
+ function readPersistedDevPath() {
2044
+ try {
2045
+ const data = JSON.parse(fs.readFileSync(getDevConfigPath(), "utf-8"));
2046
+ return typeof data.repoPath === "string" ? data.repoPath : null;
2047
+ }
2048
+ catch {
2049
+ return null;
2050
+ }
2051
+ }
2052
+ function persistDevPath(repoPath) {
2053
+ try {
2054
+ fs.mkdirSync(path.dirname(getDevConfigPath()), { recursive: true });
2055
+ fs.writeFileSync(getDevConfigPath(), JSON.stringify({ repoPath }, null, 2));
2056
+ }
2057
+ catch { /* best effort */ }
2058
+ }
2059
+ function resolveDevRepoCwd(command, checkExists, deps) {
2060
+ // 1. Explicit --repo-path: use it and persist for next time
2061
+ if (command.repoPath) {
2062
+ const resolved = path.resolve(command.repoPath);
2063
+ persistDevPath(resolved);
2064
+ return resolved;
2065
+ }
2066
+ // 2. Clone request
2067
+ if (command.clone)
2068
+ return resolveClonePath(command, checkExists, deps);
2069
+ // 3. If test/internal deps provide getRepoCwd, use it directly
2070
+ if (deps.getRepoCwd) {
2071
+ return deps.getRepoCwd();
2072
+ }
2073
+ // 4. Check CWD — if we're inside a harness repo, use it
2074
+ const cwd = process.cwd();
2075
+ if (checkExists(path.join(cwd, ".git")) && checkExists(path.join(cwd, "src", "heart", "daemon"))) {
2076
+ persistDevPath(cwd);
2077
+ return cwd;
2078
+ }
2079
+ // 5. Read persisted path from last --repo-path
2080
+ const persisted = readPersistedDevPath();
2081
+ if (persisted && checkExists(path.join(persisted, ".git"))) {
2082
+ deps.writeStdout(`using remembered dev path: ${persisted}`);
2083
+ return persisted;
2084
+ }
2085
+ // 6. Fall back to getRepoRoot (works when running from installed binary → resolves to npm package)
2086
+ return (0, identity_1.getRepoRoot)();
2087
+ }
2088
+ /* v8 ignore stop */
2089
+ /* v8 ignore start -- clone/build: requires real git clone + npm install on disk @preserve */
2090
+ function resolveClonePath(command, checkExists, deps) {
2091
+ const cloneTarget = command.clonePath
2092
+ ? path.resolve(command.clonePath)
2093
+ : path.join(os.homedir(), "Projects", "ouroboros");
2094
+ if (!checkExists(path.join(cloneTarget, ".git"))) {
2095
+ deps.writeStdout(`cloning ouroboros to ${cloneTarget}...`);
2096
+ try {
2097
+ (0, child_process_1.execSync)(`git clone ${identity_1.HARNESS_CANONICAL_REPO_URL} "${cloneTarget}"`, { stdio: "inherit" });
2098
+ }
2099
+ catch {
2100
+ throw new Error(`clone failed. check your network and try again, or clone manually and use --repo-path.`);
2101
+ }
2102
+ }
2103
+ else {
2104
+ deps.writeStdout(`repo already exists at ${cloneTarget}, pulling latest...`);
2105
+ try {
2106
+ (0, child_process_1.execSync)("git pull --ff-only", { cwd: cloneTarget, stdio: "inherit" });
2107
+ }
2108
+ catch {
2109
+ deps.writeStdout("pull failed (may have local changes). continuing with existing code.");
2110
+ }
2111
+ }
2112
+ deps.writeStdout("building...");
2113
+ try {
2114
+ (0, child_process_1.execSync)("npm install && npm run build", { cwd: cloneTarget, stdio: "inherit" });
2115
+ }
2116
+ catch {
2117
+ throw new Error(`build failed in ${cloneTarget}. check the output above.`);
2118
+ }
2119
+ return cloneTarget;
2120
+ }
2121
+ /* v8 ignore stop */
907
2122
  async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
908
- if (args.includes("--help") || args.includes("-h")) {
2123
+ if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
909
2124
  const text = usage();
910
2125
  deps.writeStdout(text);
911
2126
  return text;
912
2127
  }
2128
+ if (args.length === 1 && (args[0] === "-v" || args[0] === "--version")) {
2129
+ const text = formatVersionOutput();
2130
+ deps.writeStdout(text);
2131
+ return text;
2132
+ }
913
2133
  let command;
914
2134
  try {
915
2135
  command = parseOuroCommand(args);
@@ -980,21 +2200,1058 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
980
2200
  meta: { kind: command.kind },
981
2201
  });
982
2202
  if (command.kind === "daemon.up") {
2203
+ // ── dev mode cleanup: delete dev-config.json so the wrapper stops dispatching to dev repo ──
2204
+ /* v8 ignore start -- dev-config cleanup: requires real filesystem state @preserve */
2205
+ try {
2206
+ const devConfigPath = getDevConfigPath();
2207
+ if (fs.existsSync(devConfigPath)) {
2208
+ fs.unlinkSync(devConfigPath);
2209
+ }
2210
+ }
2211
+ catch { /* best effort */ }
2212
+ /* v8 ignore stop */
2213
+ // ── dev mode delegation: ouro up from a dev repo delegates to installed binary ──
2214
+ // Only runs when detectMode is explicitly injected (via createDefaultOuroCliDeps or tests)
2215
+ if (deps.detectMode) {
2216
+ const runtimeMode = deps.detectMode();
2217
+ if (runtimeMode === "dev") {
2218
+ /* v8 ignore next -- defensive: getInstalledBinaryPath always injected in tests @preserve */
2219
+ const installedBinary = deps.getInstalledBinaryPath ? deps.getInstalledBinaryPath() : null;
2220
+ if (installedBinary) {
2221
+ deps.writeStdout("delegating to installed ouro...");
2222
+ /* v8 ignore next 3 -- defensive: execInstalledBinary always injected; missing branch unreachable @preserve */
2223
+ if (deps.execInstalledBinary) {
2224
+ deps.execInstalledBinary(installedBinary, args);
2225
+ }
2226
+ /* v8 ignore next 2 -- unreachable after exec replaces process @preserve */
2227
+ return "";
2228
+ }
2229
+ const message = "no installed version found. run: npx @ouro.bot/cli@alpha";
2230
+ deps.writeStdout(message);
2231
+ return message;
2232
+ }
2233
+ }
2234
+ const linkedVersionBeforeUp = deps.getCurrentCliVersion?.() ?? null;
2235
+ // ── versioned CLI update check ──
2236
+ if (deps.checkForCliUpdate) {
2237
+ let pendingReExec = false;
2238
+ try {
2239
+ const updateResult = await deps.checkForCliUpdate();
2240
+ if (updateResult.available && updateResult.latestVersion) {
2241
+ /* v8 ignore next -- fallback: getCurrentCliVersion always injected in tests @preserve */
2242
+ const currentVersion = linkedVersionBeforeUp ?? "unknown";
2243
+ await deps.installCliVersion(updateResult.latestVersion);
2244
+ deps.activateCliVersion(updateResult.latestVersion);
2245
+ deps.writeStdout(`ouro updated to ${updateResult.latestVersion} (was ${currentVersion})`);
2246
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(currentVersion, updateResult.latestVersion);
2247
+ /* v8 ignore next -- buildChangelogCommand is non-null when an actual newer version is installed @preserve */
2248
+ if (changelogCommand) {
2249
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2250
+ }
2251
+ pendingReExec = true;
2252
+ }
2253
+ /* v8 ignore start -- update check error: tested via daemon-cli-update-flow.test.ts @preserve */
2254
+ }
2255
+ catch (error) {
2256
+ (0, runtime_1.emitNervesEvent)({
2257
+ level: "warn",
2258
+ component: "daemon",
2259
+ event: "daemon.cli_update_check_error",
2260
+ message: "CLI update check failed",
2261
+ meta: { error: error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error) },
2262
+ });
2263
+ }
2264
+ /* v8 ignore stop */
2265
+ if (pendingReExec) {
2266
+ deps.reExecFromNewVersion(args);
2267
+ }
2268
+ }
983
2269
  await performSystemSetup(deps);
2270
+ const linkedVersionAfterSetup = deps.getCurrentCliVersion?.() ?? null;
2271
+ const runtimeVersion = (0, bundle_manifest_1.getPackageVersion)();
2272
+ if (linkedVersionBeforeUp && linkedVersionBeforeUp !== runtimeVersion && linkedVersionAfterSetup === runtimeVersion) {
2273
+ deps.writeStdout(`ouro updated to ${runtimeVersion} (was ${linkedVersionBeforeUp})`);
2274
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(linkedVersionBeforeUp, runtimeVersion);
2275
+ if (changelogCommand) {
2276
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2277
+ }
2278
+ }
2279
+ if (deps.ensureDaemonBootPersistence) {
2280
+ try {
2281
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
2282
+ }
2283
+ catch (error) {
2284
+ (0, runtime_1.emitNervesEvent)({
2285
+ level: "warn",
2286
+ component: "daemon",
2287
+ event: "daemon.system_setup_launchd_error",
2288
+ message: "failed to persist daemon boot startup",
2289
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
2290
+ });
2291
+ }
2292
+ }
2293
+ // Run update hooks before starting daemon so user sees the output
2294
+ (0, update_hooks_1.registerUpdateHook)(bundle_meta_1.bundleMetaHook);
2295
+ (0, update_hooks_1.registerUpdateHook)(agent_config_v2_1.agentConfigV2Hook);
2296
+ const bundlesRoot = (0, identity_1.getAgentBundlesRoot)();
2297
+ const currentVersion = (0, bundle_manifest_1.getPackageVersion)();
2298
+ // Snapshot the previous CLI version from the first bundle-meta before
2299
+ // hooks overwrite it. This detects when npx downloaded a newer CLI.
2300
+ const previousCliVersion = readFirstBundleMetaVersion(bundlesRoot);
2301
+ const updateSummary = await (0, update_hooks_1.applyPendingUpdates)(bundlesRoot, currentVersion);
2302
+ // Notify about CLI binary update (npx downloaded a new version).
2303
+ // Skip when the symlink already points to the running version — that
2304
+ // means path 1 (checkForCliUpdate + reExecFromNewVersion) already
2305
+ // printed the update message before re-exec.
2306
+ /* v8 ignore start -- CLI update detection: tested via daemon-cli-version-detect.test.ts @preserve */
2307
+ if (previousCliVersion && previousCliVersion !== currentVersion && linkedVersionBeforeUp !== currentVersion) {
2308
+ deps.writeStdout(`ouro updated to ${currentVersion} (was ${previousCliVersion})`);
2309
+ const changelogCommand = (0, ouro_version_manager_1.buildChangelogCommand)(previousCliVersion, currentVersion);
2310
+ /* v8 ignore next -- buildChangelogCommand is non-null when previous/current runtime versions differ @preserve */
2311
+ if (changelogCommand) {
2312
+ deps.writeStdout(`review changes with: ${changelogCommand}`);
2313
+ }
2314
+ }
2315
+ /* v8 ignore stop */
2316
+ if (updateSummary.updated.length > 0) {
2317
+ const agents = updateSummary.updated.map((e) => e.agent);
2318
+ const from = updateSummary.updated[0].from;
2319
+ const to = updateSummary.updated[0].to;
2320
+ const fromStr = from ? ` (was ${from})` : "";
2321
+ const count = agents.length;
2322
+ deps.writeStdout(`updated ${count} agent${count === 1 ? "" : "s"} to runtime ${to}${fromStr}`);
2323
+ }
984
2324
  const daemonResult = await ensureDaemonRunning(deps);
985
2325
  deps.writeStdout(daemonResult.message);
986
2326
  return daemonResult.message;
987
2327
  }
2328
+ if (command.kind === "daemon.dev") {
2329
+ /* v8 ignore next -- defensive: existsSync always injected in tests @preserve */
2330
+ const checkExists = deps.existsSync ?? fs.existsSync;
2331
+ /* v8 ignore next -- repo resolution dispatched to v8-ignored helper @preserve */
2332
+ let repoCwd = resolveDevRepoCwd(command, checkExists, deps);
2333
+ let entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2334
+ if (!checkExists(entryPath) || !checkExists(path.join(repoCwd, ".git"))) {
2335
+ if (command.repoPath) {
2336
+ // Explicit --repo-path didn't have a valid repo — error
2337
+ const message = `no harness repo found at ${repoCwd}. run npm run build first.`;
2338
+ deps.writeStdout(message);
2339
+ return message;
2340
+ }
2341
+ /* v8 ignore start -- auto-clone: interactive prompt + existing repo discovery + real git/npm @preserve */
2342
+ const defaultClonePath = path.join(os.homedir(), "Projects", "ouroboros");
2343
+ if (checkExists(path.join(defaultClonePath, ".git"))) {
2344
+ deps.writeStdout(`found existing repo at ${defaultClonePath}`);
2345
+ try {
2346
+ repoCwd = resolveClonePath({ clonePath: defaultClonePath }, checkExists, deps);
2347
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2348
+ }
2349
+ catch (err) {
2350
+ const message = err instanceof Error ? err.message : String(err);
2351
+ deps.writeStdout(message);
2352
+ return message;
2353
+ }
2354
+ }
2355
+ else if (deps.promptInput) {
2356
+ deps.writeStdout("no harness repo found.");
2357
+ const answer = await deps.promptInput(`already have a checkout? enter its path, or press enter to clone to ${defaultClonePath}: `);
2358
+ const cloneTarget = answer.trim() || defaultClonePath;
2359
+ try {
2360
+ repoCwd = resolveClonePath({ clonePath: cloneTarget }, checkExists, deps);
2361
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2362
+ }
2363
+ catch (err) {
2364
+ const message = err instanceof Error ? err.message : String(err);
2365
+ deps.writeStdout(message);
2366
+ return message;
2367
+ }
2368
+ }
2369
+ else {
2370
+ const message = `no harness repo found. run: ouro dev --repo-path /path/to/ouroboros`;
2371
+ deps.writeStdout(message);
2372
+ return message;
2373
+ }
2374
+ /* v8 ignore stop */
2375
+ }
2376
+ // Auto-build: always rebuild in dev mode so dist/ matches source
2377
+ /* v8 ignore start -- dev auto-build: execSync in repo cwd, tested manually @preserve */
2378
+ deps.writeStdout(`building from ${repoCwd}...`);
2379
+ try {
2380
+ (0, child_process_1.execSync)("npm run build", { cwd: repoCwd, stdio: "inherit" });
2381
+ entryPath = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2382
+ }
2383
+ catch {
2384
+ const message = `build failed in ${repoCwd}. fix compilation errors and retry.`;
2385
+ deps.writeStdout(message);
2386
+ return message;
2387
+ }
2388
+ /* v8 ignore stop */
2389
+ /* v8 ignore start -- defensive: ensureDaemonBootPersistence always injected in tests @preserve */
2390
+ if (deps.ensureDaemonBootPersistence) {
2391
+ try {
2392
+ await Promise.resolve(deps.ensureDaemonBootPersistence(deps.socketPath));
2393
+ /* v8 ignore next -- defensive: boot persistence error should not block dev mode @preserve */
2394
+ }
2395
+ catch (error) {
2396
+ (0, runtime_1.emitNervesEvent)({
2397
+ level: "warn",
2398
+ component: "daemon",
2399
+ event: "daemon.dev_boot_persistence_error",
2400
+ message: "failed to persist daemon boot startup in dev mode",
2401
+ meta: { error: error instanceof Error ? error.message : String(error), socketPath: deps.socketPath },
2402
+ });
2403
+ }
2404
+ /* v8 ignore stop */
2405
+ }
2406
+ // Disable launchd KeepAlive before killing — prevents the installed daemon from respawning
2407
+ /* v8 ignore start -- dev launchd disable: requires real launchctl + plist on disk @preserve */
2408
+ const launchdDevDeps = {
2409
+ exec: (cmd) => { (0, child_process_1.execSync)(cmd); },
2410
+ existsFile: (p) => fs.existsSync(p),
2411
+ removeFile: (p) => { try {
2412
+ fs.unlinkSync(p);
2413
+ }
2414
+ catch { /* best effort */ } },
2415
+ homeDir: os.homedir(),
2416
+ userUid: process.getuid?.() ?? 0,
2417
+ };
2418
+ if ((0, launchd_1.isDaemonInstalled)(launchdDevDeps)) {
2419
+ (0, launchd_1.uninstallLaunchAgent)(launchdDevDeps);
2420
+ deps.writeStdout("disabled launchd auto-restart for dev mode");
2421
+ }
2422
+ /* v8 ignore stop */
2423
+ // Always force-restart in dev mode — you rebuilt, you want this code running
2424
+ /* v8 ignore start -- dev force-restart: socket alive/stop/spawn tested via integration; tests inject mocks @preserve */
2425
+ const alive = await deps.checkSocketAlive(deps.socketPath);
2426
+ if (alive) {
2427
+ try {
2428
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
2429
+ }
2430
+ catch { /* already stopping */ }
2431
+ }
2432
+ deps.cleanupStaleSocket(deps.socketPath);
2433
+ const devEntry = path.join(repoCwd, "dist", "heart", "daemon", "daemon-entry.js");
2434
+ const startDevDaemon = deps.startDaemonProcess === defaultStartDaemonProcess
2435
+ ? async (sp) => {
2436
+ const child = (0, child_process_1.spawn)("node", [devEntry, "--socket", sp], { detached: true, stdio: "ignore" });
2437
+ child.unref();
2438
+ return { pid: child.pid ?? null };
2439
+ }
2440
+ : deps.startDaemonProcess;
2441
+ /* v8 ignore stop */
2442
+ const started = await startDevDaemon(deps.socketPath);
2443
+ /* v8 ignore next -- defensive: pid is null only when spawn fails silently @preserve */
2444
+ const message = `daemon running in dev mode from ${repoCwd} (pid ${started.pid ?? "unknown"})\nrun 'ouro up' to return to production mode`;
2445
+ deps.writeStdout(message);
2446
+ return message;
2447
+ }
2448
+ // ── rollback command (local, no daemon socket needed for symlinks) ──
2449
+ /* v8 ignore start -- rollback/versions: tested via daemon-cli-rollback/versions tests @preserve */
2450
+ if (command.kind === "rollback") {
2451
+ const currentVersion = deps.getCurrentCliVersion?.() ?? "unknown";
2452
+ if (command.version) {
2453
+ // Rollback to a specific version
2454
+ const installed = deps.listCliVersions?.() ?? [];
2455
+ if (!installed.includes(command.version)) {
2456
+ try {
2457
+ await deps.installCliVersion(command.version);
2458
+ }
2459
+ catch (error) {
2460
+ const message = `failed to install version ${command.version}: ${error instanceof Error ? error.message : /* v8 ignore next -- defensive: non-Error catch branch @preserve */ String(error)}`;
2461
+ deps.writeStdout(message);
2462
+ return message;
2463
+ }
2464
+ }
2465
+ deps.activateCliVersion(command.version);
2466
+ }
2467
+ else {
2468
+ // Rollback to previous version
2469
+ const previousVersion = deps.getPreviousCliVersion?.();
2470
+ if (!previousVersion) {
2471
+ const message = "no previous version to roll back to";
2472
+ deps.writeStdout(message);
2473
+ return message;
2474
+ }
2475
+ deps.activateCliVersion(previousVersion);
2476
+ command = { ...command, version: previousVersion };
2477
+ }
2478
+ // Stop daemon (non-fatal if not running)
2479
+ try {
2480
+ await deps.sendCommand(deps.socketPath, { kind: "daemon.stop" });
2481
+ }
2482
+ catch {
2483
+ // Daemon may not be running — that's fine
2484
+ }
2485
+ const message = `rolled back to ${command.version} (was ${currentVersion})`;
2486
+ deps.writeStdout(message);
2487
+ return message;
2488
+ }
2489
+ // ── versions command (local install list + published update truth, no daemon socket needed) ──
2490
+ if (command.kind === "versions") {
2491
+ const versions = deps.listCliVersions?.() ?? [];
2492
+ const current = deps.getCurrentCliVersion?.();
2493
+ const previous = deps.getPreviousCliVersion?.();
2494
+ const localSection = versions.length === 0
2495
+ ? "no versions installed"
2496
+ : versions.map((v) => {
2497
+ let line = v;
2498
+ if (v === current)
2499
+ line += " * current";
2500
+ if (v === previous)
2501
+ line += " (previous)";
2502
+ return line;
2503
+ }).join("\n");
2504
+ const sections = [localSection];
2505
+ if (deps.checkForCliUpdate) {
2506
+ try {
2507
+ const updateResult = await deps.checkForCliUpdate();
2508
+ if (updateResult.latestVersion) {
2509
+ sections.push(`published alpha: ${updateResult.latestVersion} (${updateResult.available ? "update available" : "up to date"})`);
2510
+ }
2511
+ else if (updateResult.error) {
2512
+ sections.push(`published alpha: unavailable (${updateResult.error})`);
2513
+ }
2514
+ }
2515
+ catch (err) {
2516
+ const reason = err instanceof Error ? err.message : String(err);
2517
+ sections.push(`published alpha: unavailable (${reason})`);
2518
+ }
2519
+ }
2520
+ const message = sections.join("\n\n");
2521
+ deps.writeStdout(message);
2522
+ return message;
2523
+ }
2524
+ /* v8 ignore stop */
988
2525
  if (command.kind === "daemon.logs" && deps.tailLogs) {
989
2526
  deps.tailLogs();
990
2527
  return "";
991
2528
  }
992
- if (command.kind === "friend.link") {
993
- const linker = deps.linkFriendIdentity ?? defaultLinkFriendIdentity;
994
- const message = await linker(command);
2529
+ if (command.kind === "outlook") {
2530
+ let status;
2531
+ try {
2532
+ status = await deps.sendCommand(deps.socketPath, { kind: "daemon.status" });
2533
+ /* v8 ignore start — error path: daemon not running */
2534
+ }
2535
+ catch {
2536
+ const message = "daemon unavailable — start with `ouro up` first";
2537
+ deps.writeStdout(message);
2538
+ return message;
2539
+ }
2540
+ /* v8 ignore stop */
2541
+ const payload = parseStatusPayload(status.data);
2542
+ /* v8 ignore start -- ?? branch: outlookUrl always present in test fixtures */
2543
+ const outlookUrl = payload?.overview.outlookUrl ?? "unavailable";
2544
+ /* v8 ignore stop */
2545
+ if (!command.json) {
2546
+ deps.writeStdout(outlookUrl);
2547
+ return outlookUrl;
2548
+ }
2549
+ /* v8 ignore start — error path: outlook URL not available */
2550
+ if (outlookUrl === "unavailable") {
2551
+ deps.writeStdout(outlookUrl);
2552
+ return outlookUrl;
2553
+ }
2554
+ /* v8 ignore stop */
2555
+ /* v8 ignore start -- ?? branch: tests always inject fetchImpl */
2556
+ const fetchImpl = deps.fetchImpl ?? fetch;
2557
+ /* v8 ignore stop */
2558
+ const response = await fetchImpl(`${outlookUrl}/api/machine`);
2559
+ const data = await response.json();
2560
+ const text = JSON.stringify(data, null, 2);
2561
+ deps.writeStdout(text);
2562
+ return text;
2563
+ }
2564
+ // ── hook: handle Claude Code lifecycle hooks ──
2565
+ /* v8 ignore start -- hook handler: reads real stdin, sends to real daemon @preserve */
2566
+ if (command.kind === "hook") {
2567
+ let stdinData = "";
2568
+ try {
2569
+ stdinData = require("fs").readFileSync(0, "utf-8");
2570
+ }
2571
+ catch { /* no stdin */ }
2572
+ let event = {};
2573
+ try {
2574
+ event = JSON.parse(stdinData);
2575
+ }
2576
+ catch { /* malformed */ }
2577
+ const eventType = command.event;
2578
+ const sessionId = event.session_id ?? "unknown";
2579
+ const cwd = event.cwd ?? "";
2580
+ // Build notification content based on event type
2581
+ let content;
2582
+ if (eventType === "session-start") {
2583
+ const model = event.model ?? "";
2584
+ const source = event.source ?? "";
2585
+ content = `[Claude Code session started: ${sessionId}, cwd: ${cwd}${model ? `, model: ${model}` : ""}${source ? `, source: ${source}` : ""}]`;
2586
+ }
2587
+ else if (eventType === "stop") {
2588
+ const lastMsg = event.last_assistant_message ?? "";
2589
+ content = `[Claude Code session ended: ${sessionId}${lastMsg ? `, last: ${lastMsg.slice(0, 200)}` : ""}]`;
2590
+ }
2591
+ else if (eventType === "post-tool-use") {
2592
+ const toolName = event.tool_name ?? "";
2593
+ content = `[Claude Code used ${toolName} in session ${sessionId}]`;
2594
+ }
2595
+ else {
2596
+ content = `[Claude Code hook: ${eventType} in session ${sessionId}]`;
2597
+ }
2598
+ // Send to the specific agent configured for this hook
2599
+ try {
2600
+ await deps.sendCommand(deps.socketPath, { kind: "message.send", from: `claude-code:${sessionId}`, to: command.agent, content }).catch(() => { });
2601
+ await deps.sendCommand(deps.socketPath, { kind: "inner.wake", agent: command.agent }).catch(() => { });
2602
+ }
2603
+ catch { /* daemon not running — silent */ }
2604
+ // Output for Claude Code hook system
2605
+ deps.writeStdout(JSON.stringify({ continue: true }));
2606
+ return JSON.stringify({ continue: true });
2607
+ }
2608
+ /* v8 ignore stop */
2609
+ // ── setup: configure dev tool integration ──
2610
+ if (command.kind === "setup") {
2611
+ const { tool, agent: setupAgent } = command;
2612
+ const sourceRoot = (0, identity_1.getRepoRoot)();
2613
+ const runtimeMode = (0, runtime_mode_1.detectRuntimeMode)(sourceRoot);
2614
+ const mcpServeCommand = runtimeMode === "dev"
2615
+ ? `node ${path.join(sourceRoot, "dist", "heart", "daemon", "ouro-bot-entry.js")} mcp-serve --agent ${setupAgent}`
2616
+ : `ouro mcp-serve --agent ${setupAgent}`;
2617
+ if (tool === "claude-code") {
2618
+ // 1. Register MCP server with Claude Code
2619
+ const mcpAddCmd = `claude mcp add ouro-${setupAgent} -s user -- ${mcpServeCommand}`;
2620
+ (0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
2621
+ // 2. Write hooks config to ~/.claude/settings.json
2622
+ const settingsPath = path.join(os.homedir(), ".claude", "settings.json");
2623
+ let settings = {};
2624
+ if (fs.existsSync(settingsPath)) {
2625
+ try {
2626
+ settings = JSON.parse(fs.readFileSync(settingsPath, "utf-8"));
2627
+ }
2628
+ catch { /* start fresh */ }
2629
+ }
2630
+ // Use `ouro hook <event>` — resolves the right code based on dev vs installed mode.
2631
+ // Bare `ouro` works because ouro is on PATH via ~/.ouro-cli/bin/.
2632
+ settings.hooks = {
2633
+ ...(settings.hooks ?? {}),
2634
+ SessionStart: [{ hooks: [{ type: "command", command: `ouro hook session-start --agent ${setupAgent}`, timeout: 5 }] }],
2635
+ Stop: [{ hooks: [{ type: "command", command: `ouro hook stop --agent ${setupAgent}`, timeout: 5 }] }],
2636
+ PostToolUse: [{ matcher: "Bash|Edit|Write", hooks: [{ type: "command", command: `ouro hook post-tool-use --agent ${setupAgent}`, timeout: 5 }] }],
2637
+ };
2638
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true });
2639
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2));
2640
+ (0, runtime_1.emitNervesEvent)({
2641
+ component: "daemon",
2642
+ event: "daemon.setup_complete",
2643
+ message: "dev tool setup complete",
2644
+ meta: { tool, agent: setupAgent, runtimeMode },
2645
+ });
2646
+ // 3. Write conversation formatting instructions to ~/.claude/CLAUDE.md
2647
+ const claudeMdPath = path.join(os.homedir(), ".claude", "CLAUDE.md");
2648
+ const agentInstructions = `\n## Agent conversations (ouro)\nWhen using MCP \`send_message\` to talk to an ouro agent, format the exchange clearly:\n- Before the tool call, briefly say what you're asking/telling the agent\n- After the response, quote the agent's reply in a blockquote, then add your reaction\n- Example: **Me → Agent:** "question" / > **Agent:** "response" / Your synthesis here\n`;
2649
+ let existingClaudeMd = "";
2650
+ if (fs.existsSync(claudeMdPath)) {
2651
+ existingClaudeMd = fs.readFileSync(claudeMdPath, "utf-8");
2652
+ }
2653
+ if (!existingClaudeMd.includes("Agent conversations (ouro)")) {
2654
+ fs.writeFileSync(claudeMdPath, existingClaudeMd + agentInstructions);
2655
+ }
2656
+ const message = `setup complete: claude-code + ${setupAgent}\n MCP server registered\n hooks configured\n conversation formatting instructions added`;
2657
+ deps.writeStdout(message);
2658
+ return message;
2659
+ }
2660
+ else {
2661
+ // tool === "codex" (parseSetupCommand validates tool, so this is the only remaining option)
2662
+ const mcpAddCmd = `codex mcp add ouro-${setupAgent} -- ${mcpServeCommand}`;
2663
+ (0, child_process_1.execSync)(mcpAddCmd, { stdio: "pipe" });
2664
+ (0, runtime_1.emitNervesEvent)({
2665
+ component: "daemon",
2666
+ event: "daemon.setup_complete",
2667
+ message: "dev tool setup complete",
2668
+ meta: { tool, agent: setupAgent, runtimeMode },
2669
+ });
2670
+ const message = `setup complete: codex + ${setupAgent}\n MCP server registered`;
2671
+ deps.writeStdout(message);
2672
+ return message;
2673
+ }
2674
+ }
2675
+ /* v8 ignore start — mcp-serve block binds to process.stdin/stdout; tested via mcp-server unit tests */
2676
+ // ── mcp-serve: start MCP server in-process on stdin/stdout ──
2677
+ if (command.kind === "mcp-serve") {
2678
+ const { createMcpServer } = await Promise.resolve().then(() => __importStar(require("./mcp-server")));
2679
+ const friendId = command.friendId ?? `local-${os.userInfo().username}`;
2680
+ const mcpSocketPath = command.socketOverride ?? deps.socketPath;
2681
+ const server = createMcpServer({
2682
+ agent: command.agent,
2683
+ friendId,
2684
+ socketPath: mcpSocketPath,
2685
+ stdin: process.stdin,
2686
+ stdout: process.stdout,
2687
+ });
2688
+ server.start();
2689
+ (0, runtime_1.emitNervesEvent)({
2690
+ component: "daemon",
2691
+ event: "daemon.mcp_serve_started",
2692
+ message: "MCP server started via CLI",
2693
+ meta: { agent: command.agent, friendId },
2694
+ });
2695
+ // Keep process alive until stdin closes
2696
+ await new Promise((resolve) => {
2697
+ process.stdin.on("end", () => {
2698
+ server.stop();
2699
+ resolve();
2700
+ });
2701
+ });
2702
+ return "";
2703
+ }
2704
+ /* v8 ignore stop */
2705
+ // ── mcp subcommands (routed through daemon socket) ──
2706
+ if (command.kind === "mcp.list" || command.kind === "mcp.call") {
2707
+ const daemonCommand = toDaemonCommand(command);
2708
+ let response;
2709
+ try {
2710
+ response = await deps.sendCommand(deps.socketPath, daemonCommand);
2711
+ }
2712
+ catch {
2713
+ const message = "daemon unavailable — start with `ouro up` first";
2714
+ deps.writeStdout(message);
2715
+ return message;
2716
+ }
2717
+ if (!response.ok) {
2718
+ const message = response.error ?? "unknown error";
2719
+ deps.writeStdout(message);
2720
+ return message;
2721
+ }
2722
+ const message = formatMcpResponse(command, response);
2723
+ deps.writeStdout(message);
2724
+ return message;
2725
+ }
2726
+ // ── task subcommands (local, no daemon socket needed) ──
2727
+ if (command.kind === "task.board" || command.kind === "task.create" || command.kind === "task.update" ||
2728
+ command.kind === "task.show" || command.kind === "task.actionable" || command.kind === "task.deps" ||
2729
+ command.kind === "task.sessions" || command.kind === "task.fix") {
2730
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2731
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
2732
+ /* v8 ignore stop */
2733
+ const message = executeTaskCommand(command, taskMod);
995
2734
  deps.writeStdout(message);
996
2735
  return message;
997
2736
  }
2737
+ // ── reminder subcommands (local, no daemon socket needed) ──
2738
+ if (command.kind === "reminder.create") {
2739
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2740
+ const taskMod = deps.taskModule ?? (0, tasks_1.getTaskModule)();
2741
+ /* v8 ignore stop */
2742
+ const message = executeReminderCommand(command, taskMod);
2743
+ deps.writeStdout(message);
2744
+ return message;
2745
+ }
2746
+ // ── habit subcommands (local, no daemon socket needed) ──
2747
+ if (command.kind === "habit.list" || command.kind === "habit.create") {
2748
+ const { parseHabitFile, renderHabitFile } = await Promise.resolve().then(() => __importStar(require("./habit-parser")));
2749
+ /* v8 ignore start -- production default: uses real bundle root @preserve */
2750
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
2751
+ const bundleRoot = deps.agentBundleRoot ?? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
2752
+ /* v8 ignore stop */
2753
+ const habitsDir = path.join(bundleRoot, "habits");
2754
+ if (command.kind === "habit.list") {
2755
+ let files;
2756
+ try {
2757
+ files = fs.readdirSync(habitsDir).filter((f) => f.endsWith(".md") && f !== "README.md");
2758
+ }
2759
+ catch {
2760
+ const message = "no habits found";
2761
+ deps.writeStdout(message);
2762
+ return message;
2763
+ }
2764
+ if (files.length === 0) {
2765
+ const message = "no habits found";
2766
+ deps.writeStdout(message);
2767
+ return message;
2768
+ }
2769
+ const lines = [];
2770
+ for (const file of files) {
2771
+ const content = fs.readFileSync(path.join(habitsDir, file), "utf-8");
2772
+ const habit = parseHabitFile(content, path.join(habitsDir, file));
2773
+ const lastRunStr = habit.lastRun ?? "never";
2774
+ lines.push(`${habit.name} cadence=${habit.cadence ?? "none"} status=${habit.status} lastRun=${lastRunStr}`);
2775
+ }
2776
+ const message = lines.join("\n");
2777
+ deps.writeStdout(message);
2778
+ return message;
2779
+ }
2780
+ // habit.create
2781
+ const filePath = path.join(habitsDir, `${command.name}.md`);
2782
+ if (fs.existsSync(filePath)) {
2783
+ const message = `error: habit '${command.name}' already exists`;
2784
+ deps.writeStdout(message);
2785
+ return message;
2786
+ }
2787
+ fs.mkdirSync(habitsDir, { recursive: true });
2788
+ const now = new Date().toISOString();
2789
+ const content = renderHabitFile({
2790
+ title: command.name,
2791
+ cadence: command.cadence ?? "null",
2792
+ status: "active",
2793
+ lastRun: now,
2794
+ created: now,
2795
+ }, `Habit: ${command.name}`);
2796
+ fs.writeFileSync(filePath, content, "utf-8");
2797
+ const message = `created: ${filePath}`;
2798
+ deps.writeStdout(message);
2799
+ return message;
2800
+ }
2801
+ // ── friend subcommands (local, no daemon socket needed) ──
2802
+ if (command.kind === "friend.list" || command.kind === "friend.show" || command.kind === "friend.create" ||
2803
+ command.kind === "friend.update" || command.kind === "friend.link" || command.kind === "friend.unlink") {
2804
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2805
+ let store = deps.friendStore;
2806
+ if (!store) {
2807
+ // Derive agent-scoped friends dir from --agent flag or link/unlink's agent field
2808
+ const agentName = ("agent" in command && command.agent) ? command.agent : undefined;
2809
+ const friendsDir = agentName
2810
+ ? path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`, "friends")
2811
+ : path.join((0, identity_1.getAgentBundlesRoot)(), "friends");
2812
+ store = new store_file_1.FileFriendStore(friendsDir);
2813
+ }
2814
+ /* v8 ignore stop */
2815
+ const message = await executeFriendCommand(command, store);
2816
+ deps.writeStdout(message);
2817
+ return message;
2818
+ }
2819
+ // ── auth (local, no daemon socket needed) ──
2820
+ if (command.kind === "auth.run") {
2821
+ const provider = command.provider ?? (0, auth_flow_1.readAgentConfigForAgent)(command.agent).config.humanFacing.provider;
2822
+ /* v8 ignore next -- tests always inject runAuthFlow; default is for production @preserve */
2823
+ const authRunner = deps.runAuthFlow ?? auth_flow_1.runRuntimeAuthFlow;
2824
+ const result = await authRunner({
2825
+ agentName: command.agent,
2826
+ provider,
2827
+ promptInput: deps.promptInput,
2828
+ });
2829
+ // Behavior: ouro auth stores credentials only — does NOT switch provider.
2830
+ // Use `ouro auth switch` to change the active provider.
2831
+ deps.writeStdout(result.message);
2832
+ // Verify the credentials actually work by pinging the provider
2833
+ /* v8 ignore start -- integration: real API ping after auth @preserve */
2834
+ try {
2835
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2836
+ const status = await verifyProviderCredentials(provider, secrets.providers);
2837
+ deps.writeStdout(`${provider}: ${status}`);
2838
+ }
2839
+ catch {
2840
+ // Verification failure is non-blocking — credentials were saved regardless
2841
+ }
2842
+ /* v8 ignore stop */
2843
+ return result.message;
2844
+ }
2845
+ // ── auth verify (local, no daemon socket needed) ──
2846
+ /* v8 ignore start -- auth verify/switch: tested in daemon-cli.test.ts but v8 traces differ in CI @preserve */
2847
+ if (command.kind === "auth.verify") {
2848
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2849
+ const providers = secrets.providers;
2850
+ if (command.provider) {
2851
+ const status = await verifyProviderCredentials(command.provider, providers);
2852
+ const message = `${command.provider}: ${status}`;
2853
+ deps.writeStdout(message);
2854
+ return message;
2855
+ }
2856
+ const lines = [];
2857
+ for (const p of Object.keys(providers)) {
2858
+ const status = await verifyProviderCredentials(p, providers);
2859
+ lines.push(`${p}: ${status}`);
2860
+ }
2861
+ const message = lines.join("\n");
2862
+ deps.writeStdout(message);
2863
+ return message;
2864
+ }
2865
+ // ── auth switch (local, no daemon socket needed) ──
2866
+ if (command.kind === "auth.switch") {
2867
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2868
+ const providerSecrets = secrets.providers[command.provider];
2869
+ if (!providerSecrets || !hasStoredCredentials(command.provider, providerSecrets)) {
2870
+ const message = `no credentials stored for ${command.provider}. Run \`ouro auth --agent ${command.agent} --provider ${command.provider}\` first.`;
2871
+ deps.writeStdout(message);
2872
+ return message;
2873
+ }
2874
+ // Verify credentials actually work before switching
2875
+ const status = await verifyProviderCredentials(command.provider, secrets.providers);
2876
+ if (!status.startsWith("ok")) {
2877
+ const message = `${command.provider}: ${status}. fix credentials with \`ouro auth --agent ${command.agent} --provider ${command.provider}\` before switching.`;
2878
+ deps.writeStdout(message);
2879
+ return message;
2880
+ }
2881
+ if (command.facing) {
2882
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, command.facing, command.provider);
2883
+ }
2884
+ else {
2885
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, "human", command.provider);
2886
+ (0, auth_flow_1.writeAgentProviderSelection)(command.agent, "agent", command.provider);
2887
+ }
2888
+ const message = `switched ${command.agent} to ${command.provider} (verified working)`;
2889
+ deps.writeStdout(message);
2890
+ return message;
2891
+ }
2892
+ /* v8 ignore stop */
2893
+ // ── config models (local, no daemon socket needed) ──
2894
+ /* v8 ignore start -- config models: tested via daemon-cli.test.ts @preserve */
2895
+ if (command.kind === "config.models") {
2896
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2897
+ const provider = config.humanFacing.provider;
2898
+ if (provider !== "github-copilot") {
2899
+ const message = `model listing not available for ${provider} — check provider documentation.`;
2900
+ deps.writeStdout(message);
2901
+ return message;
2902
+ }
2903
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2904
+ const ghConfig = secrets.providers["github-copilot"];
2905
+ if (!ghConfig.githubToken || !ghConfig.baseUrl) {
2906
+ throw new Error(`github-copilot credentials not configured. Run \`ouro auth --agent ${command.agent} --provider github-copilot\` first.`);
2907
+ }
2908
+ const fetchFn = deps.fetchImpl ?? fetch;
2909
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2910
+ if (models.length === 0) {
2911
+ const message = "no models found";
2912
+ deps.writeStdout(message);
2913
+ return message;
2914
+ }
2915
+ const lines = ["available models:"];
2916
+ for (const m of models) {
2917
+ const caps = m.capabilities?.length ? ` (${m.capabilities.join(", ")})` : "";
2918
+ lines.push(` ${m.id}${caps}`);
2919
+ }
2920
+ const message = lines.join("\n");
2921
+ deps.writeStdout(message);
2922
+ return message;
2923
+ }
2924
+ /* v8 ignore stop */
2925
+ // ── config model (local, no daemon socket needed) ──
2926
+ /* v8 ignore start -- config model: tested via daemon-cli.test.ts @preserve */
2927
+ if (command.kind === "config.model") {
2928
+ const facing = command.facing ?? "human";
2929
+ // Validate model availability for github-copilot before writing
2930
+ const { config } = (0, auth_flow_1.readAgentConfigForAgent)(command.agent);
2931
+ const facingConfig = facing === "human" ? config.humanFacing : config.agentFacing;
2932
+ if (facingConfig.provider === "github-copilot") {
2933
+ const { secrets } = (0, auth_flow_1.loadAgentSecrets)(command.agent);
2934
+ const ghConfig = secrets.providers["github-copilot"];
2935
+ if (ghConfig.githubToken && ghConfig.baseUrl) {
2936
+ const fetchFn = deps.fetchImpl ?? fetch;
2937
+ try {
2938
+ const models = await listGithubCopilotModels(ghConfig.baseUrl, ghConfig.githubToken, fetchFn);
2939
+ const available = models.map((m) => m.id);
2940
+ if (available.length > 0 && !available.includes(command.modelName)) {
2941
+ const message = `model '${command.modelName}' not found. available models:\n${available.map((id) => ` ${id}`).join("\n")}`;
2942
+ deps.writeStdout(message);
2943
+ return message;
2944
+ }
2945
+ }
2946
+ catch {
2947
+ // Catalog validation failed — fall through to ping test
2948
+ }
2949
+ // Ping test: verify the model actually works before switching
2950
+ const pingResult = await pingGithubCopilotModel(ghConfig.baseUrl, ghConfig.githubToken, command.modelName, fetchFn);
2951
+ if (!pingResult.ok) {
2952
+ const message = `model '${command.modelName}' ping failed: ${pingResult.error}\nrun \`ouro config models --agent ${command.agent}\` to see available models.`;
2953
+ deps.writeStdout(message);
2954
+ return message;
2955
+ }
2956
+ }
2957
+ }
2958
+ const { provider, previousModel } = (0, auth_flow_1.writeAgentModel)(command.agent, facing, command.modelName);
2959
+ const message = previousModel
2960
+ ? `updated ${command.agent} model on ${provider}: ${previousModel} → ${command.modelName}`
2961
+ : `set ${command.agent} model on ${provider}: ${command.modelName}`;
2962
+ deps.writeStdout(message);
2963
+ return message;
2964
+ }
2965
+ /* v8 ignore stop */
2966
+ // ── whoami (local, no daemon socket needed) ──
2967
+ if (command.kind === "whoami") {
2968
+ if (command.agent) {
2969
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${command.agent}.ouro`);
2970
+ const message = [
2971
+ `agent: ${command.agent}`,
2972
+ `home: ${agentRoot}`,
2973
+ `bones: ${(0, runtime_metadata_1.getRuntimeMetadata)().version}`,
2974
+ ].join("\n");
2975
+ deps.writeStdout(message);
2976
+ return message;
2977
+ }
2978
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
2979
+ try {
2980
+ const info = deps.whoamiInfo
2981
+ ? deps.whoamiInfo()
2982
+ : {
2983
+ agentName: (0, identity_1.getAgentName)(),
2984
+ homePath: path.join((0, identity_1.getAgentBundlesRoot)(), `${(0, identity_1.getAgentName)()}.ouro`),
2985
+ bonesVersion: (0, runtime_metadata_1.getRuntimeMetadata)().version,
2986
+ };
2987
+ const message = [
2988
+ `agent: ${info.agentName}`,
2989
+ `home: ${info.homePath}`,
2990
+ `bones: ${info.bonesVersion}`,
2991
+ ].join("\n");
2992
+ deps.writeStdout(message);
2993
+ return message;
2994
+ }
2995
+ catch {
2996
+ const message = "error: no agent context — use --agent <name> to specify";
2997
+ deps.writeStdout(message);
2998
+ return message;
2999
+ }
3000
+ /* v8 ignore stop */
3001
+ }
3002
+ // ── changelog (local, no daemon socket needed) ──
3003
+ if (command.kind === "changelog") {
3004
+ try {
3005
+ const changelogPath = deps.getChangelogPath
3006
+ ? deps.getChangelogPath()
3007
+ : (0, bundle_manifest_1.getChangelogPath)();
3008
+ const raw = fs.readFileSync(changelogPath, "utf-8");
3009
+ const parsed = JSON.parse(raw);
3010
+ const entries = Array.isArray(parsed) ? parsed : (parsed.versions ?? []);
3011
+ let filtered = entries;
3012
+ if (command.from) {
3013
+ const fromVersion = command.from;
3014
+ filtered = entries.filter((e) => semver.valid(e.version) && semver.gt(e.version, fromVersion));
3015
+ }
3016
+ if (filtered.length === 0) {
3017
+ const message = "no changelog entries found.";
3018
+ deps.writeStdout(message);
3019
+ return message;
3020
+ }
3021
+ const lines = [];
3022
+ for (const entry of filtered) {
3023
+ lines.push(`## ${entry.version}${entry.date ? ` (${entry.date})` : ""}`);
3024
+ if (entry.changes) {
3025
+ for (const change of entry.changes) {
3026
+ lines.push(`- ${change}`);
3027
+ }
3028
+ }
3029
+ lines.push("");
3030
+ }
3031
+ const message = lines.join("\n").trim();
3032
+ deps.writeStdout(message);
3033
+ return message;
3034
+ }
3035
+ catch {
3036
+ const message = "no changelog entries found.";
3037
+ deps.writeStdout(message);
3038
+ return message;
3039
+ }
3040
+ }
3041
+ // ── thoughts (local, no daemon socket needed) ──
3042
+ if (command.kind === "thoughts") {
3043
+ try {
3044
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3045
+ const agentRoot = path.join((0, identity_1.getAgentBundlesRoot)(), `${agentName}.ouro`);
3046
+ const sessionFilePath = (0, thoughts_1.getInnerDialogSessionPath)(agentRoot);
3047
+ if (command.json) {
3048
+ try {
3049
+ const raw = fs.readFileSync(sessionFilePath, "utf-8");
3050
+ deps.writeStdout(raw);
3051
+ return raw;
3052
+ }
3053
+ catch {
3054
+ const message = "no inner dialog session found";
3055
+ deps.writeStdout(message);
3056
+ return message;
3057
+ }
3058
+ }
3059
+ const turns = (0, thoughts_1.parseInnerDialogSession)(sessionFilePath);
3060
+ const message = (0, thoughts_1.formatThoughtTurns)(turns, command.last ?? 10);
3061
+ deps.writeStdout(message);
3062
+ if (command.follow) {
3063
+ deps.writeStdout("\n\n--- following (ctrl+c to stop) ---\n");
3064
+ /* v8 ignore start -- callback tested via followThoughts unit tests @preserve */
3065
+ const stop = (0, thoughts_1.followThoughts)(sessionFilePath, (formatted) => {
3066
+ deps.writeStdout("\n" + formatted);
3067
+ });
3068
+ /* v8 ignore stop */
3069
+ // Block until process exit; cleanup watcher on SIGINT/SIGTERM
3070
+ return new Promise((resolve) => {
3071
+ const cleanup = () => { stop(); resolve(message); };
3072
+ process.once("SIGINT", cleanup);
3073
+ process.once("SIGTERM", cleanup);
3074
+ });
3075
+ }
3076
+ return message;
3077
+ }
3078
+ catch {
3079
+ const message = "error: no agent context — use --agent <name> to specify";
3080
+ deps.writeStdout(message);
3081
+ return message;
3082
+ }
3083
+ }
3084
+ // ── attention queue (local, no daemon socket needed) ──
3085
+ /* v8 ignore start -- CLI attention handler: requires real obligation store on disk @preserve */
3086
+ if (command.kind === "attention.list" || command.kind === "attention.show" || command.kind === "attention.history") {
3087
+ try {
3088
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3089
+ const { listActiveObligations, readObligation } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3090
+ if (command.kind === "attention.list") {
3091
+ const obligations = listActiveObligations(agentName);
3092
+ if (obligations.length === 0) {
3093
+ const message = "nothing held — attention queue is empty";
3094
+ deps.writeStdout(message);
3095
+ return message;
3096
+ }
3097
+ const lines = obligations.map((o) => `[${o.id}] ${o.origin.friendId} via ${o.origin.channel}/${o.origin.key} — ${o.delegatedContent.slice(0, 60)}${o.delegatedContent.length > 60 ? "..." : ""} (${o.status})`);
3098
+ const message = lines.join("\n");
3099
+ deps.writeStdout(message);
3100
+ return message;
3101
+ }
3102
+ if (command.kind === "attention.show") {
3103
+ const obligation = readObligation(agentName, command.id);
3104
+ if (!obligation) {
3105
+ const message = `no obligation found with id ${command.id}`;
3106
+ deps.writeStdout(message);
3107
+ return message;
3108
+ }
3109
+ const message = JSON.stringify(obligation, null, 2);
3110
+ deps.writeStdout(message);
3111
+ return message;
3112
+ }
3113
+ // attention.history: show returned obligations
3114
+ const { getObligationsDir } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3115
+ const obligationsDir = getObligationsDir(agentName);
3116
+ let entries = [];
3117
+ try {
3118
+ entries = fs.readdirSync(obligationsDir);
3119
+ }
3120
+ catch { /* empty */ }
3121
+ const returned = entries
3122
+ .filter((e) => e.endsWith(".json"))
3123
+ .map((e) => { try {
3124
+ return JSON.parse(fs.readFileSync(path.join(obligationsDir, e), "utf-8"));
3125
+ }
3126
+ catch {
3127
+ return null;
3128
+ } })
3129
+ .filter((o) => o?.status === "returned")
3130
+ .sort((a, b) => (b.returnedAt ?? 0) - (a.returnedAt ?? 0))
3131
+ .slice(0, 20);
3132
+ if (returned.length === 0) {
3133
+ const message = "no surfacing history yet";
3134
+ deps.writeStdout(message);
3135
+ return message;
3136
+ }
3137
+ const lines = returned.map((o) => {
3138
+ const when = o.returnedAt ? new Date(o.returnedAt).toISOString() : "unknown";
3139
+ return `[${o.id}] → ${o.origin.friendId} via ${o.returnTarget ?? "unknown"} at ${when}`;
3140
+ });
3141
+ const message = lines.join("\n");
3142
+ deps.writeStdout(message);
3143
+ return message;
3144
+ }
3145
+ catch {
3146
+ const message = "error: no agent context — use --agent <name> to specify";
3147
+ deps.writeStdout(message);
3148
+ return message;
3149
+ }
3150
+ }
3151
+ /* v8 ignore stop */
3152
+ // ── inner dialog status (local, no daemon socket needed) ──
3153
+ /* v8 ignore start -- inner status handler: requires real agent state on disk @preserve */
3154
+ if (command.kind === "inner.status") {
3155
+ try {
3156
+ const agentName = command.agent ?? (0, identity_1.getAgentName)();
3157
+ const agentRoot = (0, identity_1.getAgentRoot)(agentName);
3158
+ const { buildInnerStatusOutput } = await Promise.resolve().then(() => __importStar(require("./inner-status")));
3159
+ const { sessionPath: getSessionPath } = await Promise.resolve().then(() => __importStar(require("../config")));
3160
+ const { parseCadenceToMs: parseCadenceMs, DEFAULT_CADENCE_MS } = await Promise.resolve().then(() => __importStar(require("./cadence")));
3161
+ const { parseFrontmatter } = await Promise.resolve().then(() => __importStar(require("../../repertoire/tasks/parser")));
3162
+ const { listActiveObligations } = await Promise.resolve().then(() => __importStar(require("../../mind/obligations")));
3163
+ // Read runtime state
3164
+ const innerSessionPath = getSessionPath("inner-dialog", "inner", "session");
3165
+ const runtimeJsonPath = path.join(path.dirname(innerSessionPath), "runtime.json");
3166
+ let runtimeState = null;
3167
+ try {
3168
+ const raw = fs.readFileSync(runtimeJsonPath, "utf-8");
3169
+ runtimeState = JSON.parse(raw);
3170
+ }
3171
+ catch { /* missing or corrupt — will show "unknown" */ }
3172
+ // Read journal files
3173
+ const journalDir = path.join(agentRoot, "journal");
3174
+ let journalFiles = [];
3175
+ try {
3176
+ const entries = fs.readdirSync(journalDir, { withFileTypes: true });
3177
+ journalFiles = entries
3178
+ .filter((e) => e.isFile() && !e.name.startsWith("."))
3179
+ .map((e) => {
3180
+ const stat = fs.statSync(path.join(journalDir, e.name));
3181
+ return { name: e.name, mtimeMs: stat.mtimeMs };
3182
+ });
3183
+ }
3184
+ catch { /* missing dir — will show (empty) */ }
3185
+ // Read heartbeat cadence
3186
+ let heartbeat = null;
3187
+ try {
3188
+ const habitsDir = path.join(agentRoot, "habits");
3189
+ const heartbeatPath = path.join(habitsDir, "heartbeat.md");
3190
+ let cadenceMs = DEFAULT_CADENCE_MS;
3191
+ if (fs.existsSync(heartbeatPath)) {
3192
+ const content = fs.readFileSync(heartbeatPath, "utf-8");
3193
+ const lines = content.split(/\r?\n/);
3194
+ if (lines[0]?.trim() === "---") {
3195
+ const closing = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
3196
+ if (closing !== -1) {
3197
+ const rawFrontmatter = lines.slice(1, closing).join("\n");
3198
+ const frontmatter = parseFrontmatter(rawFrontmatter);
3199
+ const parsed = parseCadenceMs(frontmatter.cadence);
3200
+ if (parsed !== null)
3201
+ cadenceMs = parsed;
3202
+ }
3203
+ }
3204
+ }
3205
+ let lastCompletedAt = null;
3206
+ if (runtimeState?.lastCompletedAt) {
3207
+ const ms = new Date(runtimeState.lastCompletedAt).getTime();
3208
+ if (!Number.isNaN(ms))
3209
+ lastCompletedAt = ms;
3210
+ }
3211
+ heartbeat = { cadenceMs, lastCompletedAt };
3212
+ }
3213
+ catch { /* no habits — heartbeat unknown */ }
3214
+ // Attention count
3215
+ const activeObligations = listActiveObligations(agentName);
3216
+ const message = buildInnerStatusOutput({
3217
+ agentName,
3218
+ runtimeState,
3219
+ journalFiles,
3220
+ heartbeat,
3221
+ attentionCount: activeObligations.length,
3222
+ now: Date.now(),
3223
+ });
3224
+ deps.writeStdout(message);
3225
+ return message;
3226
+ }
3227
+ catch {
3228
+ const message = "error: no agent context — use --agent <name> to specify";
3229
+ deps.writeStdout(message);
3230
+ return message;
3231
+ }
3232
+ }
3233
+ /* v8 ignore stop */
3234
+ // ── session list (local, no daemon socket needed) ──
3235
+ if (command.kind === "session.list") {
3236
+ /* v8 ignore start -- production default: requires full identity setup @preserve */
3237
+ const scanner = deps.scanSessions ?? (async () => []);
3238
+ /* v8 ignore stop */
3239
+ const sessions = await scanner();
3240
+ if (sessions.length === 0) {
3241
+ const message = "no active sessions";
3242
+ deps.writeStdout(message);
3243
+ return message;
3244
+ }
3245
+ const lines = sessions.map((s) => `${s.friendId} ${s.friendName} ${s.channel} ${s.lastActivity}`);
3246
+ const message = lines.join("\n");
3247
+ deps.writeStdout(message);
3248
+ return message;
3249
+ }
3250
+ if (command.kind === "chat.connect" && deps.startChat) {
3251
+ await ensureDaemonRunning(deps);
3252
+ await deps.startChat(command.agent);
3253
+ return "";
3254
+ }
998
3255
  if (command.kind === "hatch.start") {
999
3256
  // Route through adoption specialist when no explicit hatch args were provided
1000
3257
  const hasExplicitHatchArgs = !!(command.agentName || command.humanName || command.provider || command.credentials);
@@ -1042,6 +3299,16 @@ async function runOuroCli(args, deps = createDefaultOuroCliDeps()) {
1042
3299
  deps.writeStdout(message);
1043
3300
  return message;
1044
3301
  }
3302
+ if (command.kind === "daemon.status" && isDaemonUnavailableError(error)) {
3303
+ const message = daemonUnavailableStatusOutput(deps.socketPath, deps.healthFilePath);
3304
+ deps.writeStdout(message);
3305
+ return message;
3306
+ }
3307
+ if (command.kind === "daemon.stop" && isDaemonUnavailableError(error)) {
3308
+ const message = "daemon not running";
3309
+ deps.writeStdout(message);
3310
+ return message;
3311
+ }
1045
3312
  throw error;
1046
3313
  }
1047
3314
  const fallbackMessage = response.summary ?? response.message ?? (response.ok ? "ok" : `error: ${response.error ?? "unknown error"}`);