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): one event stream follows many boards [A2,N26]

Corey Olsoneebf470274f6
diff --git a/docs/api.md b/docs/api.md
index 1ba6f257..1a01a4ff 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -205,6 +205,7 @@ The server checks any Origin against its own address and grants no CORS permissi
| `GET /api/v1/boards/:board/shouts/:id` | One shout from any point in the board's history, including its decision and answer fields |
| `GET /api/v1/boards/:board/code?ref=path:lines@commit&before=...` | A bounded preview of committed file lines from that registered board |
| `GET /api/v1/boards/:board/events?after=N` | Events after sequence N, in order, and their event-log format version |
+| `GET /api/v1/events?boards=<id>,<id>` | One live stream of every named board's events and changed signals, each tagged with its board |
| `POST /api/v1/boards/:board/moves` | One CLI move and its emitted event |
| `POST /api/v1/boards/:board/requests` | A person's request for the coordinator |
@@ -259,6 +260,8 @@ A request body is `{text}`. It creates a request from the person to the coordina
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`.
+To follow several boards on one connection, send `Accept: text/event-stream` to `GET /api/v1/events?boards=<id>,<id>`, naming each board once by its id from `GET /api/v1/boards`. A browser holds at most six connections per origin, so a project group's view follows all its repos through this one stream. Each frame's `data` also names its `board`: an event is `{"version":1,"board":"<id>","event":{...}}`, and the changed signal is `{"version":1,"board":"<id>","event":{"event_kind":"changed"}}`, sent on the same terms as a single board's. An ordinary event's `id` carries one cursor per board, `<id>:<sequence>` pairs joined by commas, so reconnecting with `Last-Event-ID`, or passing the same cursor as `after`, resumes each board where it left off. A followed board the cursor leaves out starts from its first event, and a pair for a board not followed is ignored. Every named board must be one the caller may read: otherwise the request is refused with that board's refusal, naming the board, and nothing is streamed. The path is live only; a request without `Accept: text/event-stream` is refused with `BAD_REQUEST`. The single-board events path is unchanged.
+
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.
HTTP refusals use the same versioned error envelope above: 400 for malformed calls, 401 for a missing or wrong session secret, 403 for an agent belonging to another board, 404 for an unknown board, path or shout, and 409 for the CLI engine's refusal. Shouts and answers append their events in the same transaction as their records. A move returns its own event, including when it also sends a coordinator shout.
diff --git a/docs/api.test.js b/docs/api.test.js
index 1eafde75..f5f360fd 100644
--- a/docs/api.test.js
+++ b/docs/api.test.js
@@ -55,4 +55,6 @@ test('[A2] API guide documents the local HTTP response catalog', () => {
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/);
+ assert.match(guide, /`GET \/api\/v1\/events\?boards=<id>,<id>`/);
+ assert.match(guide, /`<id>:<sequence>` pairs joined by commas/);
});
diff --git a/src/api-http.js b/src/api-http.js
index 6f65fd7f..1caee339 100644
--- a/src/api-http.js
+++ b/src/api-http.js
@@ -59,6 +59,43 @@ function sinceCursor(value) {
return eventCursor(value);
}
+/** Read a many-board stream's board ids: at least one, each named once (A2). */
+function boardList(value) {
+ const ids = String(value ?? '').split(',');
+ if (ids.some((id) => !id)) throw new Refused('BAD_REQUEST', 'name the boards to follow: /api/v1/events?boards=<id>,<id> with ids from GET /api/v1/boards');
+ const repeated = ids.find((id, index) => ids.indexOf(id) !== index);
+ if (repeated) throw new Refused('BAD_REQUEST', `board ${repeated} is named twice; name each board once`);
+ return ids;
+}
+
+/**
+ * Read a many-board cursor: board:sequence pairs joined by commas, one per board. A followed board
+ * the cursor leaves out starts from its first event, and a pair for a board not followed is ignored.
+ */
+function boardCursors(value) {
+ const cursors = new Map();
+ if (value === null || value === undefined || value === '') return cursors;
+ for (const part of String(value).split(',')) {
+ const pair = /^(.+):(\d+)$/.exec(part);
+ if (!pair || !Number.isSafeInteger(Number(pair[2])) || cursors.has(pair[1])) {
+ throw new Refused('BAD_CURSOR', 'a many-board cursor is board:sequence pairs joined by commas, each board once; use the last event id received');
+ }
+ cursors.set(pair[1], Number(pair[2]));
+ }
+ return cursors;
+}
+
+/** Name the board a many-board stream refused, unless the refusal already does (A2). */
+function namedRefusal(id, error) {
+ if (!(error instanceof Refused) || error.message.includes(id)) return error;
+ return new Refused(error.code, `board ${id}: ${error.message.replace(/^\[[A-Z0-9_]+\] /u, '')}`);
+}
+
+/** Whether a request asks for a live text/event-stream response rather than JSON. */
+function wantsLive(req) {
+ return String(req.headers.accept ?? '').split(',').some((part) => /^\s*text\/event-stream\s*(?:;|$)/i.test(part));
+}
+
/** Read a state request's detail choice: item summaries, every item in full, or null for the server's default (A2). */
function stateDetail(value) {
if (value === null) return null;
@@ -71,15 +108,34 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
if (!Number.isInteger(pollMs) || pollMs < 10 || pollMs > 60_000) throw new Refused('API_POLL', 'use a poll interval from 10 to 60000 milliseconds');
const streams = new Set();
- /** Replay and follow records, respecting slow clients and revocation between polls. */
- async function stream(req, res, board, who, after, initial, watcher, lastRevision) {
+ /**
+ * Open one board for a stream: its watcher and revision come before its replay, so a change
+ * between them is still signalled.
+ */
+ async function openFollow(board, who, after) {
+ const watcher = await adapter.watchRevision?.(board, who);
+ try {
+ const lastRevision = await watcher?.revision();
+ const initial = await adapter.events(board, after, who);
+ return { board, who, after, initial, watcher, lastRevision, lastWarning: null };
+ } catch (error) {
+ watcher?.close();
+ throw error;
+ }
+ }
+
+ /**
+ * Replay and follow one or more boards' records on one response, respecting slow clients and
+ * revocation between polls. A tagged stream names each frame's board, and each ordinary
+ * event's id carries every followed board's cursor, so one Last-Event-ID resumes them all.
+ */
+ async function stream(req, res, follows, tagged) {
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);
let closed = false;
let busy = false;
let blocked = false;
- let lastWarning = null;
let timer;
/** Remove this stream and its timer once the client disconnects or access is revoked. */
function stop() {
@@ -87,39 +143,47 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
closed = true;
clearInterval(timer);
streams.delete(res);
- watcher?.close();
+ for (const follow of follows) follow.watcher?.close();
res.end();
}
- /** Deliver only records after the latest delivered sequence, with no overlapping polls. */
+ /** Serialize one frame's data, naming its board on a tagged stream. */
+ const frame = (follow, fields) => JSON.stringify(tagged ? { version: 1, board: follow.board.id, ...fields } : { version: 1, ...fields });
+ /** The id of an ordinary event: its sequence, or every followed board's cursor on a tagged stream. */
+ const eventId = (follow) => tagged ? follows.map((each) => each.board.id + ':' + each.after).join(',') : String(follow.after);
+ /** Deliver only records after each board's latest delivered sequence, with no overlapping polls. */
async function send() {
return withGitFacts(async () => {
if (closed || busy || blocked) return;
busy = true;
+ let current = null;
try {
- who = await adapter.authenticate(req, { board: board.id, write: false });
- const warning = await adapter.warning?.(board, who);
- const serialized = warning ? JSON.stringify({ version: 1, warning }) : null;
- if (serialized !== lastWarning) {
- lastWarning = serialized;
- if (serialized && !res.write('event: warning\ndata: ' + serialized + '\n\n')) { blocked = true; return; }
- }
- const records = initial ?? await adapter.events(board, after, who);
- initial = null;
- for (const event of records) {
- if (closed) break;
- 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;
+ for (const follow of follows) {
+ current = follow;
+ follow.who = await adapter.authenticate(req, { board: follow.board.id, write: false });
+ const warning = await adapter.warning?.(follow.board, follow.who);
+ const serialized = warning ? frame(follow, { warning }) : null;
+ if (serialized !== follow.lastWarning) {
+ follow.lastWarning = serialized;
+ if (serialized && !res.write('event: warning\ndata: ' + serialized + '\n\n')) { blocked = true; return; }
+ }
+ const records = follow.initial ?? await adapter.events(follow.board, follow.after, follow.who);
+ follow.initial = null;
+ for (const event of records) {
+ if (closed) break;
+ follow.after = event.event_id;
+ if (!res.write('id: ' + eventId(follow) + '\ndata: ' + frame(follow, { event }) + '\n\n')) { blocked = true; break; }
+ }
+ if (closed || blocked) return;
+ if (follow.watcher) {
+ const revision = await follow.watcher.revision();
+ if (revision !== follow.lastRevision) {
+ follow.lastRevision = revision;
+ if (!res.write('event: changed\ndata: ' + frame(follow, { event: { event_kind: 'changed' } }) + '\n\n')) { blocked = true; return; }
+ }
}
}
} catch (error) {
- if (!closed) res.write('event: error\ndata: ' + JSON.stringify(refusal(error)) + '\n\n');
+ if (!closed) res.write('event: error\ndata: ' + JSON.stringify(refusal(tagged && current ? namedRefusal(current.board.id, error) : error)) + '\n\n');
stop();
} finally { busy = false; }
});
@@ -150,6 +214,28 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {
const listing = await adapter.boards(who);
return json(res, 200, Array.isArray(listing) ? { boards: listing } : listing);
}
+ if (url.pathname === '/api/v1/events') {
+ // One connection follows many boards, so a group view stays inside a browser's six per origin.
+ if (req.method !== 'GET') throw new Refused('BAD_REQUEST', 'follow boards with GET /api/v1/events?boards=<id>,<id>');
+ if (!wantsLive(req)) throw new Refused('BAD_REQUEST', "the many-board events path is a live stream; send Accept: text/event-stream, or read one board's events at /api/v1/boards/:board/events");
+ const ids = boardList(url.searchParams.get('boards'));
+ const cursors = boardCursors(req.headers['last-event-id'] ?? url.searchParams.get('after'));
+ const follows = [];
+ try {
+ for (const id of ids) {
+ try {
+ const reader = await adapter.authenticate(req, { board: id, write: false });
+ follows.push(await openFollow(await adapter.board(id, reader), reader, cursors.get(id) ?? 0));
+ } catch (error) {
+ throw namedRefusal(id, error);
+ }
+ }
+ return await stream(req, res, follows, true);
+ } catch (error) {
+ for (const follow of follows) follow.watcher?.close();
+ throw error;
+ }
+ }
if (!route && !shoutRoute && !itemRoute) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, item, shout, code, events, moves or requests path')));
const board = await adapter.board(boardId, who);
if (itemRoute) {
@@ -213,15 +299,12 @@ 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 live = String(req.headers.accept ?? '').split(',').some((part) => /^\s*text\/event-stream\s*(?:;|$)/i.test(part));
- if (live) {
- const watcher = await adapter.watchRevision?.(board, who);
+ if (wantsLive(req)) {
+ const follow = await openFollow(board, who, after);
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);
+ return await stream(req, res, [follow], false);
} catch (error) {
- watcher?.close();
+ follow.watcher?.close();
throw error;
}
}
diff --git a/test/api-http.test.js b/test/api-http.test.js
index 14619c81..b5831815 100644
--- a/test/api-http.test.js
+++ b/test/api-http.test.js
@@ -994,6 +994,155 @@ test('[A2, N26] the event stream says when the board changes without a move', as
await closeStream();
});
+/**
+ * Open a live event stream and read its frames one at a time. A pending read is shared across
+ * timeouts, so a quiet-period check cannot consume a later frame.
+ */
+async function liveFrames(t, url, headers) {
+ const controller = new AbortController();
+ const response = await fetchFresh(url, { headers: { ...headers, accept: 'text/event-stream' }, signal: controller.signal });
+ assert.equal(response.status, 200, 'the stream opens');
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffered = '';
+ let pending = null;
+ let closing = false;
+ /** Parse the next complete frame that carries data, skipping comments. */
+ async function read() {
+ while (true) {
+ const boundary = buffered.indexOf('\n\n');
+ if (boundary >= 0) {
+ const raw = buffered.slice(0, boundary);
+ buffered = buffered.slice(boundary + 2);
+ const data = /^data: (.+)$/m.exec(raw)?.[1];
+ if (raw.startsWith(':') || data === undefined) continue;
+ return { event: /^event: (.+)$/m.exec(raw)?.[1] ?? 'message', id: /^id: (.+)$/m.exec(raw)?.[1] ?? null, data: JSON.parse(data) };
+ }
+ const { value, done } = await reader.read();
+ if (done && closing) return null;
+ assert.equal(done, false, 'the live stream stays open while its boards are served');
+ buffered += decoder.decode(value, { stream: true });
+ }
+ }
+ /** Share one pending read until it settles. */
+ function next() {
+ pending ??= read().finally(() => { pending = null; });
+ return pending;
+ }
+ /** Read the next frame, failing rather than hanging if none comes. */
+ function frame(label) {
+ return Promise.race([
+ next(),
+ new Promise((_, reject) => setTimeout(() => reject(new Error(`no frame arrived (${label})`)), 10_000)), // budget: hang ceiling for one live frame, not a latency claim.
+ ]);
+ }
+ /** Read frames until each predicate has matched one, returning every frame read. */
+ async function until(label, ...wanted) {
+ const frames = [];
+ const left = [...wanted];
+ while (left.length) {
+ const got = await frame(label);
+ frames.push(got);
+ const matched = left.findIndex((predicate) => predicate(got));
+ if (matched >= 0) left.splice(matched, 1);
+ }
+ return frames;
+ }
+ /** Require silence for longer than one server poll. */
+ async function quiet(label) {
+ const extra = await Promise.race([next().then((value) => ({ value })), new Promise((resolve) => setTimeout(() => resolve(null), 350))]);
+ assert.equal(extra, null, `nothing is sent while nothing changes (${label})`); // budget: silence across more than one 200 ms server poll.
+ }
+ /** Stop the response and settle any pending read on pass and failure paths. */
+ async function close() {
+ if (closing) return;
+ closing = true;
+ controller.abort();
+ await reader.cancel().catch(() => {});
+ await pending?.catch(() => {});
+ }
+ t.after(close);
+ return { until, quiet, close };
+}
+
+/** Read a many-board event id as one cursor per board. */
+function boardCursorMap(id) {
+ return Object.fromEntries(id.split(',').map((pair) => {
+ const [, board, sequence] = /^(.+):(\d+)$/.exec(pair);
+ return [board, Number(sequence)];
+ }));
+}
+
+test('[A2, N26] one event stream serves many boards', async (t) => {
+ const other = fixture(t);
+ const box = await httpBox(t, { additionalProjects: [{ root: other.root, name: 'Second fixture' }] });
+ const listing = await box.call('/api/v1/boards');
+ const otherId = listing.document.boards.find((entry) => resolve(entry.root) === resolve(other.root)).id;
+ const boards = [box.id, otherId];
+ const latest = async (id) => (await box.call('/api/v1/boards/' + id + '/events')).document.events.at(-1).event_id;
+ const start = { [box.id]: await latest(box.id), [otherId]: await latest(otherId) };
+ const headers = { 'x-pullboard-key': box.key };
+ const many = box.origin + '/api/v1/events?boards=' + boards.join(',');
+ /** A frame of this kind for this board, and for one item when given. */
+ const is = (event, board, item) => (frame) => frame.event === event && frame.data.board === board
+ && (item === undefined || frame.data.event.item_id === item);
+
+ const first = await liveFrames(t, many + '&after=' + encodeURIComponent(boards.map((id) => id + ':' + start[id]).join(',')), headers);
+ await first.quiet('both boards unchanged');
+
+ // A move on each board arrives on the one connection, tagged with that board, with its changed signal.
+ const moves = [];
+ let lastId = null;
+ for (const [board, cli, root] of [[box.id, box.cli, box.root], [otherId, other.cli, other.root]]) {
+ const added = cli(root, 'add', 'app', 'Move on ' + board, '--criterion', 'arrives tagged', '--specs', 'G1').item;
+ const frames = await first.until(board, is('message', board, added.item_id), is('changed', board));
+ assert.deepEqual(frames.map((frame) => frame.data.board), frames.map(() => board), 'every frame names the board that moved');
+ const event = frames.find((frame) => frame.event === 'message');
+ assert.equal(event.data.version, 1);
+ assert.equal(event.data.event.event_kind, 'add');
+ lastId = event.id;
+ assert.equal(boardCursorMap(lastId)[board], event.data.event.event_id, 'the id carries this board at its new sequence');
+ assert.deepEqual(Object.keys(boardCursorMap(lastId)).sort(), [...boards].sort(), 'the id carries one cursor per followed board');
+ moves.push(event.data.event.event_id);
+ await first.quiet('after the move on ' + board);
+ }
+ assert.deepEqual(boardCursorMap(lastId), { [box.id]: moves[0], [otherId]: moves[1] });
+
+ // An edit that writes no event sends the changed signal for that board alone, with no id.
+ writeFileSync(join(other.root, 'SPEC.md'), readFileSync(join(other.root, 'SPEC.md'), 'utf8') + '\nThe second board follows this file.\n');
+ const edited = await first.until('eventless edit', is('changed', otherId));
+ assert.deepEqual(edited.map(({ event, id, data }) => ({ event, id, data })), [
+ { event: 'changed', id: null, data: { version: 1, board: otherId, event: { event_kind: 'changed' } } },
+ ]);
+ await first.quiet('after the eventless edit');
+ await first.close();
+
+ // Resuming from the last id picks up each board where it left off, and nothing earlier.
+ const missed = [
+ box.cli(box.root, 'add', 'app', 'Missed on the first board', '--criterion', 'replays', '--specs', 'G1').item.item_id,
+ other.cli(other.root, 'add', 'app', 'Missed on the second board', '--criterion', 'replays', '--specs', 'G1').item.item_id,
+ ];
+ const resumed = await liveFrames(t, many, { ...headers, 'last-event-id': lastId });
+ const replay = await resumed.until('resume', is('message', box.id, missed[0]), is('message', otherId, missed[1]));
+ assert.deepEqual(replay.map((frame) => [frame.event, frame.data.board, frame.data.event.item_id]), [
+ ['message', box.id, missed[0]],
+ ['message', otherId, missed[1]],
+ ], 'the resume replays only what each board wrote after its cursor');
+ assert.deepEqual(boardCursorMap(replay.at(-1).id), { [box.id]: replay[0].data.event.event_id, [otherId]: replay[1].data.event.event_id });
+ await resumed.quiet('after the resume');
+ await resumed.close();
+
+ // A board the caller cannot read is refused by name, and nothing streams.
+ const missing = 'f'.repeat(32);
+ const refused = await box.call('/api/v1/events?boards=' + box.id + ',' + missing, undefined, { accept: 'text/event-stream' });
+ assert.equal(refused.status, 404);
+ assert.equal(refused.document.error.code, 'NO_BOARD');
+ assert.match(refused.document.error.message, new RegExp(missing));
+ const repeated = await box.call('/api/v1/events?boards=' + box.id + ',' + box.id, undefined, { accept: 'text/event-stream' });
+ assert.equal(repeated.status, 400);
+ assert.match(repeated.document.error.message, new RegExp(box.id));
+});
+
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');