toolroll 0.9.130 → 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 (63) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/agent-state.js +1 -1
  3. package/dist/browser/manifest.json +14 -14
  4. package/dist/browser/{terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js} +1 -1
  5. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.br +0 -0
  6. package/dist/browser/{terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.gz} +0 -0
  7. package/dist/browser/{workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js → workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js} +1 -1
  8. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.br +0 -0
  9. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.gz +0 -0
  10. package/dist/builder-restart.js +13 -4
  11. package/dist/builder.js +4 -1
  12. package/dist/central-recovery-stage.js +2 -2
  13. package/dist/chat-follow.js +4 -0
  14. package/dist/db-tuning.js +16 -0
  15. package/dist/discord.js +9 -3
  16. package/dist/dispatch.js +32 -4
  17. package/dist/doctor.js +30 -0
  18. package/dist/evidence.js +49 -3
  19. package/dist/exec.js +3 -0
  20. package/dist/git-views.js +7 -1
  21. package/dist/invoke.js +12 -2
  22. package/dist/lead-queue-runtime.js +8 -5
  23. package/dist/lead-status.js +3 -3
  24. package/dist/loop-recovery.js +40 -0
  25. package/dist/maintenance.js +29 -1
  26. package/dist/needs-you.js +2 -0
  27. package/dist/operate.js +376 -52
  28. package/dist/planner.js +4 -1
  29. package/dist/query-index-schema.js +10 -0
  30. package/dist/read-executor-worker.js +9 -7
  31. package/dist/read-executor.js +18 -1
  32. package/dist/read-worker-connection.js +7 -0
  33. package/dist/release-adapters.js +51 -6
  34. package/dist/release-cli.js +24 -11
  35. package/dist/release-next.js +1 -1
  36. package/dist/release-stops.js +71 -0
  37. package/dist/release-supersede.js +125 -0
  38. package/dist/release-supervise.js +90 -0
  39. package/dist/release.js +252 -40
  40. package/dist/runner.js +36 -1
  41. package/dist/scout.js +4 -1
  42. package/dist/serve.js +92 -6
  43. package/dist/shutdown-proof.js +29 -0
  44. package/dist/slack.js +9 -3
  45. package/dist/sqlite-telemetry.js +26 -14
  46. package/dist/statement-cache.js +137 -0
  47. package/dist/store.js +70 -13
  48. package/dist/task-status.js +1 -1
  49. package/dist/teams.js +9 -3
  50. package/dist/teardown-git.js +10 -1
  51. package/dist/telegram.js +4 -1
  52. package/dist/up-processes.js +16 -1
  53. package/dist/up-role-child.js +2 -0
  54. package/dist/wake-hub.js +15 -6
  55. package/dist/work-index.js +101 -44
  56. package/dist/work-reads.js +53 -9
  57. package/dist/work-snapshots.js +185 -0
  58. package/dist/worker-statement-cache.js +83 -0
  59. package/dist/workspace-revision.js +145 -21
  60. package/package.json +1 -1
  61. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
  62. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
  63. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
@@ -2,7 +2,9 @@ import { updateAdmissionPaused } from "./desktop-update-gate.js";
2
2
  import { drainOf } from "./runner.js";
3
3
  import { readSchemaVersion } from "./store.js";
4
4
  export const RESTART_LIMIT = 3;
5
- export const RESTART_WINDOW_MS = 30 * 60_000;
5
+ export const RESTART_BACKOFF_MS = 5 * 60_000;
6
+ export const RESTART_BACKOFF_MAX_MS = 30 * 60_000;
7
+ export const RESTART_MEMORY_MS = 6 * 60 * 60_000;
6
8
  export function builderWish(store) {
7
9
  const row = store.handle.prepare("SELECT desired, build, schema_version, set_by, set_at FROM builder_service WHERE id = 1").get();
8
10
  return row === undefined ? null : { desired: row["desired"] === "running" ? "running" : "stopped", build: String(row["build"]), schema: Number(row["schema_version"]), setBy: String(row["set_by"]), setAt: String(row["set_at"]) };
@@ -27,11 +29,18 @@ export function admitBuilderRestart(store, now) {
27
29
  return "not-wanted";
28
30
  if (restartPaused(store, now))
29
31
  return "paused";
30
- const since = new Date(now.getTime() - RESTART_WINDOW_MS).toISOString();
31
- const tried = Number(store.handle.prepare("SELECT COUNT(*) AS n FROM builder_restart WHERE at > ?").get(since)?.["n"] ?? 0);
32
- if (tried >= RESTART_LIMIT)
32
+ if (restartBackoffMs(store, now) > 0)
33
33
  return "attempts";
34
34
  store.handle.prepare("INSERT INTO builder_restart (at) VALUES (?)").run(now.toISOString());
35
35
  return "admitted";
36
36
  });
37
37
  }
38
+ export function restartBackoffMs(store, now) {
39
+ const remembered = new Date(now.getTime() - RESTART_MEMORY_MS).toISOString();
40
+ const row = store.handle.prepare("SELECT COUNT(*) AS n, MAX(at) AS last FROM builder_restart WHERE at > ?").get(remembered);
41
+ const count = Number(row?.["n"] ?? 0);
42
+ if (count < RESTART_LIMIT || row?.["last"] == null)
43
+ return 0;
44
+ const wait = Math.min(RESTART_BACKOFF_MAX_MS, RESTART_BACKOFF_MS * 2 ** Math.min(count - RESTART_LIMIT, 8));
45
+ return Math.max(0, Date.parse(String(row["last"])) + wait - now.getTime());
46
+ }
package/dist/builder.js CHANGED
@@ -32,6 +32,7 @@ import { stopRequestedFor, stopWords, underStopWatch } from "./task-control.js";
32
32
  import { witnessedRunner } from "./process-custody.js";
33
33
  import { runWithIsolatedDatabase } from "./child-database.js";
34
34
  import { recordWorktreeProcess, saveWorkPatch } from "./worktree.js";
35
+ import { isDatabaseBusy } from "./store.js";
35
36
  import { launchSandboxOf, protectedChanges, protectedLinks } from "./agent-fence.js";
36
37
  import { fallbackBriefFor, pinnedEntryOf, ranOutOnChain } from "./fallback.js";
37
38
  import { approvalOf, digestOf, idleClock, isAcpProfile, LIVE_CHAIN_VERSION, liveChainFromJson, profileDigestOf, releaseCheckScope, routeParityProblem, watchdogsOf } from "./scope.js";
@@ -797,7 +798,9 @@ export async function build(store, request) {
797
798
  if (!answer.ok)
798
799
  fencedMidBuild = true;
799
800
  }
800
- catch {
801
+ catch (error) {
802
+ if (isDatabaseBusy(error))
803
+ return;
801
804
  fencedMidBuild = true;
802
805
  }
803
806
  if (!fencedMidBuild) {
@@ -6,9 +6,9 @@ import { openStore } from "./store.js";
6
6
  import { holdAutoPublish, autoPublishHeld, PUBLISH_ALLOWED_ACTION, PUBLISH_HELD_ACTION } from "./release-auto.js";
7
7
  import { revokeCoordinator } from "./coordinator.js";
8
8
  export const MAX_STAGE_BYTES = 128 * 1024 * 1024;
9
- const SUPPORTED_SCHEMA = 189;
9
+ const SUPPORTED_SCHEMA = 190;
10
10
  const SCHEMA_OBJECT_COUNT = 744;
11
- const SCHEMA_DIGEST = "a82e2481b74fe91978efbec608e791876bb909df9a54acf084820fdcbab81cd8";
11
+ const SCHEMA_DIGEST = "2c8956f909b9e12062c684ab857dff4737929172b510da6f4fece6b3a49112ad";
12
12
  const INVENTORY = [
13
13
  ["person-credentials", "store.ts:revokeApiToken", "credential", true],
14
14
  ["lead-credentials", "store.ts:revokeLeadCredentials", "credential", true],
@@ -1,4 +1,8 @@
1
1
  import { setTimeout as sleep } from "node:timers/promises";
2
+ export const busyError = (error) => {
3
+ const code = error?.errcode;
4
+ return typeof code === "number" && (code & 0xff) === 5;
5
+ };
2
6
  export const abortablePause = (signal) => async (ms) => {
3
7
  try {
4
8
  await sleep(ms, undefined, { signal });
@@ -0,0 +1,16 @@
1
+ export const CONNECTION_PROFILE = Object.freeze({
2
+ cacheSizeKiB: 32 * 1024,
3
+ tempStore: 'MEMORY',
4
+ journalSizeLimitBytes: 64 * 1024 * 1024,
5
+ });
6
+ export function connectionProfilePragmas(profile = CONNECTION_PROFILE) {
7
+ return [`PRAGMA cache_size = -${profile.cacheSizeKiB}`, `PRAGMA journal_size_limit = ${profile.journalSizeLimitBytes}`, `PRAGMA temp_store = ${profile.tempStore}`];
8
+ }
9
+ export function tuneConnection(db) {
10
+ for (const pragma of connectionProfilePragmas()) {
11
+ try {
12
+ db.exec(pragma);
13
+ }
14
+ catch { }
15
+ }
16
+ }
package/dist/discord.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { abortablePause, workChatQueue } from "./chat-follow.js";
2
+ import { abortablePause, busyError, workChatQueue } from "./chat-follow.js";
3
3
  import { loadDiscordCredentials, discordApi, object, discordId, } from "./discord-api.js";
4
4
  import { ChatState, chatHash } from "./chat-delivery-state.js";
5
5
  import { runChatAcks } from "./chat-live.js";
@@ -45,8 +45,14 @@ export async function followDiscord(options) {
45
45
  };
46
46
  options.signal.addEventListener("abort", stop, { once: true });
47
47
  const heartbeat = setInterval(() => {
48
- if (!same() || !state.lease(credentials.installation, owner, new Date()))
49
- stop();
48
+ try {
49
+ if (!same() || !state.lease(credentials.installation, owner, new Date()))
50
+ stop();
51
+ }
52
+ catch (error) {
53
+ if (!busyError(error))
54
+ stop();
55
+ }
50
56
  }, 10_000);
51
57
  const online = () => {
52
58
  if (!same() || !validated)
package/dist/dispatch.js CHANGED
@@ -151,10 +151,17 @@ export function buildersFor(store, repo, now, assignedRunner = null) {
151
151
  const all = store.listRunners().filter(one => one.retiredAt === null);
152
152
  const bound = all.filter(one => one.repos.includes(repo));
153
153
  const eligible = assignedRunner === null ? bound : bound.filter(one => one.name === assignedRunner);
154
- return { all, eligible, alive: eligible.filter(one => isAlive(one, now)) };
154
+ const alive = eligible.filter(one => isAlive(one, now));
155
+ return { all, eligible, alive, watching: alive.filter(one => watchingProject(store, one.name, repo, now)) };
155
156
  }
157
+ export function watchingProject(store, runner, repo, now) {
158
+ const row = store.handle.prepare("SELECT MAX(expires_at) AS until FROM watch_lease WHERE runner = ? AND repo = ?").get(runner, repo);
159
+ const until = row?.["until"];
160
+ return until === null || until === undefined || String(until) > now.toISOString();
161
+ }
162
+ export const WATCH_STALLED_WORDS = "This project's builder stopped; Toolroll is restarting it.";
156
163
  export function builderReadyFor(store, repo, now) {
157
- return repo !== null && buildersFor(store, repo, now).alive.length > 0;
164
+ return repo !== null && buildersFor(store, repo, now).watching.length > 0;
158
165
  }
159
166
  export function firstRunBuilderRepo(store, selected, visible, managed) {
160
167
  if (selected !== null)
@@ -275,7 +282,7 @@ export function diagnoseTaskDispatch(store, taskId, now, readableRepos = null) {
275
282
  const gap = missingCapability(store, ref.id, ref.repo, now);
276
283
  if (gap !== null)
277
284
  return answer("missing-requirement", "waiting", "Missing a requirement", gap, { action: "repair-capability", role });
278
- const { all, eligible, alive } = buildersFor(store, ref.repo, now, ref.assignedRunner);
285
+ const { all, eligible, alive, watching } = buildersFor(store, ref.repo, now, ref.assignedRunner);
279
286
  if (eligible.length === 0) {
280
287
  const detail = ref.assignedRunner === null
281
288
  ? all.length === 0
@@ -287,7 +294,9 @@ export function diagnoseTaskDispatch(store, taskId, now, readableRepos = null) {
287
294
  if (alive.length === 0) {
288
295
  return answer("no-worker-online", "waiting", "Builder disconnected", `${eligible.length === 1 ? "The builder for this project has" : "All builders for this project have"} stopped checking in. This task starts automatically when ${eligible.length === 1 ? "it reconnects" : "one reconnects"}.`, { action: "start-worker", role });
289
296
  }
290
- const available = alive.filter(one => store.liveClaimCount(one.name, now) < one.capacity);
297
+ if (watching.length === 0)
298
+ return answer("watch-stalled", "waiting", "Builder restarting", WATCH_STALLED_WORDS, { role });
299
+ const available = watching.filter(one => store.liveClaimCount(one.name, now) < one.capacity);
291
300
  if (available.length === 0)
292
301
  return answer("worker-at-capacity", "retrying", "Waiting its turn", "Builders are busy; it starts when one is free.", { role });
293
302
  const profile = approvedProfile(scope);
@@ -401,3 +410,22 @@ function plannerIncident(store, ownerId) {
401
410
  return null;
402
411
  return row["kind"] === "plan-attempts-exhausted" ? "stalled" : "invalid";
403
412
  }
413
+ export function watchStalledProjects(store, now, limit = 500) {
414
+ const ready = new Map();
415
+ const queued = store.handle.prepare(`SELECT t.id AS id, tr.repo AS repo FROM task t JOIN task_ref tr ON tr.backend = ? AND tr.external_id = t.id
416
+ WHERE t.state = 'queued' AND tr.repo IS NOT NULL ORDER BY t.id LIMIT ?`).all(BUILT_IN, limit);
417
+ for (const row of queued) {
418
+ if (diagnoseTaskDispatch(store, String(row["id"]), now)?.code !== "watch-stalled")
419
+ continue;
420
+ ready.set(String(row["repo"]), (ready.get(String(row["repo"])) ?? 0) + 1);
421
+ }
422
+ const repos = new Set(ready.keys());
423
+ for (const runner of store.listRunners())
424
+ if (runner.retiredAt === null)
425
+ for (const repo of runner.repos)
426
+ repos.add(repo);
427
+ return [...repos].sort().flatMap(repo => {
428
+ const builders = buildersFor(store, repo, now);
429
+ return builders.alive.length > 0 && builders.watching.length === 0 ? [{ repo, ready: ready.get(repo) ?? 0 }] : [];
430
+ });
431
+ }
package/dist/doctor.js CHANGED
@@ -383,6 +383,9 @@ export function doctorLines(report) {
383
383
  lines.push(...report.sandbox.repair, ...report.sandbox.kind === "trust" ? ["Then run `toolroll doctor` again."] : []);
384
384
  for (const agent of report.agents ?? [])
385
385
  lines.push("", `${agent.name}: ${agent.problem}`);
386
+ for (const one of report.builders ?? []) {
387
+ lines.push("", `Builder: ${one.project}'s builder stopped; Toolroll is restarting it.${one.ready === 0 ? "" : ` ${one.ready === 1 ? "1 ready task waits" : `${one.ready} ready tasks wait`} for it.`}`);
388
+ }
386
389
  if (report.checked.length > 0)
387
390
  lines.push("", "Checked:", ...report.checked.map(one => ` ${one}`));
388
391
  return lines;
@@ -409,6 +412,9 @@ export async function runDoctorCommand(argv, write, deps = {}) {
409
412
  report.processIdentity = { problem: deps.processIdentityProblem === undefined ? processIdentityProblem() : deps.processIdentityProblem };
410
413
  if (report.processIdentity.problem !== null)
411
414
  report.ok = false;
415
+ const builders = await stalledBuilders(deps.databaseFile, deps.env ?? process.env, deps.home ?? homedir());
416
+ if (builders !== null)
417
+ report.builders = builders;
412
418
  if (json)
413
419
  write(envelopeJson({ command: "doctor", ...report }));
414
420
  else
@@ -416,3 +422,27 @@ export async function runDoctorCommand(argv, write, deps = {}) {
416
422
  write(line);
417
423
  return report.ok ? 0 : 1;
418
424
  }
425
+ async function stalledBuilders(given, env, home) {
426
+ const { openStoreNoMigrate, databasePath } = await import("./store.js");
427
+ const databaseFile = given ?? databasePath(env, home);
428
+ const { watchStalledProjects } = await import("./dispatch.js");
429
+ const { projectName } = await import("./project.js");
430
+ let opened;
431
+ try {
432
+ opened = openStoreNoMigrate(databaseFile);
433
+ }
434
+ catch {
435
+ return null;
436
+ }
437
+ if (!opened.ok)
438
+ return null;
439
+ try {
440
+ return watchStalledProjects(opened.store, new Date()).map(one => ({ project: projectName(one.repo), repo: one.repo, ready: one.ready }));
441
+ }
442
+ catch {
443
+ return null;
444
+ }
445
+ finally {
446
+ opened.store.close();
447
+ }
448
+ }
package/dist/evidence.js CHANGED
@@ -293,7 +293,48 @@ export function storeEvidence(store, root, runId, kind, name, content, capture,
293
293
  }, now);
294
294
  }
295
295
  export function readVerifiedArtifact(root, artifact) {
296
- return withArtifactFile(root, artifact, readAndHash);
296
+ return withArtifactFile(root, artifact, (fd, stat, memoKey) => {
297
+ const identity = fileIdentity(artifact, stat), kept = VERIFIED_BYTES.get(memoKey);
298
+ if (displayReads > 0 && kept !== undefined && kept.identity === identity && VERIFIED_FILES.get(memoKey) === identity)
299
+ return { ok: true, content: Buffer.from(kept.content) };
300
+ const read = readAndHash(fd, stat, memoKey, artifact);
301
+ if (read.ok)
302
+ keepBytes(memoKey, identity, read.content);
303
+ return read;
304
+ });
305
+ }
306
+ let displayReads = 0;
307
+ export function forDisplay(read) {
308
+ displayReads++;
309
+ try {
310
+ return read();
311
+ }
312
+ finally {
313
+ displayReads--;
314
+ }
315
+ }
316
+ const VERIFIED_BYTES = new Map();
317
+ const VERIFIED_BYTES_LIMIT = 16 * 1024 * 1024;
318
+ const VERIFIED_BYTES_ENTRY_MAX = 1024 * 1024;
319
+ const VERIFIED_BYTES_COUNT = 2_048;
320
+ let verifiedBytesHeld = 0, hashedSoFar = 0;
321
+ export function verifiedBytesForTests() {
322
+ return { entries: VERIFIED_BYTES.size, bytes: verifiedBytesHeld, empty: [...VERIFIED_BYTES.values()].filter(one => one.content.length === 0).length, hashed: hashedSoFar };
323
+ }
324
+ function forgetBytes(memoKey) {
325
+ const kept = VERIFIED_BYTES.get(memoKey);
326
+ if (kept === undefined)
327
+ return;
328
+ verifiedBytesHeld -= kept.content.length;
329
+ VERIFIED_BYTES.delete(memoKey);
330
+ }
331
+ function keepBytes(memoKey, identity, content) {
332
+ if (content.length === 0 || content.length > VERIFIED_BYTES_ENTRY_MAX)
333
+ return;
334
+ while (VERIFIED_BYTES.size > 0 && (VERIFIED_BYTES.size >= VERIFIED_BYTES_COUNT || verifiedBytesHeld + content.length > VERIFIED_BYTES_LIMIT))
335
+ forgetBytes(VERIFIED_BYTES.keys().next().value);
336
+ VERIFIED_BYTES.set(memoKey, { identity, content: Buffer.from(content) });
337
+ verifiedBytesHeld += content.length;
297
338
  }
298
339
  export function verifyArtifact(root, artifact) {
299
340
  return withArtifactFile(root, artifact, (fd, stat, memoKey) => {
@@ -355,6 +396,8 @@ function withArtifactFile(root, artifact, use) {
355
396
  }
356
397
  function readAndHash(fd, stat, memoKey, artifact) {
357
398
  VERIFIED_FILES.delete(memoKey);
399
+ forgetBytes(memoKey);
400
+ hashedSoFar++;
358
401
  const buffer = Buffer.alloc(artifact.bytesStored);
359
402
  let offset = 0;
360
403
  while (offset < buffer.length) {
@@ -369,8 +412,11 @@ function readAndHash(fd, stat, memoKey, artifact) {
369
412
  if (digest !== artifact.sha256) {
370
413
  return { ok: false, problem: "the file no longer hashes to its record" };
371
414
  }
372
- if (VERIFIED_FILES.size >= VERIFIED_FILES_LIMIT)
373
- VERIFIED_FILES.delete(VERIFIED_FILES.keys().next().value);
415
+ if (VERIFIED_FILES.size >= VERIFIED_FILES_LIMIT) {
416
+ const oldest = VERIFIED_FILES.keys().next().value;
417
+ VERIFIED_FILES.delete(oldest);
418
+ forgetBytes(oldest);
419
+ }
374
420
  VERIFIED_FILES.set(memoKey, fileIdentity(artifact, stat));
375
421
  return { ok: true, content: buffer };
376
422
  }
package/dist/exec.js CHANGED
@@ -285,6 +285,9 @@ export function terminateLiveProviders() {
285
285
  }
286
286
  return terminated;
287
287
  }
288
+ export function liveProviderCount() {
289
+ return liveProviders.size;
290
+ }
288
291
  const CHAT_KEYS_NEVER_INHERITED = ["ANTHROPIC_API_KEY"];
289
292
  function resolveChildEnv(options) {
290
293
  const { env, omitEnv, envAllowlist } = options;
package/dist/git-views.js CHANGED
@@ -60,7 +60,7 @@ export async function lockCheckout(home, checkout, timeoutMs = 10 * 60_000) {
60
60
  throw error;
61
61
  }
62
62
  if (Date.now() > deadline)
63
- throw new Error("another of Toolroll's git commands on this checkout is still running");
63
+ throw new CheckoutBusy();
64
64
  await new Promise(done => setTimeout(done, 25));
65
65
  }
66
66
  }
@@ -97,3 +97,9 @@ export async function withCheckoutLock(home, checkout, work, timeoutMs) {
97
97
  release();
98
98
  }
99
99
  }
100
+ export class CheckoutBusy extends Error {
101
+ constructor() {
102
+ super("another of Toolroll's git commands on this checkout is still running");
103
+ this.name = "CheckoutBusy";
104
+ }
105
+ }
package/dist/invoke.js CHANGED
@@ -457,11 +457,11 @@ export async function invokeAgent(store, runId, spec, invocation, options) {
457
457
  ? runCommand(executable, ["sandbox", ...codexFenceArgv(fence, invocation.skipPermissions, grants),
458
458
  "-P", "standing-orders", "--", file, ...args], probeOptions)
459
459
  : runCommand(file, args, { ...probeOptions, fence: launchOptions.fence, confinement: "required",
460
- ...(launchOptions.fenceGrants === undefined ? {} : { fenceGrants: launchOptions.fenceGrants }) });
460
+ ...(launchOptions.fenceGrants === undefined ? {} : { fenceGrants: probeGrants(launchOptions.fenceGrants) }) });
461
461
  const check = await insideFence("git", gitArgs);
462
462
  if (check.code !== 0) {
463
463
  const trivial = await insideFence("true", []);
464
- if (trivial.code === 0)
464
+ if (fenceBlocksGit(check, trivial))
465
465
  return { kind: "refused", reason: "containment", providerVersion: attested?.version ?? null,
466
466
  diagnostic: "The build fence blocks this checkout's own Git data.\n\nDetails:\n" + check.stderr.slice(0, 2000) + "\nDenied paths:\n" + fence.join("\n").slice(0, 12000) };
467
467
  }
@@ -1106,3 +1106,13 @@ export function keptCodexSessions(store, taskRef) {
1106
1106
  });
1107
1107
  return folder;
1108
1108
  }
1109
+ const SANDBOX_NOT_STARTED = "toolroll sandbox: nothing was started";
1110
+ export function fenceBlocksGit(check, trivial) {
1111
+ if (check.code === 0 || trivial.code !== 0)
1112
+ return false;
1113
+ return !(check.code === 126 && check.stderr.includes(SANDBOX_NOT_STARTED));
1114
+ }
1115
+ export function probeGrants(grants) {
1116
+ const { network: _network, ...files } = grants;
1117
+ return files;
1118
+ }
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from "node:crypto";
3
3
  import { runLeadTurn } from "./lead.js";
4
4
  import { PersonalQueue } from "./lead-queue.js";
5
5
  import { verifyApproverStanding } from "./principal.js";
6
+ import { briefly } from "./store.js";
6
7
  import { updateAdmissionPaused } from "./desktop-update-gate.js";
7
8
  import { TURN_WALL_CLOCK_MS } from "./converse.js";
8
9
  import { withActor } from "./actor.js";
@@ -134,10 +135,12 @@ export function createPersonalQueueRuntime(options) {
134
135
  return;
135
136
  passing = true;
136
137
  try {
137
- queue.reconcile(clock(), TURN_WALL_CLOCK_MS + 60_000);
138
- cancelFallenPhoneWork(store, clock());
138
+ briefly(store, () => {
139
+ queue.reconcile(clock(), TURN_WALL_CLOCK_MS + 60_000);
140
+ cancelFallenPhoneWork(store, clock());
141
+ });
139
142
  for (;;) {
140
- const claim = queue.claimNext(runner, clock(), row => waiting.get(row.message) !== stamp(row));
143
+ const claim = briefly(store, () => queue.claimNext(runner, clock(), row => waiting.get(row.message) !== stamp(row)));
141
144
  if (claim === null)
142
145
  break;
143
146
  waiting.delete(claim.message);
@@ -156,7 +159,7 @@ export function createPersonalQueueRuntime(options) {
156
159
  const scope = detached;
157
160
  if (scope === null || closed)
158
161
  return;
159
- scope.runInAsyncScope(() => { setImmediate(() => { void pass(); }); });
162
+ scope.runInAsyncScope(() => { setImmediate(() => { void pass().catch(() => undefined); }); });
160
163
  },
161
164
  async drain() {
162
165
  await pass();
@@ -166,7 +169,7 @@ export function createPersonalQueueRuntime(options) {
166
169
  if (timer !== null || closed)
167
170
  return;
168
171
  detached = new AsyncResource("lead-queue-runtime");
169
- detached.runInAsyncScope(() => { timer = setInterval(() => { void pass(); }, options.everyMs ?? 2_000); timer.unref(); });
172
+ detached.runInAsyncScope(() => { timer = setInterval(() => { void pass().catch(() => undefined); }, options.everyMs ?? 2_000); timer.unref(); });
170
173
  },
171
174
  async close() { closed = true; if (timer !== null)
172
175
  clearInterval(timer); timer = null; await Promise.allSettled([...active]); },
@@ -122,9 +122,9 @@ export function taskWaitSnapshot(store, taskId, now, watchedRun) {
122
122
  if (!approvedNow || scope["profile_state"] !== "resolved")
123
123
  return answer("Needs a person", "Approve task", true, 1, "needs-person");
124
124
  if (state === "running" && attempt === undefined) {
125
- const liveClaim = store.handle.prepare(`SELECT 1 AS hit FROM claim INDEXED BY claim_by_task
125
+ const liveClaim = store.handle.prepare(`SELECT 1 AS hit FROM claim
126
126
  WHERE task_ref = ? AND released_at IS NULL AND expires_at > ?
127
- AND lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest INDEXED BY claim_by_task WHERE newest.task_ref = ?)
127
+ AND lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest WHERE newest.task_ref = ?)
128
128
  LIMIT 1`).get(taskRef, now.toISOString(), taskRef);
129
129
  if (liveClaim !== undefined)
130
130
  return answer("Queued", "Wait for attempt to start", false, null, null);
@@ -172,7 +172,7 @@ export function installationStatus(store, now, viewer = currentActor()?.account
172
172
  JOIN task_ref AS ref ON ref.id = run.task_ref
173
173
  JOIN claim ON claim.lease_id = run.lease_id
174
174
  WHERE run.outcome IS NULL AND claim.released_at IS NULL AND claim.expires_at > ?
175
- AND claim.lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest INDEXED BY claim_by_task WHERE newest.task_ref = run.task_ref)
175
+ AND claim.lease_generation = (SELECT MAX(newest.lease_generation) FROM claim AS newest WHERE newest.task_ref = run.task_ref)
176
176
  ORDER BY run.id`).all(now.toISOString()).filter(admitted);
177
177
  const phases = new Map();
178
178
  const runningTasks = runningRows.map(row => {
@@ -0,0 +1,40 @@
1
+ import { builderWish } from "./builder-restart.js";
2
+ import { updateAdmissionPaused } from "./desktop-update-gate.js";
3
+ import { drainOf } from "./runner.js";
4
+ const LEASE_CAUSES_RELAUNCHED = new Set(["taken", "missing", "unbound", "paused"]);
5
+ export function loopEndRecovery(end, relaunching) {
6
+ if (end.ok)
7
+ return "done";
8
+ if (end.cleanupIncomplete === true)
9
+ return "fatal";
10
+ switch (end.reason) {
11
+ case "watch-busy": return relaunching ? "relaunch" : "fatal";
12
+ case "lease-lost": return end.lost !== undefined && LEASE_CAUSES_RELAUNCHED.has(end.lost) ? "relaunch" : "fatal";
13
+ case "reconciliation-failed":
14
+ case "loop-failed": return end.busy === true ? "relaunch" : "fatal";
15
+ }
16
+ }
17
+ export function relaunchAdmission(store, runner, repo, now) {
18
+ const found = store.getRunner(runner);
19
+ if (found === null || found.runner.retiredAt !== null)
20
+ return "identity";
21
+ if (!found.runner.repos.includes(repo))
22
+ return "gone";
23
+ if (updateAdmissionPaused(store.raw()))
24
+ return "update";
25
+ if (drainOf(store, found.runner, now) !== null)
26
+ return "drain";
27
+ if (builderWish(store)?.desired === "stopped")
28
+ return "stopped";
29
+ return "go";
30
+ }
31
+ export const RELAUNCH_WAIT_WORDS = {
32
+ update: "the app update to finish",
33
+ drain: "Toolroll's restart to finish",
34
+ stopped: "the builder to be turned back on",
35
+ };
36
+ export const LOOP_RELAUNCH_MAX_MS = 30_000;
37
+ export function relaunchDelayMs(attempt, firstMs = 1_000) {
38
+ return Math.min(LOOP_RELAUNCH_MAX_MS, firstMs * 2 ** Math.min(Math.max(attempt, 0), 16));
39
+ }
40
+ export const LOOP_STABLE_MS = 60_000;
@@ -4,19 +4,39 @@ export function startMaintenance(args) {
4
4
  }
5
5
  let stopped = false;
6
6
  let pending = null;
7
+ let failures = 0;
8
+ let retry = null;
7
9
  const runNow = () => {
8
10
  if (stopped || args.shouldStop())
9
11
  return Promise.resolve();
10
12
  if (pending !== null)
11
13
  return pending;
14
+ if (retry !== null) {
15
+ clearTimeout(retry);
16
+ retry = null;
17
+ }
12
18
  pending = Promise.resolve().then(async () => {
13
- if (!stopped && !args.shouldStop())
19
+ if (!stopped && !args.shouldStop()) {
14
20
  await args.run();
21
+ failures = 0;
22
+ }
15
23
  }).catch(error => {
24
+ failures++;
16
25
  try {
17
26
  args.onError(error);
18
27
  }
19
28
  catch { }
29
+ let again = null;
30
+ try {
31
+ again = args.retryAfter?.(error, failures) ?? null;
32
+ }
33
+ catch {
34
+ again = null;
35
+ }
36
+ if (again !== null && !stopped) {
37
+ retry = setTimeout(() => { retry = null; void runNow(); }, again);
38
+ retry.unref?.();
39
+ }
20
40
  }).finally(() => { pending = null; });
21
41
  return pending;
22
42
  };
@@ -28,9 +48,17 @@ export function startMaintenance(args) {
28
48
  if (!stopped) {
29
49
  stopped = true;
30
50
  clearInterval(timer);
51
+ if (retry !== null) {
52
+ clearTimeout(retry);
53
+ retry = null;
54
+ }
31
55
  args.onStop?.();
32
56
  }
33
57
  await pending;
34
58
  },
35
59
  };
36
60
  }
61
+ export const BUSY_RETRY_MS = [5_000, 10_000, 30_000];
62
+ export function busyRetryAfter(busy, failuresInARow, steps = BUSY_RETRY_MS) {
63
+ return busy ? steps[failuresInARow - 1] ?? null : null;
64
+ }
package/dist/needs-you.js CHANGED
@@ -117,6 +117,7 @@ export const WAITS = {
117
117
  "plan-retry-later": context => `Waiting: Toolroll tries the plan again ${context.retry ?? "soon"}.`,
118
118
  "app-update": () => "Waiting: Toolroll is updating. New work starts after it.",
119
119
  "other-task": context => context.task == null ? "Waiting for another task to finish first." : `Waiting for ${context.task} to finish first.`,
120
+ "builder-restarting": () => "Waiting: this project's builder stopped, and Toolroll is restarting it.",
120
121
  };
121
122
  export { BANNED_WORDS, PLAIN_WORDS, bannedWordsIn, hasInternalWords } from "./plain-words.js";
122
123
  import { hasInternalWords } from "./plain-words.js";
@@ -165,6 +166,7 @@ export const CODE_READING = {
165
166
  "worker-at-capacity": { stage: "waiting", wait: "builders-busy" }, "retry-scheduled": { stage: "waiting", wait: "retry-later" },
166
167
  "plan-retry": { stage: "waiting", wait: "plan-retry-later" },
167
168
  updating: { stage: "waiting", wait: "app-update" }, "waiting-dependency": { stage: "waiting", wait: "other-task" },
169
+ "watch-stalled": { stage: "waiting", wait: "builder-restarting" },
168
170
  "history-problem": { stage: "needs-you", need: "history", act: "inspect-task" },
169
171
  "earlier-active": { stage: "needs-you", need: "earlier-version", act: "inspect-task" },
170
172
  "waiting-decision": { stage: "needs-you", need: "answer", act: "answer-decision" },