toolroll 0.9.116 → 0.9.117

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 (129) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +14 -3
  33. package/dist/contracts/engine-api.js +331 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-session.js +91 -47
  57. package/dist/flexible-ship.js +87 -7
  58. package/dist/flexible-start.js +4 -1
  59. package/dist/flexible-thread.js +2 -3
  60. package/dist/flexible-turns.js +26 -5
  61. package/dist/flow-triggers.js +13 -4
  62. package/dist/flows-ui.js +54 -20
  63. package/dist/handoff-cli.js +630 -0
  64. package/dist/invoke.js +55 -13
  65. package/dist/lead-contract.js +5 -4
  66. package/dist/lead-doors.js +80 -1
  67. package/dist/lead-progress.js +9 -0
  68. package/dist/lead-tools.js +681 -10
  69. package/dist/lead.js +37 -9
  70. package/dist/live-bus.js +11 -0
  71. package/dist/live-terminal.js +132 -12
  72. package/dist/local-handoff.js +363 -0
  73. package/dist/local-owner-acts.js +264 -2
  74. package/dist/local-owner.js +16 -1
  75. package/dist/multiplayer-handoff.js +528 -0
  76. package/dist/multiplayer-presence.js +471 -0
  77. package/dist/names.js +17 -4
  78. package/dist/needs-you.js +10 -0
  79. package/dist/operate.js +280 -19
  80. package/dist/policy.js +2 -2
  81. package/dist/project-delete-ui.js +18 -11
  82. package/dist/project-delete.js +65 -4
  83. package/dist/project-tools.js +1 -1
  84. package/dist/prompt.js +1 -1
  85. package/dist/provider-connection.js +2 -0
  86. package/dist/provider-home.js +251 -8
  87. package/dist/provider.js +3 -2
  88. package/dist/publish.js +119 -64
  89. package/dist/pull-request-flow.js +35 -14
  90. package/dist/read-executor-worker.js +1 -1
  91. package/dist/read-executor.js +95 -1
  92. package/dist/restore-retirement.js +152 -0
  93. package/dist/result-follow-ups.js +116 -37
  94. package/dist/route-change.js +44 -4
  95. package/dist/scope.js +62 -5
  96. package/dist/serve.js +49 -5
  97. package/dist/server/chat.js +94 -13
  98. package/dist/server/direct-chat.js +583 -0
  99. package/dist/server/engine-api.js +219 -21
  100. package/dist/server/flows.js +43 -10
  101. package/dist/server/found-repos.js +25 -0
  102. package/dist/server/guards.js +20 -6
  103. package/dist/server/live.js +81 -23
  104. package/dist/server/pages.js +67 -13
  105. package/dist/server/people-tokens.js +47 -6
  106. package/dist/server/remote.js +29 -0
  107. package/dist/server/render-results.js +6 -2
  108. package/dist/server/render-settings.js +4 -2
  109. package/dist/server/render-tasks.js +18 -17
  110. package/dist/server/route-table.js +69 -2
  111. package/dist/server/settings.js +22 -7
  112. package/dist/server/task-views.js +15 -3
  113. package/dist/server/tasks.js +39 -2
  114. package/dist/server/terminals.js +185 -11
  115. package/dist/settings-proofs.js +1 -1
  116. package/dist/store.js +499 -56
  117. package/dist/subscription-chat.js +33 -6
  118. package/dist/subscription-usage.js +233 -0
  119. package/dist/task-live.js +2 -1
  120. package/dist/teardown-git.js +34 -4
  121. package/dist/terminal-connection.js +159 -0
  122. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  123. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  124. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  125. package/dist/tui/linux-x64/toolroll-tui +0 -0
  126. package/dist/tui-contract.js +1 -1
  127. package/dist/tui-launch.js +32 -1
  128. package/dist/workspace-identity-schema.js +21 -0
  129. package/package.json +3 -1
@@ -0,0 +1,105 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+ const MAX_STORED_REQUESTS = 100;
5
+ export function agentRequestsPath(databaseFile) {
6
+ return join(dirname(databaseFile), ".toolroll-run", "agent-requests.json");
7
+ }
8
+ function readRequestFile(filePath) {
9
+ if (!existsSync(filePath))
10
+ return { version: 1, requests: [] };
11
+ try {
12
+ const parsed = JSON.parse(readFileSync(filePath, "utf8"));
13
+ if (!parsed || !Array.isArray(parsed.requests))
14
+ return { version: 1, requests: [] };
15
+ return { version: 1, requests: parsed.requests };
16
+ }
17
+ catch {
18
+ return { version: 1, requests: [] };
19
+ }
20
+ }
21
+ function writeRequestFile(filePath, data) {
22
+ const dir = dirname(filePath);
23
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
24
+ const trimmed = {
25
+ version: 1,
26
+ requests: data.requests.slice(-MAX_STORED_REQUESTS),
27
+ };
28
+ const tmp = `${filePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
29
+ writeFileSync(tmp, JSON.stringify(trimmed, null, 2) + "\n", { mode: 0o600 });
30
+ chmodSync(tmp, 0o600);
31
+ renameSync(tmp, filePath);
32
+ }
33
+ export function listAgentRequests(databaseFile, options = {}) {
34
+ const all = readRequestFile(agentRequestsPath(databaseFile)).requests;
35
+ return all.filter(one => {
36
+ if (options.status !== undefined && one.status !== options.status)
37
+ return false;
38
+ if (options.repo !== undefined && one.repo !== options.repo)
39
+ return false;
40
+ return true;
41
+ });
42
+ }
43
+ export function fileAgentRequest(databaseFile, input, now = new Date()) {
44
+ const filePath = agentRequestsPath(databaseFile);
45
+ const data = readRequestFile(filePath);
46
+ const cleanWhy = input.why.trim().slice(0, 600);
47
+ const cleanRequester = (input.requester ?? process.env["TOOLROLL_AGENT_NAME"] ?? "Agent").trim().slice(0, 80) || "Agent";
48
+ const existing = data.requests.find(one => one.status === "pending" &&
49
+ one.kind === input.kind &&
50
+ one.repo === input.repo &&
51
+ JSON.stringify(one.params) === JSON.stringify(input.params));
52
+ if (existing !== undefined) {
53
+ existing.why = cleanWhy || existing.why;
54
+ existing.requester = cleanRequester;
55
+ existing.summary = input.summary;
56
+ writeRequestFile(filePath, data);
57
+ return existing;
58
+ }
59
+ const made = {
60
+ id: `req_${randomBytes(5).toString("hex")}`,
61
+ kind: input.kind,
62
+ repo: input.repo,
63
+ projectName: basename(input.repo) || input.repo,
64
+ requester: cleanRequester,
65
+ summary: input.summary,
66
+ why: cleanWhy,
67
+ params: input.params,
68
+ status: "pending",
69
+ createdAt: now.toISOString(),
70
+ };
71
+ data.requests.push(made);
72
+ writeRequestFile(filePath, data);
73
+ return made;
74
+ }
75
+ export function resolveAgentRequest(databaseFile, id, status, note, now = new Date()) {
76
+ const filePath = agentRequestsPath(databaseFile);
77
+ const data = readRequestFile(filePath);
78
+ const found = data.requests.find(one => one.id === id);
79
+ if (found === undefined)
80
+ return null;
81
+ found.status = status;
82
+ found.resolvedAt = now.toISOString();
83
+ if (note !== undefined && note.trim() !== "")
84
+ found.resolutionNote = note.trim().slice(0, 400);
85
+ writeRequestFile(filePath, data);
86
+ return found;
87
+ }
88
+ export function clearResolvedAgentRequests(databaseFile) {
89
+ const filePath = agentRequestsPath(databaseFile);
90
+ const data = readRequestFile(filePath);
91
+ const before = data.requests.length;
92
+ data.requests = data.requests.filter(one => one.status === "pending");
93
+ writeRequestFile(filePath, data);
94
+ return before - data.requests.length;
95
+ }
96
+ export async function waitForAgentRequest(databaseFile, id, timeoutSeconds = 300) {
97
+ const deadline = Date.now() + Math.max(1, timeoutSeconds) * 1000;
98
+ while (Date.now() <= deadline) {
99
+ const current = listAgentRequests(databaseFile).find(one => one.id === id) ?? null;
100
+ if (current === null || current.status !== "pending")
101
+ return current;
102
+ await new Promise(resolve => setTimeout(resolve, 400));
103
+ }
104
+ return listAgentRequests(databaseFile).find(one => one.id === id) ?? null;
105
+ }
@@ -3,7 +3,7 @@ import { resolveScopeProfile } from "./agentconfig.js";
3
3
  import { isProtectedWork } from "./approval-policy.js";
4
4
  import { permissionPlainWords, scopeFullAccess } from "./chat-terms.js";
5
5
  import { checkAccessWords } from "./check-access.js";
6
- import { networkWords, unaccountedHosts } from "./egress.js";
6
+ import { codexCommandsOffline, networkWords, unaccountedHosts } from "./egress.js";
7
7
  import { agentModelName } from "./model-names.js";
8
8
  import { makesNoPlan, NO_READINESS, PLANNED_FIRST_REASON, projectRoute, routeFromJson, sizeWords } from "./phase-routing.js";
9
9
  import { sandboxTermsWords } from "./project-sandbox.js";
@@ -90,7 +90,7 @@ function releaseAuthorityWords(release) {
90
90
  return `Repository ${release.repo}, branch ${release.branch} into ${release.base}, check grant ${release.grant.id}, ${release.access === "sandboxed" ? "checks in the sandbox" : `checks outside the sandbox (${release.access})`}.`;
91
91
  }
92
92
  const ACCESS_GROUPS = [
93
- { name: "network", fields: ["network"], words: profile => lowerFirst(networkWords(profile.network ?? null, profile.provider).replace(/^Network: /, "")) },
93
+ { name: "network", fields: ["network"], words: profile => lowerFirst(networkWords(profile.network ?? null, profile.provider, { commandsOffline: codexCommandsOffline(profile) }).replace(/^Network: /, "")) },
94
94
  { name: "tools", fields: PERMISSION_KEYS, words: profile => permissionPlainWords(profile) ?? "not known" },
95
95
  { name: "writes", fields: ["writes"], words: profile => writesWords(profile.writes) },
96
96
  { name: "reads", fields: ["fencePolicy", "readDeny"], words: profile => sandboxTermsWords(profile).reads },
@@ -180,7 +180,7 @@ export function approvalSummaryOf(scope, context = NO_CONTEXT) {
180
180
  if (profile !== null) {
181
181
  const network = profile.network ?? null;
182
182
  const wide = network !== null && (network.mode === "open" || network.loopback === "any" || unaccountedHosts(network, profile.provider).length > 0);
183
- decisions.push({ label: "Network", words: lowerFirst(networkWords(network, profile.provider).replace(/^Network: /, "")), fields: ["profile.network"], ...(wide ? { risky: true } : {}) });
183
+ decisions.push({ label: "Network", words: lowerFirst(networkWords(network, profile.provider, { commandsOffline: codexCommandsOffline(profile) }).replace(/^Network: /, "")), fields: ["profile.network"], ...(wide ? { risky: true } : {}) });
184
184
  }
185
185
  if (tools !== null) {
186
186
  decisions.push({ label: "Tools", words: `${tools}${usualTools !== null && usualTools !== tools ? " (not the project’s usual)" : ""}`,
package/dist/backup.js CHANGED
@@ -8,6 +8,7 @@ import { verifyLedgerChain } from "./ledger-chain.js";
8
8
  import { DEFAULT_LIVENESS_MS } from "./runner.js";
9
9
  import { openStore, readSchemaVersion, SCHEMA_VERSION } from "./store.js";
10
10
  import { resetFlexibleSignInsForRestore } from "./flexible-sign-in.js";
11
+ import { retireRestoredAuthority } from "./restore-retirement.js";
11
12
  const BACKUP_NAME = /^(?:toolroll|standing-orders)-(?:([0-9a-f]{8})-)?(\d{4}-\d{2}-\d{2}-\d{6})(?:-(\d+))?\.db$/;
12
13
  export const OLDEST_RESTORABLE = 103;
13
14
  export { BACKUP_EVERY_HOURS, MAX_KEEP };
@@ -328,20 +329,33 @@ export async function restoreDatabase(options) {
328
329
  report.savedAs = saved;
329
330
  const store = openStore(databaseFile);
330
331
  let carried;
332
+ let replacedRecoveryGeneration = null;
331
333
  try {
332
334
  const running = runningNow(store, new Date());
333
335
  if (running.length > 0)
334
336
  return refuse("running", `Toolroll started (${running.join(" and ")}). Stop it first, then restore. The database is unchanged.`);
335
337
  carried = store.handle.prepare("SELECT person, generation, account_generation FROM flexible_sign_in").all()
336
338
  .map(row => ({ person: String(row["person"]), generation: String(row["generation"]), accountGeneration: Number(row["account_generation"]) }));
339
+ try {
340
+ replacedRecoveryGeneration = store.workspaceIdentity().recoveryGeneration;
341
+ }
342
+ catch { }
337
343
  }
338
344
  finally {
339
345
  store.close();
340
346
  }
347
+ let retired;
341
348
  try {
342
349
  const prepared = openStore(staged);
343
350
  try {
344
- prepared.transact(() => { resetFlexibleSignInsForRestore(prepared, { now, carried }); });
351
+ prepared.transact(() => {
352
+ resetFlexibleSignInsForRestore(prepared, { now, carried });
353
+ retired = retireRestoredAuthority(prepared, {
354
+ now,
355
+ actor: options.actor ?? "command line",
356
+ replacedRecoveryGeneration,
357
+ });
358
+ });
345
359
  }
346
360
  finally {
347
361
  prepared.close();
@@ -362,6 +376,8 @@ export async function restoreDatabase(options) {
362
376
  rmSync(`${staged}${suffix}`, { force: true });
363
377
  return refuse("schema", `That backup doesn't open as a Toolroll database (${firstLine(error)}). The database is unchanged.`);
364
378
  }
379
+ if (retired !== undefined)
380
+ report.retired = retired;
365
381
  const live = connect(databaseFile);
366
382
  try {
367
383
  live.exec("PRAGMA wal_checkpoint(TRUNCATE)");
@@ -1,3 +1,5 @@
1
+ import { keepCheckScreenshots } from "./check-screenshots.js";
2
+ import { CHECK_RECOVERY_HELD, readCheckRecoveryHoldsForRun } from "./check-recovery-hold.js";
1
3
  import { checkoutRunner, ranAtLine, widestRan } from "./invoke.js";
2
4
  import { mkdtempSync, rmSync } from "node:fs";
3
5
  import { tmpdir } from "node:os";
@@ -12,6 +14,9 @@ import { projectBatchChecks } from "./batch-policy.js";
12
14
  import { CHECKS_FINISHED, CHECKS_REQUESTED, CHECKS_STARTED, FOLLOW_UP_LOG, FOLLOW_UP_RECEIPT, followUpChecksOf, waitingRequestsOfAnyKind, } from "./result-follow-ups.js";
13
15
  export function queueBatchCheck(store, input, now) {
14
16
  return store.transact(() => {
17
+ const held = recoveryBlock(store, input.runId);
18
+ if (held !== null)
19
+ return { state: "recovery-held", recovery: held, priorExecution: "unverified" };
15
20
  const [where, params] = repoClause(input.repo);
16
21
  const existing = store.handle.prepare(`SELECT id FROM action_ledger WHERE ${where} AND run_id = ? AND action = ? AND detail LIKE ? ORDER BY id LIMIT 1`)
17
22
  .get(...params, input.runId, CHECKS_REQUESTED, `${input.head} · batch · %`);
@@ -23,6 +28,14 @@ export function queueBatchCheck(store, input, now) {
23
28
  return id;
24
29
  });
25
30
  }
31
+ function recoveryBlock(store, runId) {
32
+ if (store.handle.prepare("SELECT 1 FROM action_ledger WHERE action = ? LIMIT 1").get(CHECK_RECOVERY_HELD) === undefined)
33
+ return null;
34
+ const evidence = readCheckRecoveryHoldsForRun(store, runId);
35
+ return evidence.kind === "no-evidence" ? null : evidence;
36
+ }
37
+ class BatchRecoveryBlocked extends Error {
38
+ }
26
39
  export async function runBatchChecks(store, root, deps = {}) {
27
40
  const now = deps.now ?? (() => new Date());
28
41
  const waiting = waitingRequestsOfAnyKind(store, now()).filter(one => one.why === "batch");
@@ -35,7 +48,10 @@ export async function runBatchChecks(store, root, deps = {}) {
35
48
  continue;
36
49
  if (run.finishedAt === null)
37
50
  continue;
38
- const finish = (detail) => { claim(store, one, ref.repo, ref.externalId, 0, now()) && finishOne(store, one, ref.repo, ref.externalId, "not-run", detail, now()); settled++; };
51
+ const finish = (detail) => { if (claim(store, one, ref.repo, ref.externalId, 0, now()) && finishOne(store, one, ref.repo, ref.externalId, "not-run", detail, now()))
52
+ settled++; };
53
+ if (recoveryBlock(store, one.runId) !== null)
54
+ continue;
39
55
  if (run.role !== "builder" || run.outcome !== "built" || run.headRevision !== one.head) {
40
56
  finish("The result stopped or changed before its batch check.");
41
57
  continue;
@@ -66,6 +82,8 @@ export async function runBatchChecks(store, root, deps = {}) {
66
82
  }
67
83
  function claim(store, one, repo, task, limitMs, at) {
68
84
  return store.transact(() => {
85
+ if (recoveryBlock(store, one.runId) !== null)
86
+ return false;
69
87
  if (store.handle.prepare("SELECT 1 FROM action_ledger WHERE run_id = ? AND action = ? AND outcome = ?").get(one.runId, CHECKS_STARTED, String(one.request)) !== undefined)
70
88
  return false;
71
89
  store.recordAction({ at: at.toISOString(), actor: "system", repo, taskId: task, runId: one.runId, action: CHECKS_STARTED, outcome: String(one.request), source: "work", detail: `limit ${limitMs} · batch` });
@@ -73,14 +91,18 @@ function claim(store, one, repo, task, limitMs, at) {
73
91
  });
74
92
  }
75
93
  function finishOne(store, one, repo, task, status, detail, at) {
76
- store.recordAction({ at: at.toISOString(), actor: "system", repo, taskId: task, runId: one.runId, action: CHECKS_FINISHED, outcome: `${one.request}:${status}`, source: "work", detail });
77
- store.bumpWake();
78
- return true;
94
+ return store.transact(() => {
95
+ if (recoveryBlock(store, one.runId) !== null)
96
+ return false;
97
+ store.recordAction({ at: at.toISOString(), actor: "system", repo, taskId: task, runId: one.runId, action: CHECKS_FINISHED, outcome: `${one.request}:${status}`, source: "work", detail });
98
+ store.bumpWake();
99
+ return true;
100
+ });
79
101
  }
80
102
  async function checkCohort(store, root, repo, cohort, deps) {
81
103
  const now = deps.now ?? (() => new Date());
82
104
  const runner = deps.runner ?? execRun;
83
- const git = deps.git ?? hardenedGit(execRun);
105
+ const cleanupGit = deps.git ?? hardenedGit(execRun);
84
106
  const command = store.liveVerifyCommand(repo);
85
107
  if (command === null)
86
108
  return 0;
@@ -89,39 +111,57 @@ async function checkCohort(store, root, repo, cohort, deps) {
89
111
  const members = cohort.filter(one => claim(store, one, repo, one.task, limit, now())).sort((a, b) => a.request - b.request);
90
112
  if (members.length === 0)
91
113
  return 0;
114
+ let settled = 0;
115
+ const proveSet = (set) => { if (set.some(one => recoveryBlock(store, one.runId) !== null))
116
+ throw new BatchRecoveryBlocked(); };
92
117
  const base = members[0].base;
93
118
  const logs = new Map(members.map(one => [one.request, []]));
119
+ const observed = new Map(members.map(one => [one.request, []]));
94
120
  const attempts = new Map(members.map(one => [one.request, []]));
95
121
  const bound = (text) => { const hits = scanForSecrets(text); return boundStreamHeadTail(hits.length > 0 ? redactSecretLines(text, hits) : text, 12 * 1024); };
96
122
  const section = (label, shown, result) => `=== ${label} ===\n$ ${shown}\n(exit ${result.code}${result.notFound ? ", could not start" : ""}${result.timedOut ? ", timed out" : ""})\n\n--- stdout ---\n${bound(result.stdout)}\n\n--- stderr ---\n${bound(result.stderr)}`;
97
123
  const ranAtOf = new Map();
98
- const note = (set, text) => { for (const one of set)
99
- logs.get(one.request).push(text); };
124
+ const note = (set, text) => { for (const one of set) {
125
+ logs.get(one.request).push(text);
126
+ observed.get(one.request).push(text);
127
+ } };
128
+ const observation = (set, text) => { for (const one of set)
129
+ observed.get(one.request).push(text); };
100
130
  const attempt = (set, tested, outcome) => { for (const one of set)
101
131
  attempts.get(one.request).push({ members: set.map(m => m.task), tested, outcome }); };
102
132
  const checkOnce = async (set) => {
133
+ proveSet(set);
134
+ const guardedRunner = (file, args, options) => { proveSet(set); return runner(file, args, options); };
135
+ const guardedGit = (file, args, options) => { proveSet(set); return execRun(file, args, options); };
136
+ const git = deps.git === undefined ? hardenedGit(guardedGit) : (file, args, options) => { proveSet(set); return deps.git(file, args, options); };
137
+ let checkoutCreated = false;
103
138
  const folder = mkdtempSync(join(deps.scratch ?? tmpdir(), "toolroll-batch-"));
104
139
  const checkout = join(folder, "checkout");
105
140
  const label = set.length === 1 ? `${set[0].task} on its own` : `Batch of ${set.length}: ${set.map(one => one.task).join(", ")}`;
106
141
  try {
107
142
  const start = set.length === 1 ? set[0].head : base ?? `${set[0].head}^`;
108
143
  const added = await git("git", ["-C", repo, "worktree", "add", "--detach", checkout, start], { timeoutMs: 120_000 });
144
+ checkoutCreated = added.code === 0;
145
+ (added.code === 0 ? observation : note)(set, section(`${label} · checkout`, `git worktree add --detach <temporary folder> ${start}`, added));
146
+ proveSet(set);
109
147
  if (added.code !== 0) {
110
- note(set, section(`${label} · checkout`, `git worktree add --detach <temporary folder> ${start}`, added));
111
148
  return { conflict: false, tested: null, outcome: { ran: false, failure: "The commit couldn't be checked out. It may have been removed from this computer." }, setupFailed: false };
112
149
  }
113
150
  if (set.length > 1) {
114
151
  for (const one of set) {
115
152
  const merged = await git("git", ["-C", checkout, "-c", "user.name=Toolroll batch check", "-c", "user.email=batch-check@toolroll.invalid", "-c", "commit.gpgsign=false",
116
153
  "-c", "core.hooksPath=/dev/null", "merge", "--no-ff", "--no-edit", "--no-verify", "-m", `Batch check: ${one.task}`, one.head], { timeoutMs: 120_000 });
154
+ (merged.code === 0 ? observation : note)(set, section(`${label} · merge ${one.task}`, `git merge --no-ff ${one.head}`, merged));
155
+ proveSet(set);
117
156
  if (merged.code !== 0) {
118
- note(set, section(`${label} · merge ${one.task}`, `git merge --no-ff ${one.head}`, merged));
119
157
  await git("git", ["-C", checkout, "merge", "--abort"], { timeoutMs: 60_000 }).catch(() => null);
120
158
  return { conflict: true };
121
159
  }
122
160
  }
123
161
  }
124
162
  const head = await git("git", ["-C", checkout, "rev-parse", "HEAD"], { timeoutMs: 60_000 });
163
+ observation(set, section(`${label} · read tested commit`, "git rev-parse HEAD", head));
164
+ proveSet(set);
125
165
  const tested = head.code === 0 && /^[a-f0-9]{40}$/.test(head.stdout.trim()) ? head.stdout.trim() : null;
126
166
  if (tested === null)
127
167
  return { conflict: false, tested: null, outcome: { ran: false, failure: "The batch commit couldn't be read." }, setupFailed: false };
@@ -134,8 +174,9 @@ async function checkCohort(store, root, repo, cohort, deps) {
134
174
  return { conflict: false, tested, outcome: { ran: false, failure: "The project's approved setup changed before the check started." }, setupFailed: false };
135
175
  if (liveSetup !== null) {
136
176
  const shell = approvedCommandShell(liveSetup.command);
137
- const prepared = await runWithIsolatedDatabase(checkoutRunner(store, repo, checkout, runner, set.map(one => one.runId), setRan), shell.file, shell.args, { cwd: checkout, timeoutMs: liveSetup.timeoutMs, processGroup: true, envAllowlist: SETUP_ENV_ALLOWLIST, omitEnv: SETUP_ENV_DENYLIST });
177
+ const prepared = await runWithIsolatedDatabase(checkoutRunner(store, repo, checkout, guardedRunner, set.map(one => one.runId), setRan), shell.file, shell.args, { cwd: checkout, timeoutMs: liveSetup.timeoutMs, processGroup: true, envAllowlist: SETUP_ENV_ALLOWLIST, omitEnv: SETUP_ENV_DENYLIST });
138
178
  note(set, section(`${label} · approved project setup on ${tested.slice(0, 7)}`, liveSetup.command, prepared));
179
+ proveSet(set);
139
180
  if (prepared.code !== 0 || prepared.timedOut || prepared.notFound)
140
181
  return { conflict: false, tested, outcome: { ran: false, failure: "The project's setup failed, so the check didn't run." }, setupFailed: true };
141
182
  }
@@ -143,18 +184,26 @@ async function checkCohort(store, root, repo, cohort, deps) {
143
184
  if (live === null || live.digest !== command.digest)
144
185
  return { conflict: false, tested, outcome: { ran: false, failure: "The approved check changed before it started." }, setupFailed: false };
145
186
  const shell = approvedCommandShell(live.command);
146
- const ran = await runWithIsolatedDatabase(checkoutRunner(store, repo, checkout, runner, set.map(one => one.runId), setRan), shell.file, shell.args, { cwd: checkout, timeoutMs: live.timeoutMs, processGroup: true, envAllowlist: SETUP_ENV_ALLOWLIST, omitEnv: SETUP_ENV_DENYLIST });
187
+ const ran = await runWithIsolatedDatabase(checkoutRunner(store, repo, checkout, guardedRunner, set.map(one => one.runId), setRan), shell.file, shell.args, { cwd: checkout, timeoutMs: live.timeoutMs, processGroup: true, envAllowlist: SETUP_ENV_ALLOWLIST, omitEnv: SETUP_ENV_DENYLIST });
147
188
  note(set, section(`${label} · full check on ${tested.slice(0, 7)}`, live.command, ran));
189
+ proveSet(set);
190
+ if (set.length === 1 && !ran.timedOut && !ran.notFound) {
191
+ const kept = keepCheckScreenshots(store, root, set[0].runId, checkout, tested, (deps.now ?? (() => new Date()))());
192
+ if (kept.length > 0)
193
+ note(set, `=== Screenshots ===\n${kept.join("\n")}`);
194
+ }
148
195
  return { conflict: false, tested, setupFailed: false,
149
196
  outcome: ran.timedOut ? { ran: false, failure: "The check ran out of time." } : ran.notFound ? { ran: false, failure: "The check couldn't start." } : { ran: true, exitCode: ran.code } };
150
197
  }
151
198
  finally {
152
- await git("git", ["-C", repo, "worktree", "remove", "--force", checkout], { timeoutMs: 120_000 }).catch(() => null);
199
+ if (checkoutCreated)
200
+ await cleanupGit("git", ["-C", repo, "worktree", "remove", "--force", checkout], { timeoutMs: 120_000 }).catch(() => null);
153
201
  rmSync(folder, { recursive: true, force: true });
154
202
  }
155
203
  };
156
- const seal = (one, mode, together, tested, outcome) => {
204
+ const seal = (one, mode, together, tested, outcome) => store.transact(() => {
157
205
  const at = now();
206
+ proveSet(together);
158
207
  const ranLine = ranAtLine(widestRan(ranAtOf.get(one.request) ?? []));
159
208
  const text = logs.get(one.request).length === 0 ? "No command started." : [...logs.get(one.request), ...(ranLine === null ? [] : [ranLine])].join("\n\n");
160
209
  const logId = storeEvidence(store, root, one.runId, "structured-output", `batch-check-${one.request}.log`, Buffer.from(text, "utf8"), FOLLOW_UP_LOG, at, { captureStatus: "ok" });
@@ -170,11 +219,16 @@ async function checkCohort(store, root, repo, cohort, deps) {
170
219
  finishOne(store, one, repo, one.task, outcome.exitCode === 0 ? "passed" : "failed", `Full checks ${how} on ${(tested ?? one.head).slice(0, 7)} · exit ${outcome.exitCode}`.slice(0, 300), at);
171
220
  else
172
221
  finishOne(store, one, repo, one.task, "not-run", outcome.failure, at);
173
- };
174
- const checkSet = async (set, mode) => {
222
+ settled++;
223
+ });
224
+ const checkSet = async (offered, mode) => {
225
+ const set = offered.filter(one => recoveryBlock(store, one.runId) === null);
226
+ if (set.length === 0)
227
+ return;
175
228
  if (set.length === 1) {
176
229
  const one = set[0];
177
230
  const result = await checkOnce(set);
231
+ proveSet(set);
178
232
  const tested = result.conflict ? null : result.tested;
179
233
  const outcome = result.conflict ? { ran: false, failure: "The commit couldn't be checked out." } : result.outcome;
180
234
  attempt(set, tested, outcome.ran ? outcome.exitCode === 0 ? "passed" : "failed" : "not-run");
@@ -182,6 +236,7 @@ async function checkCohort(store, root, repo, cohort, deps) {
182
236
  return;
183
237
  }
184
238
  const result = await checkOnce(set);
239
+ proveSet(set);
185
240
  if (result.conflict) {
186
241
  attempt(set, null, "conflict");
187
242
  for (const one of set)
@@ -207,9 +262,17 @@ async function checkCohort(store, root, repo, cohort, deps) {
207
262
  seal(one, mode, [one], null, outcome);
208
263
  };
209
264
  await checkSet(members, "alone").catch(error => {
265
+ if (error instanceof BatchRecoveryBlocked || members.some(one => recoveryBlock(store, one.runId) !== null)) {
266
+ for (const one of members)
267
+ if (observed.get(one.request).length > 0)
268
+ storeEvidence(store, root, one.runId, "structured-output", `batch-check-${one.request}-held.log`, Buffer.from(observed.get(one.request).join("\n\n"), "utf8"), FOLLOW_UP_LOG, now(), { captureStatus: "ok" });
269
+ return;
270
+ }
210
271
  for (const one of members)
211
- if (followUpChecksOf(store, one.runId, now()).find(f => f.request === one.request)?.state === "running")
212
- finishOne(store, one, repo, one.task, "not-run", `The batch check failed to run: ${String(error).slice(0, 200)}`, now());
272
+ if (followUpChecksOf(store, one.runId, now()).find(f => f.request === one.request)?.state === "running") {
273
+ if (finishOne(store, one, repo, one.task, "not-run", `The batch check failed to run: ${String(error).slice(0, 200)}`, now()))
274
+ settled++;
275
+ }
213
276
  });
214
- return members.length;
277
+ return settled;
215
278
  }