toolroll 0.9.130 → 0.9.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/agent-state.js +1 -1
  3. package/dist/browser/manifest.json +14 -14
  4. package/dist/browser/{terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js} +1 -1
  5. package/dist/browser/terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.br +0 -0
  6. package/dist/browser/{terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz → terminal.8978c8cbb268e1006f4b0be371c2401b58078e6d9f1380f4a5c2a12da843909f.js.gz} +0 -0
  7. package/dist/browser/{workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js → workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js} +1 -1
  8. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.br +0 -0
  9. package/dist/browser/workspace.4f5935dc80574baadf1adafd39a08c567fb1fac1323052ca355546622f9b06d2.js.gz +0 -0
  10. package/dist/builder-restart.js +13 -4
  11. package/dist/builder.js +4 -1
  12. package/dist/central-recovery-stage.js +2 -2
  13. package/dist/chat-follow.js +4 -0
  14. package/dist/db-tuning.js +16 -0
  15. package/dist/discord.js +9 -3
  16. package/dist/dispatch.js +32 -4
  17. package/dist/doctor.js +30 -0
  18. package/dist/evidence.js +49 -3
  19. package/dist/exec.js +3 -0
  20. package/dist/git-views.js +7 -1
  21. package/dist/invoke.js +12 -2
  22. package/dist/lead-queue-runtime.js +8 -5
  23. package/dist/lead-status.js +3 -3
  24. package/dist/loop-recovery.js +40 -0
  25. package/dist/maintenance.js +29 -1
  26. package/dist/needs-you.js +2 -0
  27. package/dist/operate.js +376 -52
  28. package/dist/planner.js +4 -1
  29. package/dist/query-index-schema.js +10 -0
  30. package/dist/read-executor-worker.js +9 -7
  31. package/dist/read-executor.js +18 -1
  32. package/dist/read-worker-connection.js +7 -0
  33. package/dist/release-adapters.js +51 -6
  34. package/dist/release-cli.js +24 -11
  35. package/dist/release-next.js +1 -1
  36. package/dist/release-stops.js +71 -0
  37. package/dist/release-supersede.js +125 -0
  38. package/dist/release-supervise.js +90 -0
  39. package/dist/release.js +252 -40
  40. package/dist/runner.js +36 -1
  41. package/dist/scout.js +4 -1
  42. package/dist/serve.js +92 -6
  43. package/dist/shutdown-proof.js +29 -0
  44. package/dist/slack.js +9 -3
  45. package/dist/sqlite-telemetry.js +26 -14
  46. package/dist/statement-cache.js +137 -0
  47. package/dist/store.js +70 -13
  48. package/dist/task-status.js +1 -1
  49. package/dist/teams.js +9 -3
  50. package/dist/teardown-git.js +10 -1
  51. package/dist/telegram.js +4 -1
  52. package/dist/up-processes.js +16 -1
  53. package/dist/up-role-child.js +2 -0
  54. package/dist/wake-hub.js +15 -6
  55. package/dist/work-index.js +101 -44
  56. package/dist/work-reads.js +53 -9
  57. package/dist/work-snapshots.js +185 -0
  58. package/dist/worker-statement-cache.js +83 -0
  59. package/dist/workspace-revision.js +145 -21
  60. package/package.json +1 -1
  61. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
  62. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
  63. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
package/dist/serve.js CHANGED
@@ -62,7 +62,8 @@ import { createTeamRuntime } from './team-runtime.js';
62
62
  import { createPersonalQueueRuntime } from './lead-queue-runtime.js';
63
63
  import {} from "./tools-ui.js";
64
64
  import { WORK_INDEX_MAX_LIMIT, workCountsByProject, workIndexPage } from "./work-index.js";
65
- import { withWorkReads } from "./work-reads.js";
65
+ import { askedPages, prefetchedPage, providePages, withWorkReads } from "./work-reads.js";
66
+ import { WorkSnapshots } from "./work-snapshots.js";
66
67
  import { createEngineHandlers } from "./server/engine-api.js";
67
68
  import { enterRehearsal } from "./rehearsal.js";
68
69
  import { WORKSPACE_MOTION_SCRIPT } from "./workspace-motion.js";
@@ -250,6 +251,8 @@ function buildDecisionServer(options, leaveRehearsal) {
250
251
  };
251
252
  const workspaceRevision = prepareWorkspaceRevision(store);
252
253
  const chromeReads = new RevisionCache(workspaceRevision, clock);
254
+ const snapshots = reads === null ? null : new WorkSnapshots(workspaceRevision, clock, job => reads.snapshot(job));
255
+ const learnedPages = new Map();
253
256
  const workspaceIncarnation = randomBytes(16).toString('hex');
254
257
  const workspaceValidators = new WorkspaceValidatorCache();
255
258
  const providerHome = options.connectionHome ?? homedir();
@@ -882,7 +885,32 @@ function buildDecisionServer(options, leaveRehearsal) {
882
885
  facts.workspaceValidator = { key, revision, expiresAt,
883
886
  etag: '"' + createHash('sha256').update(`${key}:${revision}:${expiresAt}`).digest('hex') + '"' };
884
887
  }
885
- await prefetchChrome(route, url, who);
888
+ else if (facts?.workspaceRead && who.via === 'cookie' && EARLY_PAGES.has(route.id) && facts.freshWork !== true) {
889
+ const key = createHash('sha256').update(JSON.stringify([workspaceIncarnation, 'early', who.name,
890
+ who.session.generation, who.session.csrf, who.session.project, who.session.projectRevision,
891
+ admissionList(), url.pathname + url.search, localSignIn?.signedIn ?? null, facts.theme ?? null, facts.accent ?? null,
892
+ facts.updateSeen ?? null, facts.readPurpose ?? null, facts.appWork === true, facts.advanced ?? null, facts.passwordless ?? null])).digest('hex');
893
+ const revision = workspaceRevision.current(), now = clock();
894
+ const prior = workspaceValidators.get(key);
895
+ if (prior && prior.revision === revision && prior.expiresAt > now.getTime() && request.headers['if-none-match'] === prior.etag) {
896
+ response.setHeader('ETag', prior.etag);
897
+ return respond(response, 304, 'application/json; charset=utf-8', '');
898
+ }
899
+ facts.earlyValidator = { key, revision, expiresAt: Math.min(workspaceRevision.expiresAt(now), now.getTime() + EARLY_MAX_AGE_MS) };
900
+ }
901
+ const ahead = await prefetchChrome(route, url, who);
902
+ if (ahead?.snapshot !== undefined && facts !== undefined) {
903
+ const taken = ahead.snapshot, older = (revision) => revisionOrder(taken.revision) < revisionOrder(revision) ? taken.revision : revision;
904
+ if (facts.earlyValidator !== undefined)
905
+ facts.earlyValidator = { ...facts.earlyValidator,
906
+ revision: older(facts.earlyValidator.revision), expiresAt: Math.min(facts.earlyValidator.expiresAt, taken.expiresAt) };
907
+ const chat = facts.workspaceValidator;
908
+ if (chat !== undefined) {
909
+ const revision = older(chat.revision), expiresAt = Math.min(chat.expiresAt, taken.expiresAt);
910
+ facts.workspaceValidator = { key: chat.key, revision, expiresAt,
911
+ etag: '"' + createHash('sha256').update(`${chat.key}:${revision}:${expiresAt}`).digest('hex') + '"' };
912
+ }
913
+ }
886
914
  timeline.mark("chrome and worker reads");
887
915
  if (who.via === 'cookie') {
888
916
  const current = identify(request, false);
@@ -898,7 +926,17 @@ function buildDecisionServer(options, leaveRehearsal) {
898
926
  if (!projectRequestAllowed(route, route.project, url, who, request, response, null))
899
927
  return;
900
928
  }
901
- return withWorkReads(() => handleGet(route, url, who, request, response));
929
+ if (ahead === null)
930
+ return withWorkReads(() => handleGet(route, url, who, request, response));
931
+ return withWorkReads(async () => {
932
+ providePages(store, ahead.pages);
933
+ try {
934
+ return await handleGet(route, url, who, request, response);
935
+ }
936
+ finally {
937
+ learnPages(ahead.learn, askedPages());
938
+ }
939
+ });
902
940
  }
903
941
  return handlePost(route, url, who, request, response, body);
904
942
  };
@@ -1501,6 +1539,9 @@ function buildDecisionServer(options, leaveRehearsal) {
1501
1539
  if (status === 200 && validator === undefined && path.pathname !== '/chat') {
1502
1540
  const etag = '"w' + createHash('sha256').update(body).digest('base64url') + '"';
1503
1541
  response.setHeader('ETag', etag);
1542
+ const early = requestFacts.earlyValidator;
1543
+ if (early !== undefined)
1544
+ workspaceValidators.set(early.key, { etag, revision: early.revision, expiresAt: early.expiresAt });
1504
1545
  if (requestFacts.workspaceIfNoneMatch === etag)
1505
1546
  return respond(response, 304, 'application/json; charset=utf-8', '');
1506
1547
  }
@@ -1563,8 +1604,9 @@ function buildDecisionServer(options, leaveRehearsal) {
1563
1604
  const access = workAccess();
1564
1605
  const rows = chromeRead(summaryKey(actor, access, projects), () => projectSummaryOf(store, clock(), access, actor, projects, evidenceRoot));
1565
1606
  let counts;
1607
+ const held = requestContext.getStore()?.chromeReads?.get(countsKey(access));
1566
1608
  try {
1567
- counts = projectCounts(clock());
1609
+ counts = held ?? projectCounts(clock());
1568
1610
  }
1569
1611
  catch {
1570
1612
  return rows;
@@ -1667,6 +1709,9 @@ function buildDecisionServer(options, leaveRehearsal) {
1667
1709
  function sharedIndexPage(access, options) {
1668
1710
  if (requestContext.getStore()?.freshWork === true)
1669
1711
  return workIndexPage(store, clock(), access, options);
1712
+ const ahead = prefetchedPage(store, access, options);
1713
+ if (ahead !== undefined)
1714
+ return ahead;
1670
1715
  return chromeRead(indexKey(access, options), () => workIndexPage(store, clock(), access, options));
1671
1716
  }
1672
1717
  function chromeRead(key, compute) {
@@ -1681,10 +1726,51 @@ function buildDecisionServer(options, leaveRehearsal) {
1681
1726
  }
1682
1727
  const chatHomeViews = () => ["all", "needs-you", "completed"]
1683
1728
  .map(view => ({ view, limit: WORK_INDEX_MAX_LIMIT, ...(evidenceRoot === undefined ? {} : { root: evidenceRoot }) }));
1729
+ const revisionOrder = (revision) => Number(/^v1:(\d+)$/.exec(revision)?.[1] ?? -1);
1730
+ const EARLY_PAGES = new Set(["home", "projects.page"]);
1731
+ const EARLY_MAX_AGE_MS = 30_000;
1732
+ const SNAPSHOT_PAGES = new Set(["spend", "people.page", "kit.page", "subagent.page", "routine.page", "sweep.page"]);
1684
1733
  const CHROME_PAGES = new Set(["home", "work", "board", "agents", "agents.live", "task.page", "run.page", "chat.page", "review", "tasks", "inbox",
1685
1734
  "next", "done", "projects.page", "flows.page", "flow.page", "settings.page", "decision.page", "menu"]);
1686
1735
  async function prefetchChrome(route, url, who) {
1687
- if (reads === null || who.via !== "cookie" || !CHROME_PAGES.has(route.id))
1736
+ if (reads === null || who.via !== "cookie" || !(CHROME_PAGES.has(route.id) || SNAPSHOT_PAGES.has(route.id) || route.id.startsWith("settings.")))
1737
+ return null;
1738
+ if (snapshots !== null && requestContext.getStore()?.freshWork !== true) {
1739
+ try {
1740
+ const facts = requestContext.getStore();
1741
+ const actor = facts?.actor ?? "";
1742
+ const access = workAccess(), projects = sidebarProjects();
1743
+ const query = new URLSearchParams(url.searchParams);
1744
+ query.delete("format");
1745
+ const learn = JSON.stringify([route.id, url.pathname, query.toString(), actor, accessKey(access)]);
1746
+ const job = { now: clock().toISOString(), chrome: { access, actor, projects, evidenceRoot: evidenceRoot ?? null }, pages: learnedPages.get(learn) ?? [] };
1747
+ const snapshot = await snapshots.take(job);
1748
+ if (snapshot !== null && facts !== undefined) {
1749
+ const held = facts.chromeReads ??= new Map();
1750
+ if (snapshot.counts !== null)
1751
+ held.set(countsKey(access), snapshot.counts);
1752
+ if (snapshot.summary !== null)
1753
+ held.set(summaryKey(actor, access, projects), snapshot.summary);
1754
+ const pages = new Map();
1755
+ snapshot.keys.forEach((one, at) => { const page = snapshot.pages[at]; if (page != null)
1756
+ pages.set(one, page); });
1757
+ return { pages, learn, snapshot: { revision: snapshot.revision, expiresAt: snapshot.expiresAt } };
1758
+ }
1759
+ return { pages: new Map(), learn };
1760
+ }
1761
+ catch { }
1762
+ }
1763
+ await prefetchChromeEach(route, url, who);
1764
+ return null;
1765
+ }
1766
+ function learnPages(key, asked) {
1767
+ learnedPages.delete(key);
1768
+ if (learnedPages.size >= 256)
1769
+ learnedPages.delete(learnedPages.keys().next().value);
1770
+ learnedPages.set(key, asked.slice(0, 16));
1771
+ }
1772
+ async function prefetchChromeEach(route, url, who) {
1773
+ if (reads === null)
1688
1774
  return;
1689
1775
  try {
1690
1776
  const actor = requestContext.getStore()?.actor ?? "";
@@ -1886,7 +1972,7 @@ function buildDecisionServer(options, leaveRehearsal) {
1886
1972
  directChatHandlers.close();
1887
1973
  detachReads();
1888
1974
  liveFollower.close();
1889
- void Promise.all([closeCoding(), terminalClosing.close?.().then(problem => { terminalClosing.problem = problem; }), bounded(team.close()), bounded(personalQueue.close()), bounded(leadMaintenance?.stop()), bounded(backgroundChecks?.stop()), bounded(reads?.close()), bounded(engineHandlers.close()), bounded(phoneAccessRef?.stop())])
1975
+ void Promise.all([closeCoding(), terminalClosing.close?.().then(problem => { terminalClosing.problem = problem; }), bounded(team.close()), bounded(personalQueue.close()), bounded(leadMaintenance?.stop()), bounded(backgroundChecks?.stop()), bounded((snapshots?.close(), reads?.close())), bounded(engineHandlers.close()), bounded(phoneAccessRef?.stop())])
1890
1976
  .then(() => { const closing = closeServer(error => callback?.(error ?? terminalClosing.problem ?? undefined)); server.closeAllConnections?.(); return closing; }).catch(error => {
1891
1977
  if (callback)
1892
1978
  callback(error instanceof Error ? error : Error('Coding session shutdown failed.'));
@@ -0,0 +1,29 @@
1
+ export async function endAfterExitProof(args) {
2
+ args.hardStop();
3
+ let said = -1;
4
+ for (;;) {
5
+ const left = args.liveBuilds();
6
+ if (left === 0)
7
+ break;
8
+ if (left !== said)
9
+ args.say(`still stopping: waiting for ${left === 1 ? "1 build" : `${left} builds`} to confirm ${left === 1 ? "it" : "they"} stopped; this worker won't end while ${left === 1 ? "it runs" : "they run"}`);
10
+ said = left;
11
+ await new Promise(resolveLater => setTimeout(resolveLater, args.pollMs ?? 100));
12
+ }
13
+ if (args.exit === undefined)
14
+ return "no-exit";
15
+ args.before?.();
16
+ args.exit(args.code);
17
+ return "exited";
18
+ }
19
+ export function watchdogVerdict(facts) {
20
+ const silent = facts.silentMs >= facts.silenceMs;
21
+ const overran = facts.stoppingForMs !== null && facts.stoppingForMs > facts.graceMs + facts.deadlineMs + facts.silenceMs / 2;
22
+ if (!silent && !overran)
23
+ return "fine";
24
+ if (facts.paused)
25
+ return "leave";
26
+ if (!silent && facts.liveBuilds > 0)
27
+ return "wait";
28
+ return "restart";
29
+ }
package/dist/slack.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 { loadSlackCredentials, slackApi } from "./slack-api.js";
4
4
  import { ChatState } from "./chat-delivery-state.js";
5
5
  import { runChatAcks } from "./chat-live.js";
@@ -55,8 +55,14 @@ export async function followSlack(options) {
55
55
  };
56
56
  options.signal.addEventListener("abort", stop, { once: true });
57
57
  const heartbeat = setInterval(() => {
58
- if (!same() || !state.lease(credentials.installation, owner, new Date()))
59
- stop();
58
+ try {
59
+ if (!same() || !state.lease(credentials.installation, owner, new Date()))
60
+ stop();
61
+ }
62
+ catch (error) {
63
+ if (!busyError(error))
64
+ stop();
65
+ }
60
66
  }, 10_000);
61
67
  client.on("connected", () => {
62
68
  connected = true;
@@ -1,6 +1,7 @@
1
+ import { StatementCache } from './statement-cache.js';
1
2
  let writes = 0;
2
3
  export const writesSoFar = () => writes;
3
- const ownTemp = (op) => /^(?:CREATE\s+TEMP\s+TABLE\s+"so_work_ranked_\d+"|DROP\s+TABLE\s+IF\s+EXISTS\s+temp\."so_work_ranked_\d+"$)/i.test(op);
4
+ const ownTemp = (op) => /^(?:CREATE\s+TEMP\s+TABLE\s+"so_work_ranked_\d+"|(?:DROP\s+TABLE\s+IF\s+EXISTS|DELETE\s+FROM)\s+temp\."so_work_ranked_\d+"$|INSERT\s+INTO\s+temp\."so_work_ranked_\d+"\s)/i.test(op);
4
5
  const opening = (op) => /^(?:BEGIN(?:\s+(?:DEFERRED|IMMEDIATE|EXCLUSIVE))?(?:\s+TRANSACTION)?|SAVEPOINT\s+\w+)\s*;?$/i.test(op);
5
6
  const settingOnly = (op) => /^PRAGMA\s+busy_timeout\s*=\s*\d+\s*;?$/i.test(op);
6
7
  const ending = (op) => /^(?:COMMIT|END|ROLLBACK|RELEASE)\b[^;]*;?\s*$/i.test(op);
@@ -19,7 +20,7 @@ export function measureWriteWait(db, body) {
19
20
  state.telemetry.writeWait.observe((state.telemetry.clock() - started) / 1000);
20
21
  }
21
22
  }
22
- export function instrumentDatabase(db, telemetry) {
23
+ export function instrumentDatabase(db, telemetry, options = {}) {
23
24
  const state = { telemetry, measuringWait: false };
24
25
  let heldAt = null;
25
26
  const elapsed = (at) => (telemetry.clock() - at) / 1000;
@@ -99,27 +100,38 @@ export function instrumentDatabase(db, telemetry) {
99
100
  const methods = {
100
101
  exec(sql) {
101
102
  const op = operation(sql);
102
- tracked(op, 'exec', true, () => execNow(sql, op));
103
+ try {
104
+ tracked(op, 'exec', true, () => execNow(sql, op));
105
+ }
106
+ finally {
107
+ cache?.executed(sql);
108
+ }
103
109
  },
104
110
  prepare(sql) {
105
- const op = operation(sql), statement = db.prepare(sql), write = writing(op);
106
- const methods = {
107
- run: (...params) => tracked(op, 'run', write, () => standalone(write, () => statement.run(...params))),
108
- get: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.get(...params))),
109
- all: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.all(...params))),
110
- };
111
- const rows = statement;
112
- if (typeof rows.iterate === 'function')
113
- Object.assign(methods, { iterate: (...params) => tracked(op, 'read', write, () => rows.iterate(...params)) });
114
- return preservingNative(statement, methods);
111
+ return cache === null ? compile(sql) : cache.prepare(sql);
115
112
  },
116
- close() { try {
113
+ close() { cache?.clear(); try {
117
114
  db.close();
118
115
  }
119
116
  finally {
120
117
  finish();
121
118
  } },
122
119
  };
120
+ function compile(sql) {
121
+ const op = operation(sql), statement = db.prepare(sql), write = writing(op);
122
+ const methods = {
123
+ run: (...params) => tracked(op, 'run', write, () => standalone(write, () => statement.run(...params))),
124
+ get: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.get(...params))),
125
+ all: (...params) => tracked(op, 'read', write, () => standalone(write, () => statement.all(...params))),
126
+ };
127
+ const rows = statement;
128
+ if (typeof rows.iterate === 'function')
129
+ Object.assign(methods, { iterate: (...params) => tracked(op, 'read', write, () => rows.iterate(...params)) });
130
+ return preservingNative(statement, methods);
131
+ }
132
+ const cache = options.cacheStatements === true ? new StatementCache(compile) : null;
133
+ if (cache !== null)
134
+ Object.assign(methods, { prepareUncached: (sql) => cache.prepareUncached(sql), statementCacheStats: () => ({ ...cache.stats }) });
123
135
  const wrapped = preservingNative(db, methods);
124
136
  states.set(wrapped, state);
125
137
  return wrapped;
@@ -0,0 +1,137 @@
1
+ export const STATEMENT_CACHE_ENTRIES = 512;
2
+ export const STATEMENT_CACHE_BYTES = 2 * 1024 * 1024;
3
+ export const STATEMENT_CACHE_ENTRY_BYTES = 256 * 1024;
4
+ const SETTINGS = new Set(['setReadBigInts', 'setReturnArrays', 'setAllowBareNamedParameters', 'setAllowUnknownNamedParameters']);
5
+ const lead = (sql) => sql.replace(/^(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)+/, '');
6
+ export const transientSql = (sql) => /\btemp\s*\.|\bCREATE\s+TEMP(?:ORARY)?\b|\bso_work_ranked_\d+\b/i.test(sql);
7
+ export const schemaChanging = (sql) => sql.split(';').some(part => /^(?:CREATE|DROP|ALTER|VACUUM|REINDEX|ANALYZE)\b/i.test(lead(part)) && !transientSql(part));
8
+ export class StatementCache {
9
+ compile;
10
+ limits;
11
+ #entries = new Map();
12
+ #bytes = 0;
13
+ stats = { hits: 0, misses: 0, bypassed: 0, entries: 0, bytes: 0, cleared: 0 };
14
+ constructor(compile, limits = { entries: STATEMENT_CACHE_ENTRIES, bytes: STATEMENT_CACHE_BYTES, entryBytes: STATEMENT_CACHE_ENTRY_BYTES }) {
15
+ this.compile = compile;
16
+ this.limits = limits;
17
+ }
18
+ prepare(sql) {
19
+ if (schemaChanging(sql)) {
20
+ this.stats.bypassed++;
21
+ return this.#clearingOnRun(this.compile(sql));
22
+ }
23
+ const bytes = Buffer.byteLength(sql);
24
+ if (bytes > this.limits.entryBytes || transientSql(sql)) {
25
+ this.stats.bypassed++;
26
+ return this.compile(sql);
27
+ }
28
+ const found = this.#entries.get(sql);
29
+ if (found !== undefined) {
30
+ if (found.running > 0) {
31
+ this.stats.bypassed++;
32
+ return this.compile(sql);
33
+ }
34
+ this.stats.hits++;
35
+ this.#entries.delete(sql);
36
+ this.#entries.set(sql, found);
37
+ return this.#handle(sql, found);
38
+ }
39
+ this.stats.misses++;
40
+ const statement = this.compile(sql);
41
+ const entry = { statement, bytes, running: 0 };
42
+ this.#entries.set(sql, entry);
43
+ this.#bytes += bytes;
44
+ this.#evict();
45
+ this.#count();
46
+ return this.#handle(sql, entry);
47
+ }
48
+ prepareUncached(sql) {
49
+ this.stats.bypassed++;
50
+ return schemaChanging(sql) ? this.#clearingOnRun(this.compile(sql)) : this.compile(sql);
51
+ }
52
+ executed(sql) { if (schemaChanging(sql))
53
+ this.clear(); }
54
+ clear() {
55
+ if (this.#entries.size > 0)
56
+ this.stats.cleared++;
57
+ this.#entries.clear();
58
+ this.#bytes = 0;
59
+ this.#count();
60
+ }
61
+ get size() { return this.#entries.size; }
62
+ get bytes() { return this.#bytes; }
63
+ #count() { this.stats.entries = this.#entries.size; this.stats.bytes = this.#bytes; }
64
+ #evict() {
65
+ for (const [sql, entry] of this.#entries) {
66
+ if (this.#entries.size <= this.limits.entries && this.#bytes <= this.limits.bytes)
67
+ break;
68
+ this.#entries.delete(sql);
69
+ this.#bytes -= entry.bytes;
70
+ }
71
+ }
72
+ #handle(sql, entry) {
73
+ let own = null;
74
+ const guarded = (call) => {
75
+ if (own !== null)
76
+ return call(own);
77
+ if (entry.running > 0)
78
+ return call(this.compile(sql));
79
+ entry.running++;
80
+ try {
81
+ return call(entry.statement);
82
+ }
83
+ finally {
84
+ entry.running--;
85
+ }
86
+ };
87
+ const methods = {
88
+ run: (...params) => guarded(target => target.run(...params)),
89
+ get: (...params) => guarded(target => target.get(...params)),
90
+ all: (...params) => guarded(target => target.all(...params)),
91
+ iterate: (...params) => (own ?? this.compile(sql)).iterate(...params),
92
+ };
93
+ return new Proxy(methods, {
94
+ get: (target, property) => {
95
+ if (Object.hasOwn(target, property))
96
+ return Reflect.get(target, property);
97
+ if (typeof property === 'string' && SETTINGS.has(property)) {
98
+ return (...args) => {
99
+ own ??= this.compile(sql);
100
+ return own[property].apply(own, args);
101
+ };
102
+ }
103
+ const statement = own ?? entry.statement;
104
+ const value = Reflect.get(statement, property, statement);
105
+ return typeof value === 'function' ? value.bind(statement) : value;
106
+ },
107
+ has: (target, property) => Reflect.has(target, property) || Reflect.has(own ?? entry.statement, property),
108
+ getPrototypeOf: () => Object.getPrototypeOf(entry.statement),
109
+ });
110
+ }
111
+ #clearingOnRun(statement) {
112
+ const after = (body) => { try {
113
+ return body();
114
+ }
115
+ finally {
116
+ this.clear();
117
+ } };
118
+ return new Proxy(statement, {
119
+ get: (target, property) => {
120
+ if (property === 'run' || property === 'get' || property === 'all' || property === 'iterate') {
121
+ const method = Reflect.get(target, property, target);
122
+ return (...params) => after(() => method.apply(target, params));
123
+ }
124
+ const value = Reflect.get(target, property, target);
125
+ return typeof value === 'function' ? value.bind(target) : value;
126
+ },
127
+ });
128
+ }
129
+ }
130
+ export function prepareUncached(db, sql) {
131
+ const own = db.prepareUncached;
132
+ return typeof own === 'function' ? own.call(db, sql) : db.prepare(sql);
133
+ }
134
+ export function statementCacheStats(db) {
135
+ const stats = db.statementCacheStats;
136
+ return typeof stats === 'function' ? stats.call(db) : null;
137
+ }
package/dist/store.js CHANGED
@@ -35,6 +35,7 @@ import { V173_ADDED_COLUMNS, V173_STEPS } from "./plan-problems-schema.js";
35
35
  import { V175_OBJECTS, V175_SCHEMA, V175_STEPS } from "./flexible-interactive-schema.js";
36
36
  import { V176_ADDED_COLUMNS, V176_STEPS, V176_SCHEMA, V176_OBJECTS } from "./subagent-backup-schema.js";
37
37
  import { V178_STEPS, V178_SCHEMA, V178_INDEX } from "./check-recovery-index-schema.js";
38
+ import { V190_DROPPED_INDEXES, V190_INDEXES, V190_SCHEMA, V190_STEPS } from "./query-index-schema.js";
38
39
  import { V180_SCHEMA, V180_STEPS } from "./agent-change-schema.js";
39
40
  import { V181_REQUIRED_COLUMNS, V181_SCHEMA, V181_STEPS, V181_TABLES, V182_REQUIRED_COLUMNS, V182_SCHEMA, V182_STEPS, V182_TABLES, V183_ADDED_COLUMNS, V183_STEPS, V184_ADDED_COLUMNS, V184_STEPS } from "./direct-chat-schema.js";
40
41
  import { V177_STEPS, V177_SCHEMA, V177_OBJECTS, WORKSPACE_ID_PATTERN, RECOVERY_GENERATION_PATTERN } from "./workspace-identity-schema.js";
@@ -54,6 +55,7 @@ import { isLifecycleNotification, isTelegramProgressNotification, LIFECYCLE_KEY_
54
55
  import { chatTablesShared, convertChatTables, legacyAppTables, legacyChatProblem, legacyChatTablesPresent } from "./chat-migration.js";
55
56
  import { ServerTelemetry } from "./server-telemetry.js";
56
57
  import { instrumentDatabase, measureWriteWait } from "./sqlite-telemetry.js";
58
+ import { tuneConnection } from "./db-tuning.js";
57
59
  import { trackWorkspaceWrites } from "./workspace-revision.js";
58
60
  import { parseStoreColumn, readStoreColumn, readStoreStringifiedList, readStoreTextList } from "./contracts/store-json.js";
59
61
  import { assessmentFromSavedEvidence, verificationEvidence } from "./verification-evidence.js";
@@ -848,7 +850,7 @@ export function checkSuitesOf(value) {
848
850
  }
849
851
  }
850
852
  const REGISTERED_AT_FILING = "again, as it was filed";
851
- export const SCHEMA_VERSION = 189;
853
+ export const SCHEMA_VERSION = 190;
852
854
  export const V179_STEPS = Object.freeze(["antigravity-provider"]);
853
855
  export const V118_MERGED_TABLES = Object.freeze({ api_token: "person", coordinator_credential: "coordinator", lead_credential: "lead" });
854
856
  const V118_REFERENCES = /REFERENCES (?:coordinator_credential\(cid\)|api_token\(id\))/g;
@@ -914,7 +916,7 @@ export const V115_DROPPED_TABLES = Object.freeze([
914
916
  "fallback_config", "fallback_cycle", "fallback_transition",
915
917
  ]);
916
918
  const V115_DROPPED_REFERENCES = /\s+REFERENCES (?:contestant|contest|tournament_terms|session_turn|attended_authorization|held_session|fallback_cycle|fallback_config|fallback_transition|routine|routine_fire)\(id\)(?: ON DELETE CASCADE)?/g;
917
- export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189]);
919
+ export const UPDATE_SAFE_MIGRATIONS = Object.freeze([108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190]);
918
920
  export const V119_ADDED_COLUMNS = Object.freeze({
919
921
  task_ref: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
920
922
  run: { planning_generation: { definition: "INTEGER NOT NULL DEFAULT 0", saved: "0" } },
@@ -1457,7 +1459,7 @@ export { V156_STEPS };
1457
1459
  export { V157_STEPS };
1458
1460
  export { V158_STEPS };
1459
1461
  export { V159_STEPS };
1460
- export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS, V185_STEPS, V186_STEPS, V187_STEPS, V188_STEPS, V189_STEPS };
1462
+ export { V160_STEPS, V161_STEPS, V162_STEPS, V163_STEPS, V164_STEPS, V165_STEPS, V166_STEPS, V167_STEPS, V168_STEPS, V169_STEPS, V170_STEPS, V171_STEPS, V172_STEPS, V173_STEPS, V174_STEPS, V175_STEPS, V176_STEPS, V177_STEPS, V178_STEPS, V180_STEPS, V181_STEPS, V182_STEPS, V183_STEPS, V184_STEPS, V185_STEPS, V186_STEPS, V187_STEPS, V188_STEPS, V189_STEPS, V190_STEPS };
1461
1463
  export const RELEASE_ONCE_SCHEMA = `
1462
1464
  CREATE TABLE IF NOT EXISTS release_authority (
1463
1465
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -4030,7 +4032,7 @@ CREATE TABLE IF NOT EXISTS run_process_summary (
4030
4032
 
4031
4033
  CREATE INDEX IF NOT EXISTS task_by_state ON task (state);
4032
4034
  CREATE INDEX IF NOT EXISTS edge_by_blocker ON task_edge (blocker);
4033
- CREATE INDEX IF NOT EXISTS claim_by_task ON claim (task_ref, lease_generation DESC);
4035
+ -- claim_by_task (task_ref, lease_generation DESC) duplicated UNIQUE (task_ref, lease_generation); v190 dropped it.
4034
4036
  CREATE INDEX IF NOT EXISTS hold_by_task ON hold (task_ref);
4035
4037
  CREATE INDEX IF NOT EXISTS run_stop_by_task ON run_stop (task_ref, requested_at DESC);
4036
4038
  `;
@@ -4041,18 +4043,20 @@ export function databasePath(env, home) {
4041
4043
  return namedPath(configBase(env, home), ["orders.db"]);
4042
4044
  }
4043
4045
  export const CONCURRENT_WRITER_WAIT_MS = 15_000;
4044
- function waitForConcurrentWriter(db) {
4045
- db.exec(`PRAGMA busy_timeout = ${CONCURRENT_WRITER_WAIT_MS}`);
4046
+ export const BRIEF_WRITER_WAIT_MS = 500;
4047
+ const briefBudgets = new WeakMap();
4048
+ function waitForConcurrentWriter(db, waitMs = CONCURRENT_WRITER_WAIT_MS) {
4049
+ db.exec(`PRAGMA busy_timeout = ${waitMs}`);
4046
4050
  }
4047
4051
  const WRITE_WAIT_SLICE_MS = 100;
4048
4052
  export function isDatabaseBusy(error) {
4049
4053
  const code = error?.errcode;
4050
4054
  return typeof code === "number" && (code & 0xff) === 5;
4051
4055
  }
4052
- function beginWriteWithin(db, budgetMs) {
4053
- measureWriteWait(db, () => beginWriteAttempt(db, budgetMs));
4056
+ function beginWriteWithin(db, budgetMs, restoreMs = CONCURRENT_WRITER_WAIT_MS) {
4057
+ measureWriteWait(db, () => beginWriteAttempt(db, budgetMs, restoreMs));
4054
4058
  }
4055
- function beginWriteAttempt(db, budgetMs) {
4059
+ function beginWriteAttempt(db, budgetMs, restoreMs = CONCURRENT_WRITER_WAIT_MS) {
4056
4060
  const deadline = performance.now() + budgetMs;
4057
4061
  db.exec(`PRAGMA busy_timeout = ${WRITE_WAIT_SLICE_MS}`);
4058
4062
  try {
@@ -4068,7 +4072,7 @@ function beginWriteAttempt(db, budgetMs) {
4068
4072
  }
4069
4073
  }
4070
4074
  finally {
4071
- waitForConcurrentWriter(db);
4075
+ waitForConcurrentWriter(db, restoreMs);
4072
4076
  }
4073
4077
  }
4074
4078
  export function openStore(file, options = {}) {
@@ -4246,7 +4250,7 @@ function initializeStore(db, file, options = {}) {
4246
4250
  throw new Error(`${file}: ${problem}; refusing to move chat history it cannot name`);
4247
4251
  }
4248
4252
  if (preflight === SCHEMA_VERSION && !findingSourcesStale(db)) {
4249
- const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db) ?? flexibleConversationShapeProblem(db) ?? skillLibraryShapeProblem(db) ?? companionShapeProblem(db) ?? companionPasskeyShapeProblem(db) ?? companionChatShapeProblem(db);
4253
+ const missing = codeMapShapeProblem(db) ?? viewPreferenceShapeProblem(db) ?? flexibleTermsShapeProblem(db) ?? flexibleThreadShapeProblem(db) ?? typedByPersonShapeProblem(db) ?? flexibleTurnsShapeProblem(db) ?? flexibleLaunchShapeProblem(db) ?? flexibleRelayShapeProblem(db) ?? flexibleAnswersShapeProblem(db) ?? flexibleShipShapeProblem(db) ?? taskSizingShapeProblem(db) ?? agentSaidShapeProblem(db) ?? flexibleSettingShapeProblem(db) ?? flexibleSignInShapeProblem(db) ?? planProblemsShapeProblem(db) ?? flexibleEverydayShapeProblem(db) ?? flexibleInteractiveShapeProblem(db) ?? subagentBackupShapeProblem(db) ?? workspaceIdentityShapeProblem(db) ?? pendingAgentChangeShapeProblem(db) ?? directChatShapeProblem(db) ?? directChatPhase1bShapeProblem(db) ?? directChatHardeningShapeProblem(db) ?? flexibleConversationShapeProblem(db) ?? skillLibraryShapeProblem(db) ?? companionShapeProblem(db) ?? companionPasskeyShapeProblem(db) ?? companionChatShapeProblem(db) ?? queryIndexShapeProblem(db);
4250
4254
  if (missing !== null)
4251
4255
  throw new Error(`${file}: refusing to open — ${missing}, though the schema says v${SCHEMA_VERSION}`);
4252
4256
  db.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -4786,6 +4790,19 @@ CREATE INDEX IF NOT EXISTS run_checkpoint_by_task ON run_checkpoint (task_ref, i
4786
4790
  throw new Error(`${file}: refusing to open — ${error.message}`);
4787
4791
  throw error;
4788
4792
  }
4793
+ db.exec("BEGIN IMMEDIATE");
4794
+ try {
4795
+ db.exec(V190_SCHEMA);
4796
+ const indexesDamaged = queryIndexShapeProblem(db);
4797
+ if (indexesDamaged !== null)
4798
+ throw new Error(`${file}: refusing to open — ${indexesDamaged}`);
4799
+ step("query-indexes");
4800
+ db.exec("COMMIT");
4801
+ }
4802
+ catch (error) {
4803
+ db.exec("ROLLBACK");
4804
+ throw error;
4805
+ }
4789
4806
  if (!fresh)
4790
4807
  reclaimDatabase(db, "migration");
4791
4808
  const expectedMarker = preflight < 0 ? preflight : -preflight;
@@ -5680,7 +5697,8 @@ export class Store {
5680
5697
  db;
5681
5698
  constructor(db) {
5682
5699
  this.telemetry = new ServerTelemetry();
5683
- this.db = instrumentDatabase(trackWorkspaceWrites(db), this.telemetry);
5700
+ tuneConnection(db);
5701
+ this.db = instrumentDatabase(trackWorkspaceWrites(db), this.telemetry, { cacheStatements: true });
5684
5702
  lockStoreMoneyMethods(this);
5685
5703
  rememberStoredHostAliases(this.db);
5686
5704
  }
@@ -6157,7 +6175,8 @@ export class Store {
6157
6175
  transact(body) {
6158
6176
  if (this.transacting)
6159
6177
  return body();
6160
- beginWriteWithin(this.db, CONCURRENT_WRITER_WAIT_MS);
6178
+ const budget = briefBudgets.get(this.db) ?? CONCURRENT_WRITER_WAIT_MS;
6179
+ beginWriteWithin(this.db, budget, budget);
6161
6180
  this.transacting = true;
6162
6181
  let result;
6163
6182
  try {
@@ -19756,3 +19775,41 @@ function skillLibraryShapeProblem(db) {
19756
19775
  }
19757
19776
  return null;
19758
19777
  }
19778
+ function queryIndexShapeProblem(db) {
19779
+ for (const [name, table, ddl] of V190_INDEXES) {
19780
+ const row = db.prepare("SELECT type, tbl_name, sql FROM sqlite_master WHERE name = ?").get(name);
19781
+ if (row === undefined)
19782
+ return `the query index ${name} is missing`;
19783
+ if (row["type"] !== "index" || row["tbl_name"] !== table || canonicalDdl(String(row["sql"]).replace(/;$/, "")).trim() !== canonicalDdl(ddl).trim())
19784
+ return `the query index ${name} has an unknown shape`;
19785
+ }
19786
+ for (const name of V190_DROPPED_INDEXES) {
19787
+ if (db.prepare("SELECT 1 FROM sqlite_master WHERE name = ?").get(name) !== undefined)
19788
+ return `the duplicate index ${name} is still here`;
19789
+ }
19790
+ return null;
19791
+ }
19792
+ export function briefly(store, body, budgetMs = BRIEF_WRITER_WAIT_MS) {
19793
+ const db = store.raw();
19794
+ if (briefBudgets.has(db) || db.isTransaction === true)
19795
+ return body();
19796
+ briefBudgets.set(db, budgetMs);
19797
+ db.exec(`PRAGMA busy_timeout = ${budgetMs}`);
19798
+ try {
19799
+ return body();
19800
+ }
19801
+ finally {
19802
+ briefBudgets.delete(db);
19803
+ waitForConcurrentWriter(db);
19804
+ }
19805
+ }
19806
+ export function watchLeaseRow(store, runner, repo) {
19807
+ const row = store.handle.prepare("SELECT owner, generation, expires_at FROM watch_lease WHERE runner = ? AND repo = ?").get(runner, repo);
19808
+ return row === undefined ? null : { owner: String(row["owner"]), generation: Number(row["generation"]), expiresAt: String(row["expires_at"]) };
19809
+ }
19810
+ export function reviveWatchLease(store, runner, repo, owner, generation, ttlMs, now) {
19811
+ const { changes } = store.handle
19812
+ .prepare("UPDATE watch_lease SET expires_at = ?, heartbeat_at = ? WHERE runner = ? AND repo = ? AND owner = ? AND generation = ?")
19813
+ .run(new Date(now.getTime() + Math.min(ttlMs, MAX_WATCH_LEASE_MS)).toISOString(), now.toISOString(), runner, repo, owner, generation);
19814
+ return Number(changes) > 0;
19815
+ }
@@ -282,7 +282,7 @@ export function statusOf(facts) {
282
282
  }
283
283
  export const taskStatusOf = statusOf;
284
284
  const ALWAYS_NEEDS = new Set(["planner-source", "signed-out", "needs-approval", "waiting-decision", "decision-queue"]);
285
- const QUEUED_REASONS = new Set(["worker-at-capacity", "waiting-dependency", "retry-scheduled", "plan-retry", "updating", "planning-ready", "scouting-ready", "provider-quota"]);
285
+ const QUEUED_REASONS = new Set(["worker-at-capacity", "watch-stalled", "waiting-dependency", "retry-scheduled", "plan-retry", "updating", "planning-ready", "scouting-ready", "provider-quota"]);
286
286
  export function plainReasonOf(stage, code, detail) {
287
287
  if (stage === "building" || stage === "checking" || stage === "reviewing" || stage === "planning")
288
288
  return null;
package/dist/teams.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { adapterPolicy } from "./server/route-policy.js";
2
2
  import { randomBytes } from "node:crypto";
3
- import { abortablePause, workChatQueue } from "./chat-follow.js";
3
+ import { abortablePause, busyError, workChatQueue } from "./chat-follow.js";
4
4
  import { ChatState } from "./chat-delivery-state.js";
5
5
  import { chatObject as object } from "./chat-delivery.js";
6
6
  import { loadTeamsCredentials, teamsAccessToken, teamsApi, verifyTeamsToken, TeamsError } from "./teams-api.js";
@@ -84,8 +84,14 @@ export async function followTeams(options) {
84
84
  const problem = (message) => state.setProblem(credentials.installation, owner, message);
85
85
  const stop = () => { alive = false; };
86
86
  options.signal.addEventListener("abort", stop, { once: true });
87
- const heartbeat = setInterval(() => { if (!same() || !state.lease(credentials.installation, owner, new Date()))
88
- stop(); }, 10_000);
87
+ const heartbeat = setInterval(() => { try {
88
+ if (!same() || !state.lease(credentials.installation, owner, new Date()))
89
+ stop();
90
+ }
91
+ catch (error) {
92
+ if (!busyError(error))
93
+ stop();
94
+ } }, 10_000);
89
95
  const chat = { ...options, identity: credentials, owner, api: teamsApi(credentials, options.fetcher), canNotify: options.notifications, current: same, liveReplies: true };
90
96
  try {
91
97
  try {