@ouro.bot/cli 0.1.0-alpha.1394 → 0.1.0-alpha.1396

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,6 +1,12 @@
1
1
  {
2
2
  "_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
3
3
  "versions": [
4
+ {
5
+ "version": "0.1.0-alpha.1396",
6
+ "changes": [
7
+ "A BlueBubbles listener that stops proving itself now reads as an error and is restarted, timed on the daemon's own clock so sleep never triggers it, and slow syncs, failed syncs and recoveries are logged."
8
+ ]
9
+ },
4
10
  {
5
11
  "version": "0.1.0-alpha.1394",
6
12
  "changes": [
@@ -1,5 +1,5 @@
1
1
  {
2
- "runtimeVersion": "0.1.0-alpha.1394",
2
+ "runtimeVersion": "0.1.0-alpha.1396",
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.1394</Repository>
4
+ <Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1396</Repository>
5
5
  <Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
6
6
  <Network>host</Network>
7
7
  <Shell>sh</Shell>
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.DaemonSenseManager = void 0;
36
+ exports.DaemonSenseManager = exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = void 0;
37
37
  const fs = __importStar(require("fs"));
38
38
  const bluebubbles_host_account_1 = require("../bluebubbles-host-account");
39
39
  const os = __importStar(require("os"));
@@ -54,6 +54,14 @@ const DEFAULT_TEAMS_PORT = 3978;
54
54
  const DEFAULT_BLUEBUBBLES_PORT = 18790;
55
55
  const DEFAULT_BLUEBUBBLES_WEBHOOK_PATH = "/bluebubbles-webhook";
56
56
  const BLUEBUBBLES_RUNTIME_FRESHNESS_WINDOW_MS = 90_000;
57
+ /**
58
+ * The listener's 30 s sync loop refreshes its proof on every tick, even while a slow pass runs, and a pass that
59
+ * hangs is abandoned after two minutes without progress. So a proof this daemon has watched stay unchanged this long means the loop
60
+ * itself has stopped. Busy turns never hold it back.
61
+ */
62
+ exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS = 10 * 60_000;
63
+ /** Each restart that brings no fresh proof doubles the wait before the next, up to this many doublings. */
64
+ const BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS = 3;
57
65
  const SENSE_CONFIG_RETRY_DELAYS_MS = [1_000, 2_000, 5_000, 10_000, 30_000, 60_000];
58
66
  const WORKBENCH_RUNTIME_INJECTION_DETAIL = "runtime-injected by Workbench app; no agent.json entry required";
59
67
  const WORKBENCH_STALE_BUNDLE_DETAIL = "stale agent.json Workbench entry; run 'ouro connect workbench' to clean it and use runtime injection";
@@ -490,6 +498,7 @@ function readBlueBubblesRuntimeJson(runtimePath) {
490
498
  ? parsed.detail
491
499
  : "startup health probe pending",
492
500
  lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
501
+ lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
493
502
  proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
494
503
  ? parsed.proofMethod
495
504
  : undefined,
@@ -518,10 +527,19 @@ function readBlueBubblesRuntimeJson(runtimePath) {
518
527
  /* v8 ignore start -- defensive: catch for missing/corrupt BB runtime state file @preserve */
519
528
  }
520
529
  catch {
521
- return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0 };
530
+ return { upstreamStatus: "unknown", detail: "startup health probe pending", pendingRecoveryCount: 0, failedRecoveryCount: 0, unreadable: true };
522
531
  }
523
532
  /* v8 ignore stop */
524
533
  }
534
+ /** The listener's latest sign of life: its last health check, or a sync heartbeat written since. */
535
+ function blueBubblesLatestProof(state) {
536
+ const checkedMs = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : Number.NaN;
537
+ const heartbeatMs = state.lastHeartbeatAt ? Date.parse(state.lastHeartbeatAt) : Number.NaN;
538
+ if (!Number.isFinite(heartbeatMs) || checkedMs >= heartbeatMs)
539
+ return { at: state.lastCheckedAt, method: state.proofMethod };
540
+ // Every write stamps a heartbeat a moment after its check, so the heartbeat is named the proof only once the check is old.
541
+ return { at: state.lastHeartbeatAt, method: blueBubblesRuntimeStateIsFresh(state.lastCheckedAt) ? state.proofMethod : "bluebubbles.syncHeartbeat" };
542
+ }
525
543
  function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
526
544
  const agentRoot = path.join(bundlesRoot, `${agent}.ouro`);
527
545
  const runtimePath = path.join(agentRoot, "state", "senses", "bluebubbles", "runtime.json");
@@ -529,11 +547,12 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
529
547
  return { runtime: snapshot?.runtime };
530
548
  }
531
549
  const state = readBlueBubblesRuntimeJson(runtimePath);
532
- const checkedAtMs = state.lastCheckedAt ? Date.parse(state.lastCheckedAt) : Number.NaN;
550
+ const proof = blueBubblesLatestProof(state);
551
+ const proofAtMs = proof.at ? Date.parse(proof.at) : Number.NaN;
533
552
  const proofFacts = {
534
- proofMethod: state.proofMethod ?? "bluebubbles.checkHealth",
535
- lastProofAt: state.lastCheckedAt,
536
- proofAgeMs: Number.isFinite(checkedAtMs) ? Math.max(0, Date.now() - checkedAtMs) : undefined,
553
+ proofMethod: proof.method ?? "bluebubbles.checkHealth",
554
+ lastProofAt: proof.at,
555
+ proofAgeMs: Number.isFinite(proofAtMs) ? Math.max(0, Date.now() - proofAtMs) : undefined,
537
556
  pendingRecoveryCount: state.pendingRecoveryCount,
538
557
  failedRecoveryCount: state.failedRecoveryCount,
539
558
  oldestPendingRecoveryAt: state.oldestPendingRecoveryAt,
@@ -543,11 +562,21 @@ function readBlueBubblesRuntimeFacts(agent, bundlesRoot, snapshot) {
543
562
  oldestActiveTurnStartedAt: state.oldestActiveTurnStartedAt,
544
563
  oldestActiveTurnAgeMs: state.oldestActiveTurnAgeMs,
545
564
  };
546
- if (!blueBubblesRuntimeStateIsFresh(state.lastCheckedAt)) {
565
+ if (!blueBubblesRuntimeStateIsFresh(proof.at)) {
566
+ // A running listener that has stopped proving itself is not healthy, whatever its process state says.
567
+ if (proof.at && snapshot?.runtime === "running") {
568
+ return {
569
+ runtime: "error",
570
+ ...proofFacts,
571
+ lastFailure: "BlueBubbles proof is stale",
572
+ failureLayer: "proof_freshness",
573
+ recoveryAction: `the daemon restarts the BlueBubbles listener once its proof has not changed for ${Math.round(exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS / 60_000)}m`,
574
+ };
575
+ }
547
576
  return {
548
577
  runtime: snapshot?.runtime,
549
- lastFailure: state.lastCheckedAt ? "BlueBubbles proof is stale" : undefined,
550
- failureLayer: state.lastCheckedAt ? "proof_freshness" : undefined,
578
+ lastFailure: proof.at ? "BlueBubbles proof is stale" : undefined,
579
+ failureLayer: proof.at ? "proof_freshness" : undefined,
551
580
  };
552
581
  }
553
582
  if (snapshot?.runtime !== "running") {
@@ -617,9 +646,14 @@ class DaemonSenseManager {
617
646
  presenceFlagOn;
618
647
  /** Shared senses skipped because another machine owns them; started here when ownership arrives. */
619
648
  notOwnerSkipped = new Set();
649
+ monotonicNow;
650
+ /** Per agent: the listener process and proof last seen, since when (monotonic), and restarts that brought no new proof. */
651
+ blueBubblesProofWatch = new Map();
620
652
  constructor(options) {
621
653
  const bundlesRoot = options.bundlesRoot ?? path.join(os.homedir(), "AgentBundles");
622
654
  this.bundlesRoot = bundlesRoot;
655
+ /* v8 ignore next -- production default; tests inject the clock @preserve */
656
+ this.monotonicNow = options.monotonicNow ?? (() => performance.now());
623
657
  /* v8 ignore start -- production default reads the real roster and machine identity; tests inject presenceOwner @preserve */
624
658
  this.presenceOwner = options.presenceOwner ?? ((agent, sense) => {
625
659
  if (!(0, presence_1.isSharedSense)(sense))
@@ -977,9 +1011,69 @@ class DaemonSenseManager {
977
1011
  // something else triggers a tight respawn cycle for any reason, the
978
1012
  // guard fires and refuses further restarts after N attempts in M
979
1013
  // minutes, so we can never re-enter the 2026-05-11 spiral.
1014
+ //
1015
+ // What we do watch is the listener's own proof. Its sync loop rewrites
1016
+ // runtime.json every 30 s on a timer that turns never block, so a proof
1017
+ // ten minutes old means that loop has stopped, not that it is busy. The
1018
+ // probe only reads the file; it never calls into the listener.
1019
+ probes.push(this.blueBubblesProofProbe(agent));
980
1020
  }
981
1021
  return probes;
982
1022
  }
1023
+ blueBubblesProofProbe(agent) {
1024
+ const managedName = `${agent}:bluebubbles`;
1025
+ return {
1026
+ name: `bluebubbles-proof:${agent}`,
1027
+ managedName,
1028
+ check: async () => {
1029
+ const snapshot = this.processManager.listAgentSnapshots().find((row) => row.name === managedName);
1030
+ if (snapshot?.status !== "running")
1031
+ return { ok: true };
1032
+ const runtimePath = path.join(this.bundlesRoot, `${agent}.ouro`, "state", "senses", "bluebubbles", "runtime.json");
1033
+ const state = fs.existsSync(runtimePath) ? readBlueBubblesRuntimeJson(runtimePath) : null;
1034
+ // A file caught mid-write says nothing either way.
1035
+ if (state?.unreadable)
1036
+ return { ok: true };
1037
+ const proofAt = (state && blueBubblesLatestProof(state).at) ?? null;
1038
+ const processKey = `${snapshot.pid ?? ""}:${snapshot.startedAt ?? ""}`;
1039
+ // Timed on this daemon's own clock, which stops while the machine sleeps just as the listener's timers do,
1040
+ // so waking from sleep or a wall-clock correction never makes a proof look stale.
1041
+ const now = this.monotonicNow();
1042
+ const watch = this.blueBubblesProofWatch.get(agent);
1043
+ if (!watch || watch.process !== processKey || watch.proofAt !== proofAt) {
1044
+ const restarts = watch && watch.proofAt === proofAt ? watch.restarts : 0;
1045
+ this.blueBubblesProofWatch.set(agent, { process: processKey, proofAt, sinceMs: now, restarts });
1046
+ return { ok: true };
1047
+ }
1048
+ const stalledMs = now - watch.sinceMs;
1049
+ if (stalledMs < exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS))
1050
+ return { ok: true };
1051
+ // If the restart brings no new proof either, wait longer before the next one.
1052
+ watch.restarts += 1;
1053
+ watch.sinceMs = now;
1054
+ const stalledMinutes = Math.round(stalledMs / 60_000);
1055
+ (0, runtime_1.emitNervesEvent)({
1056
+ level: "warn",
1057
+ component: "daemon",
1058
+ event: "daemon.bluebubbles_stale_proof_restart",
1059
+ message: "restarting a BlueBubbles listener whose proof stopped updating",
1060
+ meta: {
1061
+ agent,
1062
+ stalledMs,
1063
+ lastProofAt: proofAt,
1064
+ restarts: watch.restarts,
1065
+ nextRestartAfterMs: exports.BLUEBUBBLES_STALE_PROOF_RESTART_MS * 2 ** Math.min(watch.restarts, BLUEBUBBLES_STALE_PROOF_MAX_DOUBLINGS),
1066
+ },
1067
+ });
1068
+ return {
1069
+ ok: false,
1070
+ detail: proofAt === null
1071
+ ? `the BlueBubbles listener has written no BlueBubbles proof in ${stalledMinutes}m; restarting it`
1072
+ : `BlueBubbles proof has not changed in ${stalledMinutes}m; restarting the listener`,
1073
+ };
1074
+ },
1075
+ };
1076
+ }
983
1077
  async restartSense(managedName) {
984
1078
  const parsed = parseSenseSnapshotName(managedName);
985
1079
  if (parsed?.sense === "shepherd" && this.quiescedShepherdOwners.has(parsed.agent))
@@ -429,6 +429,13 @@ const defaultDeps = {
429
429
  }),
430
430
  };
431
431
  const BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS = 30_000;
432
+ /** After a failed sync, the next one comes sooner than the interval: 5 s, then 10 s, then 20 s. */
433
+ const BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS = 5_000;
434
+ /**
435
+ * A sync that makes no progress (no probe answer, catch-up page or capture) for this long is abandoned so the next
436
+ * one can start. Every request times out in 30 s, so only a hang gets here; a slow catch-up that keeps going finishes.
437
+ */
438
+ const BLUEBUBBLES_RUNTIME_SYNC_STALL_MS = 2 * 60_000;
432
439
  const BLUEBUBBLES_RECOVERY_PASS_DELAY_MS = 1_000;
433
440
  const BLUEBUBBLES_RECOVERY_PASS_INTERVAL_MS = 30_000;
434
441
  // A turn that is still thinking after this long is treated as hung. It is generous on purpose: a slow reply that
@@ -3082,7 +3089,8 @@ function resolveBlueBubblesCatchUpSince(previousState, nowMs = Date.now()) {
3082
3089
  if (previousState.upstreamStatus === "error") {
3083
3090
  return nowMs - BLUEBUBBLES_RECOVERY_CATCHUP_LOOKBACK_MS;
3084
3091
  }
3085
- const lastCheckedAt = parseTimestampMs(previousState.lastCheckedAt);
3092
+ // A sync abandoned partway through catch-up has moved lastCheckedAt but not the cursor.
3093
+ const lastCheckedAt = parseTimestampMs(previousState.catchUpThrough ?? previousState.lastCheckedAt);
3086
3094
  if (lastCheckedAt !== null) {
3087
3095
  return Math.max(0, lastCheckedAt - BLUEBUBBLES_HEALTHY_CATCHUP_OVERLAP_MS);
3088
3096
  }
@@ -3124,16 +3132,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3124
3132
  options.lifecycleSignal?.throwIfAborted();
3125
3133
  const resolvedDeps = { ...defaultDeps, ...deps };
3126
3134
  const agentName = resolvedDeps.getAgentName();
3127
- // Allocate before the first health-probe await. Any live webhook accepted
3128
- // while that probe is pending must remain causally newer than this pass.
3129
- const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3130
- pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
3131
- const client = resolvedDeps.createClient();
3132
3135
  const checkedAt = new Date().toISOString();
3133
3136
  const previousState = (0, runtime_state_1.readBlueBubblesRuntimeState)(agentName);
3137
+ let probeStarted = false;
3138
+ let probePassed = false;
3134
3139
  try {
3140
+ // Setup failures land in the catch below too, so they write an error proof like any failed sync.
3141
+ // Allocate before the first health-probe await. Any live webhook accepted
3142
+ // while that probe is pending must remain causally newer than this pass.
3143
+ const catchUpObservationBatch = options.catchUpObservationBatch ?? (0, latest_turn_1.beginObservationBatch)(BLUEBUBBLES_CATCHUP_PAGE_SIZE * BLUEBUBBLES_CATCHUP_MAX_PAGES);
3144
+ pruneBlueBubblesSemanticObservationGenerations(Date.now(), new Set((0, semantic_receipts_1.listPendingBlueBubblesSemanticCaptures)(agentName).map((capture) => capture.keyHash)));
3145
+ const client = resolvedDeps.createClient();
3146
+ probeStarted = true;
3135
3147
  await client.checkHealth();
3136
3148
  options.lifecycleSignal?.throwIfAborted();
3149
+ probePassed = true;
3150
+ options.onProgress?.();
3151
+ // The listener logs at warn, so a healthy pass is silent; a recovery must not be.
3152
+ if (previousState.upstreamStatus === "error") {
3153
+ (0, runtime_1.emitNervesEvent)({
3154
+ level: "warn",
3155
+ component: "senses",
3156
+ event: "senses.bluebubbles_upstream_recovered",
3157
+ message: "bluebubbles upstream answered again after a failed sync",
3158
+ meta: { previousDetail: previousState.detail, previousCheckedAt: previousState.lastCheckedAt },
3159
+ });
3160
+ }
3137
3161
  const pendingBeforeCatchup = blueBubblesPendingRecoverySnapshot(agentName);
3138
3162
  const activeBeforeCatchup = (0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS);
3139
3163
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
@@ -3150,6 +3174,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3150
3174
  processTurns: false,
3151
3175
  observationBatch: catchUpObservationBatch,
3152
3176
  lifecycleSignal: options.lifecycleSignal,
3177
+ onProgress: options.onProgress,
3153
3178
  });
3154
3179
  options.lifecycleSignal?.throwIfAborted();
3155
3180
  const failed = catchUp.failed;
@@ -3164,6 +3189,7 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3164
3189
  upstreamStatus: "ok",
3165
3190
  detail: formatBlueBubblesRuntimeDetail(pendingAfterCatchup, failed, activeAfterCatchup),
3166
3191
  lastCheckedAt: checkedAt,
3192
+ catchUpThrough: checkedAt,
3167
3193
  proofMethod: "bluebubbles.checkHealth",
3168
3194
  ...pendingAfterCatchup,
3169
3195
  ...activeAfterCatchup,
@@ -3172,19 +3198,32 @@ async function syncBlueBubblesRuntime(deps = {}, options = {}) {
3172
3198
  lastRecoveredAt: previousState.lastRecoveredAt,
3173
3199
  lastRecoveredMessageGuid: previousState.lastRecoveredMessageGuid,
3174
3200
  });
3201
+ return "ok";
3175
3202
  }
3176
3203
  catch (error) {
3177
3204
  if (options.lifecycleSignal?.aborted)
3178
- return;
3205
+ return "aborted";
3206
+ const detail = error instanceof Error ? error.message : String(error);
3207
+ // A failed probe logs itself, so a streak of them adds only the line that starts it. Anything else logs here.
3208
+ if (!probeStarted || probePassed || previousState.upstreamStatus !== "error") {
3209
+ (0, runtime_1.emitNervesEvent)({
3210
+ level: "warn",
3211
+ component: "senses",
3212
+ event: "senses.bluebubbles_runtime_sync_failed",
3213
+ message: "bluebubbles runtime sync failed; recorded upstream error",
3214
+ meta: { reason: detail, probePassed },
3215
+ });
3216
+ }
3179
3217
  (0, runtime_state_1.writeBlueBubblesRuntimeState)(agentName, {
3180
3218
  upstreamStatus: "error",
3181
- detail: error instanceof Error ? error.message : String(error),
3219
+ detail,
3182
3220
  lastCheckedAt: checkedAt,
3183
3221
  proofMethod: "bluebubbles.checkHealth",
3184
3222
  ...blueBubblesPendingRecoverySnapshot(agentName),
3185
3223
  ...(0, active_turns_1.snapshotBlueBubblesActiveTurns)(agentName, BLUEBUBBLES_LIVE_TURN_STALLED_MS),
3186
3224
  failedRecoveryCount: 0,
3187
3225
  });
3226
+ return "error";
3188
3227
  }
3189
3228
  }
3190
3229
  async function recoverQueuedBlueBubblesMessages(deps = {}, options = {}) {
@@ -3315,6 +3354,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3315
3354
  break;
3316
3355
  }
3317
3356
  options.lifecycleSignal?.throwIfAborted();
3357
+ options.onProgress?.();
3318
3358
  const pageMessages = pageEvents
3319
3359
  .filter((event) => event.kind === "message")
3320
3360
  .sort((left, right) => right.timestamp - left.timestamp);
@@ -3375,6 +3415,7 @@ async function catchUpMissedBlueBubblesMessagesInScope(scope, deps, previousStat
3375
3415
  try {
3376
3416
  options.lifecycleSignal?.throwIfAborted();
3377
3417
  const captured = await captureBlueBubblesSemanticEvent(event, resolvedDeps, "upstream-catchup", observationReservation);
3418
+ options.onProgress?.();
3378
3419
  if (captured.status === "audit_only") {
3379
3420
  result.skipped++;
3380
3421
  continue;
@@ -4233,7 +4274,9 @@ function startBlueBubblesApp(deps = {}) {
4233
4274
  lifecycleSignal: lifecycleController.signal,
4234
4275
  }));
4235
4276
  let recoveryPassRunning = false;
4236
- let runtimeSyncRunning = false;
4277
+ let runtimeSync = null;
4278
+ let runtimeSyncFailures = 0;
4279
+ let runtimeSyncRetryTimer = null;
4237
4280
  let recoveryDelayTimer = null;
4238
4281
  let webhookReconciler = null;
4239
4282
  let closed = false;
@@ -4276,16 +4319,65 @@ function startBlueBubblesApp(deps = {}) {
4276
4319
  triggerRecoveryPass();
4277
4320
  }, BLUEBUBBLES_RECOVERY_PASS_DELAY_MS);
4278
4321
  }
4322
+ function scheduleRuntimeSyncRetry() {
4323
+ runtimeSyncFailures += 1;
4324
+ const delayMs = BLUEBUBBLES_RUNTIME_SYNC_RETRY_BASE_MS * 2 ** (runtimeSyncFailures - 1);
4325
+ // From here the 30 s interval retries soon enough.
4326
+ if (closed || delayMs >= BLUEBUBBLES_RUNTIME_SYNC_INTERVAL_MS)
4327
+ return;
4328
+ runtimeSyncRetryTimer = setTimeout(() => {
4329
+ runtimeSyncRetryTimer = null;
4330
+ triggerRuntimeSync();
4331
+ }, delayMs);
4332
+ }
4279
4333
  function triggerRuntimeSync(catchUpObservationBatch) {
4280
- if (closed || runtimeSyncRunning)
4334
+ /* v8 ignore next -- close clears the interval and the retry timer; guard covers an already-queued host callback @preserve */
4335
+ if (closed)
4281
4336
  return;
4282
- runtimeSyncRunning = true;
4337
+ if (runtimeSync) {
4338
+ const runningMs = Date.now() - runtimeSync.startedAt;
4339
+ const idleMs = Date.now() - runtimeSync.lastProgressAt;
4340
+ if (idleMs < BLUEBUBBLES_RUNTIME_SYNC_STALL_MS) {
4341
+ // A slow pass is still a live loop; say so, so the daemon does not take it for a stopped one.
4342
+ (0, runtime_state_1.touchBlueBubblesRuntimeHeartbeat)(resolvedDeps.getAgentName());
4343
+ return;
4344
+ }
4345
+ // A sync that never finishes must not stop every later one, which would leave the proof to go stale.
4346
+ (0, runtime_1.emitNervesEvent)({
4347
+ level: "warn",
4348
+ component: "senses",
4349
+ event: "senses.bluebubbles_runtime_sync_timeout",
4350
+ message: "abandoned a bluebubbles runtime sync that did not finish",
4351
+ meta: { runningMs, idleMs },
4352
+ });
4353
+ runtimeSync.controller.abort(new Error("bluebubbles_runtime_sync_timeout"));
4354
+ runtimeSync = null;
4355
+ }
4356
+ if (runtimeSyncRetryTimer !== null) {
4357
+ clearTimeout(runtimeSyncRetryTimer);
4358
+ runtimeSyncRetryTimer = null;
4359
+ }
4360
+ const sync = { startedAt: Date.now(), lastProgressAt: Date.now(), controller: new AbortController() };
4361
+ runtimeSync = sync;
4283
4362
  void syncBlueBubblesRuntime(resolvedDeps, {
4284
4363
  ...(catchUpObservationBatch ? { catchUpObservationBatch } : {}),
4285
- lifecycleSignal: lifecycleController.signal,
4364
+ lifecycleSignal: AbortSignal.any([lifecycleController.signal, sync.controller.signal]),
4365
+ onProgress: () => { sync.lastProgressAt = Date.now(); },
4366
+ })
4367
+ .then((outcome) => {
4368
+ if (runtimeSync !== sync)
4369
+ return;
4370
+ runtimeSync = null;
4371
+ if (outcome === "error")
4372
+ scheduleRuntimeSyncRetry();
4373
+ else
4374
+ runtimeSyncFailures = 0;
4375
+ scheduleRecoveryPass();
4286
4376
  })
4287
- .then(scheduleRecoveryPass)
4377
+ /* v8 ignore start -- defensive: every failure of the sync itself is caught inside it and written as an error proof @preserve */
4288
4378
  .catch((error) => {
4379
+ if (runtimeSync === sync)
4380
+ runtimeSync = null;
4289
4381
  if (closed)
4290
4382
  return;
4291
4383
  (0, runtime_1.emitNervesEvent)({
@@ -4295,10 +4387,9 @@ function startBlueBubblesApp(deps = {}) {
4295
4387
  message: "bluebubbles runtime sync failed",
4296
4388
  meta: { reason: error instanceof Error ? error.message : String(error) },
4297
4389
  });
4298
- })
4299
- .finally(() => {
4300
- runtimeSyncRunning = false;
4390
+ scheduleRuntimeSyncRetry();
4301
4391
  });
4392
+ /* v8 ignore stop */
4302
4393
  }
4303
4394
  const runtimeTimer = setInterval(() => {
4304
4395
  /* v8 ignore next -- close clears this interval; guard covers an already-queued host callback @preserve */
@@ -4316,6 +4407,10 @@ function startBlueBubblesApp(deps = {}) {
4316
4407
  lifecycleController.abort(new Error("bluebubbles_runtime_shutdown"));
4317
4408
  clearInterval(runtimeTimer);
4318
4409
  clearInterval(recoveryTimer);
4410
+ if (runtimeSyncRetryTimer !== null) {
4411
+ clearTimeout(runtimeSyncRetryTimer);
4412
+ runtimeSyncRetryTimer = null;
4413
+ }
4319
4414
  if (recoveryDelayTimer !== null) {
4320
4415
  clearTimeout(recoveryDelayTimer);
4321
4416
  recoveryDelayTimer = null;
@@ -36,8 +36,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.getBlueBubblesRuntimeStatePath = getBlueBubblesRuntimeStatePath;
37
37
  exports.readBlueBubblesRuntimeState = readBlueBubblesRuntimeState;
38
38
  exports.writeBlueBubblesRuntimeState = writeBlueBubblesRuntimeState;
39
+ exports.touchBlueBubblesRuntimeHeartbeat = touchBlueBubblesRuntimeHeartbeat;
39
40
  const fs = __importStar(require("node:fs"));
40
41
  const path = __importStar(require("node:path"));
42
+ const atomic_file_1 = require("../../heart/atomic-file");
41
43
  const identity_1 = require("../../heart/identity");
42
44
  const runtime_1 = require("../../nerves/runtime");
43
45
  const DEFAULT_RUNTIME_STATE = {
@@ -64,6 +66,8 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
64
66
  ? parsed.detail
65
67
  : DEFAULT_RUNTIME_STATE.detail,
66
68
  lastCheckedAt: typeof parsed.lastCheckedAt === "string" ? parsed.lastCheckedAt : undefined,
69
+ lastHeartbeatAt: typeof parsed.lastHeartbeatAt === "string" ? parsed.lastHeartbeatAt : undefined,
70
+ catchUpThrough: typeof parsed.catchUpThrough === "string" ? parsed.catchUpThrough : undefined,
67
71
  proofMethod: typeof parsed.proofMethod === "string" && parsed.proofMethod.trim()
68
72
  ? parsed.proofMethod
69
73
  : undefined,
@@ -102,8 +106,13 @@ function readBlueBubblesRuntimeState(agentName, agentRoot) {
102
106
  function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
103
107
  const filePath = getBlueBubblesRuntimeStatePath(agentName, agentRoot);
104
108
  try {
105
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
106
- fs.writeFileSync(filePath, JSON.stringify(state, null, 2) + "\n", "utf-8");
109
+ const catchUpThrough = state.catchUpThrough ?? readBlueBubblesRuntimeState(agentName, agentRoot).catchUpThrough;
110
+ // Replaced whole, so the daemon reading it mid-write never sees half a file.
111
+ (0, atomic_file_1.writeJsonAtomicSync)(filePath, {
112
+ ...state,
113
+ ...(catchUpThrough === undefined ? {} : { catchUpThrough }),
114
+ lastHeartbeatAt: new Date(Date.now()).toISOString(),
115
+ });
107
116
  }
108
117
  catch (error) {
109
118
  (0, runtime_1.emitNervesEvent)({
@@ -135,3 +144,9 @@ function writeBlueBubblesRuntimeState(agentName, state, agentRoot) {
135
144
  });
136
145
  return filePath;
137
146
  }
147
+ /** Refresh the heartbeat of the state on disk, while a sync that has not written yet is still running. */
148
+ function touchBlueBubblesRuntimeHeartbeat(agentName, agentRoot) {
149
+ if (!fs.existsSync(getBlueBubblesRuntimeStatePath(agentName, agentRoot)))
150
+ return;
151
+ writeBlueBubblesRuntimeState(agentName, readBlueBubblesRuntimeState(agentName, agentRoot), agentRoot);
152
+ }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@ouro.bot/cli",
3
- "version": "0.1.0-alpha.1394",
3
+ "version": "0.1.0-alpha.1396",
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.1394",
9
+ "version": "0.1.0-alpha.1396",
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.1394",
3
+ "version": "0.1.0-alpha.1396",
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": {