@ouro.bot/cli 0.1.0-alpha.1586 → 0.1.0-alpha.1588

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.
package/changelog.json CHANGED
@@ -1,13 +1,33 @@
1
1
  {
2
2
  "_note": "Each pull request writes its own change note under changes/; the release job on main gives each landed change its version and adds the notes here (scripts/release-version.cjs). On main this file stops at the last version set by hand; the published package has every release. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1588",
6
+ "changes": [
7
+ "Test-only: the Telegram approval lifecycle \"A006 terminalizes …\" cases now track phases (fixture, propose, mutate, callback, verification, cleanup). Cases that finish under 4s print nothing; a failure gets the phase report appended to its error; a case still running at 4s prints the completed timings and the latest observed phase once to stderr (even if it later passes), with actual elapsed time. This is a sample, not proof of which phase a 5s timeout interrupted. Assertions and the 5s limit are unchanged."
8
+ ]
9
+ },
10
+ {
11
+ "version": "0.1.0-alpha.1587",
12
+ "changes": [
13
+ "iMessages sent while BlueBubbles or the Mac was down now reach the agent after recovery. iMessage delivers the messages it held minutes after BlueBubbles answers again, dated when they were sent, and BlueBubbles sends no webhook for them, so one catch-up at the moment of recovery missed them. For 30 minutes after an outage every catch-up now keeps reaching back 24 hours, even when the recovery pass itself is cut short by a restart, and outage catch-ups are logged.",
14
+ "A habit whose run was lost before it finished (a crash or restart mid-run) no longer stops for good. Every later firing reused the lost run's occurrence and was refused as its duplicate, which stopped Slugger's heartbeat for 14 hours. A habit a whole interval past due now gets a new occurrence, and the overdue habit and each refused duplicate are logged as warnings.",
15
+ "launchd now runs interval habits on schedule. The scheduler reloaded every habit's launch agent on its 5-minute pass, which restarted the launch agent's 30-minute clock each time, so launchd never ran the heartbeat. A loaded launch agent whose plist has not changed is now left alone, and a launchd or cron firing for a habit that already ran within its cadence is skipped, so one interval never runs it twice.",
16
+ "Self-update no longer rolls back a release because one sense is down. `ouro up` refuses to finish while any sense is unhealthy, so a BlueBubbles outage rolled back and blacklisted every release that arrived during it. `ouro up` now exits with code 3 when only that health check refused. The updater accepts such a release only when the daemon answers on it with its health checks reported and its workers listed, and everything still wrong was already wrong, at the same severity, before the update. Any other `ouro up` failure still rolls back, and a failed `ouro up` reports its reason instead of an empty one."
17
+ ]
18
+ },
4
19
  {
5
20
  "version": "0.1.0-alpha.1586",
6
21
  "changes": [
7
- "Update the Ouro UI files to Ouro UI v1.3.569.",
8
22
  "Update the Ouro UI files to Ouro UI v1.3.570."
9
23
  ]
10
24
  },
25
+ {
26
+ "version": "0.1.0-alpha.1585",
27
+ "changes": [
28
+ "Update the Ouro UI files to Ouro UI v1.3.569."
29
+ ]
30
+ },
11
31
  {
12
32
  "version": "0.1.0-alpha.1584",
13
33
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1586",
2
+ "runtimeVersion": "0.1.0-alpha.1588",
3
3
  "bundleSchemaVersion": 3,
4
4
  "lastUpdated": "2026-09-03T00:00:00.000Z"
5
5
  }
@@ -1,7 +1,7 @@
1
1
  <?xml version="1.0"?>
2
2
  <Container version="2">
3
3
  <Name>ouro-butler</Name>
4
- <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1586</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1588</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -5,6 +5,7 @@ exports.parseCadenceToCron = parseCadenceToCron;
5
5
  exports.parseCadenceToMs = parseCadenceToMs;
6
6
  exports.nextCadenceRunAt = nextCadenceRunAt;
7
7
  exports.cadenceFallbackDelayMs = cadenceFallbackDelayMs;
8
+ exports.cadenceRetrySuffix = cadenceRetrySuffix;
8
9
  exports.evaluateCadenceDue = evaluateCadenceDue;
9
10
  const runtime_1 = require("../../nerves/runtime");
10
11
  exports.DEFAULT_CADENCE_MS = 30 * 60 * 1000; // 30 minutes
@@ -145,6 +146,23 @@ function cadenceFallbackDelayMs(raw, nowMs) {
145
146
  const delay = Date.parse(nextRunAt) - nowMs;
146
147
  return delay;
147
148
  }
149
+ /**
150
+ * The suffix that moves an interval habit to a new occurrence once a whole interval has passed since it fell due.
151
+ * A run that is lost before it records `lastRun` (the daemon restarts, the Mac crashes) leaves `lastRun` where it was,
152
+ * so an occurrence keyed only on `lastRun` is the one the lost run already spent, and every later firing is refused as
153
+ * its duplicate. The heartbeat stopped this way for 14 hours on 2026-11-25. Firings within one interval still share
154
+ * an occurrence, so the 5-minute reconcile cannot start a run per pass.
155
+ */
156
+ function cadenceRetrySuffix(raw, lastRun, nowMs) {
157
+ const intervalMs = parseCadenceToMs(raw);
158
+ if (intervalMs === null || lastRun === null)
159
+ return "";
160
+ const lastRunMs = Date.parse(lastRun);
161
+ if (!Number.isFinite(lastRunMs))
162
+ return "";
163
+ const missedIntervals = Math.floor((nowMs - lastRunMs) / intervalMs) - 1;
164
+ return missedIntervals >= 1 ? `:retry:${missedIntervals}` : "";
165
+ }
148
166
  function evaluateCadenceDue(raw, lastRun, nowMs) {
149
167
  const intervalMs = parseCadenceToMs(raw);
150
168
  if (intervalMs !== null) {
@@ -158,7 +176,9 @@ function evaluateCadenceDue(raw, lastRun, nowMs) {
158
176
  return {
159
177
  due: elapsedMs >= intervalMs,
160
178
  elapsedMs,
161
- occurrenceId: elapsedMs >= intervalMs ? `overdue:last-run:${lastRun}:cadence:${String(raw).trim()}` : null,
179
+ occurrenceId: elapsedMs >= intervalMs
180
+ ? `overdue:last-run:${lastRun}:cadence:${String(raw).trim()}${cadenceRetrySuffix(raw, lastRun, nowMs)}`
181
+ : null,
162
182
  };
163
183
  }
164
184
  const fixed = parseFixedDailyCron(raw);
@@ -57,6 +57,7 @@ exports.resolveFrontendFriendId = resolveFrontendFriendId;
57
57
  exports.setupBlueBubblesHostForConnect = setupBlueBubblesHostForConnect;
58
58
  exports.resolveMailImportFilePath = resolveMailImportFilePath;
59
59
  exports.runOuroCli = runOuroCli;
60
+ const handoff_blockers_1 = require("./handoff-blockers");
60
61
  const child_process_1 = require("child_process");
61
62
  const bluebubbles_host_account_1 = require("../bluebubbles-host-account");
62
63
  const sanctuary_bundle_migration_1 = require("./sanctuary-bundle-migration");
@@ -864,32 +865,6 @@ function finalDaemonFailureMessage(deps, reason) {
864
865
  lines.push("Run `ouro up` again or `ouro doctor` for a deeper diagnosis.");
865
866
  return lines.join("\n");
866
867
  }
867
- function finalHandoffBlockingHealthChecks(payload) {
868
- return payload.healthChecks
869
- .filter((check) => {
870
- if (check.status === "ok")
871
- return false;
872
- if (check.status === "critical")
873
- return true;
874
- return check.name === "agent-processes"
875
- || check.name === "cron-health"
876
- || check.name === "sense-probes"
877
- || check.name.startsWith("sense-probe:");
878
- })
879
- .map((check) => `${check.name}: ${check.status} - ${check.message}`);
880
- }
881
- function finalHandoffBlockingWorkers(payload) {
882
- return payload.workers
883
- .filter((worker) => !(worker.autoStart === false && worker.status === "stopped") && worker.status !== "running")
884
- .map((worker) => {
885
- const detail = [
886
- worker.errorReason,
887
- worker.fixHint ? `fix: ${worker.fixHint}` : null,
888
- ].filter((part) => part !== null).join("; ");
889
- const suffix = detail.length > 0 ? ` - ${detail}` : "";
890
- return `${worker.agent}/${worker.worker}: ${worker.status}${suffix}`;
891
- });
892
- }
893
868
  async function verifyDaemonReadyForHandoff(deps, options) {
894
869
  const settleTimeoutMs = options.settleTimeoutMs;
895
870
  const settlePollIntervalMs = options.settlePollIntervalMs;
@@ -947,12 +922,7 @@ async function verifyDaemonReadyForHandoffOnce(deps, options = {}) {
947
922
  };
948
923
  }
949
924
  if (payload.overview.health !== "ok") {
950
- const blockingWorkers = finalHandoffBlockingWorkers(payload);
951
- const degradedSenses = payload.senses
952
- .filter((sense) => sense.enabled && !["running", "interactive", "disabled", "not_attached"].includes(sense.status))
953
- .map((sense) => `${sense.agent}/${sense.sense}: ${sense.status} - ${sense.detail}`);
954
- const blockingHealthChecks = finalHandoffBlockingHealthChecks(payload);
955
- const details = [...blockingWorkers, ...degradedSenses, ...blockingHealthChecks];
925
+ const details = (0, handoff_blockers_1.finalHandoffBlockers)(payload).map((blocker) => blocker.text);
956
926
  const detail = details.length > 0 ? `; ${details.join("; ")}` : "";
957
927
  if (options.allowDegradedHealth) {
958
928
  return {
@@ -960,7 +930,7 @@ async function verifyDaemonReadyForHandoffOnce(deps, options = {}) {
960
930
  summary: `runtime health ${payload.overview.health}`,
961
931
  };
962
932
  }
963
- if (blockingWorkers.length === 0 && degradedSenses.length === 0 && blockingHealthChecks.length === 0) {
933
+ if (details.length === 0) {
964
934
  return {
965
935
  ok: true,
966
936
  summary: "daemon answered with advisory health warnings",
@@ -973,6 +943,7 @@ async function verifyDaemonReadyForHandoffOnce(deps, options = {}) {
973
943
  message: finalDaemonFailureMessage(deps, reason),
974
944
  retryable: true,
975
945
  reason,
946
+ healthRefusal: true,
976
947
  };
977
948
  }
978
949
  const workerCount = payload.workers.length;
@@ -7590,7 +7561,8 @@ async function runOuroCli(args, deps = (0, cli_defaults_1.createDefaultOuroCliDe
7590
7561
  progress.failPhase?.("final daemon check", finalDaemonCheck.summary);
7591
7562
  progress.end();
7592
7563
  const message = finalDaemonCheck.message ?? "background service stopped before boot finished";
7593
- return returnCliFailure(deps, message);
7564
+ // A distinct exit code lets the self-updater tell a health refusal from up itself failing.
7565
+ return returnCliFailure(deps, message, finalDaemonCheck.healthRefusal ? handoff_blockers_1.HANDOFF_HEALTH_REFUSED_EXIT_CODE : 1);
7594
7566
  }
7595
7567
  progress.completePhase("final daemon check", finalDaemonCheck.summary);
7596
7568
  progress.end();
@@ -84,6 +84,7 @@ const turn_execution_lease_1 = require("../turn-execution-lease");
84
84
  const frontend_session_service_1 = require("../frontend-session-service");
85
85
  const frontend_socket_1 = require("../frontend-socket");
86
86
  const frontend_journal_1 = require("../frontend-journal");
87
+ const cadence_1 = require("./cadence");
87
88
  const PIDFILE_PATH = path.join(os.homedir(), ".ouro-cli", "daemon.pids");
88
89
  /**
89
90
  * Defense-in-depth: detect if we're running under vitest. The pidfile lives
@@ -1461,10 +1462,17 @@ class OuroDaemon {
1461
1462
  if (habit.lastRun === null) {
1462
1463
  return { kind: "ready", habit, occurrenceId: `${options.trigger}:first-run:${habit.cadence}` };
1463
1464
  }
1465
+ const nowMs = Date.now();
1466
+ // The idempotency key carries the trigger, so a launchd fire minutes after the overdue sweep ran the habit
1467
+ // would get a fresh key and run it twice in one interval. Only a due habit runs from a timer.
1468
+ const dueState = (0, cadence_1.evaluateCadenceDue)(habit.cadence, habit.lastRun, nowMs);
1469
+ if (dueState !== null && !dueState.due) {
1470
+ return { kind: "skipped", habit, skipReason: `habit not due yet: last ran ${habit.lastRun}, cadence ${habit.cadence}` };
1471
+ }
1464
1472
  return {
1465
1473
  kind: "ready",
1466
1474
  habit,
1467
- occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}`,
1475
+ occurrenceId: `${options.trigger}:last-run:${habit.lastRun}:cadence:${habit.cadence}${(0, cadence_1.cadenceRetrySuffix)(habit.cadence, habit.lastRun, nowMs)}`,
1468
1476
  };
1469
1477
  }
1470
1478
  emitHabitDispatchSkipped(options) {
@@ -1904,6 +1912,23 @@ class OuroDaemon {
1904
1912
  ...this.privateRuntimePolicyDeps,
1905
1913
  });
1906
1914
  if (!decision.executable) {
1915
+ const habitWake = (0, habit_private_wake_1.habitMessageFromPrivateWakeCommand)(command);
1916
+ if (habitWake && decision.duplicateOf) {
1917
+ // Quiet duplicates are how a lost run hid a stopped heartbeat for 14 hours; say so where logs keep it.
1918
+ (0, runtime_1.emitNervesEvent)({
1919
+ level: "warn",
1920
+ component: "daemon",
1921
+ event: "daemon.habit_wake_duplicate_suppressed",
1922
+ message: "habit wake refused as a duplicate of an earlier run of the same occurrence",
1923
+ meta: {
1924
+ agent: command.agent,
1925
+ habitName: habitWake.habitName,
1926
+ trigger: habitWake.trigger,
1927
+ idempotencyKey: decision.idempotencyKey,
1928
+ duplicateOf: decision.duplicateOf,
1929
+ },
1930
+ });
1931
+ }
1907
1932
  return {
1908
1933
  ok: true,
1909
1934
  message: `private-runtime wake denied for ${command.agent}: ${decision.deniedReason}`,
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HANDOFF_HEALTH_REFUSED_EXIT_CODE = void 0;
4
+ exports.finalHandoffBlockers = finalHandoffBlockers;
5
+ exports.handoffSnapshot = handoffSnapshot;
6
+ exports.unsettledReason = unsettledReason;
7
+ exports.judgeRestartAfterUpFailure = judgeRestartAfterUpFailure;
8
+ const runtime_1 = require("../../nerves/runtime");
9
+ /** Everything `ouro up`'s final daemon check refuses on, in the order it reports them: workers, senses, health checks. */
10
+ /**
11
+ * The exit code `ouro up` uses when it refuses to hand off only because the final daemon check found the daemon's
12
+ * health blocked. Every other failure (a migration, a provider step, a crash, a timeout) keeps exit code 1, so the
13
+ * self-updater can tell "the daemon came up but something is unhealthy" from "up itself failed".
14
+ */
15
+ exports.HANDOFF_HEALTH_REFUSED_EXIT_CODE = 3;
16
+ /** Summary checks roll several problems into one row, so a new failure can hide behind an old warning by name alone. */
17
+ const SUMMARY_HEALTH_CHECKS = new Set(["agent-processes", "cron-health", "sense-probes"]);
18
+ /** Everything `ouro up`'s final daemon check refuses on, in the order it reports them: workers, senses, health checks. */
19
+ function finalHandoffBlockers(payload) {
20
+ const workers = payload.workers
21
+ .filter((worker) => !(worker.autoStart === false && worker.status === "stopped") && worker.status !== "running")
22
+ .map((worker) => {
23
+ const detail = [
24
+ worker.errorReason,
25
+ worker.fixHint ? `fix: ${worker.fixHint}` : null,
26
+ ].filter((part) => part !== null).join("; ");
27
+ const suffix = detail.length > 0 ? ` - ${detail}` : "";
28
+ const name = `${worker.agent}/${worker.worker}`;
29
+ return { key: `${name}:${worker.status}`, text: `${name}: ${worker.status}${suffix}` };
30
+ });
31
+ const senses = payload.senses
32
+ .filter((sense) => sense.enabled && !["running", "interactive", "disabled", "not_attached"].includes(sense.status))
33
+ .map((sense) => {
34
+ const name = `${sense.agent}/${sense.sense}`;
35
+ return { key: `${name}:${sense.status}`, text: `${name}: ${sense.status} - ${sense.detail}` };
36
+ });
37
+ const healthChecks = payload.healthChecks
38
+ .filter((check) => {
39
+ if (check.status === "ok")
40
+ return false;
41
+ if (check.status === "critical")
42
+ return true;
43
+ return SUMMARY_HEALTH_CHECKS.has(check.name) || check.name.startsWith("sense-probe:");
44
+ })
45
+ .map((check) => ({
46
+ // Severity always counts; a summary row's message counts too, since it says which problems it rolls up.
47
+ key: SUMMARY_HEALTH_CHECKS.has(check.name)
48
+ ? `${check.name}:${check.status}:${check.message}`
49
+ : `${check.name}:${check.status}`,
50
+ text: `${check.name}: ${check.status} - ${check.message}`,
51
+ }));
52
+ return [...workers, ...senses, ...healthChecks];
53
+ }
54
+ function handoffSnapshot(payload) {
55
+ return {
56
+ blockers: finalHandoffBlockers(payload),
57
+ workers: payload.workers.map((worker) => `${worker.agent}/${worker.worker}`),
58
+ healthCheckCount: payload.healthChecks.length,
59
+ };
60
+ }
61
+ /**
62
+ * Why a new daemon's status is not settled enough to judge yet, or null when it is: a status read before its health
63
+ * checks run or its workers register shows fewer problems than it has.
64
+ */
65
+ function unsettledReason(before, after) {
66
+ if (after.healthCheckCount === 0)
67
+ return "the new daemon has not reported any health checks yet";
68
+ const listed = new Set(after.workers);
69
+ const missing = before.workers.filter((worker) => !listed.has(worker));
70
+ if (missing.length > 0)
71
+ return `the new daemon does not list workers it had before: ${missing.join(", ")}`;
72
+ return null;
73
+ }
74
+ /**
75
+ * Whether a release whose `ouro up` refused to hand off still came up healthy for the updater.
76
+ *
77
+ * `ouro up` refuses while any sense is down, so one sense's outage (BlueBubbles while its macOS account is logged
78
+ * out) rolled back every release for a day and marked each one failed (2026-10-24, and alpha.1559 to alpha.1586 on
79
+ * 2026-11-25). A release is only at fault for what it broke: it passes when `ouro up` failed only on the final
80
+ * health check, the daemon answers on it with a settled status, and every blocker it reports was already there,
81
+ * at the same severity, before the update.
82
+ */
83
+ function judgeRestartAfterUpFailure(input) {
84
+ if (!input.upRefusedOnHandoffHealth) {
85
+ return { ok: false, detail: input.upFailure };
86
+ }
87
+ if (input.seenVersion !== input.expectedVersion) {
88
+ const answered = input.seenVersion ? `; the daemon answered with ${input.seenVersion}` : "; the daemon did not answer";
89
+ return { ok: false, detail: `${input.upFailure}${answered}` };
90
+ }
91
+ if (input.before === null || input.after === null) {
92
+ return { ok: false, detail: `${input.upFailure}; could not compare daemon status before and after the update` };
93
+ }
94
+ const unsettled = unsettledReason(input.before, input.after);
95
+ if (unsettled !== null) {
96
+ return { ok: false, detail: `${input.upFailure}; ${unsettled}` };
97
+ }
98
+ const knownBefore = new Set(input.before.blockers.map((blocker) => blocker.key));
99
+ const introduced = input.after.blockers.filter((blocker) => !knownBefore.has(blocker.key));
100
+ if (introduced.length > 0) {
101
+ return { ok: false, detail: `${input.upFailure}; new since the update: ${introduced.map((blocker) => blocker.text).join("; ")}` };
102
+ }
103
+ const carried = input.after.blockers.map((blocker) => blocker.text);
104
+ (0, runtime_1.emitNervesEvent)({
105
+ level: "warn",
106
+ component: "daemon",
107
+ event: "daemon.self_update_preexisting_blockers_accepted",
108
+ message: "accepted a release whose ouro up refused only on problems that predate the update",
109
+ meta: { expectedVersion: input.expectedVersion, blockers: carried },
110
+ });
111
+ return {
112
+ ok: true,
113
+ detail: carried.length > 0
114
+ ? `came up on ${input.expectedVersion}; still blocked by what was already wrong before the update: ${carried.join("; ")}`
115
+ : `came up on ${input.expectedVersion}`,
116
+ };
117
+ }
@@ -67,6 +67,23 @@ function createRealOsCronDeps() {
67
67
  }
68
68
  },
69
69
  existsFile: (p) => fs.existsSync(p),
70
+ readFile: (p) => {
71
+ try {
72
+ return fs.readFileSync(p, "utf-8");
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ },
78
+ isLoaded: (label) => {
79
+ try {
80
+ (0, child_process_1.execSync)(`launchctl list "${label}"`, { stdio: "ignore" });
81
+ return true;
82
+ }
83
+ catch {
84
+ return false;
85
+ }
86
+ },
70
87
  listDir: (dir) => {
71
88
  try {
72
89
  return fs.readdirSync(dir);
@@ -151,6 +151,11 @@ class LaunchdCronManager {
151
151
  const filename = `${label}.plist`;
152
152
  const fullPath = `${this.launchAgentsDir}/${filename}`;
153
153
  const xml = generatePlistXml(job, this.deps.envPath);
154
+ // Reloading restarts a StartInterval job's clock, and the scheduler syncs every 5 minutes, so a 30-minute
155
+ // job reloaded on every sync never fires: launchd ran the heartbeat 0 times in 14 hours (2026-11-25).
156
+ // Leave a loaded job with an unchanged plist alone.
157
+ if (this.deps.readFile?.(fullPath) === xml && this.deps.isLoaded?.(label) === true)
158
+ continue;
154
159
  try {
155
160
  this.deps.exec(`launchctl unload "${fullPath}"`);
156
161
  }
@@ -123,6 +123,17 @@ class HabitScheduler {
123
123
  if (dueState === null)
124
124
  continue;
125
125
  if (dueState.due) {
126
+ const missedRuns = (0, cadence_1.cadenceRetrySuffix)(habit.cadence, habit.lastRun, nowMs);
127
+ if (missedRuns) {
128
+ // A whole interval past due means a run was lost or refused. Warn, so the gap shows in kept logs.
129
+ (0, runtime_1.emitNervesEvent)({
130
+ level: "warn",
131
+ component: "daemon",
132
+ event: "daemon.habit_overdue",
133
+ message: "habit is more than one interval overdue; an earlier run did not record completion",
134
+ meta: { habitName: habit.name, agent: this.agent, lastRun: habit.lastRun, elapsedMs: dueState.elapsedMs },
135
+ });
136
+ }
126
137
  (0, runtime_1.emitNervesEvent)({
127
138
  component: "daemon",
128
139
  event: "daemon.habit_fire",
@@ -49,6 +49,7 @@ const runtime_1 = require("../../nerves/runtime");
49
49
  const cli_render_1 = require("../daemon/cli-render");
50
50
  const socket_client_1 = require("../daemon/socket-client");
51
51
  const launchd_1 = require("../daemon/launchd");
52
+ const handoff_blockers_1 = require("../daemon/handoff-blockers");
52
53
  const runtime_replacement_handoff_1 = require("../daemon/runtime-replacement-handoff");
53
54
  const ouro_version_manager_1 = require("./ouro-version-manager");
54
55
  const release_sources_1 = require("./release-sources");
@@ -99,9 +100,12 @@ async function fetchJson(url, timeoutMs) {
99
100
  */
100
101
  function runDetachedFromStdin(command, args, timeoutMs) {
101
102
  return new Promise((resolve, reject) => {
102
- const child = (0, child_process_1.spawn)(command, args, { stdio: ["ignore", "ignore", "pipe"], env: { ...process.env, OURO_UNATTENDED: "1" } });
103
+ const child = (0, child_process_1.spawn)(command, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, OURO_UNATTENDED: "1" } });
103
104
  let stderr = "";
105
+ let stdout = "";
104
106
  child.stderr?.on("data", (chunk) => { stderr = (stderr + String(chunk)).slice(-4000); });
107
+ // `ouro up` reports why it failed on stdout, so without it a failure reads "exited 1: " with nothing after.
108
+ child.stdout?.on("data", (chunk) => { stdout = (stdout + String(chunk)).slice(-4000); });
105
109
  const timer = setTimeout(() => {
106
110
  child.kill("SIGTERM");
107
111
  reject(new Error(`${command} ${args.join(" ")} timed out after ${Math.round(timeoutMs / 1000)}s`));
@@ -115,10 +119,26 @@ function runDetachedFromStdin(command, args, timeoutMs) {
115
119
  if (code === 0)
116
120
  resolve();
117
121
  else
118
- reject(new Error(`${args.join(" ")} exited ${code}: ${stderr.trim().split("\n").slice(-3).join(" ")}`));
122
+ reject(Object.assign(new Error(`${args.join(" ")} exited ${code}: ${failureTail(stderr) || failureTail(stdout) || "no output"}`), { exitCode: code }));
119
123
  });
120
124
  });
121
125
  }
126
+ /** The last three non-empty lines of a command's output, without terminal colour codes. */
127
+ function failureTail(output) {
128
+ // eslint-disable-next-line no-control-regex -- strips ANSI escape sequences
129
+ return output.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").split("\n").map((line) => line.trim()).filter(Boolean).slice(-3).join(" ");
130
+ }
131
+ async function daemonHandoffSnapshot(socketPath) {
132
+ try {
133
+ const response = await (0, socket_client_1.sendDaemonCommand)(socketPath, { kind: "daemon.status" });
134
+ const payload = (0, cli_render_1.parseStatusPayload)(response.data);
135
+ return payload ? (0, handoff_blockers_1.handoffSnapshot)(payload) : null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
141
+ const EMPTY_HANDOFF_SNAPSHOT = { blockers: [], workers: [], healthCheckCount: 0 };
122
142
  exports.releaseSourceDeps = { fetchJson, execFile: execFileText, ...(0, release_sources_1.selfUpdateE2eOverrides)(process.env) };
123
143
  function isPidAlive(pid) {
124
144
  try {
@@ -223,20 +243,43 @@ function createDefaultSelfUpdateDeps(options = {}) {
223
243
  isDaemonRunning: () => (0, socket_client_1.checkDaemonSocketAlive)(socketPath),
224
244
  runningDaemonVersion: async () => (await (0, socket_client_1.checkDaemonSocketAlive)(socketPath)) ? runningDaemonVersion(socketPath) : null,
225
245
  restartDaemon: async (expectedVersion) => {
246
+ // What already blocks handoff on the daemon being replaced: a release is not at fault for those.
247
+ const before = (await (0, socket_client_1.checkDaemonSocketAlive)(socketPath)) ? await daemonHandoffSnapshot(socketPath) : EMPTY_HANDOFF_SNAPSHOT;
248
+ let upFailure = null;
249
+ let upRefusedOnHandoffHealth = false;
226
250
  try {
227
251
  await runDetachedFromStdin(process.execPath, [launcher, "up"], DAEMON_UP_TIMEOUT_MS);
228
252
  }
229
253
  catch (error) {
230
- return { ok: false, detail: error instanceof Error ? error.message : String(error) };
254
+ upFailure = error instanceof Error ? error.message : String(error);
255
+ upRefusedOnHandoffHealth = error.exitCode === handoff_blockers_1.HANDOFF_HEALTH_REFUSED_EXIT_CODE;
231
256
  }
232
257
  const deadline = Date.now() + DAEMON_HEALTH_WAIT_MS;
233
258
  let seen = null;
234
259
  while (Date.now() < deadline) {
235
260
  seen = await runningDaemonVersion(socketPath);
236
261
  if (seen === expectedVersion)
237
- return { ok: true };
262
+ break;
238
263
  await new Promise((resolve) => setTimeout(resolve, 2_000));
239
264
  }
265
+ if (upFailure !== null) {
266
+ let after = null;
267
+ if (upRefusedOnHandoffHealth && seen === expectedVersion) {
268
+ // Judge only a settled status: one read before health checks run or workers register hides problems.
269
+ const settleDeadline = Date.now() + DAEMON_HEALTH_WAIT_MS;
270
+ for (;;) {
271
+ after = await daemonHandoffSnapshot(socketPath);
272
+ if (after === null || before === null || (0, handoff_blockers_1.unsettledReason)(before, after) === null)
273
+ break;
274
+ if (Date.now() >= settleDeadline)
275
+ break;
276
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
277
+ }
278
+ }
279
+ return (0, handoff_blockers_1.judgeRestartAfterUpFailure)({ upFailure, upRefusedOnHandoffHealth, expectedVersion, seenVersion: seen, before, after });
280
+ }
281
+ if (seen === expectedVersion)
282
+ return { ok: true };
240
283
  return { ok: false, detail: seen ? `daemon answered with ${seen}, expected ${expectedVersion}` : "daemon did not answer after ouro up" };
241
284
  },
242
285
  isDevMode: () => fs.existsSync(path.join(cliHome, "dev-config.json")),
@@ -475,6 +475,12 @@ const BLUEBUBBLES_CATCHUP_PAGE_SIZE = 50;
475
475
  const BLUEBUBBLES_CATCHUP_MAX_PAGES = 20;
476
476
  const BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS = 90_000;
477
477
  const BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS = 24 * 60 * 60 * 1000;
478
+ /**
479
+ * How long after an outage every catch-up keeps the outage lookback. Messages iMessage held while the Mac or
480
+ * BlueBubbles was down land minutes after the server answers, dated when they were sent, and BlueBubbles sends no
481
+ * webhook for a row older than its last poll, so one pass at the moment of recovery misses them (2026-11-25).
482
+ */
483
+ const BLUEBUBBLES_RECOVERY_SETTLE_MS = 30 * 60 * 1000;
478
484
  const BLUEBUBBLES_FIRST_CATCHUP_LOOKBACK_MS = 10 * 60 * 1000;
479
485
  class BlueBubblesRecoveryTurnTimeoutError extends Error {
480
486
  constructor(timeoutMs) {
@@ -3268,6 +3274,18 @@ function parseTimestampMs(value) {
3268
3274
  const parsed = Date.parse(value);
3269
3275
  return Number.isFinite(parsed) ? parsed : null;
3270
3276
  }
3277
+ function resolveBlueBubblesCatchUpWindow(previousState, nowMs = Date.now()) {
3278
+ if (previousState.upstreamStatus === "error") {
3279
+ return { since: nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS, mode: "recovery" };
3280
+ }
3281
+ const settleUntil = parseTimestampMs(previousState.recoveryLookbackUntil);
3282
+ const settleSince = parseTimestampMs(previousState.recoveryLookbackSince);
3283
+ if (settleUntil !== null && settleSince !== null && nowMs < settleUntil) {
3284
+ return { since: settleSince, mode: "settling" };
3285
+ }
3286
+ const since = resolveBlueBubblesCatchUpSince(previousState, nowMs);
3287
+ return { since, mode: parseTimestampMs(previousState.catchUpThrough ?? previousState.lastCheckedAt) === null ? "first" : "healthy" };
3288
+ }
3271
3289
  function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
3272
3290
  if (previousState.upstreamStatus === "error") {
3273
3291
  return nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS;
@@ -3341,12 +3359,21 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3341
3359
  meta: { previousDetail: previousState.detail, previousCheckedAt: previousState.lastCheckedAt },
3342
3360
  });
3343
3361
  }
3362
+ // Open the settling window in the same write that marks upstream ok: a recovery pass cut short by a restart
3363
+ // must still leave later catch-ups reaching back to the outage.
3364
+ const recoveryLookback = previousState.upstreamStatus === "error"
3365
+ ? {
3366
+ recoveryLookbackSince: new Date(resolveBlueBubblesCatchUpSince(previousState, Date.parse(checkedAt))).toISOString(),
3367
+ recoveryLookbackUntil: new Date(Date.parse(checkedAt) + BLUEBUBBLES_RECOVERY_SETTLE_MS).toISOString(),
3368
+ }
3369
+ : {};
3344
3370
  const pendingBeforeCatchup = blueBubblesPendingRecoverySnapshot(agentName);
3345
3371
  const activeBeforeCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3346
3372
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3347
3373
  upstreamStatus: "ok",
3348
3374
  detail: "upstream reachable; recovery pass running",
3349
3375
  lastCheckedAt: checkedAt,
3376
+ ...recoveryLookback,
3350
3377
  proofMethod: "bluebubbles.checkHealth",
3351
3378
  ...pendingBeforeCatchup,
3352
3379
  ...activeBeforeCatchup,
@@ -3373,6 +3400,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3373
3400
  detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
3374
3401
  lastCheckedAt: checkedAt,
3375
3402
  catchUpThrough: checkedAt,
3403
+ ...recoveryLookback,
3376
3404
  proofMethod: "bluebubbles.checkHealth",
3377
3405
  ...pendingAfterCatchup,
3378
3406
  ...activeAfterCatchup,
@@ -3488,7 +3516,10 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3488
3516
  const result = { inspected: 0, recovered: 0, skipped: 0, failed: 0 };
3489
3517
  const state = previousState ?? (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3490
3518
  const cutover = (0, semantic_receipts_1.initializeBlueBubblesSemanticCutover)(agentName);
3491
- const catchUpSince = Math.max(resolveBlueBubblesCatchUpSince(state), Date.parse(cutover.effectiveAt));
3519
+ const catchUpWindow = resolveBlueBubblesCatchUpWindow(state);
3520
+ const catchUpSince = Math.max(catchUpWindow.since, Date.parse(cutover.effectiveAt));
3521
+ // Healthy passes run every 30 s and stay at info; outage passes are logged, so a miss leaves evidence.
3522
+ const catchUpLogLevel = catchUpWindow.mode === "recovery" || catchUpWindow.mode === "settling" ? "warn" : "info";
3492
3523
  const processTurns = options.processTurns !== false;
3493
3524
  let pendingKeyHashes = null;
3494
3525
  const pendingCaptureKeyHashes = () => {
@@ -3499,11 +3530,13 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3499
3530
  if (!client.listRecentMessages)
3500
3531
  return result;
3501
3532
  (0, runtime_1.emitNervesEvent)({
3533
+ level: catchUpWindow.mode === "recovery" ? "warn" : "info",
3502
3534
  component: "senses",
3503
3535
  event: "senses.bluebubbles_catchup_start",
3504
3536
  message: "bluebubbles upstream catch-up pass started",
3505
3537
  meta: {
3506
3538
  since: new Date(catchUpSince).toISOString(),
3539
+ mode: catchUpWindow.mode,
3507
3540
  pageSize: BLUEBUBBLES_CATCHUP_PAGE_SIZE,
3508
3541
  maxPages: BLUEBUBBLES_CATCHUP_MAX_PAGES,
3509
3542
  },
@@ -3672,12 +3705,14 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3672
3705
  }
3673
3706
  }
3674
3707
  }));
3675
- if (result.inspected > 0 || result.recovered > 0 || result.skipped > 0 || result.failed > 0) {
3708
+ const foundWork = result.recovered > 0 || (result.queued ?? 0) > 0 || result.failed > 0;
3709
+ if (result.inspected > 0 || foundWork || catchUpWindow.mode === "recovery") {
3676
3710
  (0, runtime_1.emitNervesEvent)({
3711
+ level: foundWork || catchUpWindow.mode === "recovery" ? catchUpLogLevel : "info",
3677
3712
  component: "senses",
3678
3713
  event: "senses.bluebubbles_catchup_complete",
3679
3714
  message: "bluebubbles upstream catch-up pass completed",
3680
- meta: { ...result },
3715
+ meta: { ...result, mode: catchUpWindow.mode },
3681
3716
  });
3682
3717
  }
3683
3718
  return result;
@@ -68,6 +68,8 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
68
68
  lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
69
69
  lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
70
70
  catchUpThrough: typeof parsed.catchUpThrough === "string" ? parsed.catchUpThrough : undefined,
71
+ recoveryLookbackSince: typeof parsed.recoveryLookbackSince === "string" ? parsed.recoveryLookbackSince : undefined,
72
+ recoveryLookbackUntil: typeof parsed.recoveryLookbackUntil === "string" ? parsed.recoveryLookbackUntil : undefined,
71
73
  proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
72
74
  ? parsed.proofMethod
73
75
  : undefined,
@@ -106,11 +108,17 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
106
108
  function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
107
109
  const filePath = getBlueBubblesRuntimeStatePath(agentName, agentRoot);
108
110
  try {
109
- const catchUpThrough = state.catchUpThrough ?? readBlueBubblesRuntimeState(agentName, agentRoot).catchUpThrough;
111
+ const kept = state.catchUpThrough === undefined || state.recoveryLookbackUntil === undefined
112
+ ? readBlueBubblesRuntimeState(agentName, agentRoot)
113
+ : null;
114
+ const catchUpThrough = state.catchUpThrough ?? kept?.catchUpThrough;
115
+ const recoveryLookbackSince = state.recoveryLookbackUntil === undefined ? kept?.recoveryLookbackSince : state.recoveryLookbackSince;
116
+ const recoveryLookbackUntil = state.recoveryLookbackUntil ?? kept?.recoveryLookbackUntil;
110
117
  // Replaced whole, so the daemon reading it mid-write never sees half a file.
111
118
  (0, atomic_file_1.writeJsonAtomicSync)(filePath, {
112
119
  ...state,
113
120
  ...(catchUpThrough === undefined ? {} : { catchUpThrough }),
121
+ ...(recoveryLookbackSince === undefined || recoveryLookbackUntil === undefined ? {} : { recoveryLookbackSince, recoveryLookbackUntil }),
114
122
  lastHeartbeatAt: new Date(Date.now()).toISOString(),
115
123
  });
116
124
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1586",
3
+ "version": "0.1.0-alpha.1588",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@ouro.bot/cli",
9
- "version": "0.1.0-alpha.1586",
9
+ "version": "0.1.0-alpha.1588",
10
10
  "bundleDependencies": [
11
11
  "@ouro.bot/friends"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1586",
3
+ "version": "0.1.0-alpha.1588",
4
4
  "description": "Ouroboros, the agent harness: agents with durable memory that live where you talk (terminal, Teams, iMessage, mail, voice) and use real tools. Start with npx ouro.bot@latest.",
5
5
  "homepage": "https://ouroboros.bot/",
6
6
  "engines": {