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.

feat(api): notify streams of state changes [A2,N26]

Corey Olsonb9ab879a7d0b
diff --git a/docs/api.md b/docs/api.md
index dc73067c..a80b6f2e 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -242,7 +242,7 @@ The SQLite schema marker is now `PRAGMA user_version = 2`. Opening an older boar
A request body is `{text}`. It creates a request from the person to the coordinator. Open requests stay first in coordinator `resume` and `inbox` until answered `done`, or `declined` with a reason, and do not count as open decisions.
-For live events, send `Accept: text/event-stream` to the events path. Each message's `id` is its event sequence and its `data` has the `stream` shape above. Reconnect with `Last-Event-ID` to resume after that sequence; it takes precedence over `after`.
+For live events, send `Accept: text/event-stream` to the events path. Ordinary messages have an `id` equal to their event sequence and `data` has the `stream` shape above. The local server also sends `event: changed` with `data: {"version":1,"event":{"event_kind":"changed"}}` when a view input changes without a board event; that notification has no `id` and does not move the reconnect cursor. Reconnect with `Last-Event-ID` to resume after the last ordinary event sequence; it takes precedence over `after`.
The local server uses a shared HTTP router. Streams recheck access before each poll and close with a versioned refusal if access ends. Slow readers pause delivery and resume from the last delivered sequence.
diff --git a/docs/api.test.js b/docs/api.test.js
index dd4c7c3d..15e65e70 100644
--- a/docs/api.test.js
+++ b/docs/api.test.js
@@ -47,4 +47,6 @@ test('[A2] API guide documents the local HTTP response catalog', () => {
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/state\?seen=N`/);
assert.match(guide, /`GET \/api\/v1\/boards\/:board\/code\?ref=path:lines@commit&before=\.\.\.`/);
assert.match(guide, /`CODE_NOT_AVAILABLE` refusal/);
+ assert.match(guide, /`event: changed` with `data: \{"version":1,"event":\{"event_kind":"changed"\}\}`/);
+ assert.match(guide, /notification has no `id` and does not move the reconnect cursor/);
});
diff --git a/src/api-http.js b/src/api-http.js
index 19c3d63e..f27697c9 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -59,7 +59,7 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
const streams = new Set();
/** Replay and follow records, respecting slow clients and revocation between polls. */
- async function stream(req, res, board, who, after, initial) {
+ async function stream(req, res, board, who, after, initial, watcher, lastRevision) {
res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer' });
res.write(': API v1\n\n');
streams.add(res);
@@ -74,6 +74,7 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
closed = true;
clearInterval(timer);
streams.delete(res);
+ watcher?.close();
res.end();
}
/** Deliver only records after the latest delivered sequence, with no overlapping polls. */
@@ -96,6 +97,14 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
after = event.event_id;
if (!res.write('id: ' + after + '\ndata: ' + JSON.stringify({ version: 1, event }) + '\n\n')) { blocked = true; break; }
}
+ if (!closed && !blocked && watcher) {
+ const revision = await watcher.revision();
+ if (revision !== lastRevision) {
+ const accepted = res.write('event: changed\ndata: {"version":1,"event":{"event_kind":"changed"}}\n\n');
+ lastRevision = revision;
+ if (!accepted) blocked = true;
+ }
+ }
} catch (error) {
if (!closed) res.write('event: error\ndata: ' + JSON.stringify(refusal(error)) + '\n\n');
stop();
@@ -170,9 +179,19 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
}
if (req.method === 'GET' && route[2] === 'events') {
const after = eventCursor(req.headers['last-event-id'] ?? url.searchParams.get('after'));
- const initial = await adapter.events(board, after, who);
const live = String(req.headers.accept ?? '').split(',').some((part) => /^\s*text\/event-stream\s*(?:;|$)/i.test(part));
- if (live) return await stream(req, res, board, who, after, initial);
+ if (live) {
+ const watcher = await adapter.watchRevision?.(board, who);
+ try {
+ const lastRevision = await watcher?.revision();
+ const initial = await adapter.events(board, after, who);
+ return await stream(req, res, board, who, after, initial, watcher, lastRevision);
+ } catch (error) {
+ watcher?.close();
+ throw error;
+ }
+ }
+ const initial = await adapter.events(board, after, who);
const warning = await adapter.warning?.(board, who);
const eventLogVersion = await adapter.eventLogVersion?.(board, who);
return json(res, 200, { events: initial, ...(eventLogVersion === undefined ? {} : { eventLogVersion }), ...(warning ? { warning } : {}) });
diff --git a/src/api.js b/src/api.js
index 5f97ec57..6409d7c7 100644
--- a/src/api.js
+++ b/src/api.js
@@ -1,8 +1,8 @@
/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
-import { join } from 'node:path';
-import { existsSync, readFileSync } from 'node:fs';
+import { basename, join, resolve } from 'node:path';
+import { existsSync, readFileSync, statSync } from 'node:fs';
import { displayAgentName } from './agent-names.js';
import * as store from './board.js';
import { CONFIG_FILE, COORDINATOR, loadConfig } from './config.js';
@@ -10,7 +10,7 @@ import { codeIsFromMain, repoInfo, resolveCommit } from './git.js';
import { refusalDocument } from './json.js';
import { relayLinked, relayOperation, relayRevoke, relayTokens } from './relay.js';
import { laneNames } from './lanes.js';
-import { listApiProjects } from './projects.js';
+import { listApiProjects, registryFile } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
import { proofStats } from './stats.js';
import { prepareFlowHistory, projectFlowStats } from './stats-flow.js';
@@ -23,23 +23,37 @@ import { moveArgs } from './api-moves.js';
import { personRequestStatuses } from './relay-requests.js';
export { moveArgs } from './api-moves.js';
-/** Hash the exact bytes of one state input, preserving a missing-file marker. */
-function fileRevision(root, file) {
- const path = join(root, file);
- if (!existsSync(path)) return [file, null];
- return [file, createHash('sha256').update(readFileSync(path)).digest('hex')];
+/** Inputs shared by the complete state cache and the lightweight live-change watcher. */
+const STATE_REVISION_INPUTS = Object.freeze([
+ 'identity', 'head', 'files', 'event', 'agents', 'leases', 'requestReceipts', 'milestones', 'externalRoadmap', 'eventLogVersion',
+]);
+
+/** Serialize named state inputs in one stable order for cache and stream comparisons. */
+function stateRevision(inputs) {
+ return JSON.stringify(STATE_REVISION_INPUTS.map((name) => [name, inputs[name]]));
+}
+
+/** Name project and built-in files separately, even when their basenames collide. */
+function stateFileInputs(root, config) {
+ return [
+ { name: `config:${CONFIG_FILE}`, path: join(root, CONFIG_FILE) },
+ { name: `spec:${config.spec}`, path: join(root, config.spec) },
+ { name: `practice:${config.practice}`, path: join(root, config.practice) },
+ { name: 'builtin:standard-doctrine.md', path: new URL('./standard-doctrine.md', import.meta.url) },
+ ];
+}
+
+/** Hash the exact bytes of one named input, preserving a missing-file marker. */
+function fileRevision(file) {
+ if (!existsSync(file.path)) return [file.name, null];
+ return [file.name, createHash('sha256').update(readFileSync(file.path)).digest('hex')];
}
/** Capture the inexpensive inputs that can invalidate a complete board-state snapshot. */
-function boardStateRevision(root, id, isMain) {
+function boardStateRevision(root, id, isMain, projects) {
const info = repoInfo(root);
const config = loadConfig(info.root);
- const files = [
- fileRevision(info.root, CONFIG_FILE),
- fileRevision(info.root, config.spec),
- fileRevision(info.root, config.practice),
- ['standard-doctrine.md', createHash('sha256').update(readFileSync(new URL('./standard-doctrine.md', import.meta.url))).digest('hex')],
- ];
+ const files = stateFileInputs(info.root, config).map(fileRevision);
const local = withBoard(info.root, (board) => {
const now = board.clock.now().toISOString();
const agents = store.listAgents(board);
@@ -57,16 +71,294 @@ function boardStateRevision(root, id, isMain) {
leases,
requestReceipts: board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('relay_person_requests')?.meta_value ?? null,
milestones,
- externalMilestones: hasExternalMilestones ? milestoneRoadmap(info.root, board) : null,
+ externalMilestones: hasExternalMilestones ? milestoneRoadmap(info.root, board, projects) : null,
};
}, isMain);
- const revision = JSON.stringify([
- info.commonDir, id, resolveCommit(info.root, 'HEAD'), files,
- local.event, local.agents, local.leases, local.requestReceipts, local.milestones, local.externalMilestones, store.EVENT_LOG_VERSION,
- ]);
+ const revision = stateRevision({
+ identity: [info.commonDir, id],
+ head: resolveCommit(info.root, 'HEAD'),
+ files,
+ event: local.event,
+ agents: local.agents,
+ leases: local.leases,
+ requestReceipts: local.requestReceipts,
+ milestones: local.milestones,
+ externalRoadmap: local.externalMilestones,
+ eventLogVersion: store.EVENT_LOG_VERSION,
+ });
return { cacheId: info.commonDir + '\0' + id, revision, milestones: local.externalMilestones, cacheable: true };
}
+/** Cheap file identity for an event-stream poll; content is read only after this marker changes. */
+function fileMarker(file) {
+ try {
+ const stat = statSync(file.path);
+ return [file.name, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs];
+ } catch (error) {
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return [file.name, null];
+ throw error;
+ }
+}
+
+/** Capture a marker for a single absolute path, including an explicit missing-file value. */
+function fileMarkerForPath(path) {
+ try {
+ const stat = statSync(path);
+ return JSON.stringify([stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs]);
+ } catch (error) {
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return 'missing';
+ throw error;
+ }
+}
+
+/** Read HEAD and its selected ref without spawning Git on every 200 ms poll. */
+function headFileRevision(info) {
+ const head = readFileSync(join(info.gitDir, 'HEAD'), 'utf8').trim();
+ if (/^[0-9a-f]{40,64}$/iu.test(head)) return head.toLowerCase();
+ const symbolic = /^ref: (.+)$/.exec(head);
+ if (!symbolic) return head;
+ const ref = symbolic[1];
+ try { return readFileSync(join(info.commonDir, ref), 'utf8').trim(); }
+ catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ let packed;
+ try { packed = readFileSync(join(info.commonDir, 'packed-refs'), 'utf8'); }
+ catch (packedError) {
+ if (packedError.code === 'ENOENT') return head;
+ throw packedError;
+ }
+ return packed.split('\n').find((line) => line.endsWith(' ' + ref))?.split(' ')[0] ?? head;
+ }
+}
+
+/** Read default registry names without listApiProjects' pruning or metadata writes. */
+function watcherProjects(projects) {
+ if (projects !== listApiProjects) return projects();
+ try {
+ const value = JSON.parse(readFileSync(registryFile(), 'utf8'));
+ if (!Array.isArray(value.projects)) return [];
+ return value.projects.filter((project) => typeof project?.root === 'string').map((project) => ({
+ ...project,
+ root: resolve(project.root),
+ name: project.name ?? basename(project.root),
+ }));
+ } catch {
+ return [];
+ }
+}
+
+/** Open only boards named by this board's external milestone references. */
+function openRoadmapInputs(root, milestones, projects, localDb) {
+ const references = milestones.flatMap((milestone) => milestone.items.filter((item) => typeof item !== 'number'));
+ const registered = references.length ? watcherProjects(projects) : [];
+ const opened = new Map();
+ const pathMarkers = new Map();
+ const watchPath = (path) => {
+ if (!pathMarkers.has(path)) pathMarkers.set(path, fileMarkerForPath(path));
+ };
+ let inputs;
+ try {
+ inputs = references.map((reference) => {
+ const match = /^(.+)#([1-9]\d*)$/.exec(reference);
+ if (!match) return { reference, unavailable: true };
+ const [, repo, number] = match;
+ const candidates = registered.filter((project) => project.name === repo || basename(project.root) === repo);
+ for (const candidate of candidates) {
+ watchPath(candidate.root);
+ watchPath(join(candidate.root, '.git'));
+ }
+ if (candidates.length !== 1) return { reference, unavailable: true };
+ try {
+ const info = repoInfo(candidates[0].root);
+ const path = join(info.commonDir, 'pullboard', 'board.sqlite');
+ watchPath(path);
+ const db = resolve(candidates[0].root) === resolve(root) ? localDb : (opened.get(path) ?? store.openBoardReadOnly(path));
+ if (db !== localDb) opened.set(path, db);
+ return { reference, id: Number(number), db, path };
+ } catch {
+ return { reference, unavailable: true };
+ }
+ });
+ } catch (error) {
+ for (const db of opened.values()) {
+ try { db.close(); } catch {}
+ }
+ throw error;
+ }
+ return {
+ inputs,
+ close() {
+ for (const db of opened.values()) {
+ try { db.close(); } catch {}
+ }
+ },
+ needsRefresh() {
+ for (const [path, marker] of pathMarkers) if (fileMarkerForPath(path) !== marker) return true;
+ return false;
+ },
+ revision(now) {
+ const values = [];
+ let nextExpiry = null;
+ for (const input of inputs) {
+ if (input.unavailable) { values.push([input.reference, 'unavailable']); continue; }
+ const item = input.db.prepare('SELECT item_title, item_status, item_lease_until FROM item WHERE item_id = ?').get(input.id);
+ if (!item) { values.push([input.reference, 'missing']); continue; }
+ const status = item.item_status === 'claimed' && (item.item_lease_until ?? '') <= now ? 'open' : item.item_status;
+ if (item.item_status === 'claimed' && item.item_lease_until > now && (!nextExpiry || item.item_lease_until < nextExpiry)) nextExpiry = item.item_lease_until;
+ values.push([input.reference, item.item_title, status]);
+ }
+ return { values, nextExpiry };
+ },
+ };
+}
+
+/** Watch the same named state inputs as the cache without rebuilding a board-state response. */
+function watchLocalStateRevision(board, projects) {
+ const info = repoInfo(board.root);
+ const config = loadConfig(info.root);
+ let files = stateFileInputs(info.root, config);
+ const dbPath = join(info.commonDir, 'pullboard', 'board.sqlite');
+ let db = store.openBoardReadOnly(dbPath);
+ let closed = false;
+ let dbMarker;
+ let fileMarkers;
+ let fileContent;
+ let head;
+ let dataVersion;
+ let local = null;
+ let external = null;
+ let externalVersion = new Map();
+ let externalValues = null;
+ let externalNextExpiry = null;
+ let externalReferences = null;
+ let registryMarker = null;
+
+ try {
+ dbMarker = fileMarkerForPath(dbPath);
+ fileMarkers = files.map(fileMarker);
+ fileContent = files.map(fileRevision);
+ head = headFileRevision(info);
+ dataVersion = db.prepare('PRAGMA data_version').get().data_version;
+ } catch (error) {
+ db.close();
+ throw error;
+ }
+
+ /** Capture only the board columns that the cached view exposes. */
+ function localInputs(now) {
+ const agents = store.listAgents({ db, clock: store.systemClock });
+ const leases = db.prepare('SELECT item_id, item_status, item_owner, item_lease_until, item_review_by, item_review_until FROM item ORDER BY item_id').all()
+ .map((item) => [
+ item.item_id, item.item_status, item.item_owner, item.item_lease_until, item.item_review_by, item.item_review_until,
+ item.item_status === 'claimed' && (item.item_lease_until ?? '') > now,
+ item.item_status === 'submitted' && Boolean(item.item_review_by) && (item.item_review_until ?? '') > now,
+ ]);
+ const milestones = store.milestones({ db });
+ const expiries = db.prepare(`SELECT MIN(CASE WHEN item_status = 'claimed' AND item_lease_until > ? THEN item_lease_until END) AS claim,
+ MIN(CASE WHEN item_status = 'submitted' AND item_review_by IS NOT NULL AND item_review_until > ? THEN item_review_until END) AS review FROM item`).get(now, now);
+ return {
+ event: db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id,
+ agents,
+ leases,
+ requestReceipts: db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get('relay_person_requests')?.meta_value ?? null,
+ milestones,
+ nextExpiry: [expiries.claim, expiries.review].filter(Boolean).sort()[0] ?? null,
+ };
+ }
+
+ /** Refresh related external board reads only after their retained connection reports a commit. */
+ function externalInputs(now, milestoneDefinitions, localChanged) {
+ const references = milestoneDefinitions.flatMap((milestone) => milestone.items.filter((item) => typeof item !== 'number'));
+ const currentRegistryMarker = fileMarkerForPath(registryFile());
+ const registryChanged = registryMarker !== currentRegistryMarker;
+ if (!external || JSON.stringify(externalReferences) !== JSON.stringify(references) || registryChanged || external.needsRefresh()) {
+ external?.close();
+ external = openRoadmapInputs(info.root, milestoneDefinitions, projects, db);
+ externalVersion = new Map();
+ externalValues = null;
+ externalNextExpiry = null;
+ externalReferences = references;
+ registryMarker = currentRegistryMarker;
+ }
+ let changed = false;
+ for (const input of external.inputs) {
+ if (!input.unavailable && input.db !== db) {
+ // Keep the version observed before row reads. A commit during revision() is then
+ // detected on the next poll instead of pairing old rows with a newer version.
+ const value = input.db.prepare('PRAGMA data_version').get().data_version;
+ const key = input.db;
+ if (externalVersion.has(key) && externalVersion.get(key) !== value) changed = true;
+ externalVersion.set(key, value);
+ }
+ }
+ if (changed || localChanged || !externalValues || (externalNextExpiry && externalNextExpiry <= now)) {
+ const current = external.revision(now);
+ externalValues = current.values;
+ externalNextExpiry = current.nextExpiry;
+ }
+ return externalValues;
+ }
+
+ /** Return the current cheap revision, updating heavier SQL projections only when needed. */
+ function revision() {
+ if (closed) throw new Error('the event-stream revision watcher is closed');
+ const latestDbMarker = fileMarkerForPath(dbPath);
+ if (latestDbMarker !== dbMarker) {
+ const replacement = store.openBoardReadOnly(dbPath);
+ const replacementVersion = replacement.prepare('PRAGMA data_version').get().data_version;
+ external?.close();
+ external = null;
+ db.close();
+ db = replacement;
+ dbMarker = latestDbMarker;
+ dataVersion = replacementVersion;
+ local = null;
+ externalValues = null;
+ externalVersion = new Map();
+ }
+ const currentMarkers = files.map(fileMarker);
+ if (JSON.stringify(currentMarkers) !== JSON.stringify(fileMarkers)) {
+ fileMarkers = currentMarkers;
+ const latestConfig = loadConfig(info.root);
+ files = stateFileInputs(info.root, latestConfig);
+ fileMarkers = files.map(fileMarker);
+ fileContent = files.map(fileRevision);
+ }
+ const latestHead = headFileRevision(info);
+ const latestDataVersion = db.prepare('PRAGMA data_version').get().data_version;
+ const now = new Date().toISOString();
+ const localChanged = latestDataVersion !== dataVersion;
+ const localExpiryChanged = Boolean(local?.nextExpiry && local.nextExpiry <= now);
+ if (!local || localChanged || localExpiryChanged) {
+ local = localInputs(now);
+ dataVersion = latestDataVersion;
+ }
+ head = latestHead;
+ const externalRoadmap = externalInputs(now, local.milestones, localChanged || localExpiryChanged);
+ return stateRevision({
+ identity: [info.commonDir, board.id],
+ head,
+ files: fileContent,
+ event: local.event,
+ agents: local.agents,
+ leases: local.leases,
+ requestReceipts: local.requestReceipts,
+ milestones: local.milestones,
+ externalRoadmap,
+ eventLogVersion: store.EVENT_LOG_VERSION,
+ });
+ }
+
+ return {
+ revision,
+ close() {
+ if (closed) return;
+ closed = true;
+ try { external?.close(); } finally { db.close(); }
+ },
+ };
+}
+
/** Build the complete local API state, including fields that the shared project snapshot omits. */
function buildLocalBoardState(board, codeIsMain, milestones) {
let state = projectState(board.root, { seen: null, isMain: codeIsMain });
@@ -274,11 +566,11 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
const stateCache = new Map();
/** Return the current state and its cached-static JSON representation under revision checks. */
function localState(board, seen) {
- const before = boardStateRevision(board.root, board.id, codeIsMain);
+ const before = boardStateRevision(board.root, board.id, codeIsMain, projects);
const cached = stateCache.get(before.cacheId);
if (before.cacheable && cached?.revision === before.revision) {
const state = stateForRequest(cached.state, board.root, seen, cached.preparedFlow, true, codeIsMain);
- const after = boardStateRevision(board.root, board.id, codeIsMain);
+ const after = boardStateRevision(board.root, board.id, codeIsMain, projects);
if (after.cacheable && after.revision === before.revision) {
stateCache.delete(before.cacheId);
stateCache.set(before.cacheId, cached);
@@ -290,7 +582,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
const state = buildLocalBoardState(board, codeIsMain, before.milestones);
const history = withBoard(board.root, (db) => store.events(db), codeIsMain);
const preparedFlow = prepareFlowHistory(history);
- const after = boardStateRevision(board.root, board.id, codeIsMain);
+ const after = boardStateRevision(board.root, board.id, codeIsMain, projects);
const stateJsonFields = prepareStateJson(state);
if (before.cacheable && after.cacheable && before.revision === after.revision) {
const entry = { revision: before.revision, state, preparedFlow, stateJsonFields };
@@ -317,6 +609,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =
board: (id) => findBoard(id, projects, codeIsMain),
state: (board, who, seen) => localState(board, seen).state,
stateJson: (board, who, seen) => localState(board, seen).json,
+ watchRevision: (board) => watchLocalStateRevision(board, projects),
shout: (board, id) => relayLinked(board.root)
? relayPresentationShout(board.root, id)
: withBoard(board.root, (db) => store.shoutDetails(db, id), codeIsMain),
diff --git a/src/roadmap.js b/src/roadmap.js
index 36ec3839..c1d2663a 100644
--- a/src/roadmap.js
+++ b/src/roadmap.js
@@ -5,13 +5,13 @@ import { codeIsFromMain, repoInfo } from './git.js';
import { listApiProjects } from './projects.js';
/** Resolve a repo-qualified milestone item against this machine's registered boards. */
-export function milestoneRoadmap(root, board) {
- const projects = listApiProjects();
+export function milestoneRoadmap(root, board, projects = listApiProjects) {
+ const registered = projects();
const resolveExternal = (reference) => {
const match = /^(.+)#([1-9]\d*)$/.exec(reference);
if (!match) return { id: reference, title: reference, status: 'unavailable' };
const [, repo, number] = match;
- const candidates = projects.filter((project) => project.name === repo || basename(project.root) === repo);
+ const candidates = registered.filter((project) => project.name === repo || basename(project.root) === repo);
if (candidates.length !== 1) return { id: reference, title: `#${number} (${repo})`, status: 'unavailable' };
try {
const info = repoInfo(candidates[0].root);
diff --git a/test/api-http.test.js b/test/api-http.test.js
index ee9df79f..e140498e 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -2,7 +2,7 @@
import assert from 'node:assert/strict';
import { randomUUID } from 'node:crypto';
import { runFixtureChild, runFixtureGit } from './fixture-child.js';
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { createServer, request as httpRequest } from 'node:http';
import { join, resolve } from 'node:path';
@@ -73,9 +73,9 @@ function fixture(t) {
}
/** Serve this fixture's explicit project, avoiding any registry outside its private home. */
-async function httpBox(t, { includeMissing = false, onStateBuild } = {}) {
+async function httpBox(t, { includeMissing = false, onStateBuild, additionalProjects = [] } = {}) {
const box = fixture(t);
- const api = await serveApi({ runCommand: main, onStateBuild, projects: () => [...(includeMissing ? [{ root: join(box.dir, 'gone'), name: 'Missing fixture' }] : []), { root: box.root, name: 'HTTP fixture' }] });
+ const api = await serveApi({ runCommand: main, onStateBuild, projects: () => [...(includeMissing ? [{ root: join(box.dir, 'gone'), name: 'Missing fixture' }] : []), { root: box.root, name: 'HTTP fixture' }, ...additionalProjects] });
t.after(() => api.close());
const url = new URL(api.url);
const key = url.searchParams.get('k');
@@ -93,8 +93,8 @@ async function httpBox(t, { includeMissing = false, onStateBuild } = {}) {
}
const listed = await call('/api/v1/boards');
assert.equal(listed.status, 200);
- assert.equal(listed.document.boards.length, 1);
- const id = listed.document.boards[0].id;
+ assert.equal(listed.document.boards.length, 1 + additionalProjects.length);
+ const id = listed.document.boards.find((entry) => resolve(entry.root) === resolve(box.root)).id;
assert.match(id, /^[0-9a-f]{32}$/);
return { ...box, api, origin, key, id, call, path: '/api/v1/boards/' + id };
}
@@ -535,6 +535,147 @@ test('[A2] a live HTTP stream follows CLI writes and reconnects after Last-Event
assert.equal(invalid.document.error.code, 'BAD_CURSOR');
});
+test('[A2, N26] the event stream says when the board changes without a move', async (t) => {
+ const external = fixture(t);
+ const externalAdded = external.cli(external.root, 'add', 'app', 'Roadmap item', '--criterion', 'remain open', '--specs', 'G1');
+ const externalAgent = external.cli(external.root, 'worktree', 'app', '--model', 'fixture-agent');
+ const box = await httpBox(t, { additionalProjects: [{ root: external.root, name: 'Roadmap fixture' }] });
+ const boardListing = await box.call('/api/v1/boards');
+ const externalId = boardListing.document.boards.find((entry) => resolve(entry.root) === resolve(external.root)).id;
+ const configPath = join(box.root, 'pullboard.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ writeFileSync(configPath, JSON.stringify({ ...config, spec: 'standard-doctrine.md' }));
+ const projectSpec = join(box.root, 'standard-doctrine.md');
+ writeFileSync(projectSpec, '# Project spec\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n');
+ runFixtureGit(['add', '--', 'pullboard.json', 'standard-doctrine.md'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ runFixtureGit(['commit', '-q', '-m', 'chore: select the project spec input', '--', 'pullboard.json', 'standard-doctrine.md'], { cwd: box.root, env: box.env, stdio: 'pipe' });
+ box.cli(box.root, 'milestone', 'add', 'External work', '--items', `Roadmap fixture#${externalAdded.item.item_id}`);
+ box.cli(box.root, 'shout', 'all', 'mark this after the stream starts');
+ const agent = box.cli(box.root, 'worktree', 'app', '--model', 'fixture-agent');
+ const leaseItem = box.cli(box.root, 'add', 'app', 'Expiring stream claim', '--criterion', 'becomes open', '--specs', 'G1').item;
+ const localClaim = await box.call(box.path + '/moves', { verb: 'claim', item: leaseItem.item_id, agent: agent.agent });
+ assert.equal(localClaim.status, 200);
+ const leaseUntil = new Date(Date.now() + 60 * 60 * 1000).toISOString();
+ const db = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'));
+ try {
+ db.db.prepare('UPDATE item SET item_lease_until = ? WHERE item_id = ?')
+ .run(leaseUntil, leaseItem.item_id);
+ } finally { store.closeBoard(db); }
+ const initial = await box.call(box.path + '/events');
+ const after = initial.document.events.at(-1).event_id;
+ const controller = new AbortController();
+ const response = await fetchFresh(box.origin + box.path + '/events?after=' + after, {
+ headers: { 'x-pullboard-key': box.key, accept: 'text/event-stream' },
+ signal: controller.signal,
+ });
+ const reader = response.body.getReader();
+ let buffered = '';
+ let pendingFrame;
+ let closing = false;
+ let streamClosed = false;
+ /** Stop the live response and settle any pending frame read on both pass and failure paths. */
+ async function closeStream() {
+ if (streamClosed) return;
+ streamClosed = true;
+ closing = true;
+ controller.abort();
+ await reader.cancel().catch(() => {});
+ await pendingFrame?.catch(() => {});
+ }
+ t.after(closeStream);
+ /** Read and parse the next complete server-sent-event frame. */
+ async function readFrame() {
+ while (true) {
+ const boundary = buffered.indexOf('\n\n');
+ if (boundary >= 0) {
+ const raw = buffered.slice(0, boundary);
+ buffered = buffered.slice(boundary + 2);
+ if (raw.startsWith(':')) continue;
+ const event = /^event: (.+)$/m.exec(raw)?.[1] ?? 'message';
+ const id = /^id: (\d+)$/m.exec(raw)?.[1];
+ const data = /^data: (.+)$/m.exec(raw)?.[1];
+ if (data !== undefined) return { event, id: id === undefined ? null : Number(id), data: JSON.parse(data) };
+ continue;
+ }
+ const { value, done } = await reader.read();
+ if (done && closing) return { event: 'closed', id: null, data: null };
+ assert.equal(done, false, 'the live stream remains open while the board is served');
+ buffered += new TextDecoder().decode(value);
+ }
+ }
+ /** Share a pending frame read across timeouts so a quiet-period check cannot consume a later frame. */
+ function nextFrame() {
+ if (!pendingFrame) pendingFrame = readFrame().finally(() => { pendingFrame = null; });
+ return pendingFrame;
+ }
+ /** Require an unchanged view to remain silent for longer than one server poll. */
+ async function quietPeriod() {
+ const extra = await Promise.race([nextFrame().then((value) => ({ value })), new Promise((resolve) => setTimeout(() => resolve(null), 350))]);
+ assert.equal(extra, null, 'a quiet interval produces no duplicate or unrelated frame');
+ }
+ /** Require exactly one changed notification for the most recent input change. */
+ async function changedOnce(label) {
+ const frame = await Promise.race([
+ nextFrame(),
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`changed event did not arrive within two seconds (${label})`)), 2000)),
+ ]);
+ assert.equal(frame.event, 'changed');
+ assert.equal(frame.id, null, 'a state notification does not advance the append-only event cursor');
+ assert.deepEqual(frame.data, { version: 1, event: { event_kind: 'changed' } });
+ await quietPeriod();
+ }
+
+ await quietPeriod();
+
+ writeFileSync(projectSpec, '# Project spec\n\n## Goals\n- G1 [approved, must] Keep the board fresh. | gate: true\n');
+ await changedOnce('project-spec');
+
+ runFixtureGit(['commit', '--allow-empty', '-m', 'chore(test): move fixture head'], { cwd: box.root, env: box.env, encoding: 'utf8' });
+ await changedOnce('head');
+
+ const externalClaim = await box.call('/api/v1/boards/' + externalId + '/moves', { verb: 'claim', item: externalAdded.item.item_id, agent: externalAgent.agent });
+ assert.equal(externalClaim.status, 200);
+ await changedOnce('external-claim');
+
+ const unavailableRoot = external.root + '.temporarily-unavailable';
+ renameSync(external.root, unavailableRoot);
+ await changedOnce('external-unavailable');
+ renameSync(unavailableRoot, external.root);
+ await changedOnce('external-restored');
+
+ const localBoardPath = join(box.root, '.git', 'pullboard', 'board.sqlite');
+ const cursorBefore = store.openBoard(localBoardPath);
+ let beforeSeen;
+ let beforeEvent;
+ try {
+ beforeSeen = store.listAgents(cursorBefore).find((entry) => entry.agent_id === agent.agent).agent_last_shout_id;
+ beforeEvent = cursorBefore.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id;
+ } finally { store.closeBoard(cursorBefore); }
+ box.cli(agent.path, 'inbox');
+ const cursorAfter = store.openBoard(localBoardPath);
+ try {
+ const afterSeen = store.listAgents(cursorAfter).find((entry) => entry.agent_id === agent.agent).agent_last_shout_id;
+ const afterEvent = cursorAfter.db.prepare('SELECT COALESCE(MAX(event_id), 0) AS id FROM event').get().id;
+ assert.ok(afterSeen > beforeSeen, 'the joined agent inbox advances its shout cursor');
+ assert.equal(afterEvent, beforeEvent, 'reading the inbox changes no append-only board event');
+ } finally { store.closeBoard(cursorAfter); }
+ await changedOnce('seen-cursor');
+
+ const clockNow = Date.now();
+ t.mock.timers.enable({ apis: ['Date'], now: clockNow });
+ t.mock.timers.tick(Date.parse(leaseUntil) - clockNow + 1);
+ await changedOnce('lease-expiry');
+
+ const evented = box.cli(box.root, 'add', 'app', 'Event plus state notification', '--criterion', 'both frames arrive', '--specs', 'G1');
+ const eventFrame = await nextFrame();
+ assert.equal(eventFrame.event, 'message');
+ assert.equal(eventFrame.data.event.event_kind, 'add');
+ assert.equal(eventFrame.data.event.item_id, evented.item.item_id);
+ await changedOnce('ordinary-event-state');
+
+ await closeStream();
+});
+
test('[A2] local auth, origin, unknown board and malformed calls refuse without moving', async (t) => {
const box = await httpBox(t);
const unauthenticated = await fetchFresh(box.origin + '/api/v1/boards');