toolroll 0.9.116 → 0.9.118

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 (136) hide show
  1. package/CHANGELOG.md +46 -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 +93 -16
  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 +12 -2
  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/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
package/dist/publish.js CHANGED
@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
  import { run as execRun } from "./exec.js";
9
9
  import { summarizeChecks } from "./pulls.js";
10
- import { parseCiRollup, recordCiChecks, releasePublication } from "./store.js";
10
+ import { parseCiRollup, recordCiChecks, releasePublication, mergeIntentRecoveryHeld, settleObservedMergeIntent } from "./store.js";
11
11
  import { headWithin } from "./names.js";
12
12
  export const BODY_TEMPLATE_VERSION = 2;
13
13
  export const MAX_PUBLISH_ATTEMPTS = 5;
@@ -231,7 +231,7 @@ export async function observeChecks(store, options) {
231
231
  const viewed = await exec("gh", [
232
232
  "pr", "view", String(publication.prNumber),
233
233
  "--repo", publication.githubRepo,
234
- "--json", "statusCheckRollup,headRefOid,state,mergeCommit",
234
+ "--json", "statusCheckRollup,headRefOid,state,mergeCommit,number,url,baseRefName",
235
235
  ], { timeoutMs: EXEC_TIMEOUT_MS });
236
236
  if (viewed.code !== 0) {
237
237
  report.problems.push(`PR #${publication.prNumber}: not read — ${viewed.notFound ? "gh is not on PATH" : firstLine(viewed.stderr) || `exit ${viewed.code}`}`);
@@ -255,26 +255,12 @@ export async function observeChecks(store, options) {
255
255
  const mergeCommit = typeof payload.mergeCommit === "object" && payload.mergeCommit !== null && typeof payload.mergeCommit.oid === "string"
256
256
  ? payload.mergeCommit.oid : null;
257
257
  if (remoteState === "MERGED" || remoteState === "CLOSED") {
258
- let won = false;
259
- store.transact(() => {
260
- const settled = store.settleObservation({ githubRepo: publication.githubRepo, prNumber: publication.prNumber, headSha: headOid, state: "none", generation }, clock());
261
- if (!settled.won)
262
- return;
263
- won = true;
264
- recordCiChecks(store, publication.githubRepo, publication.prNumber, headOid, parseCiRollup(payload.statusCheckRollup), clock());
265
- store.recordPublicationRemoteState(publication.id, remoteState, clock());
266
- report.resolved += store.resolveCiEpisodes(publication.githubRepo, publication.prNumber, null, clock());
267
- store.liftMergeBlocker(publication.id, "the-remote", clock());
268
- store.resolveEpisodes(`merge-attn:${publication.id}`, clock());
269
- const intent = store.mergeIntentFor(publication.id);
270
- if (intent !== null && ["pending", "claimed", "waiting-human", "firing"].includes(intent.state)) {
271
- store.settleMergeIntent(intent.id, intent.generation, remoteState === "MERGED" ? "merged" : "superseded", clock(), {
272
- receipt: `observed ${remoteState.toLowerCase()} remotely`, bumpGeneration: true,
273
- });
274
- }
275
- });
276
- if (won)
258
+ const observed = settleObservedMergeIntent(store, publication.id, { githubRepo: publication.githubRepo, prNumber: publication.prNumber, generation, head: headOid,
259
+ base: typeof payload.baseRefName === "string" ? payload.baseRefName : "", url: typeof payload.url === "string" ? payload.url : "", number: typeof payload.number === "number" ? payload.number : 0, state: remoteState }, clock(), payload.statusCheckRollup);
260
+ if (observed.won) {
261
+ report.resolved += observed.resolved;
277
262
  report.seen.push({ publication, headOid, state: "none", remoteState, rollup: payload.statusCheckRollup, mergeCommit });
263
+ }
278
264
  continue;
279
265
  }
280
266
  const state = summarizeChecks(payload.statusCheckRollup);
@@ -346,7 +332,7 @@ export function mergeTermsHash(grant) {
346
332
  }
347
333
  async function observeOne(store, exec, clock, githubRepo, prNumber) {
348
334
  const generation = store.reserveObservation(githubRepo, prNumber);
349
- const viewed = await exec("gh", ["pr", "view", String(prNumber), "--repo", githubRepo, "--json", "statusCheckRollup,headRefOid,state,isDraft,baseRefName"], { timeoutMs: EXEC_TIMEOUT_MS });
335
+ const viewed = await exec("gh", ["pr", "view", String(prNumber), "--repo", githubRepo, "--json", "statusCheckRollup,headRefOid,state,isDraft,baseRefName,number,url"], { timeoutMs: EXEC_TIMEOUT_MS });
350
336
  if (viewed.code !== 0)
351
337
  return { ok: false, why: firstLine(viewed.stderr) || ("exit " + viewed.code) };
352
338
  let payload;
@@ -361,8 +347,13 @@ async function observeOne(store, exec, clock, githubRepo, prNumber) {
361
347
  return { ok: false, why: "no head OID in the answer" };
362
348
  if (payload.isDraft === true)
363
349
  return { ok: false, why: "draft" };
364
- if (String(payload.state ?? "").toUpperCase() === "MERGED")
365
- return { ok: false, why: "pr-merged" };
350
+ if (String(payload.state ?? "").toUpperCase() === "MERGED") {
351
+ const publication = store.handle.prepare("SELECT id FROM publication WHERE github_repo=? AND pr_number=? ORDER BY id DESC LIMIT 1").get(githubRepo, prNumber);
352
+ if (publication === undefined)
353
+ return { ok: false, why: "unbound-observation" };
354
+ const observed = settleObservedMergeIntent(store, Number(publication["id"]), { githubRepo, prNumber, generation, head: headSha, base: typeof payload.baseRefName === "string" ? payload.baseRefName : "", url: typeof payload.url === "string" ? payload.url : "", number: typeof payload.number === "number" ? payload.number : 0, state: "MERGED" }, clock(), payload.statusCheckRollup);
355
+ return observed.won ? { ok: false, why: "pr-merged", intentSettled: observed.settled } : { ok: false, why: "stale-observation" };
356
+ }
366
357
  if (String(payload.state ?? "").toUpperCase() !== "OPEN")
367
358
  return { ok: false, why: "pr-" + String(payload.state ?? "gone").toLowerCase() };
368
359
  const state = summarizeChecks(payload.statusCheckRollup);
@@ -409,11 +400,13 @@ export async function sweepMerges(store, options) {
409
400
  store.enqueueEpisode(`merge-attn:${publication.id}`, { source: { run: publication.run }, kind: "merge", subject, body, pushClass: "merge", link: "/tasks?view=ready" }, suffix, clock());
410
401
  };
411
402
  const grant = store.publicationGrantFor(options.repo);
412
- if (grant === null || grant.merge !== true || grant.mergeMethod == null)
413
- return report;
414
- const method = grant.mergeMethod;
415
- const termsHash = mergeTermsHash(grant);
416
- for (const publication of store.openedPublications()) {
403
+ const publications = new Map(store.openedPublications().map(p => [p.id, p]));
404
+ for (const row of store.handle.prepare("SELECT p.run FROM publication p JOIN merge_intent i ON i.publication=p.id WHERE i.state='firing'").all()) {
405
+ const publication = store.publicationForRun(Number(row["run"]));
406
+ if (publication !== null)
407
+ publications.set(publication.id, publication);
408
+ }
409
+ for (const publication of publications.values()) {
417
410
  if (releasePublication(store, publication.id)) {
418
411
  report.skipped++;
419
412
  continue;
@@ -426,35 +419,23 @@ export async function sweepMerges(store, options) {
426
419
  const ref = store.refForId(publication.taskRef);
427
420
  if (ref === null || ref.repo !== options.repo)
428
421
  continue;
429
- if (publication.githubRepo !== grant.githubRepo)
430
- continue;
431
422
  if (flexibleMergeRefusal(store, ref.externalId, "publish-sweep") !== null) {
432
423
  report.skipped++;
433
424
  continue;
434
425
  }
435
- const blocker = store.mergeBlockerFor(publication.id);
436
- if (blocker !== null) {
437
- report.skipped++;
438
- pagePerson(publication, "blocked", "PR #" + prNumber + " holds for a repair", "A CI repair (" + (blocker.taskId ?? "?") + ") is in flight. It merges nothing until you lift it: toolroll publish unblock " + prNumber + ".");
439
- continue;
440
- }
441
- store.createMergeIntent({ publication: publication.id, repo: options.repo, grantTermsHash: termsHash, headSha, method, deleteBranch: grant.mergeDeleteBranch === true }, clock());
442
- const intent = store.mergeIntentFor(publication.id);
443
- if (intent === null || intent.state === "merged" || intent.state === "refused" || intent.state === "superseded")
444
- continue;
445
- if (intent.state === "waiting-human") {
446
- report.skipped++;
447
- pagePerson(publication, "waiting-human", "PR #" + prNumber + " waits for your go-ahead", "Merges wait for you while this posture holds. When you want it merged: toolroll publish merge " + prNumber + " --as <you> --token <t>. It still merges only when CI is seen green on the exact head.");
448
- continue;
449
- }
450
- if (intent.state === "firing") {
426
+ const prospectiveExec = (file, args, options) => { if (mergeIntentRecoveryHeld(store, publication.id))
427
+ throw new MergeRecoveryStop(); return exec(file, args, options); };
428
+ const previous = store.mergeIntentFor(publication.id);
429
+ if (previous?.state === "firing") {
430
+ const intent = previous;
451
431
  if (intent.firingDeadline !== null && intent.firingDeadline <= clock().toISOString()) {
452
- const reread = await observeOne(store, exec, clock, grant.githubRepo, prNumber);
432
+ const reread = await observeOne(store, exec, clock, publication.githubRepo, prNumber);
453
433
  if (!reread.ok && reread.why === "pr-merged") {
454
- store.settleMergeIntent(intent.id, intent.generation, "merged", clock(), {
455
- receipt: "observed merged remotely after a stale firing claim", from: "firing", bumpGeneration: true,
456
- });
457
- report.merged++;
434
+ if (reread.intentSettled === true)
435
+ report.merged++;
436
+ }
437
+ else if (mergeIntentRecoveryHeld(store, publication.id)) {
438
+ report.skipped++;
458
439
  }
459
440
  else if (!reread.ok && reread.why.startsWith("pr-")) {
460
441
  store.settleMergeIntent(intent.id, intent.generation, "superseded", clock(), {
@@ -476,6 +457,35 @@ export async function sweepMerges(store, options) {
476
457
  }
477
458
  continue;
478
459
  }
460
+ if (grant === null || grant.merge !== true || grant.mergeMethod == null || publication.githubRepo !== grant.githubRepo) {
461
+ report.skipped++;
462
+ continue;
463
+ }
464
+ const method = grant.mergeMethod;
465
+ const termsHash = mergeTermsHash(grant);
466
+ if (mergeIntentRecoveryHeld(store, publication.id) && previous?.state !== "firing") {
467
+ report.skipped++;
468
+ continue;
469
+ }
470
+ const blocker = store.mergeBlockerFor(publication.id);
471
+ if (blocker !== null) {
472
+ report.skipped++;
473
+ pagePerson(publication, "blocked", "PR #" + prNumber + " holds for a repair", "A CI repair (" + (blocker.taskId ?? "?") + ") is in flight. It merges nothing until you lift it: toolroll publish unblock " + prNumber + ".");
474
+ continue;
475
+ }
476
+ const created = store.createMergeIntent({ publication: publication.id, repo: options.repo, grantTermsHash: termsHash, headSha, method, deleteBranch: grant.mergeDeleteBranch === true }, clock());
477
+ if (created === "recovery-held") {
478
+ report.skipped++;
479
+ continue;
480
+ }
481
+ const intent = store.mergeIntentFor(publication.id);
482
+ if (intent === null || intent.state === "merged" || intent.state === "refused" || intent.state === "superseded")
483
+ continue;
484
+ if (intent.state === "waiting-human") {
485
+ report.skipped++;
486
+ pagePerson(publication, "waiting-human", "PR #" + prNumber + " waits for your go-ahead", "Merges wait for you while this posture holds. When you want it merged: toolroll publish merge " + prNumber + " --as <you> --token <t>. It still merges only when CI is seen green on the exact head.");
487
+ continue;
488
+ }
479
489
  const claim = store.claimMergeIntent(intent.id, who, MERGE_LEASE_MS, clock());
480
490
  if (claim === null)
481
491
  continue;
@@ -485,19 +495,37 @@ export async function sweepMerges(store, options) {
485
495
  settle("superseded", { error: "the grant or the head moved since this intent was written" });
486
496
  continue;
487
497
  }
488
- const queue = await proveNoMergeQueue(exec, grant.githubRepo, grant.base);
498
+ const queue = await proveNoMergeQueue(prospectiveExec, grant.githubRepo, grant.base);
499
+ if (mergeIntentRecoveryHeld(store, publication.id)) {
500
+ report.skipped++;
501
+ continue;
502
+ }
489
503
  if (!queue.ok) {
490
- settle("refused", { error: queue.why });
504
+ if (!settle("refused", { error: queue.why })) {
505
+ report.skipped++;
506
+ continue;
507
+ }
491
508
  report.refused++;
492
509
  pagePerson(publication, queue.why, "PR #" + prNumber + " will not auto-merge", queue.why === "merge-queue"
493
510
  ? "The base branch requires a merge queue - out of this release's scope. Merge it on GitHub, or lift the queue and run: toolroll publish rearm " + prNumber + "."
494
511
  : "The branch's protection could not be READ well enough to prove no merge queue governs it - auto-merge stays paused. Check access, then run: toolroll publish rearm " + prNumber + ".");
495
512
  continue;
496
513
  }
497
- const seen = await observeOne(store, exec, clock, grant.githubRepo, prNumber);
514
+ const seen = await observeOne(store, prospectiveExec, clock, grant.githubRepo, prNumber);
515
+ if (mergeIntentRecoveryHeld(store, publication.id)) {
516
+ report.skipped++;
517
+ continue;
518
+ }
498
519
  if (!seen.ok) {
520
+ if (seen.why === "pr-merged" && seen.intentSettled === true) {
521
+ report.merged++;
522
+ continue;
523
+ }
499
524
  if (seen.why === "draft") {
500
- settle("refused", { error: "draft" });
525
+ if (!settle("refused", { error: "draft" })) {
526
+ report.skipped++;
527
+ continue;
528
+ }
501
529
  report.refused++;
502
530
  pagePerson(publication, "draft", "PR #" + prNumber + " is a draft", "Drafts never merge themselves. Mark it ready on GitHub, then run: toolroll publish rearm " + prNumber + ".");
503
531
  }
@@ -524,45 +552,66 @@ export async function sweepMerges(store, options) {
524
552
  }
525
553
  continue;
526
554
  }
527
- const merged = await exec("gh", [
555
+ const merged = await prospectiveExec("gh", [
528
556
  "pr", "merge", String(prNumber),
529
557
  "--repo", grant.githubRepo,
530
558
  "--" + method,
531
559
  "--match-head-commit", headSha,
532
560
  ...(grant.mergeDeleteBranch === true ? ["--delete-branch"] : []),
533
561
  ], { timeoutMs: EXEC_TIMEOUT_MS });
562
+ if (mergeIntentRecoveryHeld(store, publication.id)) {
563
+ const observed = await observeOne(store, exec, clock, publication.githubRepo, prNumber);
564
+ if (!observed.ok && observed.why === "pr-merged" && observed.intentSettled === true)
565
+ report.merged++;
566
+ else
567
+ report.skipped++;
568
+ continue;
569
+ }
534
570
  if (merged.code === 0) {
571
+ let won = false;
535
572
  store.transact(() => {
536
- settle("merged", { receipt: "merged " + headSha.slice(0, 12) + " at " + clock().toISOString(), countAttempt: true, from: "firing" });
573
+ won = settle("merged", { receipt: "merged " + headSha.slice(0, 12) + " at " + clock().toISOString(), countAttempt: true, from: "firing" });
574
+ if (!won)
575
+ return;
537
576
  store.recordPublicationRemoteState(publication.id, "MERGED", clock());
538
577
  store.resolveCiEpisodes(grant.githubRepo, prNumber, null, clock());
539
578
  });
579
+ if (!won) {
580
+ report.skipped++;
581
+ continue;
582
+ }
540
583
  report.merged++;
541
584
  store.resolveEpisodes(`merge-attn:${publication.id}`, clock());
542
585
  page(publication, "merge:" + publication.id + ":merged", "merged: PR #" + prNumber, (publication.prUrl ?? grant.githubRepo) + " - " + method + " of " + headSha.slice(0, 12) + ", under the merge terms you approved.");
543
586
  continue;
544
587
  }
545
588
  if (merged.code === 4) {
546
- settle("refused", { error: "credential", countAttempt: true, from: "firing" });
589
+ if (!settle("refused", { error: "credential", countAttempt: true, from: "firing" })) {
590
+ report.skipped++;
591
+ continue;
592
+ }
547
593
  report.refused++;
548
594
  pagePerson(publication, "credential", "PR #" + prNumber + ": gh is not signed in", "The merge acts as this machine's GitHub account, and it could not authenticate. Run gh auth login, then: toolroll publish rearm " + prNumber + ".");
549
595
  continue;
550
596
  }
551
597
  const after = await observeOne(store, exec, clock, grant.githubRepo, prNumber);
552
598
  if (!after.ok && after.why === "pr-merged") {
553
- settle("merged", { receipt: "merged (confirmed by re-read after an ambiguous exit)", countAttempt: true, from: "firing" });
554
- report.merged++;
599
+ if (after.intentSettled === true)
600
+ report.merged++;
555
601
  }
556
602
  else if (!after.ok && (after.why === "draft" || after.why.startsWith("pr-"))) {
557
- settle(after.why === "draft" ? "refused" : "superseded", { error: after.why, countAttempt: true, from: "firing" });
558
- if (after.why === "draft")
603
+ const won = settle(after.why === "draft" ? "refused" : "superseded", { error: after.why, countAttempt: true, from: "firing" });
604
+ if (won && after.why === "draft")
559
605
  report.refused++;
560
606
  }
561
607
  else if (after.ok && after.headSha !== headSha) {
562
608
  settle("superseded", { error: "the head moved during the attempt", countAttempt: true, from: "firing" });
563
609
  }
564
610
  else if (intent.attempts + 1 >= MERGE_MAX_ATTEMPTS) {
565
- settle("refused", { error: firstLine(merged.stderr) || "the merge was rejected", countAttempt: true, from: "firing" });
611
+ if (!settle("refused", { error: firstLine(merged.stderr) || "the merge was rejected", countAttempt: true, from: "firing" })) {
612
+ report.skipped++;
613
+ continue;
614
+ }
566
615
  report.refused++;
567
616
  pagePerson(publication, "rejected", "PR #" + prNumber + " would not merge", (firstLine(merged.stderr) || "GitHub rejected the merge") + " - likely branch protection, required reviews, or a conflict. Fix the cause, then run: toolroll publish rearm " + prNumber + ".");
568
617
  }
@@ -571,6 +620,10 @@ export async function sweepMerges(store, options) {
571
620
  }
572
621
  }
573
622
  catch (error) {
623
+ if (error instanceof MergeRecoveryStop) {
624
+ report.skipped++;
625
+ continue;
626
+ }
574
627
  report.problems.push("publication " + publication.id + ": " + (error instanceof Error ? error.message : String(error)));
575
628
  }
576
629
  }
@@ -584,3 +637,5 @@ export function settleWithChecks(store, observation, rollup, now) {
584
637
  return settled;
585
638
  });
586
639
  }
640
+ class MergeRecoveryStop extends Error {
641
+ }
@@ -419,6 +419,8 @@ export async function mergePullRequest(store, input) {
419
419
  return refuse(reason, message);
420
420
  };
421
421
  const gate = fullCheckGate(store, publication.run, clock());
422
+ if (gate.state === "recovery-held")
423
+ return refuse("recovery-held", gate.message);
422
424
  if (gate.state === "not-requested")
423
425
  requestFollowUpChecks(store, { runId: publication.run, level: "full", actor: input.by, why: "pull-request" }, clock());
424
426
  const skippedFullCheck = gate.state !== "clear";
@@ -444,20 +446,35 @@ export async function mergePullRequest(store, input) {
444
446
  if (before.checks !== "passing")
445
447
  return fail("checks", before.checks === "failing" ? "Checks are failing, so it can't merge." : before.checks === "running" ? "Checks are still running. Merge once they pass." : "No checks have reported yet. Merge once they pass.");
446
448
  const token = randomUUID();
447
- const reserved = store.transact(() => {
448
- if (input.proceed?.({ base: before.base, url: before.url, head: before.head }) === false)
449
- return "halted";
450
- if (flexibleMergeRefusal(store, mergedTask, "pull-request", flexibleAuthority, "reserve") !== null)
451
- return "halted";
452
- if (refArchived(store, publication.taskRef))
453
- return "archived";
454
- if (store.handle.prepare("SELECT 1 FROM hold WHERE task_ref = ? AND owner_id LIKE 'project-delete:%' AND (until IS NULL OR until > ?)").get(publication.taskRef, clock().toISOString()) !== undefined)
455
- return "deleting";
456
- if (store.handle.prepare("SELECT 1 FROM merge_in_flight WHERE publication = ? AND at > ?").get(publication.id, new Date(clock().getTime() - 15 * 60_000).toISOString()) !== undefined)
457
- return "merging";
458
- store.handle.prepare("INSERT OR REPLACE INTO merge_in_flight (publication, task_ref, token, by, at) VALUES (?, ?, ?, ?, ?)").run(publication.id, publication.taskRef, token, input.by, clock().toISOString());
459
- return "ok";
460
- });
449
+ let reserved;
450
+ try {
451
+ reserved = store.transact(() => {
452
+ if (fullCheckGate(store, publication.run, clock()).state === "recovery-held")
453
+ return "recovery-held";
454
+ if (input.proceed?.({ base: before.base, url: before.url, head: before.head }) === false)
455
+ return "halted";
456
+ if (flexibleMergeRefusal(store, mergedTask, "pull-request", flexibleAuthority, "reserve") !== null)
457
+ return "halted";
458
+ if (refArchived(store, publication.taskRef))
459
+ return "archived";
460
+ if (store.handle.prepare("SELECT 1 FROM hold WHERE task_ref = ? AND owner_id LIKE 'project-delete:%' AND (until IS NULL OR until > ?)").get(publication.taskRef, clock().toISOString()) !== undefined)
461
+ return "deleting";
462
+ if (store.handle.prepare("SELECT 1 FROM merge_in_flight WHERE publication = ? AND at > ?").get(publication.id, new Date(clock().getTime() - 15 * 60_000).toISOString()) !== undefined)
463
+ return "merging";
464
+ const reservedAt = clock();
465
+ if (fullCheckGate(store, publication.run, reservedAt).state === "recovery-held")
466
+ throw new RecoveryHeldReservation();
467
+ store.handle.prepare("INSERT OR REPLACE INTO merge_in_flight (publication, task_ref, token, by, at) VALUES (?, ?, ?, ?, ?)").run(publication.id, publication.taskRef, token, input.by, reservedAt.toISOString());
468
+ return "ok";
469
+ });
470
+ }
471
+ catch (error) {
472
+ if (error instanceof RecoveryHeldReservation)
473
+ return refuse("recovery-held", "Checks are on hold after recovery. Earlier execution is unverified.");
474
+ throw error;
475
+ }
476
+ if (reserved === "recovery-held")
477
+ return refuse("recovery-held", "Checks are on hold after recovery. Earlier execution is unverified.");
461
478
  if (reserved === "halted")
462
479
  return refuse("halted", "The worker is stopping or paused, so this merge waits for its next pass.");
463
480
  if (reserved === "archived")
@@ -508,6 +525,8 @@ export function pullRequestViewOf(store, runId) {
508
525
  return { ...base, state: "closed", label: "Closed", detail: "The pull request was closed on GitHub without merging." };
509
526
  switch (publication.lastCheckState) {
510
527
  case "passing":
528
+ if (fullCheck?.state === "recovery-held")
529
+ return { ...base, state: "waiting", label: "Checks held after recovery", detail: fullCheck.message };
511
530
  if (fullCheck !== null)
512
531
  return { ...base, state: "waiting", label: fullCheck.state === "failed" ? "Full checks failed" : "Waiting for full checks", detail: `CI passed on GitHub. ${fullCheck.message}${error}`, canMerge: grant !== null };
513
532
  return { ...base, state: "ready", label: "Ready to merge", detail: `CI passed on GitHub.${grant?.mergeWhenGreen === true ? " It merges by itself." : ""}${error}`, canMerge: grant !== null };
@@ -533,3 +552,5 @@ export function newestPullRequestOf(store, versions) {
533
552
  return null;
534
553
  }
535
554
  export const MERGE_NEEDS_PERSON = "Only a person can merge. Merge it on the task page or from your paired chat.";
555
+ class RecoveryHeldReservation extends Error {
556
+ }
@@ -9,7 +9,7 @@ function connection() {
9
9
  const opened = openStoreReadOnly(String(workerData.file));
10
10
  if (opened === null)
11
11
  throw new Error('The read worker could not open the database read-only at the current schema.');
12
- opened.handle.exec('PRAGMA query_only=1');
12
+ opened.handle.exec('PRAGMA query_only=1; PRAGMA temp_store=MEMORY; PRAGMA cache_size=-16000;');
13
13
  return store = opened;
14
14
  }
15
15
  parentPort.on('message', ({ id, job }) => {
@@ -1,7 +1,34 @@
1
+ import { createRequire } from 'node:module';
1
2
  import { Worker } from 'node:worker_threads';
2
3
  import { availableParallelism } from 'node:os';
3
4
  import { WorkIndexCursorError } from './work-index.js';
4
5
  export const READ_QUEUE_MAX = 1_000;
6
+ const READ_CACHE_MAX = 64;
7
+ const READ_CACHE_TTL_MS = 1_000;
8
+ const INFLIGHT_COALESCE_MS = 250;
9
+ function canonicalAccess(access) {
10
+ return {
11
+ ...access,
12
+ repos: access.repos === null ? null : [...access.repos].sort(),
13
+ ...(access.dependencyRepos === undefined ? {} : { dependencyRepos: access.dependencyRepos === null ? null : [...access.dependencyRepos].sort() }),
14
+ };
15
+ }
16
+ function readCacheKey(job) {
17
+ const secondBucket = Math.floor(Date.parse(job.now) / 1_000);
18
+ if (job.kind === 'work-index-page') {
19
+ const o = job.options;
20
+ return JSON.stringify([
21
+ 'wip',
22
+ secondBucket,
23
+ canonicalAccess(job.access),
24
+ { ...o, ...(o.roots === undefined ? {} : { roots: [...o.roots].sort() }) },
25
+ ]);
26
+ }
27
+ if (job.kind === 'work-counts') {
28
+ return JSON.stringify(['wc', secondBucket, canonicalAccess(job.access)]);
29
+ }
30
+ return JSON.stringify(['ps', secondBucket, canonicalAccess(job.access), job.actor, job.projects, job.evidenceRoot]);
31
+ }
5
32
  export class ReadExecutorError extends Error {
6
33
  constructor(message) { super(message); this.name = 'ReadExecutorError'; }
7
34
  }
@@ -10,6 +37,10 @@ export class ReadExecutor {
10
37
  #size;
11
38
  #slots = [];
12
39
  #queue = [];
40
+ #cache = new Map();
41
+ #inflight = new Map();
42
+ #probeDb = undefined;
43
+ #probeStmt = null;
13
44
  #next = 1;
14
45
  #closed = false;
15
46
  constructor(file, size = defaultReadWorkers()) {
@@ -17,6 +48,25 @@ export class ReadExecutor {
17
48
  this.#size = Math.max(1, Math.floor(size));
18
49
  }
19
50
  get size() { return this.#size; }
51
+ #dataVersion() {
52
+ if (this.#probeDb === null)
53
+ return null;
54
+ try {
55
+ if (this.#probeDb === undefined) {
56
+ const require = createRequire(import.meta.url);
57
+ const { DatabaseSync } = require('node:sqlite');
58
+ this.#probeDb = new DatabaseSync(this.#file, { readOnly: true });
59
+ this.#probeStmt = this.#probeDb.prepare('PRAGMA data_version');
60
+ }
61
+ const row = this.#probeStmt?.get();
62
+ return typeof row?.data_version === 'number' ? row.data_version : null;
63
+ }
64
+ catch {
65
+ this.#probeDb = null;
66
+ this.#probeStmt = null;
67
+ return null;
68
+ }
69
+ }
20
70
  async workIndexPage(now, access, options) {
21
71
  try {
22
72
  return await this.#run({ kind: 'work-index-page', now: now.toISOString(), access, options });
@@ -36,12 +86,48 @@ export class ReadExecutor {
36
86
  #run(job) {
37
87
  if (this.#closed)
38
88
  return Promise.reject(new ReadExecutorError('The server is closing.'));
89
+ const version = this.#dataVersion();
90
+ const key = version === null ? null : readCacheKey(job);
91
+ const nowMs = Date.now();
92
+ if (key !== null && version !== null) {
93
+ const hit = this.#cache.get(key);
94
+ if (hit !== undefined) {
95
+ if (hit.dataVersion === version && nowMs - hit.at <= READ_CACHE_TTL_MS) {
96
+ return Promise.resolve(structuredClone(hit.value));
97
+ }
98
+ this.#cache.delete(key);
99
+ }
100
+ const running = this.#inflight.get(key);
101
+ if (running !== undefined && nowMs - running.startedAt <= INFLIGHT_COALESCE_MS) {
102
+ return running.promise.then(value => structuredClone(value));
103
+ }
104
+ }
39
105
  if (this.#queue.length >= READ_QUEUE_MAX)
40
106
  return Promise.reject(new ReadExecutorError('The server is too busy to read this now; try again shortly.'));
41
- return new Promise((resolve, reject) => {
107
+ const promise = new Promise((resolve, reject) => {
42
108
  this.#queue.push({ id: this.#next++, job, resolve, reject });
43
109
  this.#pump();
44
110
  });
111
+ if (key !== null && version !== null) {
112
+ const entry = { promise, startedAt: nowMs };
113
+ this.#inflight.set(key, entry);
114
+ void promise.then(value => {
115
+ if (this.#inflight.get(key) === entry)
116
+ this.#inflight.delete(key);
117
+ if (!this.#closed && this.#dataVersion() === version) {
118
+ if (this.#cache.size >= READ_CACHE_MAX) {
119
+ const oldest = this.#cache.keys().next().value;
120
+ if (oldest !== undefined)
121
+ this.#cache.delete(oldest);
122
+ }
123
+ this.#cache.set(key, { value: structuredClone(value), dataVersion: version, at: Date.now() });
124
+ }
125
+ }, () => {
126
+ if (this.#inflight.get(key) === entry)
127
+ this.#inflight.delete(key);
128
+ });
129
+ }
130
+ return promise;
45
131
  }
46
132
  #pump() {
47
133
  while (this.#queue.length > 0) {
@@ -92,6 +178,14 @@ export class ReadExecutor {
92
178
  if (this.#closed)
93
179
  return;
94
180
  this.#closed = true;
181
+ this.#cache.clear();
182
+ this.#inflight.clear();
183
+ try {
184
+ this.#probeDb?.close();
185
+ }
186
+ catch { }
187
+ this.#probeDb = null;
188
+ this.#probeStmt = null;
95
189
  const stopped = new ReadExecutorError('The server is closing.');
96
190
  for (const pending of this.#queue.splice(0))
97
191
  pending.reject(stopped);