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.

refactor(view): serve.js exports a per-item projector [A2,N26]

Corey Olsonf28edeae9d0b
diff --git a/src/serve.js b/src/serve.js
index eab348b0..72811ab6 100644
--- a/src/serve.js
+++ b/src/serve.js
@@ -215,15 +215,67 @@ function viewReleaseNotes() {
return { ...keptViewReleaseNotes, releases: keptViewReleaseNotes.releases.map((release) => ({ ...release })) };
}
+/**
+ * One verdict as the page shows it.
+ *
+ * @param {any} row A verdict row from store.verdictsFor.
+ * @returns {{ decision: any, reason: any, note: any, by: any, at: any, commit: any }}
+ */
+function verdictOf(row) {
+ return { decision: row.verdict_decision, reason: row.verdict_reason, note: row.verdict_note, by: row.verdict_by, at: row.verdict_at, commit: row.verdict_commit };
+}
+
+/**
+ * One item as the page and the API show it (A2, N26): its fields, its verdicts, the items it waits on that are not yet
+ * verified, and its full history. The API projects one item's detail with it, without building the whole state, so
+ * the page and the API never word an item two ways. It only reads: it returns a fresh object and changes neither the
+ * row nor the map.
+ *
+ * @param {any} board
+ * @param {any} item The item's current row, as store.listItems reads it.
+ * @param {Map<number, string>} status Every current item's status by its id.
+ * @returns {any}
+ */
+export function projectItemState(board, item, status) {
+ const verdicts = store.verdictsFor(board, item.item_id).map(verdictOf);
+ const after = item.item_after ? item.item_after.split(',').map(Number) : [];
+ return {
+ id: item.item_id,
+ title: item.item_title,
+ lane: item.item_lane,
+ status: item.item_status,
+ route: item.item_route,
+ owner: item.item_owner,
+ // Who holds the review under a live lease (V15), by the board's own rule.
+ reviewer: store.reviewHolder(board, item),
+ reviewUntil: item.item_review_until ?? null,
+ builtBy: item.item_built_by,
+ verifiedBy: item.item_verified_by,
+ specs: item.item_spec_ids ? item.item_spec_ids.split(',') : [],
+ criterion: item.item_criterion,
+ brief: item.item_brief,
+ commit: item.item_commit,
+ merged: item.item_merged_commit,
+ blockedBy: after.filter((id) => status.get(id) !== 'verified'),
+ updatedAt: item.item_updated_at,
+ verdict: verdicts.at(-1) ?? null,
+ verdicts,
+ history: store.events(board, { itemId: item.item_id }).map((event) => ({ kind: event.event_kind, by: event.event_by, at: event.event_at })),
+ };
+}
+
/**
* Everything the page shows for one project. Given the newest shout the person has seen there,
- * it also counts every shout since, which the forty it sends cannot always show.
+ * it also counts every shout since, which the forty it sends cannot always show. An itemProjector
+ * lets a caller that keeps its own item projections reuse them: it is called once per item, in
+ * order, and returns that item's projection, calling project() for a fresh one only when it has none.
*
* @param {string} root
- * @param {{ seen?: number | null, board?: any }} [options] A supplied board stays owned by its caller.
+ * @param {{ seen?: number | null, board?: any, itemProjector?: ((item: any, context: { board: any, status: Map<number, string>, project: () => any }) => any) | null }} [options]
+ * A supplied board stays owned by its caller.
* @returns {any}
*/
-export function projectState(root, { seen = null, board: providedBoard = null } = {}) {
+export function projectState(root, { seen = null, board: providedBoard = null, itemProjector = null } = {}) {
return withProject(root, (board, info, config) => {
const all = store.listItems(board, { all: true });
const status = new Map(all.map((item) => [item.item_id, item.item_status]));
@@ -239,7 +291,6 @@ export function projectState(root, { seen = null, board: providedBoard = null }
// A decline's text is its reason. Keep the inherited rule available so the page strikes the
// rule itself, while showing the repo's reason beside it.
const inherited = new Map(standardDoctrine().rows.map((row) => [row.id, row.text]));
- const verdict = (row) => ({ decision: row.verdict_decision, reason: row.verdict_reason, note: row.verdict_note, by: row.verdict_by, at: row.verdict_at, commit: row.verdict_commit });
const log = store.events(board);
// When each agent last moved on the board: the log is in order, so the last write wins.
const lastMove = new Map(log.map((event) => [event.event_by, event.event_at]));
@@ -250,33 +301,10 @@ export function projectState(root, { seen = null, board: providedBoard = null }
lanes: [COORDINATOR, ...Object.keys(config.lanes)],
// The lanes that own folders, where builders work; review lanes own none.
owning: Object.keys(config.lanes).filter((lane) => (config.lanes[lane].owns ?? []).length > 0),
- items: all.map((item) => {
- const verdicts = store.verdictsFor(board, item.item_id).map(verdict);
- const after = item.item_after ? item.item_after.split(',').map(Number) : [];
- return {
- id: item.item_id,
- title: item.item_title,
- lane: item.item_lane,
- status: item.item_status,
- route: item.item_route,
- owner: item.item_owner,
- // Who holds the review under a live lease (V15), by the board's own rule.
- reviewer: store.reviewHolder(board, item),
- reviewUntil: item.item_review_until ?? null,
- builtBy: item.item_built_by,
- verifiedBy: item.item_verified_by,
- specs: item.item_spec_ids ? item.item_spec_ids.split(',') : [],
- criterion: item.item_criterion,
- brief: item.item_brief,
- commit: item.item_commit,
- merged: item.item_merged_commit,
- blockedBy: after.filter((id) => status.get(id) !== 'verified'),
- updatedAt: item.item_updated_at,
- verdict: verdicts.at(-1) ?? null,
- verdicts,
- history: store.events(board, { itemId: item.item_id }).map((event) => ({ kind: event.event_kind, by: event.event_by, at: event.event_at })),
- };
- }),
+ // A caller with its own copy of an item returns it; project() builds the item only when asked.
+ items: all.map((item) => (itemProjector
+ ? itemProjector(item, { board, status, project: () => projectItemState(board, item, status) })
+ : projectItemState(board, item, status))),
shouts: store.recentShouts(board, 40),
// Every ask still waiting for an answer, however far back the forty shouts reach (B21): the
// person's to answer here, and the rest with who holds them (B26).
diff --git a/test/cockpit/projector.test.js b/test/cockpit/projector.test.js
new file mode 100644
index 00000000..fb7cae32
--- /dev/null
+++ b/test/cockpit/projector.test.js
@@ -0,0 +1,125 @@
+/** The per-item projector the API reuses, checked against the full projection on a real board [A2,N26]. */
+import assert from 'node:assert/strict';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import * as store from '../../src/board.js';
+import * as serve from '../../src/serve.js';
+import { machine, project, build, sendBack, accept } from './fixture.js';
+
+/**
+ * One item exactly as projectState wrote it inline before the per-item projector existed: the frozen reference that
+ * says what "today's output" is, field for field and in the same order.
+ */
+function todayItem(board, item, status) {
+ const verdict = (row) => ({ decision: row.verdict_decision, reason: row.verdict_reason, note: row.verdict_note, by: row.verdict_by, at: row.verdict_at, commit: row.verdict_commit });
+ const verdicts = store.verdictsFor(board, item.item_id).map(verdict);
+ const after = item.item_after ? item.item_after.split(',').map(Number) : [];
+ return {
+ id: item.item_id,
+ title: item.item_title,
+ lane: item.item_lane,
+ status: item.item_status,
+ route: item.item_route,
+ owner: item.item_owner,
+ reviewer: store.reviewHolder(board, item),
+ reviewUntil: item.item_review_until ?? null,
+ builtBy: item.item_built_by,
+ verifiedBy: item.item_verified_by,
+ specs: item.item_spec_ids ? item.item_spec_ids.split(',') : [],
+ criterion: item.item_criterion,
+ brief: item.item_brief,
+ commit: item.item_commit,
+ merged: item.item_merged_commit,
+ blockedBy: after.filter((id) => status.get(id) !== 'verified'),
+ updatedAt: item.item_updated_at,
+ verdict: verdicts.at(-1) ?? null,
+ verdicts,
+ history: store.events(board, { itemId: item.item_id }).map((event) => ({ kind: event.event_kind, by: event.event_by, at: event.event_at })),
+ };
+}
+
+/** The same board connection, counting the per-item verdict reads that only building an item makes. */
+function countingVerdictReads(board) {
+ const counted = { reads: 0 };
+ const db = new Proxy(board.db, {
+ get(target, key) {
+ if (key === 'prepare') return (sql) => { if (/FROM verdict WHERE item_id/.test(sql)) counted.reads += 1; return target.prepare(sql); };
+ const value = target[key];
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ return { board: { ...board, db }, counted };
+}
+
+test('the item projector matches the full projection [A2,N26]', () => {
+ const box = machine();
+ const p = project(box, 'projector-items');
+ const add = (...args) => Number(/#(\d+)/.exec(box.run(p.repo, 'add', 'web', ...args))[1]);
+ // Every state, with waits, verdicts and history: verified twice over, sent back, under review, claimed, open,
+ // waiting, and withdrawn.
+ const verified = add('Verified after a send-back', '--criterion', 'the page renders', '--specs', 'G1');
+ build(box, p, verified, 'one.txt');
+ sendBack(box, p, verified, 'the heading is missing');
+ build(box, p, verified, 'two.txt');
+ accept(box, p, verified);
+ const reviewed = add('Under review', '--criterion', 'the page says goodbye', '--specs', 'G2');
+ build(box, p, reviewed, 'three.txt');
+ box.run(p.repo, 'next', '--verify', String(reviewed), '--as', 'coordinator');
+ const sentBack = add('Sent back', '--criterion', 'a third page');
+ build(box, p, sentBack, 'four.txt');
+ sendBack(box, p, sentBack, 'it shows the wrong page');
+ const claimed = add('Claimed', '--criterion', 'a fourth page');
+ box.run(p.web, 'claim', String(claimed));
+ const open = add('Open', '--criterion', 'a fifth page');
+ const waiting = add('Waits on open and verified work', '--criterion', 'after the others', '--after', `${open},${verified},${claimed}`);
+ const withdrawn = add('Withdrawn', '--criterion', 'nobody builds it');
+ box.run(p.repo, 'withdraw', String(withdrawn), 'a duplicate of the open item');
+
+ const file = join(p.repo, '.git', 'pullboard', 'board.sqlite');
+ const board = store.openBoard(file);
+ try {
+ const all = store.listItems(board, { all: true });
+ const status = new Map(all.map((item) => [item.item_id, item.item_status]));
+ assert.deepEqual([...new Set(status.values())].sort(), ['claimed', 'open', 'submitted', 'verified', 'withdrawn'], 'the board holds an item in every state');
+ const full = serve.projectState(p.repo, { board });
+ const byId = new Map(full.items.map((item) => [item.id, item]));
+ assert.equal(byId.get(reviewed).reviewer !== null, true, 'the item under review names its reviewer');
+ assert.deepEqual(byId.get(waiting).blockedBy, [open, claimed], 'the waiting item waits only on unverified work');
+ assert.deepEqual(byId.get(verified).verdicts.map((verdict) => verdict.decision), ['REJECT', 'ACCEPT'], 'the verified item keeps both verdicts');
+ assert.equal(byId.get(sentBack).verdict.decision, 'REJECT', 'the sent-back item shows its verdict');
+
+ // With no callback, the projection is today's, byte for byte.
+ assert.equal(JSON.stringify(full), JSON.stringify({ ...full, items: all.map((item) => todayItem(board, item, status)) }), 'projectState with no callback is today\'s output');
+ // A pass-through callback changes nothing, and is offered each item in order with the board and the status map.
+ const offered = [];
+ const passed = serve.projectState(p.repo, { board, itemProjector: (item, context) => { offered.push([item.item_id, context.board === board, context.status.get(item.item_id)]); return context.project(); } });
+ assert.equal(JSON.stringify(passed), JSON.stringify(full), 'projectState with a pass-through callback equals it too');
+ assert.deepEqual(offered, all.map((item) => [item.item_id, true, item.item_status]), 'the callback is offered every item with its board and status');
+
+ // Each item projected on its own is that item in the full projection, a fresh object each time, and it changes
+ // neither the row nor the status map.
+ assert.equal(typeof serve.projectItemState, 'function', 'serve.js exports projectItemState');
+ for (const item of all) {
+ const row = structuredClone(item), statuses = new Map(status);
+ const one = serve.projectItemState(board, item, status);
+ assert.equal(JSON.stringify(one), JSON.stringify(byId.get(item.item_id)), `projectItemState for #${item.item_id} equals that item in the full projection`);
+ assert.notEqual(serve.projectItemState(board, item, status), one, `projectItemState for #${item.item_id} returns a fresh object`);
+ assert.deepEqual(item, row, `projectItemState leaves #${item.item_id}'s row as it was`);
+ assert.deepEqual(status, statuses, 'projectItemState leaves the status map as it was');
+ }
+
+ // A callback that returns its own object never has the item built: no per-item verdict read runs. The pass-through
+ // control on the same counting connection reads one verdict list per item.
+ const own = countingVerdictReads(board);
+ const kept = new Map(all.map((item) => [item.item_id, { id: item.item_id, kept: true }]));
+ const reused = serve.projectState(p.repo, { board: own.board, itemProjector: (item) => kept.get(item.item_id) });
+ assert.equal(own.counted.reads, 0, 'project() is not called when the callback returns its own object');
+ assert.deepEqual(reused.items, [...kept.values()], 'the items are the callback\'s own objects');
+ assert.ok(reused.items.every((item, n) => item === kept.get(all[n].item_id)), 'each one is the very object the callback returned');
+ const control = countingVerdictReads(board);
+ serve.projectState(p.repo, { board: control.board, itemProjector: (item, { project }) => project() });
+ assert.equal(control.counted.reads, all.length, 'project() reads each item\'s verdicts once when called');
+ } finally {
+ store.closeBoard(board);
+ }
+});