Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

fix(health): read item event history by index [C7]

Corey Olson45911ff8d2bc
diff --git a/src/health.js b/src/health.js
index 9b6d76f8..2a2df568 100644
--- a/src/health.js
+++ b/src/health.js
@@ -101,7 +101,7 @@ export function healthReport({ db, root, config, now }) {
}
const items = db.prepare('SELECT * FROM item ORDER BY item_id').all();
const byId = new Map(items.map((item) => [item.item_id, item]));
- const history = itemHistory(db);
+ const history = itemHistory(db, items.map((item) => item.item_id));
const trunk = trunkTip(root);
const releases = roadmap(board);
const found = (list, finding) => list.push(finding);
@@ -481,10 +481,12 @@ function releaseOverdue(db, root, now, deadlineMs, history) {
* finalizes an unreferenced statement when garbage collection runs mid-iterate, which crashed
* resume with "statement has been finalized" on a large board. Exported for that regression test.
*/
-export function itemHistory(db) {
+export function itemHistory(db, itemIds) {
const history = new Map();
- const statement = db.prepare('SELECT event_id, event_at, event_by, event_kind, item_id, event_detail FROM event WHERE item_id IS NOT NULL ORDER BY event_id');
- try { readItemHistory(statement.iterate(), history); }
+ const statement = db.prepare('SELECT event_id, event_at, event_by, event_kind, item_id, event_detail FROM event WHERE item_id = ? ORDER BY event_id');
+ try {
+ for (const itemId of itemIds) readItemHistory(statement.iterate(itemId), history);
+ }
finally { keepAlive(statement); }
return history;
}
diff --git a/test/health.test.js b/test/health.test.js
index 2a7ea940..17ca9e53 100644
--- a/test/health.test.js
+++ b/test/health.test.js
@@ -332,17 +332,20 @@ test('item history survives garbage collection mid-read [A6]', () => {
import { DatabaseSync } from 'node:sqlite';
import { itemHistory } from ${JSON.stringify(health)};
const real = new DatabaseSync(':memory:');
- real.exec('CREATE TABLE event (event_id INTEGER PRIMARY KEY, event_at TEXT, event_by TEXT, event_kind TEXT, item_id INTEGER, event_detail TEXT)');
+ real.exec('CREATE TABLE event (event_id INTEGER PRIMARY KEY, event_at TEXT, event_by TEXT, event_kind TEXT, item_id INTEGER, event_detail TEXT); CREATE INDEX event_item_id_event_id ON event (item_id, event_id)');
const insert = real.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)');
for (let i = 0; i < 20000; i += 1) insert.run('2026-10-18T00:00:00.000Z', 'agent', i % 3 ? 'claim' : 'submit', i % 50, '{}');
// Defined outside any scope that holds the statement, so only the code under test can keep it alive.
- const collecting = (rows) => { let read = 0; return { [Symbol.iterator]() { return this; }, next() { read += 1; if (read % 500 === 0) globalThis.gc(); return rows.next(); } }; };
- const db = { prepare: (sql) => { const statement = real.prepare(sql); return { iterate: () => collecting(statement.iterate()) }; } };
- process.stdout.write(String(itemHistory(db).size));
+ let reads = 0;
+ let collections = 0;
+ const collecting = (rows) => ({ [Symbol.iterator]() { return this; }, next() { reads += 1; if (reads % 500 === 0) { globalThis.gc(); collections += 1; } return rows.next(); } });
+ const db = { prepare: (sql) => { const statement = real.prepare(sql); return { iterate: (...values) => collecting(statement.iterate(...values)) }; } };
+ const history = itemHistory(db, Array.from({ length: 50 }, (_, id) => id));
+ process.stdout.write(String(history.size) + ':' + String(collections));
`;
const child = runFixtureChild(process.execPath, ['--expose-gc', '--no-warnings', '--input-type=module', '-e', script], { encoding: 'utf8' });
assert.equal(child.status, 0, `reading item history must not lose its statement to garbage collection: ${child.stderr}`);
- assert.equal(child.stdout, '50', 'every item with events has a history entry');
+ assert.match(child.stdout, /^50:[1-9]\d*$/u, 'every item is read and garbage collection runs across item cursors');
});
test('health names a route with open work and no agent [N2,B13]', async (t) => {
diff --git a/test/query-plans.test.js b/test/query-plans.test.js
index 37898ed9..dd12a78b 100644
--- a/test/query-plans.test.js
+++ b/test/query-plans.test.js
@@ -11,7 +11,9 @@ import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { DatabaseSync } from 'node:sqlite';
import { after, test } from 'node:test';
+import { submitFixture } from './board-submit-fixture.js';
import * as store from '../src/board.js';
+import { healthReport } from '../src/health.js';
import { runFixtureChild, runFixtureGit } from './fixture-child.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
@@ -22,11 +24,11 @@ const SHOUTS = 23_000;
const SEATS = 800;
const sandboxes = [];
// Reads that fold the whole history by design, so no index can serve them, each with the item that
-// rewrites it: health's itemHistory (#1053), coordinator resume's undrafted Rigor in personNeedsState
-// (#1052), resume's proofStats (#1051) and the view state's projectState (#1055, which uses
+// rewrites it: coordinator resume's undrafted Rigor in personNeedsState (#1052), resume's proofStats
+// (#1051) and the view state's projectState (#1055, which uses
// lastMoves and recentEvents). The test fails if one stops scanning while still listed, so the list
// can only shrink.
-const WHOLE_HISTORY = ['itemHistory', 'personNeedsState', 'projectState', 'proofStats'];
+const WHOLE_HISTORY = ['personNeedsState', 'projectState', 'proofStats'];
after(() => {
for (const dir of sandboxes) rmSync(dir, { recursive: true, force: true });
@@ -203,3 +205,57 @@ test('hot board queries never scan events or shouts [C7]', () => {
store.closeBoard(board);
}
});
+
+test('health reads item history by index [C7]', () => {
+ const box = fixture();
+ seed(box.board);
+ const board = store.openBoard(box.board, { now: () => new Date('2026-10-22T22:30:00.000Z') });
+ const rejectAt = '2026-10-22T21:00:00.000Z';
+ const reopenAt = '2026-10-22T22:00:00.000Z';
+ const submitAt = '2026-10-22T23:00:00.000Z';
+ try {
+ store.claim(board, 2, { agentId: 'web-100', lane: 'web', leaseMs: 60_000,
+ freeze: (item) => ({ text: item.item_title, digest: `digest:${item.item_title}` }) });
+ submitFixture(board, 2, { agentId: 'web-100', commit: 'a'.repeat(40), tree: 'b'.repeat(40) });
+ const event = board.db.prepare('INSERT INTO event (event_at, event_by, event_kind, item_id, event_detail) VALUES (?, ?, ?, ?, ?)');
+ event.run(rejectAt, 'web-100', 'reject', 1, JSON.stringify({ reason: 'TEST_FAILURE' }));
+ event.run(reopenAt, 'coordinator', 'reopen', 1, '{}');
+ event.run(submitAt, 'web-100', 'submit', 2, JSON.stringify({ commit: 'a'.repeat(40) }));
+ } finally {
+ store.closeBoard(board);
+ }
+
+ const originalPrepare = DatabaseSync.prototype.prepare;
+ let historyPlans = 0;
+ DatabaseSync.prototype.prepare = function (sql, ...args) {
+ if (/\bSELECT\s+event_id\s*,\s*event_at\s*,\s*event_by\s*,\s*event_kind\s*,\s*item_id\s*,\s*event_detail\s+FROM event\b/iu.test(sql)) {
+ const explanation = originalPrepare.call(this, `EXPLAIN QUERY PLAN ${sql}`);
+ const plan = (sql.includes('?') ? explanation.all(1) : explanation.all()).map((row) => row.detail);
+ historyPlans += 1;
+ assert.ok(plan.some((detail) => /\bSEARCH event USING INDEX event_item_id_event_id\b/u.test(detail)),
+ `health item history must search its index before reading: ${sql}\n${plan.join('\n')}`);
+ assert.ok(!plan.some((detail) => /^SCAN event\b/u.test(detail)),
+ `health item history must not scan the event table: ${sql}\n${plan.join('\n')}`);
+ }
+ return originalPrepare.call(this, sql, ...args);
+ };
+ try {
+ const db = store.openBoardReadOnly(box.board);
+ try {
+ const started = performance.now();
+ const report = healthReport({ db, root: box.repo, now: new Date('2026-10-23T00:00:00.000Z') });
+ const elapsed = performance.now() - started;
+ assert.ok(historyPlans > 0, 'health planned its item-history statement');
+ assert.ok(elapsed < 1_000, `health on 45,000 events took ${elapsed.toFixed(2)} ms, over 1 s`); // budget: approved row C7 requires health under 1s on the seeded board.
+ const rework = report.stuck.find((entry) => entry.key === 'REWORK_UNCLAIMED:item:1');
+ assert.equal(rework?.since, reopenAt, 'health keeps the latest lifecycle event for the open item');
+ assert.deepEqual(rework?.detail, { move: 'reopen', by: 'coordinator' });
+ const unreviewed = report.stuck.find((entry) => entry.key === 'NO_REVIEWER:item:2');
+ assert.equal(unreviewed?.since, submitAt, 'health keeps the latest submit event for the submitted item');
+ } finally {
+ db.close();
+ }
+ } finally {
+ DatabaseSync.prototype.prepare = originalPrepare;
+ }
+});