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
@@ -3,44 +3,20 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync, realpat
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { homedir, hostname } from "node:os";
5
5
  import { fileURLToPath } from "node:url";
6
- import { createHmac } from "node:crypto";
7
- import { openStore, openStoreNoMigrate, databasePath, readSchemaVersion, SCHEMA_VERSION } from "./store.js";
8
- import { createRequire } from "node:module";
6
+ import { openStore, openStoreNoMigrate, databasePath } from "./store.js";
9
7
  import { authenticateApprover, hashPassword } from "./scope.js";
10
8
  import { runOperate, writeLoginFileDurably } from "./operate.js";
11
9
  import { ensureSecretsDir, migrateLegacyLogin, savedLoginFile } from "./login-secrets.js";
12
- import { daemonStatus, installLaunchdService, planDesktopService, stopLaunchdService } from "./daemon.js";
13
10
  import { run as execRun } from "./exec.js";
14
- import { containmentStatus, effectiveContainment, parseContainmentPolicy, probeContainmentCapability } from "./containment.js";
11
+ import { parseContainmentPolicy } from "./containment.js";
15
12
  import { updateRepos, addRepos } from "./repos.js";
16
13
  import { projectSelection } from "./project.js";
17
14
  import { superviseController } from "./controller-supervisor.js";
18
- import { normalizeRunnerName, validRunnerName } from "./runner.js";
15
+ import { normalizeRunnerName } from "./runner.js";
19
16
  import { checkDesktopProjects, currentDesktopAccess } from "./desktop-access.js";
20
- import { updateAdmissionPaused, updateGateOwned, UPDATE_PAUSED } from "./desktop-update-gate.js";
21
- import { envTwins, envValue } from "./names.js";
22
- export function readDesktopConfig(stateDir) {
23
- const config = JSON.parse(readFileSync(join(stateDir, "desktop.json"), "utf8"));
24
- if (config.version !== 1 || typeof config.databaseFile !== "string" || !Array.isArray(config.repos) || config.repos.some(repo => typeof repo !== "string") || !Number.isInteger(config.port) || config.port < 1024 || config.port > 65535 || !/^[a-f0-9]{64}$/.test(config.identity))
25
- throw new Error("Desktop configuration is invalid.");
26
- if (config.runnerName !== undefined && (typeof config.runnerName !== "string" || !validRunnerName(config.runnerName)))
27
- throw new Error("Desktop worker identity is invalid.");
28
- if (config.containment !== undefined && (typeof config.containment !== "string" || !parseContainmentPolicy(config.containment).ok))
29
- throw new Error("Desktop containment policy is invalid.");
30
- if (config.databaseInitialized !== undefined && typeof config.databaseInitialized !== "boolean")
31
- throw new Error("Desktop database setup state is invalid.");
32
- config.repos = [...new Set(config.repos.map(repo => {
33
- try {
34
- return realpathSync(repo);
35
- }
36
- catch (error) {
37
- if (["ENOENT", "EACCES", "EPERM"].includes(error.code ?? ""))
38
- return resolve(repo);
39
- throw error;
40
- }
41
- }))];
42
- return config;
43
- }
17
+ import { envValue } from "./names.js";
18
+ import { readDesktopConfig, desktopDatabaseStatus, verifyDesktopLiveness, desktopServiceCommand } from "./desktop-config.js";
19
+ export { readDesktopConfig, desktopDatabaseStatus, desktopServiceDefinition, verifyDesktopLiveness, desktopServiceCommand } from "./desktop-config.js";
44
20
  export function writeDesktopConfig(stateDir, config) {
45
21
  mkdirSync(stateDir, { recursive: true, mode: 0o700 });
46
22
  const path = join(stateDir, "desktop.json");
@@ -105,30 +81,6 @@ export function openConfiguredDesktopStore(stateDir) {
105
81
  throw error;
106
82
  }
107
83
  }
108
- export function desktopDatabaseStatus(file) {
109
- let db;
110
- const result = (ready, message) => ({ ready, message, expectedSchema: SCHEMA_VERSION });
111
- try {
112
- db = new createRequire(import.meta.url)("node:sqlite").DatabaseSync(file, { readOnly: true });
113
- db.exec("PRAGMA busy_timeout = 1000");
114
- const schema = readSchemaVersion(db);
115
- if (!schema.ok)
116
- return result(false, `This app cannot use the saved task database: ${schema.problem}. Keep the database; use a compatible release or restore a verified backup separately.`);
117
- if (schema.version === SCHEMA_VERSION)
118
- return result(true, "The saved task database is compatible with this app.");
119
- if (schema.version === null)
120
- return result(false, "The task database has not been set up. Complete setup before starting work.");
121
- if (schema.version < 0)
122
- return result(false, "A database update did not finish. Keep the service stopped and complete the documented database upgrade before starting work.");
123
- return result(false, `The saved tasks need a database upgrade (version ${schema.version} → ${SCHEMA_VERSION}). Keep the service stopped, back up the database, then complete the documented upgrade. This check changes nothing.`);
124
- }
125
- catch {
126
- return result(false, "The saved task database cannot be read. Check that its disk is connected and accessible. If the file is damaged, keep it and restore a verified backup separately; do not create a replacement queue.");
127
- }
128
- finally {
129
- db?.close();
130
- }
131
- }
132
84
  async function readInput() {
133
85
  let input = "";
134
86
  for await (const part of process.stdin) {
@@ -169,104 +121,6 @@ export function pairDesktopLogin(store, file, login) {
169
121
  if (!authenticateApprover(store, login.name, login.password).ok)
170
122
  throw new Error("Another operator was created during setup. Sign in again.");
171
123
  }
172
- export function desktopServiceDefinition(stateDir, args) {
173
- const runtimeDir = dirname(args.node);
174
- const home = args.home ?? homedir();
175
- return planDesktopService({
176
- node: args.node,
177
- helper: args.helper,
178
- stateDir,
179
- label: args.label,
180
- associatedBundleId: args.bundleId ?? "com.standing-orders.desktop",
181
- home,
182
- environment: { ...envTwins("CONTAINMENT", args.containment ?? "observed"), ...(args.buildId ? envTwins("DESKTOP_BUILD", args.buildId) : {}) },
183
- pathEnv: [runtimeDir, ...(args.providerBin ? [args.providerBin] : []), join(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":"),
184
- });
185
- }
186
- export async function verifyDesktopLiveness(config, fetchImpl = fetch) {
187
- const challenge = randomBytes(32).toString("hex");
188
- try {
189
- const response = await fetchImpl(`http://127.0.0.1:${config.port}/desktop/health?challenge=${challenge}`, { signal: AbortSignal.timeout(2_000) });
190
- if (response.status !== 200)
191
- return { alive: false, port: config.port, problem: `the controller answered ${response.status} on port ${config.port}` };
192
- const body = (await response.json());
193
- const expected = createHmac("sha256", Buffer.from(config.identity, "hex")).update(challenge).digest("hex");
194
- if (body.proof !== expected)
195
- return { alive: false, port: config.port, problem: `something on port ${config.port} is not this installation's controller` };
196
- return { alive: true, port: config.port };
197
- }
198
- catch (error) {
199
- return { alive: false, port: config.port, problem: `no controller answered on port ${config.port} (${error instanceof Error ? error.message : String(error)})` };
200
- }
201
- }
202
- export async function desktopServiceCommand(verb, stateDir, config, argv, supervise = execRun) {
203
- const read = (name) => {
204
- const at = argv.indexOf(`--${name}`);
205
- const value = at >= 0 ? argv[at + 1] : undefined;
206
- if (value === undefined || value.startsWith("--"))
207
- throw new Error(`${verb} needs --${name}.`);
208
- return value;
209
- };
210
- const parsed = parseContainmentPolicy(config.containment ?? envValue(process.env, "CONTAINMENT"));
211
- if (!parsed.ok)
212
- throw new Error(parsed.problem);
213
- const providerAt = argv.indexOf("--provider-bin");
214
- const bundleAt = argv.indexOf("--bundle-id");
215
- const buildAt = argv.indexOf("--build-id");
216
- const definition = desktopServiceDefinition(stateDir, { node: read("node"), helper: read("helper"), label: read("label"), containment: parsed.policy, ...(providerAt >= 0 ? { providerBin: read("provider-bin") } : {}), ...(bundleAt >= 0 ? { bundleId: read("bundle-id") } : {}), ...(buildAt >= 0 ? { buildId: read("build-id") } : {}) });
217
- if (verb === "service-start") {
218
- if (argv.includes("--update-id")) {
219
- const update = await import("./desktop-update.js");
220
- const journal = update.readUpdateJournal(stateDir);
221
- if (!journal || journal.id !== read("update-id") || update.updateStopRequested(journal))
222
- throw new Error("This update is no longer allowed to start the background service.");
223
- }
224
- if (config.repos.length === 0)
225
- throw new Error("Choose a repository in the desktop app first.");
226
- const database = desktopDatabaseStatus(config.databaseFile);
227
- if (!database.ready)
228
- throw new Error(database.message);
229
- const opened = openStoreNoMigrate(config.databaseFile);
230
- if (!opened.ok)
231
- throw new Error(opened.message);
232
- try {
233
- const updateAt = argv.indexOf("--update-id");
234
- if (updateAdmissionPaused(opened.store.raw()) && (updateAt < 0 || !updateGateOwned(opened.store.raw(), read("update-id"))))
235
- throw new Error(UPDATE_PAUSED);
236
- }
237
- finally {
238
- opened.store.close();
239
- }
240
- if (!existsSync(definition.logPath))
241
- writeFileSync(definition.logPath, "", { mode: 0o600 });
242
- const started = await installLaunchdService(definition, supervise);
243
- if (!started.ok)
244
- throw new Error(started.message);
245
- return { ok: true, action: started.action, changed: started.changed, label: definition.label, unit: definition.unitPath };
246
- }
247
- if (verb === "service-stop") {
248
- if (!argv.includes("--update-id") && existsSync(join(stateDir, "desktop-update.json"))) {
249
- try {
250
- await (await import("./desktop-update.js")).requestUpdateStop(stateDir);
251
- }
252
- catch {
253
- const recoveryLabel = `${definition.label}.update`;
254
- const recoveryStopped = await stopLaunchdService({ ...definition, label: recoveryLabel, unitPath: join(dirname(definition.unitPath), `${recoveryLabel}.plist`) }, supervise);
255
- console.error(recoveryStopped.ok ? "The update stop request could not be recorded, so automatic update recovery was disabled. Preserve the update files and check Update status before restarting." : "The update stop request and recovery-service stop could not be confirmed. Check Update status and service logs before leaving this installation unattended.");
256
- }
257
- }
258
- const stopped = await stopLaunchdService(definition, supervise);
259
- if (!stopped.ok)
260
- throw new Error(stopped.message);
261
- return { ok: true, wasLoaded: stopped.wasLoaded, label: definition.label };
262
- }
263
- if (verb === "service-status") {
264
- const status = await daemonStatus(definition, supervise);
265
- const liveness = status.state === "running" ? await verifyDesktopLiveness(config) : null;
266
- return { ok: true, ...status, label: definition.label, liveness, database: desktopDatabaseStatus(config.databaseFile), containment: containmentStatus(effectiveContainment(parsed.policy, probeContainmentCapability())) };
267
- }
268
- throw new Error("Unknown desktop service operation.");
269
- }
270
124
  export async function desktopMain(argv, supervise = execRun) {
271
125
  const stateArg = argv.indexOf("--state");
272
126
  if (stateArg >= 0 && !argv[stateArg + 1])
@@ -6,7 +6,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
6
6
  import { savedLoginFile } from "./login-secrets.js";
7
7
  import { createRequire } from "node:module";
8
8
  import { bundleHash, readDesktopBundle, verifyDesktopUpdateBundles } from "./desktop-bundle.js";
9
- import { readDesktopConfig, desktopServiceCommand, desktopServiceDefinition, verifyDesktopLiveness } from "./desktop-host.js";
9
+ import { readDesktopConfig, desktopServiceCommand, desktopServiceDefinition, verifyDesktopLiveness } from "./desktop-config.js";
10
10
  import { daemonStatus } from "./daemon.js";
11
11
  import { run } from "./exec.js";
12
12
  import { readSchemaVersion, SCHEMA_VERSION, Store } from "./store.js";
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;
@@ -0,0 +1,14 @@
1
+ import { COMPLETION_ACTION } from "./result-completion.js";
2
+ export function finishedTask(r) {
3
+ return `EXISTS (SELECT 1 FROM task t WHERE t.id = ${r}.external_id AND ${r}.backend = 'built-in' AND (t.state = 'cancelled' OR (t.state = 'done' AND EXISTS (
4
+ SELECT 1 FROM action_ledger a WHERE a.action = '${COMPLETION_ACTION}' AND (a.task_id = ${r}.external_id OR a.run_id IN (SELECT id FROM run WHERE task_ref = ${r}.id))))))
5
+ AND NOT EXISTS (SELECT 1 FROM hold h WHERE h.task_ref = ${r}.id)
6
+ AND NOT EXISTS (SELECT 1 FROM run live WHERE live.task_ref = ${r}.id AND live.finished_at IS NULL)
7
+ AND NOT EXISTS (SELECT 1 FROM task_scope s WHERE s.task_id = ${r}.external_id AND s.candidate IS NOT NULL)
8
+ AND NOT EXISTS (WITH RECURSIVE family(ext) AS (
9
+ SELECT rv.external_id FROM task_ref rv WHERE rv.revision_of = ${r}.external_id
10
+ UNION SELECT rv.external_id FROM task_ref rv JOIN family ON rv.revision_of = family.ext)
11
+ SELECT 1 FROM family JOIN task tv ON tv.id = family.ext
12
+ WHERE NOT (tv.state = 'cancelled' OR (tv.state = 'done' AND EXISTS (SELECT 1 FROM action_ledger a WHERE a.action = '${COMPLETION_ACTION}'
13
+ AND (a.task_id = family.ext OR a.run_id IN (SELECT run.id FROM run JOIN task_ref x ON x.id = run.task_ref WHERE x.external_id = family.ext))))))`;
14
+ }
@@ -36,7 +36,6 @@ const WORDS = Object.freeze({
36
36
  "scope-unshown": "This request couldn't be shown in full, so it can't be allowed. You can deny it. Nothing was sent.",
37
37
  });
38
38
  const refuse = (reason, state, message = WORDS[reason]) => state === undefined ? { ok: false, reason, message } : { ok: false, reason, message, state };
39
- export const FLEXIBLE_ANSWER_UNCERTAIN = WORDS["uncertain"];
40
39
  export function streamAnswerSender(stream) {
41
40
  return (bytes, { deadlineMs, signal }) => new Promise(resolve => {
42
41
  if (stream.destroyed || !stream.writable || signal.aborted) {
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
+ }
@@ -0,0 +1,41 @@
1
+ import { execFile } from "node:child_process";
2
+ import { sleep } from "./sleep.js";
3
+ import { retryingExec } from "./release-net.js";
4
+ export const exec = (command, args, options = {}) => new Promise(done => {
5
+ const child = execFile(command, [...args], { cwd: options.cwd, env: options.env ?? process.env, timeout: options.timeoutMs ?? 120_000, maxBuffer: 64 * 1024 * 1024, encoding: "utf8" }, (error, stdout, stderr) => {
6
+ const failure = error;
7
+ const code = failure === null ? 0 : failure.code === "ENOENT" ? 127 : failure.killed === true ? 124 : typeof failure.code === "number" ? failure.code : 1;
8
+ done({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
9
+ });
10
+ child.stdin?.on("error", () => { });
11
+ if (options.input !== undefined)
12
+ child.stdin?.end(options.input);
13
+ else
14
+ child.stdin?.end();
15
+ });
16
+ export function ciEnv() {
17
+ const kept = Object.fromEntries(["HOME", "LANG", "LC_ALL", "TMPDIR", "USER", "LOGNAME", "GH_TOKEN", "GITHUB_TOKEN"].flatMap(name => process.env[name] === undefined ? [] : [[name, process.env[name]]]));
18
+ return { ...kept, PATH: "/usr/bin:/bin", GH_HOST: "github.com", GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1" };
19
+ }
20
+ export function githubReads(run, gh, options = {}) {
21
+ return async (path, timeoutMs) => {
22
+ if (!/^repos\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_./?&=%-]+$/.test(path) || timeoutMs <= 0)
23
+ return { ok: false, why: "not a read this makes" };
24
+ const exec = options.retry === true ? retryingExec(run, { say: () => { }, sleep, budgetMs: timeoutMs }) : run;
25
+ let result;
26
+ try {
27
+ result = await exec(gh, ["api", "--hostname", "github.com", "--method", "GET", path], { cwd: "/", env: ciEnv(), timeoutMs });
28
+ }
29
+ catch (error) {
30
+ return { ok: false, why: String(error?.message ?? error).slice(0, 200) };
31
+ }
32
+ if (result.code !== 0)
33
+ return { ok: false, why: result.code === 124 ? "GitHub didn't answer in time" : result.code === 127 ? "gh isn't installed" : (result.stderr || result.stdout).trim().split("\n").slice(-1)[0].slice(0, 200) || `gh exited ${result.code}` };
34
+ try {
35
+ return { ok: true, body: JSON.parse(result.stdout) };
36
+ }
37
+ catch {
38
+ return { ok: false, why: "GitHub's answer couldn't be read" };
39
+ }
40
+ };
41
+ }
package/dist/guides.js CHANGED
@@ -437,9 +437,10 @@ with a time limit.
437
437
  entry (\`## <version>\`, in the format the top of CHANGELOG.md
438
438
  describes). No tag or npm package has that version yet.
439
439
  - \`gh\` is signed in, the console, worker and both CLI names
440
- (\`toolroll\`, \`standing-orders\`) run one build, and the gate checkout
441
- is a clone whose origin is the GitHub repository. Credentials are never
442
- asked for in chat or written to the release journal.
440
+ (\`toolroll\`, \`standing-orders\`) run one build (\`toolroll update --yes\`
441
+ brings them together), and the gate checkout is a clone whose origin is
442
+ the GitHub repository. Credentials are never asked for in chat or written
443
+ to the release journal.
443
444
 
444
445
  ## What it does, in order
445
446
 
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
+ }