toolroll 0.9.129 → 0.9.131

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 (155) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/agent-fence.js +0 -2
  3. package/dist/agent-state.js +1 -1
  4. package/dist/agents-board.js +0 -3
  5. package/dist/assignment.js +4 -3
  6. package/dist/backup-ui.js +6 -3
  7. package/dist/bounded-spawn.js +0 -1
  8. package/dist/browser/manifest.json +57 -0
  9. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  10. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  11. package/dist/browser/{terminal.js → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js} +1 -1
  12. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.br +0 -0
  13. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.gz +0 -0
  14. package/dist/browser/{workspace.js → workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js} +25 -25
  15. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.br +0 -0
  16. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.gz +0 -0
  17. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  18. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  19. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  20. package/dist/browser-shell.js +271 -25
  21. package/dist/builder-restart.js +13 -4
  22. package/dist/builder.js +4 -1
  23. package/dist/canvas-freshness.js +122 -0
  24. package/dist/canvas-fs.js +273 -0
  25. package/dist/canvas-reads.js +747 -0
  26. package/dist/canvas-state-key.js +45 -0
  27. package/dist/canvas-state-worker.js +12 -0
  28. package/dist/central-recovery-stage.js +3 -3
  29. package/dist/chat-actions.js +26 -0
  30. package/dist/chat-channel.js +4 -3
  31. package/dist/chat-follow.js +4 -0
  32. package/dist/chat-task-actions.js +1 -1
  33. package/dist/chat-warmth.js +0 -1
  34. package/dist/check-report.js +0 -6
  35. package/dist/commit-extract.js +79 -40
  36. package/dist/companion/access.js +1 -0
  37. package/dist/companion/actions.js +79 -16
  38. package/dist/companion/canvas.js +141 -0
  39. package/dist/companion/chat-origin.js +92 -0
  40. package/dist/companion/chat.js +571 -0
  41. package/dist/companion/daemon.js +46 -5
  42. package/dist/companion/finish.js +51 -0
  43. package/dist/companion/reads.js +5 -1
  44. package/dist/companion/schema.js +64 -0
  45. package/dist/companion/service.js +1 -0
  46. package/dist/companion/store.js +1 -0
  47. package/dist/companion/webauthn.js +11 -2
  48. package/dist/console-instance.js +0 -4
  49. package/dist/contracts/console-api.js +1 -1
  50. package/dist/converse.js +0 -1
  51. package/dist/coordinator.js +1 -1
  52. package/dist/db-tuning.js +16 -0
  53. package/dist/desktop-config.js +156 -0
  54. package/dist/desktop-host.js +6 -152
  55. package/dist/desktop-update.js +1 -1
  56. package/dist/discord.js +9 -3
  57. package/dist/dispatch.js +32 -4
  58. package/dist/doctor.js +30 -0
  59. package/dist/evidence.js +49 -3
  60. package/dist/exec.js +3 -0
  61. package/dist/finished-task-sql.js +14 -0
  62. package/dist/flexible-answers.js +0 -1
  63. package/dist/git-views.js +7 -1
  64. package/dist/github-read.js +41 -0
  65. package/dist/guides.js +4 -3
  66. package/dist/invoke.js +12 -2
  67. package/dist/lead-doors.js +50 -3
  68. package/dist/lead-queue-runtime.js +18 -6
  69. package/dist/lead-queue.js +25 -0
  70. package/dist/lead-status.js +3 -3
  71. package/dist/live-backup-change.js +93 -0
  72. package/dist/live-backup.js +75 -31
  73. package/dist/live-bus.js +3 -2
  74. package/dist/live-records.js +0 -1
  75. package/dist/local-owner.js +0 -1
  76. package/dist/loop-recovery.js +40 -0
  77. package/dist/maintenance.js +29 -1
  78. package/dist/model-choices.js +0 -11
  79. package/dist/needs-you.js +2 -0
  80. package/dist/nightly-check.js +0 -3
  81. package/dist/nightly-github.js +1 -2
  82. package/dist/notification-retention.js +119 -0
  83. package/dist/observations.js +0 -1
  84. package/dist/operate.js +393 -56
  85. package/dist/planner.js +4 -1
  86. package/dist/pull-request-flow.js +56 -15
  87. package/dist/qr.js +0 -25
  88. package/dist/query-index-schema.js +10 -0
  89. package/dist/read-executor-worker.js +9 -7
  90. package/dist/read-executor.js +18 -1
  91. package/dist/read-worker-connection.js +7 -0
  92. package/dist/release-adapters.js +63 -48
  93. package/dist/release-auto.js +17 -13
  94. package/dist/release-card.js +0 -4
  95. package/dist/release-cli.js +58 -10
  96. package/dist/release-next.js +1 -1
  97. package/dist/release-stops.js +71 -0
  98. package/dist/release-supersede.js +125 -0
  99. package/dist/release-supervise.js +90 -0
  100. package/dist/release.js +265 -42
  101. package/dist/restore-retirement.js +4 -1
  102. package/dist/result-review.js +0 -3
  103. package/dist/retention-ui.js +1 -1
  104. package/dist/retention.js +14 -21
  105. package/dist/review-context.js +0 -5
  106. package/dist/route-rules.js +1 -5
  107. package/dist/runner.js +36 -1
  108. package/dist/sandbox-runtime.js +0 -1
  109. package/dist/scope.js +1 -13
  110. package/dist/scout.js +4 -7
  111. package/dist/serve.js +122 -12
  112. package/dist/server/kit.js +1 -0
  113. package/dist/server/live.js +9 -2
  114. package/dist/server/pages.js +3 -2
  115. package/dist/server/phone-engine-api.js +22 -2
  116. package/dist/server/render-pages.js +1 -11
  117. package/dist/server/render-results.js +0 -1
  118. package/dist/server/render-tasks.js +0 -68
  119. package/dist/server/route-table.js +1 -1
  120. package/dist/server/settings-phone.js +32 -9
  121. package/dist/server/settings-scripts.js +1 -1
  122. package/dist/server/settings-section-table.js +0 -3
  123. package/dist/server/settings-sections.js +4 -2
  124. package/dist/server/settings.js +20 -5
  125. package/dist/server/terminals.js +2 -1
  126. package/dist/shutdown-proof.js +29 -0
  127. package/dist/slack.js +9 -3
  128. package/dist/sqlite-telemetry.js +26 -14
  129. package/dist/statement-cache.js +137 -0
  130. package/dist/store.js +86 -14
  131. package/dist/structured-output.js +0 -1
  132. package/dist/style-asset.js +20 -7
  133. package/dist/tailnet.js +0 -3
  134. package/dist/task-control.js +5 -0
  135. package/dist/task-sizing.js +0 -1
  136. package/dist/task-status.js +1 -1
  137. package/dist/teams.js +9 -3
  138. package/dist/teardown-git.js +10 -1
  139. package/dist/telegram.js +4 -1
  140. package/dist/toolroll-update-cli.js +19 -3
  141. package/dist/toolroll-update-ui.js +2 -2
  142. package/dist/toolroll-update.js +95 -15
  143. package/dist/up-processes.js +16 -1
  144. package/dist/up-role-child.js +2 -0
  145. package/dist/wake-hub.js +15 -6
  146. package/dist/work-index.js +101 -44
  147. package/dist/work-reads.js +53 -9
  148. package/dist/work-snapshots.js +185 -0
  149. package/dist/worker-statement-cache.js +83 -0
  150. package/dist/workspace-revision.js +145 -21
  151. package/package.json +1 -1
  152. package/dist/companion/webauthn-test-support.js +0 -44
  153. package/dist/contracts/contract-test.js +0 -55
  154. package/dist/unfenced-test-support.js +0 -6
  155. /package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +0 -0
package/dist/operate.js CHANGED
@@ -44,6 +44,7 @@ import { RemoteMains } from "./remote-main.js";
44
44
  import { checkoutPlan, cleanCheckouts, discardCheckout, finishedCheckouts, slimKeptCheckouts, whyWords } from "./checkout-cleanup.js";
45
45
  import { closeOutCheckouts, closeOutRuns, stoppedWords } from "./run-closeout.js";
46
46
  import { proveFinishedRunsStopped, proveRunStopped } from "./stop-proof.js";
47
+ import { LIFECYCLE_RETENTION_DAYS, NOTIFICATION_RETENTION_WORDS, notificationLifecyclePreview } from "./notification-retention.js";
47
48
  import { MIN_DAYS, RETENTION_KINDS, countWords, dailyRetention, isRetentionKind, lastSweepAt, parsePeriod, periodLabel, periodWords, retentionPlan, sweepWords } from "./retention.js";
48
49
  import { checkPolicy, parseList, policyParts } from "./policy.js";
49
50
  import { billingOf, budgetHoldWords, budgetLabel, budgetStates, monthNamed, monthOf, spendItems, subagentNames, usd as spendUsd } from "./spend.js";
@@ -107,9 +108,9 @@ import { taskReviewBrief, renderReviewBrief } from "./task-review-brief.js";
107
108
  import { homedir, hostname } from "node:os";
108
109
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
109
110
  import { CHECK_RECOVERY_HELD, readCheckRecoveryHoldsForTaskRef } from "./check-recovery-hold.js";
110
- import { releaseStalledUpdate, waitingUpdate } from "./toolroll-update.js";
111
+ import { currentRuntime, driftWords, releaseStalledUpdate, serviceDriftHere, waitingUpdate } from "./toolroll-update.js";
111
112
  import { dur } from "./design/kit.js";
112
- import { requeueEligibility, checkoutIdle, setCheckoutIdle, leadQuickAnswersOn, setLeadQuickAnswers, openStore, openStoreNoMigrate, initLocalMode, localModeCandidate, consoleServingNow, consoleComponent, consoleRowForPort, openConsoleRows, enrollOwnerPassword, installationCreatedBy, laptopPortOf, recordLaptopPort, localModeOf, localOwnerBinding, archiveTaskFamily, restoreTaskFamily, shipChecksForTask, elapsedSeconds, CONCURRENT_WRITER_WAIT_MS, isDatabaseBusy, databasePath, BUILT_IN, parseCapabilityKey, verifiedAuthor, isDigestTime, predecessorWatches, RESULT_SCREENSHOTS, lifecycleOf, reportLifecycle, beatLifecycle, } from "./store.js";
113
+ import { requeueEligibility, checkoutIdle, setCheckoutIdle, leadQuickAnswersOn, setLeadQuickAnswers, openStore, openStoreNoMigrate, initLocalMode, localModeCandidate, consoleServingNow, consoleComponent, consoleRowForPort, openConsoleRows, enrollOwnerPassword, installationCreatedBy, laptopPortOf, recordLaptopPort, localModeOf, localOwnerBinding, archiveTaskFamily, restoreTaskFamily, shipChecksForTask, elapsedSeconds, CONCURRENT_WRITER_WAIT_MS, isDatabaseBusy, briefly, databasePath, BUILT_IN, parseCapabilityKey, verifiedAuthor, isDigestTime, predecessorWatches, RESULT_SCREENSHOTS, lifecycleOf, reportLifecycle, beatLifecycle, } from "./store.js";
113
114
  import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
114
115
  import { claimInstance, clearInstance, instanceRunDir, openInstanceSocket, prepareRunDir, proveLiveConsole } from "./console-instance.js";
115
116
  import { backgroundOff, backgroundOn, backgroundShow, laptopStatus, laptopStop, restartOwnBuilder } from "./laptop-background.js";
@@ -204,7 +205,7 @@ import { moveTask } from "./task-moves.js";
204
205
  import { disposeBuildOutcome, holdStaleApproval, regateTask } from "./dispose.js";
205
206
  import { proposeGrant, describeGrant, describeWithheld, permits, MUTATION_CLASSES, DEFAULT_MUTATIONS, } from "./grant.js";
206
207
  import { builtIn, guarded } from "./backend.js";
207
- import { register, authenticate, heartbeat as heartbeatRunner, isAlive, recoverDead, recoveredAnything, acquireWatchLeaseAuthed, heartbeatWatchLeaseAuthed, addRunnerReposAuthed, removeRunnerRepoAuthed, registerRunnerIfIdle, retireRunnerIfCurrent, drainRunnerIfCurrent, RUNNER_HEARTBEAT_MS, MAX_WATCH_LEASE_MS, normalizeRunnerName, validRunnerName, canonicalRepos, RUNNER_NAME_MAX, RUNNER_CAPACITY_MAX, parseRunnerCapacity, hashToken as hashRunnerToken, } from "./runner.js";
208
+ import { register, authenticate, heartbeat as heartbeatRunner, isAlive, recoverDead, recoveredAnything, acquireWatchLeaseAuthed, renewWatchLeaseAuthed, addRunnerReposAuthed, removeRunnerRepoAuthed, registerRunnerIfIdle, retireRunnerIfCurrent, drainRunnerIfCurrent, drainOf, RUNNER_HEARTBEAT_MS, MAX_WATCH_LEASE_MS, normalizeRunnerName, validRunnerName, canonicalRepos, RUNNER_NAME_MAX, RUNNER_CAPACITY_MAX, parseRunnerCapacity, hashToken as hashRunnerToken, } from "./runner.js";
208
209
  import { processIdentityProblem } from "./process-identity.js";
209
210
  import { openAddress } from "./browser-open.js";
210
211
  import { credentialDigest, recordedHolderProvedGone, processGone, processStart, readRunnerProcessRecord, runnerProcessFile, sealRunnerProcessRecord, writeRunnerProcessRecord } from "./runner-process.js";
@@ -259,18 +260,21 @@ import { attachTmux, elapsedWords, openInTmux, PEEK_TAIL_LINES, runPeek, snapsho
259
260
  import { scout as scoutTask } from "./scout.js";
260
261
  import { profileDigestOf } from "./scope.js";
261
262
  import { PROVIDER_KEY_ENV, clearProviderKey, keyStatus, readAuthMode, readAuthModeStrict, readProviderKey, saveProviderKey, setAuthMode, verifyProviderKey, verdictWords } from "./keys.js";
262
- import { run, terminateLiveProviders, run as execRun } from "./exec.js";
263
+ import { run, terminateLiveProviders, liveProviderCount, run as execRun } from "./exec.js";
263
264
  import { hardenedGit, lazyFetchSafeGit, noLazyFetch, PARTIAL_CLONE_REFUSAL } from "./teardown-git.js";
264
265
  import { installedGitFloorProblem } from "./git-floor.js";
265
266
  import { noticeGitIncidents } from "./git-incident.js";
266
267
  import { containmentNotice, containmentStatus, currentContainment, describeContainment, resolveContainment } from "./containment.js";
267
268
  import { readPulls } from "./pulls.js";
268
- import { startMaintenance } from "./maintenance.js";
269
+ import { startMaintenance, busyRetryAfter } from "./maintenance.js";
269
270
  import { WakePoker, wakeHubFor } from "./wake-hub.js";
270
271
  import { livePin, modelWatchPass } from "./model-catalog.js";
271
272
  import { runModelsCommand } from "./models-cli.js";
272
273
  import { ALL_PROJECTS, chatApprovalSettings, chatApprovalWords, setChatApproval } from "./chat-approval.js";
273
274
  import { updateAdmissionPaused, UPDATE_PAUSED } from "./desktop-update-gate.js";
275
+ import { abortablePause } from "./chat-follow.js";
276
+ import { endAfterExitProof, watchdogVerdict } from "./shutdown-proof.js";
277
+ import { loopEndRecovery, relaunchAdmission, relaunchDelayMs, LOOP_STABLE_MS, RELAUNCH_WAIT_WORDS } from "./loop-recovery.js";
274
278
  import { beads } from "./beads.js";
275
279
  import { githubIssues } from "./issues.js";
276
280
  import { installationStatus, renderInstallationStatus, renderTaskWait, repairStaleStatuses, taskWaitSnapshot } from "./lead-status.js";
@@ -987,6 +991,8 @@ async function dispatchOn(command, positional, flags, repoList, base, options, e
987
991
  ...(options.flowTriggerIo === undefined ? {} : { flowTriggerIo: options.flowTriggerIo }),
988
992
  ...(options.flowStepIo === undefined ? {} : { flowStepIo: options.flowStepIo }),
989
993
  ...(options.flowEveryMs === undefined ? {} : { flowEveryMs: options.flowEveryMs }),
994
+ ...(options.watchHeartbeatMs === undefined ? {} : { watchHeartbeatMs: options.watchHeartbeatMs }),
995
+ ...(options.loopRelaunchMs === undefined ? {} : { loopRelaunchMs: options.loopRelaunchMs }),
990
996
  ...(options.platform === undefined ? {} : { platform: options.platform }),
991
997
  ...(options.fenceAvailable === undefined ? {} : { fenceAvailable: options.fenceAvailable }),
992
998
  ...(options.flowFetch === undefined ? {} : { flowFetch: options.flowFetch }),
@@ -3514,6 +3520,7 @@ export async function startConsole(options) {
3514
3520
  clock: context.clock,
3515
3521
  telegramTokenFile: context.telegramTokenFile,
3516
3522
  configDir: dirname(context.databaseFile),
3523
+ browserAssetCache: join(dirname(context.databaseFile), "browser-assets"),
3517
3524
  ...(options.localRunner === undefined ? {} : { localRunner: options.localRunner }),
3518
3525
  poolRoot: options.poolRoot,
3519
3526
  ...(options.allowedHosts === undefined ? {} : { allowedHosts: options.allowedHosts }),
@@ -5486,6 +5493,10 @@ function startTelegramFollower(args) {
5486
5493
  });
5487
5494
  }
5488
5495
  const TELEGRAM_STOP_WAIT_MS = 5_000;
5496
+ const CLEANUP_SLOW_MS = 30_000;
5497
+ const SHUTDOWN_DEADLINE_MS = 60_000;
5498
+ const WORKER_ALIVE_EVERY_MS = 5_000;
5499
+ const WORKER_SILENCE_MS = 60_000;
5489
5500
  let staleStatusesRepaired = false;
5490
5501
  async function runWatchLoop(args) {
5491
5502
  const { context, flags, runner, token, repo, progress } = args;
@@ -5541,8 +5552,10 @@ async function runWatchLoop(args) {
5541
5552
  progress(`watch: recorded ${repaired.exitsRecorded} finished process exit(s) left open by an earlier version`);
5542
5553
  }
5543
5554
  let leaseLost = false;
5555
+ let leaseLostReason = null;
5556
+ let custodyUnknown = false;
5544
5557
  const followController = new AbortController();
5545
- const hub = wakeHubFor(store);
5558
+ const hub = wakeHubFor(store, read => briefly(store, read));
5546
5559
  const wakes = new WakePoker();
5547
5560
  args.onFollowController?.(followController);
5548
5561
  let failed = false;
@@ -5554,45 +5567,86 @@ async function runWatchLoop(args) {
5554
5567
  wakes.poke();
5555
5568
  };
5556
5569
  const stopping = () => args.isStopping() || leaseLost || failed;
5557
- const heartbeat = setInterval(() => {
5558
- let renewed = false;
5559
- let problem = "the lease or credential was taken";
5570
+ const heartbeatEveryMs = context.watchHeartbeatMs ?? WATCH_HEARTBEAT_MS;
5571
+ let heartbeatTimer = null;
5572
+ let heartbeatStopped = false;
5573
+ let busyBeats = 0;
5574
+ const scheduleBeat = (ms) => {
5575
+ if (heartbeatStopped)
5576
+ return;
5577
+ heartbeatTimer = setTimeout(beat, ms);
5578
+ heartbeatTimer.unref?.();
5579
+ };
5580
+ function beat() {
5581
+ heartbeatTimer = null;
5582
+ if (heartbeatStopped || leaseLost)
5583
+ return;
5584
+ let answer = null;
5585
+ let problem = null;
5560
5586
  try {
5561
- renewed = heartbeatWatchLeaseAuthed(store, { runner, token, repo, owner: incarnation, ttlMs: WATCH_LEASE_MS }, new Date());
5587
+ answer = briefly(store, () => renewWatchLeaseAuthed(store, { runner, token, repo, owner: incarnation, ttlMs: WATCH_LEASE_MS }, new Date()));
5562
5588
  }
5563
5589
  catch (error) {
5590
+ if (isDatabaseBusy(error)) {
5591
+ busyBeats++;
5592
+ if (!custodyUnknown)
5593
+ progress(`watch: ${runner} on ${repo}: the database is busy, so this worker can't prove it still holds the project yet — no new work starts until it can`);
5594
+ custodyUnknown = true;
5595
+ scheduleBeat(Math.min(heartbeatEveryMs, 1_000 * 2 ** Math.min(busyBeats - 1, 4)));
5596
+ return;
5597
+ }
5564
5598
  problem = `renewal could not be proved: ${describe(error)}`;
5565
5599
  }
5566
- if (!renewed && !leaseLost) {
5567
- leaseLost = true;
5568
- followController.abort();
5569
- wakes.poke();
5570
- progress(`watch: ${runner} on ${repo}: ${problem} — stopping without admitting more work`);
5600
+ if (answer !== null && answer.ok) {
5601
+ busyBeats = 0;
5602
+ if (answer.lateMs > 0)
5603
+ progress(`watch: renewal late by ${Math.max(1, Math.round(answer.lateMs / 1000))}s — this worker still holds ${repo}; carrying on`);
5604
+ if (custodyUnknown) {
5605
+ custodyUnknown = false;
5606
+ progress(`watch: ${runner} on ${repo}: proved it still holds the project — new work may start again`);
5607
+ wakes.poke();
5608
+ }
5609
+ scheduleBeat(heartbeatEveryMs);
5610
+ return;
5571
5611
  }
5572
- }, WATCH_HEARTBEAT_MS);
5573
- heartbeat.unref?.();
5612
+ leaseLostReason = answer === null ? "error" : answer.reason;
5613
+ leaseLost = true;
5614
+ followController.abort();
5615
+ wakes.poke();
5616
+ progress(`watch: ${runner} on ${repo}: ${problem ?? renewalRefusedWords(answer.reason)} — stopping without admitting more work`);
5617
+ }
5618
+ scheduleBeat(heartbeatEveryMs);
5619
+ const stopHeartbeat = () => {
5620
+ heartbeatStopped = true;
5621
+ if (heartbeatTimer !== null)
5622
+ clearTimeout(heartbeatTimer);
5623
+ heartbeatTimer = null;
5624
+ };
5625
+ let cleanupStage = null;
5626
+ let lastPassAt = null;
5627
+ args.health?.(() => ({ repo, leaseLive: !leaseLost && !custodyUnknown && cleanupStage === null, lastPassAt, stopping: stopping(), cleanup: cleanupStage }));
5574
5628
  const serviceBridge = args.serviceBridge === true;
5575
5629
  const follower = serviceBridge
5576
5630
  ? null
5577
5631
  : startTelegramFollower({ context, publicUrl: text(flags, "public-url"), signal: followController.signal, progress, label: "watch: bridge", died: { prefix: "watch: ", then: "taps wait for the next watch" } });
5578
- const slackFollower = followSlack({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5632
+ const slackFollower = superviseChatFollower("Slack", followController.signal, progress, () => followSlack({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5579
5633
  readProjects: telegramReadProjects(context), evidenceRoot: context.evidenceRoot,
5580
5634
  ...(context.leadSeams?.subscriptionRunner ? { subscriptionRunner: context.leadSeams.subscriptionRunner } : {}),
5581
5635
  origin: () => phoneOrigin(process.env, dirname(context.databaseFile), { serverOrigin: text(flags, "public-url") ?? null }),
5582
5636
  notifications: () => effectivePrimary(process.env, dirname(context.databaseFile), loadBotToken(process.env, context.telegramTokenFile) !== null).channel === "slack",
5583
- }).catch(() => progress("watch: Slack stopped. Check Slack settings before reconnecting."));
5584
- const teamsFollower = followTeams({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5637
+ }));
5638
+ const teamsFollower = superviseChatFollower("Teams", followController.signal, progress, () => followTeams({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5585
5639
  readProjects: telegramReadProjects(context), evidenceRoot: context.evidenceRoot,
5586
5640
  ...(context.leadSeams?.subscriptionRunner ? { subscriptionRunner: context.leadSeams.subscriptionRunner } : {}),
5587
5641
  origin: () => phoneOrigin(process.env, dirname(context.databaseFile), { serverOrigin: text(flags, "public-url") ?? null }),
5588
5642
  notifications: () => effectivePrimary(process.env, dirname(context.databaseFile), loadBotToken(process.env, context.telegramTokenFile) !== null).channel === "teams",
5589
- }).catch(() => progress("watch: Teams stopped. Check Teams settings before reconnecting."));
5590
- const discordFollower = followDiscord({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5643
+ }));
5644
+ const discordFollower = superviseChatFollower("Discord", followController.signal, progress, () => followDiscord({ store, dir: dirname(context.databaseFile), signal: followController.signal,
5591
5645
  readProjects: telegramReadProjects(context), evidenceRoot: context.evidenceRoot,
5592
5646
  ...(context.leadSeams?.subscriptionRunner ? { subscriptionRunner: context.leadSeams.subscriptionRunner } : {}),
5593
5647
  origin: () => phoneOrigin(process.env, dirname(context.databaseFile), { serverOrigin: text(flags, "public-url") ?? null }),
5594
5648
  notifications: () => effectivePrimary(process.env, dirname(context.databaseFile), loadBotToken(process.env, context.telegramTokenFile) !== null).channel === "discord",
5595
- }).catch(() => progress("watch: Discord stopped. Check Discord settings before reconnecting."));
5649
+ }));
5596
5650
  const quiet = [];
5597
5651
  const sink = line => quiet.push(line);
5598
5652
  const passFlags = (extra = {}) => {
@@ -5605,7 +5659,8 @@ async function runWatchLoop(args) {
5605
5659
  };
5606
5660
  let reconciliationReady = false;
5607
5661
  let reconciliationFailure = null;
5608
- const paused = () => !reconciliationReady || updateAdmissionPaused(store.raw()) || context.shouldPauseAdmission?.() === true;
5662
+ let reconciliationBusy = false;
5663
+ const paused = () => custodyUnknown || !reconciliationReady || updateAdmissionPaused(store.raw()) || context.shouldPauseAdmission?.() === true;
5609
5664
  const admissionStopped = () => stopping() || paused();
5610
5665
  const quietContext = { ...context, write: sink, json: true, shouldStop: stopping, shouldPauseAdmission: paused };
5611
5666
  const startedAt = Date.now();
@@ -5626,7 +5681,9 @@ async function runWatchLoop(args) {
5626
5681
  if (detail !== reconciliationFailure)
5627
5682
  progress(`watch: reconciliation failed — ${detail}; new work is paused until a recovery pass succeeds`);
5628
5683
  reconciliationFailure = detail;
5684
+ reconciliationBusy = busyFailure(error);
5629
5685
  },
5686
+ retryAfter: (error, failuresInARow) => busyRetryAfter(busyFailure(error), failuresInARow),
5630
5687
  run: async () => {
5631
5688
  const maintenanceLines = [];
5632
5689
  const maintenanceContext = { ...quietContext, ...(runFor === null ? { sweepOwner } : {}), write: line => maintenanceLines.push(line) };
@@ -5771,7 +5828,7 @@ async function runWatchLoop(args) {
5771
5828
  run: async () => { if (await modelWatchPass(store, context.clock()))
5772
5829
  progress("watch: checked models and CLI versions"); },
5773
5830
  });
5774
- const leaveServiceBeats = joinServiceBeats({ context, progress, ciReady: () => !admissionStopped() });
5831
+ const leaveServiceBeats = joinServiceBeats({ context, progress, ciReady: () => !admissionStopped(), stopping });
5775
5832
  const passes = args.passes ?? new ProjectPasses();
5776
5833
  const slotFacts = (yieldingSince) => {
5777
5834
  const now = new Date();
@@ -5883,6 +5940,7 @@ async function runWatchLoop(args) {
5883
5940
  const code = await tickCommand(passFlags(yieldBuilds ? { "yield-builds": "1" } : {}), quietContext);
5884
5941
  passes.passed(repo);
5885
5942
  ticks++;
5943
+ lastPassAt = new Date().toISOString();
5886
5944
  if (code === EXIT.ok) {
5887
5945
  tickDidWork = true;
5888
5946
  built++;
@@ -5934,31 +5992,44 @@ async function runWatchLoop(args) {
5934
5992
  fail(error);
5935
5993
  }
5936
5994
  finally {
5937
- await Promise.all(lanes);
5938
- await maintenance.stop();
5939
- await followUpChecks.stop();
5940
- await codeMapChecks.stop();
5941
- await flowMoves.stop();
5942
- await flowSteps.stop();
5943
- await modelWatch.stop();
5944
- await leaveServiceBeats();
5945
- clearInterval(heartbeat);
5995
+ const step = async (name, work) => {
5996
+ cleanupStage = name;
5997
+ const slow = setTimeout(() => progress(`watch: stopping is still waiting on ${name}`), CLEANUP_SLOW_MS);
5998
+ slow.unref?.();
5999
+ try {
6000
+ await work();
6001
+ }
6002
+ finally {
6003
+ clearTimeout(slow);
6004
+ }
6005
+ };
6006
+ await step("its builds", () => Promise.all(lanes));
6007
+ await step("reconciliation", () => maintenance.stop());
6008
+ await step("follow-up checks", () => followUpChecks.stop());
6009
+ await step("the code map check", () => codeMapChecks.stop());
6010
+ await step("flow moves", () => flowMoves.stop());
6011
+ await step("flow steps", () => flowSteps.stop());
6012
+ await step("the model check", () => modelWatch.stop());
6013
+ await step("deliveries and fast CI", () => leaveServiceBeats());
6014
+ stopHeartbeat();
5946
6015
  followController.abort();
5947
6016
  if (follower !== null)
5948
- await follower;
5949
- await slackFollower;
5950
- await teamsFollower;
5951
- await discordFollower;
6017
+ await step("the Telegram follower", () => follower);
6018
+ await step("the Slack follower", () => slackFollower);
6019
+ await step("the Teams follower", () => teamsFollower);
6020
+ await step("the Discord follower", () => discordFollower);
6021
+ cleanupStage = "releasing the project";
5952
6022
  store.endWatchEpisode(incarnation, { ticks, built, broke: brokeCount }, new Date());
5953
6023
  store.releaseWatchLease(runner, repo, incarnation, new Date());
6024
+ cleanupStage = null;
5954
6025
  }
5955
6026
  if (failed)
5956
6027
  throw failure;
5957
6028
  if (leaseLost) {
5958
- return { ok: false, reason: "lease-lost", detail: `the watch lease for ${runner} on ${repo} stopped renewing — another process may have taken this worker over`, ticks, built, broke: brokeCount };
6029
+ return { ok: false, reason: "lease-lost", lost: leaseLostReason ?? "error", detail: `the watch lease for ${runner} on ${repo} stopped renewing — ${renewalRefusedWords(leaseLostReason ?? "error")}`, ticks, built, broke: brokeCount };
5959
6030
  }
5960
6031
  if (reconciliationFailure !== null) {
5961
- return { ok: false, reason: "reconciliation-failed", detail: reconciliationFailure, ticks, built, broke: brokeCount };
6032
+ return { ok: false, reason: "reconciliation-failed", detail: reconciliationFailure, ticks, built, broke: brokeCount, busy: reconciliationBusy };
5962
6033
  }
5963
6034
  return { ok: true, ticks, built, broke: brokeCount, incarnation };
5964
6035
  }
@@ -6014,7 +6085,7 @@ async function watchCommand(flags, context) {
6014
6085
  }
6015
6086
  stopping = true;
6016
6087
  followAbort?.abort();
6017
- wakeHubFor(context.store).poke();
6088
+ wakeHubFor(context.store, read => briefly(context.store, read)).poke();
6018
6089
  graceTimer = setTimeout(hardStop, stopGraceMs);
6019
6090
  };
6020
6091
  process.on("SIGINT", stop);
@@ -6660,6 +6731,16 @@ async function upCommand(flags, context) {
6660
6731
  workerRole = startUpRole({
6661
6732
  role: "worker", split, context, build, onSpawned: pid => roleSpawned("worker", pid),
6662
6733
  shutdownMs: Math.max(1, stopGraceMs) + 15_000,
6734
+ watchdog: {
6735
+ graceMs: stopGraceMs, say: line => roleLine("worker")(line),
6736
+ ...(context.upSeams?.watchdogSilenceMs === undefined ? {} : { silenceMs: context.upSeams.watchdogSilenceMs }),
6737
+ paused: () => briefly(store, () => {
6738
+ if (updateAdmissionPaused(store.raw()))
6739
+ return true;
6740
+ const own = store.getRunner(runnerName)?.runner;
6741
+ return own !== undefined && drainOf(store, own, clock()) !== null;
6742
+ }),
6743
+ },
6663
6744
  start: generation => ({
6664
6745
  type: "start", role: "worker", databaseFile: context.databaseFile, containment: containmentFlag, build,
6665
6746
  config: {
@@ -6704,7 +6785,17 @@ async function upCommand(flags, context) {
6704
6785
  }
6705
6786
  }
6706
6787
  const runnerHeartbeat = setInterval(() => {
6707
- const beat = heartbeatRunner(store, runnerName, runnerToken, clock());
6788
+ let beat;
6789
+ try {
6790
+ beat = briefly(store, () => heartbeatRunner(store, runnerName, runnerToken, clock()));
6791
+ }
6792
+ catch (error) {
6793
+ if (isDatabaseBusy(error) || stopping)
6794
+ return;
6795
+ fatal = `the builder's heartbeat could not be recorded (${describe(error)})`;
6796
+ stop();
6797
+ return;
6798
+ }
6708
6799
  if (!beat.ok && !stopping) {
6709
6800
  fatal = `the builder identity changed (${beat.reason})`;
6710
6801
  stop();
@@ -7537,16 +7628,24 @@ async function statusCommand(positional, flags, context) {
7537
7628
  const waiting = waitingUpdate(context.databaseFile, run => context.store.stopQuiescenceProblem(run) !== null, context.clock());
7538
7629
  const updateWaiting = waiting === null ? {} : { updateWaiting: { app: waiting.app, version: waiting.version, stopped: waiting.stopped, run: waiting.run, on: waiting.on, action: waiting.action } };
7539
7630
  const legacyWebhookWarning = loadWebhookTargets(process.env, dirname(context.databaseFile)).length > 0 ? LEGACY_WEBHOOK_WARNING : null;
7631
+ const drift = ["source", "npx", "desktop"].includes(method.kind) ? null : (() => { try {
7632
+ return serviceDriftHere(context.databaseFile, { version: current, dist: context.laptopSeams?.dist ?? currentRuntime(current).dist }, context.laptopSeams ?? {});
7633
+ }
7634
+ catch {
7635
+ return null;
7636
+ } })();
7637
+ const driftLine = drift === null ? null : driftWords(drift.service, drift.cli);
7638
+ const runtimeDrift = drift === null ? {} : { runtimeDrift: { service: drift.service.version, serviceRuntime: drift.service.dist, cli: current, words: driftLine, fix: "toolroll update --yes" } };
7540
7639
  const projects = projectBuildsStatus(context);
7541
7640
  const projectsLine = projects.length === 0 ? null
7542
- : `Builds by project: ${projects.slice(0, 8).map(one => `${one.name} ${one.running} of ${one.limit}`).join(", ")}${projects.length > 8 ? ", …" : ""}`;
7641
+ : `Builds by project: ${projects.slice(0, 8).map(one => `${one.name} ${one.running} of ${one.limit}${one.builder === "restarting" ? " (builder restarting)" : ""}`).join(", ")}${projects.length > 8 ? ", …" : ""}`;
7543
7642
  const unsent = context.store.unsentTelegramReplies(null, null, new Date(context.clock().getTime() - UNSENT_REPLY_MS));
7544
7643
  const unsentLine = unsentRepliesLine(unsent);
7545
7644
  const unsentReplies = unsent.length === 0 ? {} : { unsentReplies: unsent.map(one => ({ ...one, retry: "toolroll bridge telegram retry" })) };
7546
7645
  const laptop = { laptop: await laptopStatus(context.store, context.databaseFile, context.laptopSeams) };
7547
7646
  if (!laptop.laptop.running && laptop.laptop.background === "on" && !machineActing())
7548
7647
  await restartOwnBuilder(context.store, context.databaseFile, context.laptopSeams, context.clock()).catch(() => null);
7549
- return succeed(context.write, context.json, command, { ...status, projects, ...laptop, ...update, ...integrations, ...signedOut, ...updateWaiting, ...unsentReplies, ...(legacyWebhookWarning === null ? {} : { legacyWebhookWarning }) }, () => [...(waiting === null ? [] : [waiting.words]), ...(unsentLine === null ? [] : [unsentLine]), ...renderInstallationStatus(status), ...(projectsLine === null ? [] : [projectsLine]), ...(line === null ? [] : [line]), ...signedOutLines, ...(brokenLine === null ? [] : [brokenLine]), ...(legacyWebhookWarning === null ? [] : [legacyWebhookWarning])]);
7648
+ return succeed(context.write, context.json, command, { ...status, projects, ...laptop, ...update, ...integrations, ...signedOut, ...updateWaiting, ...runtimeDrift, ...unsentReplies, ...(legacyWebhookWarning === null ? {} : { legacyWebhookWarning }) }, () => [...(waiting === null ? [] : [waiting.words]), ...(unsentLine === null ? [] : [unsentLine]), ...renderInstallationStatus(status), ...(projectsLine === null ? [] : [projectsLine]), ...(line === null ? [] : [line]), ...(driftLine === null ? [] : [driftLine]), ...signedOutLines, ...(brokenLine === null ? [] : [brokenLine]), ...(legacyWebhookWarning === null ? [] : [legacyWebhookWarning])]);
7550
7649
  }
7551
7650
  function unsentRepliesLine(unsent) {
7552
7651
  if (unsent.length === 0)
@@ -7564,7 +7663,9 @@ function projectBuildsStatus(context) {
7564
7663
  return repos.map(repo => {
7565
7664
  const capacities = workers.filter(one => one.repos.includes(repo)).map(one => one.capacity);
7566
7665
  const setting = saved.get(repo) ?? PROJECT_CONCURRENCY_DEFAULT;
7567
- return { repo, name: projectName(repo), running: running.get(repo) ?? 0, limit: capacities.length === 0 ? setting : effectiveConcurrency(setting, Math.max(...capacities)) };
7666
+ const builders = buildersFor(context.store, repo, now);
7667
+ const restarting = builders.alive.length > 0 && builders.watching.length === 0;
7668
+ return { repo, name: projectName(repo), running: running.get(repo) ?? 0, limit: capacities.length === 0 ? setting : effectiveConcurrency(setting, Math.max(...capacities)), ...(restarting ? { builder: "restarting" } : {}) };
7568
7669
  });
7569
7670
  }
7570
7671
  async function integrationIoFor(context) {
@@ -10151,15 +10252,18 @@ async function retentionCommand(positional, flags, context) {
10151
10252
  const last = lastSweepAt(store);
10152
10253
  return succeed(context.write, context.json, command, { periods, defaulted, lastSweep: last }, () => [
10153
10254
  ...RETENTION_KINDS.map(one => ` ${one.kind.padEnd(14)} ${periodLabel(one.kind, periods[one.kind], one.kind in chosen).toLowerCase().padEnd(18)} ${one.label}`),
10255
+ ` ${NOTIFICATION_RETENTION_WORDS}`,
10154
10256
  last === null ? "No sweep yet; the worker runs one a day." : `Last sweep ${last.slice(0, 16).replace("T", " ")} UTC.`,
10155
10257
  ]);
10156
10258
  }
10157
10259
  if (action === "preview") {
10158
10260
  const plan = retentionPlan(store, context.evidenceRoot, context.clock());
10159
10261
  const kept = plan.counts.filter(one => one.days === null).map(one => one.kind);
10160
- return succeed(context.write, context.json, command, { counts: plan.counts }, () => [
10262
+ const fixed = notificationLifecyclePreview(store, context.clock());
10263
+ return succeed(context.write, context.json, command, { counts: plan.counts, lifecycle: fixed }, () => [
10161
10264
  ...plan.counts.filter(one => one.days !== null).map(one => ` ${label(one.kind).padEnd(26)} ${countWords(one)} older than ${periodWords(one.days)}, about ${bytesWords(one.bytes)}${one.more ? " (more after this sweep)" : ""}`),
10162
- kept.length === RETENTION_KINDS.length ? "Everything is kept forever; nothing would be removed." : `Nothing was removed.${kept.length === 0 ? "" : ` Kept forever: ${kept.join(", ")}.`}`,
10265
+ ` ${"Progress updates".padEnd(26)} ${fixed.pings} settled and older than ${LIFECYCLE_RETENTION_DAYS} days, task finished; ${fixed.legacy} undeliverable delivery records older than ${LIFECYCLE_RETENTION_DAYS} days`,
10266
+ kept.length === RETENTION_KINDS.length ? "Everything else is kept forever." : `Nothing was removed.${kept.length === 0 ? "" : ` Kept forever: ${kept.join(", ")}.`}`,
10163
10267
  ]);
10164
10268
  }
10165
10269
  if (action !== "set")
@@ -10713,7 +10817,7 @@ function upNeedsOneProcess(options) {
10713
10817
  return options.openDatabase !== undefined || options.desktopIdentity !== undefined || options.additionalProjectRepos !== undefined ||
10714
10818
  options.agentRunner !== undefined || options.gitRunner !== undefined || options.telegramTransport !== undefined || options.telegramEnv !== undefined ||
10715
10819
  options.publishExec !== undefined || options.dispatchAdapter !== undefined || options.flowTriggerIo !== undefined || options.flowStepIo !== undefined ||
10716
- options.flowEveryMs !== undefined || options.platform !== undefined || options.fenceAvailable !== undefined || options.flowFetch !== undefined ||
10820
+ options.flowEveryMs !== undefined || options.watchHeartbeatMs !== undefined || options.loopRelaunchMs !== undefined || options.platform !== undefined || options.fenceAvailable !== undefined || options.flowFetch !== undefined ||
10717
10821
  options.integrationIo !== undefined || options.shouldStop !== undefined || options.leadSeams !== undefined || options.waitSleep !== undefined ||
10718
10822
  options.releaseIo !== undefined || options.installBin !== undefined || options.tempRoots !== undefined || options.filingSizer !== undefined ||
10719
10823
  options.now !== undefined || options.folderLook !== undefined;
@@ -10795,6 +10899,8 @@ function startUpRole(args) {
10795
10899
  closedProblem = message.problem;
10796
10900
  return;
10797
10901
  }
10902
+ if (message.type === "alive")
10903
+ return;
10798
10904
  args.onMessage(message);
10799
10905
  };
10800
10906
  if (!args.split) {
@@ -10824,6 +10930,53 @@ function startUpRole(args) {
10824
10930
  const controller = new AbortController();
10825
10931
  let child = null;
10826
10932
  const command = upRoleChildCommand(role);
10933
+ let heardAt = Date.now();
10934
+ let stoppingSince = null;
10935
+ let liveBuilds = 0;
10936
+ let saidPaused = false;
10937
+ let saidWaiting = false;
10938
+ const watchdog = args.watchdog === undefined ? null : setInterval(() => {
10939
+ const owned = child;
10940
+ if (stopping || controller.signal.aborted || owned === null || owned.exitCode !== null || owned.signalCode !== null || !generations.current())
10941
+ return;
10942
+ const now = Date.now();
10943
+ const silentMs = now - heardAt;
10944
+ const silenceMs = args.watchdog.silenceMs ?? WORKER_SILENCE_MS;
10945
+ const facts = { silentMs, silenceMs, stoppingForMs: stoppingSince === null ? null : now - stoppingSince, graceMs: args.watchdog.graceMs, deadlineMs: SHUTDOWN_DEADLINE_MS, liveBuilds, paused: false };
10946
+ if (watchdogVerdict(facts) === "fine") {
10947
+ saidPaused = false;
10948
+ saidWaiting = false;
10949
+ return;
10950
+ }
10951
+ try {
10952
+ facts.paused = args.watchdog.paused();
10953
+ }
10954
+ catch {
10955
+ facts.paused = true;
10956
+ }
10957
+ const verdict = watchdogVerdict(facts);
10958
+ if (verdict === "leave") {
10959
+ if (!saidPaused)
10960
+ args.watchdog.say(`the ${role} isn't answering, but an update or restart is under way; leaving it to that`);
10961
+ saidPaused = true;
10962
+ return;
10963
+ }
10964
+ if (verdict === "wait") {
10965
+ if (!saidWaiting)
10966
+ args.watchdog.say(`the ${role} is still stopping: ${liveBuilds === 1 ? "a build hasn't" : `${liveBuilds} builds haven't`} confirmed ${liveBuilds === 1 ? "it" : "they"} stopped; leaving it to finish`);
10967
+ saidWaiting = true;
10968
+ return;
10969
+ }
10970
+ if (verdict !== "restart")
10971
+ return;
10972
+ args.watchdog.say(silentMs < silenceMs
10973
+ ? `the ${role}'s stop overran its deadline; stopping it and starting it again`
10974
+ : `the ${role} hasn't answered for ${Math.round(silentMs / 1000)}s; stopping it and starting it again`);
10975
+ if (!stopProcessTree(owned))
10976
+ owned.kill("SIGKILL");
10977
+ heardAt = now;
10978
+ }, WORKER_ALIVE_EVERY_MS);
10979
+ watchdog?.unref?.();
10827
10980
  const supervised = superviseController({
10828
10981
  file: command.file, argv: command.argv, signal: controller.signal, ipc: true, shutdownMs: args.shutdownMs,
10829
10982
  label: envValue(process.env, "LOG_FORMAT") === "json" ? "" : `[${role}]`,
@@ -10832,7 +10985,17 @@ function startUpRole(args) {
10832
10985
  fatal = null;
10833
10986
  failed = null;
10834
10987
  generations.spawned();
10835
- owned.on("message", raw => receive(raw, () => controller.abort()));
10988
+ heardAt = Date.now();
10989
+ stoppingSince = null;
10990
+ owned.on("message", raw => {
10991
+ heardAt = Date.now();
10992
+ const alive = roleMessage(raw, role);
10993
+ if (alive?.type === "alive") {
10994
+ stoppingSince = alive.stopping ? stoppingSince ?? heardAt : null;
10995
+ liveBuilds = alive.liveBuilds;
10996
+ }
10997
+ receive(raw, () => controller.abort());
10998
+ });
10836
10999
  owned.on("error", () => { });
10837
11000
  let recorded = false;
10838
11001
  try {
@@ -10874,11 +11037,16 @@ function startUpRole(args) {
10874
11037
  endForGood(fatal ?? `the ${role} stopped (exit ${exit})`);
10875
11038
  return;
10876
11039
  }
11040
+ if (generations.struggling()) {
11041
+ args.onEnded(`${fatal === null ? "" : `${fatal} — `}the ${role} is still restarting (${generations.notReady()} tries so far, exit ${exit})`, true);
11042
+ return;
11043
+ }
10877
11044
  args.onEnded(`${fatal === null ? "" : `${fatal} — `}the ${role} stopped unexpectedly (exit ${exit})`, true);
10878
11045
  },
10879
11046
  }).catch(error => { if (!generations.wasReady())
10880
11047
  resolveReady({ ok: false, reason: "start", detail: describe(error) }); });
10881
- const done = supervised.then(() => {
11048
+ const done = supervised.finally(() => { if (watchdog !== null)
11049
+ clearInterval(watchdog); }).then(() => {
10882
11050
  if (!generations.wasReady())
10883
11051
  resolveReady({ ok: false, ...(failed ?? { reason: "start", detail: fatal ?? `the ${role} did not start` }) });
10884
11052
  else
@@ -11063,16 +11231,35 @@ async function runUpWorkerRole(context, config, port, build) {
11063
11231
  if (terminated > 0)
11064
11232
  progress(`Stopped ${terminated} running build(s). Their work is saved, and each resumes when the builder starts again.`);
11065
11233
  };
11234
+ const loopHealth = new Map();
11235
+ let deadlineTimer;
11236
+ const stillWaitingOn = () => {
11237
+ const named = [...loopHealth.values()].map(read => read()).filter(one => one.cleanup !== null).map(one => `${projectName(one.repo)}: ${one.cleanup}`);
11238
+ return named.length === 0 ? "the worker's own shutdown" : named.join(", ");
11239
+ };
11240
+ const forceEnd = async () => {
11241
+ const waiting = stillWaitingOn();
11242
+ progress(`Stopping is taking too long (still waiting on ${waiting}); stopping this worker's builds now`);
11243
+ await endAfterExitProof({ hardStop, liveBuilds: liveProviderCount, say: progress, exit: port.exit, code: EXIT.failed,
11244
+ before: () => port.send({ type: "fatal", detail: `the worker's stop didn't finish (still waiting on ${waiting}); Toolroll is restarting it` }) });
11245
+ };
11246
+ const armDeadline = () => {
11247
+ if (deadlineTimer !== undefined)
11248
+ return;
11249
+ deadlineTimer = setTimeout(() => { void forceEnd(); }, config.stopGraceMs + SHUTDOWN_DEADLINE_MS);
11250
+ deadlineTimer.unref?.();
11251
+ };
11066
11252
  const stop = () => {
11067
11253
  if (stopping) {
11068
11254
  hardStop();
11069
11255
  return;
11070
11256
  }
11071
11257
  stopping = true;
11258
+ armDeadline();
11072
11259
  resolveStopped();
11073
11260
  for (const controller of followControllers)
11074
11261
  controller.abort();
11075
- wakeHubFor(store).poke();
11262
+ wakeHubFor(store, read => briefly(store, read)).poke();
11076
11263
  const building = store.liveClaimCount(runnerName, clock());
11077
11264
  if (building > 0) {
11078
11265
  progress(`Stopping: ${building} build(s) running. Waiting up to ${Math.round(config.stopGraceMs / 1000)}s for them to finish; any still running then is saved and resumes when the builder starts again.`);
@@ -11117,9 +11304,82 @@ async function runUpWorkerRole(context, config, port, build) {
11117
11304
  const loopResults = new Map();
11118
11305
  const projectPasses = new ProjectPasses();
11119
11306
  const releasedRepos = new Set();
11120
- const launchRepo = async (repo, bind, drain = false) => {
11307
+ const relaunches = new Map();
11308
+ const relaunchAttempts = new Map();
11309
+ const relaunchAbort = new AbortController();
11310
+ followControllers.push(relaunchAbort);
11311
+ const relaunchPause = (ms) => new Promise(resolvePause => {
11312
+ const timer = setTimeout(done, ms);
11313
+ function done() { clearTimeout(timer); relaunchAbort.signal.removeEventListener("abort", done); resolvePause(); }
11314
+ if (relaunchAbort.signal.aborted)
11315
+ done();
11316
+ else
11317
+ relaunchAbort.signal.addEventListener("abort", done, { once: true });
11318
+ });
11319
+ const scheduleRelaunch = (repo, detail) => {
11320
+ if (relaunches.has(repo) || stopping)
11321
+ return;
11322
+ const attempt = relaunchAttempts.get(repo) ?? 0;
11323
+ relaunchAttempts.set(repo, attempt + 1);
11324
+ const delay = relaunchDelayMs(attempt, context.loopRelaunchMs);
11325
+ progress(`${prefix(repo)}this project's builder stopped (${detail}); Toolroll is restarting it in ${Math.max(1, Math.round(delay / 1000))}s`);
11326
+ const pending = (async () => {
11327
+ await relaunchPause(delay);
11328
+ let waited = 0;
11329
+ let saidWaiting = false;
11330
+ for (;;) {
11331
+ if (stopping)
11332
+ return;
11333
+ if (releasedRepos.has(repo)) {
11334
+ fatal = `${prefix(repo)}${detail}`;
11335
+ stop();
11336
+ return;
11337
+ }
11338
+ if (!activeRepos.has(repo))
11339
+ return;
11340
+ let admission;
11341
+ try {
11342
+ admission = briefly(store, () => relaunchAdmission(store, runnerName, repo, clock()));
11343
+ }
11344
+ catch (error) {
11345
+ if (!isDatabaseBusy(error))
11346
+ throw error;
11347
+ await relaunchPause(relaunchDelayMs(waited++, context.loopRelaunchMs));
11348
+ continue;
11349
+ }
11350
+ if (admission === "identity") {
11351
+ fatal = `the builder identity changed while restarting ${projectName(repo)}`;
11352
+ stop();
11353
+ return;
11354
+ }
11355
+ if (admission === "gone") {
11356
+ loopResults.delete(repo);
11357
+ activeRepos.delete(repo);
11358
+ reportRepos();
11359
+ progress(`project removed — ${projectName(repo)} is no longer built here`);
11360
+ return;
11361
+ }
11362
+ if (admission === "go")
11363
+ break;
11364
+ if (!saidWaiting)
11365
+ progress(`${prefix(repo)}still restarting: waiting for ${RELAUNCH_WAIT_WORDS[admission]}`);
11366
+ saidWaiting = true;
11367
+ await relaunchPause(relaunchDelayMs(waited++, context.loopRelaunchMs));
11368
+ }
11369
+ loopResults.delete(repo);
11370
+ relaunches.delete(repo);
11371
+ await launchRepo(repo, false, false, true);
11372
+ })().catch(error => {
11373
+ fatal = `${prefix(repo)}the builder couldn't be restarted (${describe(error)})`;
11374
+ stop();
11375
+ }).finally(() => { if (relaunches.get(repo) === pending)
11376
+ relaunches.delete(repo); });
11377
+ relaunches.set(repo, pending);
11378
+ };
11379
+ const launchRepo = async (repo, bind, drain = false, relaunching = false) => {
11121
11380
  if (loopResults.has(repo) || stopping)
11122
11381
  return;
11382
+ let readyAt = null;
11123
11383
  if (drain)
11124
11384
  releasedRepos.add(repo);
11125
11385
  if (bind) {
@@ -11149,14 +11409,18 @@ async function runUpWorkerRole(context, config, port, build) {
11149
11409
  containmentLines,
11150
11410
  passes: projectPasses,
11151
11411
  serviceBridge: true,
11412
+ health: read => loopHealth.set(repo, read),
11152
11413
  leaseWaitMs: config.leaseWaitMs,
11153
11414
  ...(drain ? { leaseWaitStopping: () => stopping } : {}),
11154
11415
  onReady: () => {
11416
+ readyAt = Date.now();
11155
11417
  markReady();
11156
11418
  if (bind)
11157
11419
  progress(`${prefix(repo)}builder connected — queued work can start`);
11420
+ if (relaunching)
11421
+ progress(`${prefix(repo)}builder restarted automatically — queued work can start`);
11158
11422
  },
11159
- }).then(result => ({ repo, result }), error => ({ repo, result: { ok: false, reason: "loop-failed", detail: describe(error), ticks: 0, built: 0, broke: 0 } }));
11423
+ }).then(result => ({ repo, result }), error => ({ repo, result: { ok: false, reason: "loop-failed", detail: describe(error), ticks: 0, built: 0, broke: 0, busy: isDatabaseBusy(error) } }));
11160
11424
  loopResults.set(repo, loop);
11161
11425
  void loop.then(({ repo: endedRepo, result }) => {
11162
11426
  if (releasedRepos.has(endedRepo) && !stopping && !result.ok) {
@@ -11178,6 +11442,13 @@ async function runUpWorkerRole(context, config, port, build) {
11178
11442
  return;
11179
11443
  }
11180
11444
  if (!result.ok && !stopping) {
11445
+ if (readyAt !== null && Date.now() - readyAt >= LOOP_STABLE_MS)
11446
+ relaunchAttempts.delete(endedRepo);
11447
+ if (loopEndRecovery(result, relaunching) === "relaunch" && activeRepos.has(endedRepo)) {
11448
+ scheduleRelaunch(endedRepo, result.detail);
11449
+ markReady();
11450
+ return;
11451
+ }
11181
11452
  fatal = `${prefix(endedRepo)}${result.detail}`;
11182
11453
  stop();
11183
11454
  }
@@ -11363,10 +11634,35 @@ async function runUpWorkerRole(context, config, port, build) {
11363
11634
  : null;
11364
11635
  if (fatal === null && !stopping)
11365
11636
  port.send({ type: "ready", role: "worker", build, pid: process.pid, url: null, port: null });
11637
+ const cleanupSince = new Map();
11638
+ const aliveTimer = setInterval(() => {
11639
+ const repos = [...loopHealth.entries()].filter(([repo]) => loopResults.has(repo)).map(([, read]) => read());
11640
+ port.send({ type: "alive", stopping, repos, liveBuilds: liveProviderCount() });
11641
+ if (stopping)
11642
+ return;
11643
+ for (const one of repos) {
11644
+ if (one.cleanup === null || one.cleanup === "its builds") {
11645
+ cleanupSince.delete(one.repo);
11646
+ continue;
11647
+ }
11648
+ const since = cleanupSince.get(one.repo);
11649
+ if (since === undefined || since.stage !== one.cleanup) {
11650
+ cleanupSince.set(one.repo, { stage: one.cleanup, at: Date.now() });
11651
+ continue;
11652
+ }
11653
+ if (Date.now() - since.at < config.stopGraceMs + SHUTDOWN_DEADLINE_MS)
11654
+ continue;
11655
+ fatal = `${prefix(one.repo)}its loop stopped but never finished stopping (still waiting on ${one.cleanup})`;
11656
+ stop();
11657
+ return;
11658
+ }
11659
+ }, WORKER_ALIVE_EVERY_MS);
11660
+ aliveTimer.unref?.();
11366
11661
  await stopped;
11367
11662
  if (readinessTimer !== undefined)
11368
11663
  clearInterval(readinessTimer);
11369
11664
  await registrySupervisor;
11665
+ await Promise.all([...relaunches.values()]);
11370
11666
  await Promise.all([...loopResults.values()]);
11371
11667
  await stopLiveBackups?.();
11372
11668
  await new Promise(done => {
@@ -11376,6 +11672,9 @@ async function runUpWorkerRole(context, config, port, build) {
11376
11672
  });
11377
11673
  if (graceTimer !== undefined)
11378
11674
  clearTimeout(graceTimer);
11675
+ if (deadlineTimer !== undefined)
11676
+ clearTimeout(deadlineTimer);
11677
+ clearInterval(aliveTimer);
11379
11678
  if (fatal !== null) {
11380
11679
  port.send({ type: "fatal", detail: fatal });
11381
11680
  return EXIT.failed;
@@ -12473,10 +12772,11 @@ function startServiceBeats(store) {
12473
12772
  shouldStop: () => beats.stopped,
12474
12773
  onError: () => { },
12475
12774
  run: async () => {
12476
- const standing = () => !beats.stopped && beats.members.size > 0 && [...beats.members].every(one => one.ciReady());
12775
+ const standingMembers = () => [...beats.members].filter(one => one.stopping?.() !== true);
12776
+ const standing = () => { const members = standingMembers(); return !beats.stopped && members.length > 0 && members.every(one => one.ciReady()); };
12477
12777
  if (!standing())
12478
12778
  return;
12479
- const { context, progress } = beats.members.values().next().value;
12779
+ const { context, progress } = standingMembers()[0];
12480
12780
  const now = context.clock();
12481
12781
  const waiting = fastCiWaiting(store, now, FAST_CI_LIMIT, attempted);
12482
12782
  if (waiting.length === 0)
@@ -12499,7 +12799,7 @@ function startServiceBeats(store) {
12499
12799
  },
12500
12800
  });
12501
12801
  const poker = new WakePoker();
12502
- const hub = wakeHubFor(store);
12802
+ const hub = wakeHubFor(store, read => briefly(store, read));
12503
12803
  const beats = { members: new Set(), stopped: false, delivery, fastCi, poker, wakeLoop: Promise.resolve() };
12504
12804
  beats.wakeLoop = (async () => {
12505
12805
  while (!beats.stopped) {
@@ -13580,3 +13880,40 @@ function acceptedWords(completion) {
13580
13880
  const by = completedByOf(completion);
13581
13881
  return by === null ? "accepted" : `accepted by ${by}`;
13582
13882
  }
13883
+ function renewalRefusedWords(reason) {
13884
+ switch (reason) {
13885
+ case "taken": return "another watch took this project over";
13886
+ case "missing": return "the project's lease record is gone (the project was removed)";
13887
+ case "unbound": return "the project is no longer connected to this builder";
13888
+ case "paused": return "the lease lapsed while an update or restart was under way";
13889
+ case "error": return "the renewal failed";
13890
+ default: return `the builder's credential no longer holds (${reason})`;
13891
+ }
13892
+ }
13893
+ const CHAT_CONFIG_FAILURE = /\b(invalid_auth|not_authed|account_inactive|token_revoked|unauthori[sz]ed|forbidden|401|403|missing_scope|invalid token|bad token)\b/i;
13894
+ async function superviseChatFollower(name, signal, progress, start) {
13895
+ const pause = abortablePause(signal);
13896
+ let attempt = 0;
13897
+ while (!signal.aborted) {
13898
+ const began = Date.now();
13899
+ try {
13900
+ await start();
13901
+ return;
13902
+ }
13903
+ catch (error) {
13904
+ if (signal.aborted)
13905
+ return;
13906
+ if (Date.now() - began >= 60_000)
13907
+ attempt = 0;
13908
+ const delay = Math.min(30_000, 1_000 * 2 ** Math.min(attempt++, 5));
13909
+ const detail = describe(error);
13910
+ progress(CHAT_CONFIG_FAILURE.test(detail)
13911
+ ? `watch: ${name} stopped (${detail.slice(0, 160)}). Check ${name} settings; Toolroll tries again in ${Math.round(delay / 1000)}s.`
13912
+ : `watch: ${name} stopped for a moment (${isDatabaseBusy(error) ? "the database was busy" : detail.slice(0, 160)}); reconnecting in ${Math.round(delay / 1000)}s.`);
13913
+ await pause(delay);
13914
+ }
13915
+ }
13916
+ }
13917
+ function busyFailure(error) {
13918
+ return isDatabaseBusy(error) || /\b(database[- ](is )?(locked|busy)|SQLITE_BUSY)\b/i.test(describe(error));
13919
+ }