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.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(api): share the bounded HTTP transport [A2]
Corey Olson15349b00d0d2
diff --git a/docs/api.md b/docs/api.mdindex cb3d5987..0ed88a50 100644--- a/docs/api.md+++ b/docs/api.md@@ -95,6 +95,8 @@ The result and refusal tables are checked against `JSON_SHAPES` in `src/json.js`Run `pullboard serve --port 0` to print a private API address on `127.0.0.1`. Authenticate each call with the address's `k` query parameter, an `X-Pullboard-Key` header, or `Authorization: Bearer <key>`. The secret belongs to that server session. Board ids are random 128-bit values stored in each board; reopening or moving a repo preserves its id.+The server checks any Origin against its own address and grants no CORS permission. JSON request bodies are limited to 100000 bytes; oversized bodies are drained and refused without applying a partial move. A missing or invalid registered folder is skipped so the other readable boards stay available.+| Method and path | Result || --- | --- || `GET /api/v1/boards` | Registered boards with their project details and ids |@@ -124,4 +126,6 @@ A request body is `{text}`. It creates a request from the person to the coordinaFor 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`.+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 or path, 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/src/api-http.js b/src/api-http.jsnew file mode 100644index 00000000..a6b5c767--- /dev/null+++ b/src/api-http.js@@ -0,0 +1,120 @@+/** API v1's shared HTTP boundary; local and relay adapters supply the same board operations (A2). */+import { Refused } from './refused.js';+import { refusalDocument } from './json.js';++const BODY_BYTES = 100_000;++/** Keep unexpected internal failures out of the public refusal document. */+function refusal(error) {+ return refusalDocument(error instanceof Refused ? error : new Refused('SERVICE_ERROR', 'the board service could not complete the call; retry or check the service'));+}++/** Emit exactly one versioned JSON response with no caching or content sniffing. */+function json(res, status, value) {+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });+ res.end(JSON.stringify({ version: 1, ...value }));+}++/** Read a bounded JSON object, draining oversize requests so a refusal reaches the caller. */+async function readBody(req) {+ if (!/^application\/json(?:\s*;|$)/i.test(String(req.headers['content-type'] ?? ''))) throw new Refused('BAD_REQUEST', 'send an application/json object as the request body');+ const chunks = [];+ let size = 0;+ for await (const chunk of req) {+ size += chunk.length;+ if (size <= BODY_BYTES) chunks.push(chunk);+ }+ if (size > BODY_BYTES) throw new Refused('BAD_REQUEST', 'the body exceeds ' + BODY_BYTES + ' bytes; send one move or request at a time');+ let value;+ try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Refused('BAD_REQUEST', 'the body is not JSON; send an application/json object'); }+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Refused('BAD_REQUEST', 'the body needs a JSON object; send one move or request at a time');+ return value;+}++/** Reject unsafe sequence coercion while retaining the CLI's empty-cursor default. */+function eventCursor(value) {+ if (value === null || value === undefined || value === '') return 0;+ if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Refused('BAD_CURSOR', 'after and Last-Event-ID need a nonnegative integer; use the last event id received');+ return Number(value);+}++/** Create the common API router; an adapter controls authorization and board storage. */+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) {+ 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 timer;+ /** Remove this stream and its timer once the client disconnects or access is revoked. */+ function stop() {+ if (closed) return;+ closed = true;+ clearInterval(timer);+ streams.delete(res);+ res.end();+ }+ /** Deliver only records after the latest delivered sequence, with no overlapping polls. */+ async function send() {+ if (closed || busy || blocked) return;+ busy = true;+ try {+ who = await adapter.authenticate(req, { board: board.id, write: false });+ 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; }+ }+ } catch (error) {+ if (!closed) res.write('event: error\ndata: ' + JSON.stringify(refusal(error)) + '\n\n');+ stop();+ } finally { busy = false; }+ }+ res.once('close', stop);+ res.on('drain', () => { blocked = false; void send(); });+ timer = setInterval(send, pollMs);+ timer.unref();+ await send();+ }++ /** Route a request through the adapter and keep every HTTP response inside API v1. */+ async function handle(req, res) {+ try {+ let url;+ try { url = new URL(req.url ?? '/', 'http://127.0.0.1'); } catch { throw new Refused('BAD_REQUEST', 'use a valid path under /api/v1/boards'); }+ const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests)$/.exec(url.pathname);+ const who = await adapter.authenticate(req, { board: route?.[1] ?? null, write: req.method === 'POST' });+ if (req.method === 'GET' && url.pathname === '/api/v1/boards') return json(res, 200, { boards: await adapter.boards(who) });+ if (!route) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, events, moves or requests path')));+ const board = await adapter.board(route[1], who);+ if (req.method === 'GET' && route[2] === 'state') return json(res, 200, { state: await adapter.state(board, who) });+ 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);+ return json(res, 200, { events: initial });+ }+ if (req.method === 'POST' && route[2] === 'moves') {+ const moved = await adapter.move(board, await readBody(req), who);+ return json(res, moved.status, moved.body);+ }+ if (req.method === 'POST' && route[2] === 'requests') return json(res, 200, await adapter.request(board, await readBody(req), who));+ return json(res, 400, refusal(new Refused('BAD_REQUEST', 'use GET for reads and POST for moves and requests')));+ } catch (error) {+ const status = { AUTH_REQUIRED: 401, TOKEN_BOARD: 403, API_ORIGIN: 403, WRITE_REQUIRED: 403, NO_BOARD: 404, BOARD_NOT_LINKED: 404 }[error.code] ?? (error instanceof Refused ? 400 : 500);+ if (!res.headersSent) json(res, status, refusal(error));+ else res.end();+ }+ }+ handle.close = () => { for (const res of streams) res.end(); };+ return handle;+}diff --git a/src/api.js b/src/api.jsindex a521dc57..c7e4ab97 100644--- a/src/api.js+++ b/src/api.js@@ -10,58 +10,39 @@ import { laneNames } from './lanes.js';import { listProjects } from './projects.js';import { Refused } from './refused.js';import { projectState } from './serve.js';+import { createApiHandler } from './api-http.js';const ADDRESS = '127.0.0.1';const VERSION = 1;-const BODY_BYTES = 100_000;/** Read a registered board and release its SQLite connection on every path. */function withBoard(root, read) {const info = repoInfo(root);+ loadConfig(info.root);const board = store.openBoard(join(info.commonDir, 'pullboard', 'board.sqlite'));try { return read(board, info); } finally { store.closeBoard(board); }}/** Registered boards carry one persistent identity across local and relay addresses. */-export function apiBoards() {- return listProjects().map((project) => withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) })));+export function apiBoards(projects = listProjects) {+ return projects().flatMap((project) => {+ try { return [withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) }))]; }+ catch { return []; }+ });}/** Resolve only registered boards, so a request cannot open an arbitrary path on the machine. */-function findBoard(id) {- const board = apiBoards().find((entry) => entry.id === id);+function findBoard(id, projects) {+ const board = apiBoards(projects).find((entry) => entry.id === id);if (!board) throw new Refused('NO_BOARD', `no registered board ${id}; run pullboard serve in its repo and use GET /api/v1/boards`);return board;}-/** A decimal event cursor never skips records through coercion or unsafe integer rounding. */-function eventCursor(value) {- if (value === null || value === undefined || value === '') return 0;- if (!/^\d+$/.test(String(value)) || !Number.isSafeInteger(Number(value))) throw new Refused('BAD_CURSOR', 'after and Last-Event-ID need a nonnegative integer; use the last event id received');- return Number(value);-}-/** Read events in sequence, including changes made by other processes on the same board. */function afterEvents(root, after) {return withBoard(root, (board) => board.db.prepare('SELECT * FROM event WHERE event_id > ? ORDER BY event_id').all(after));}-/** Only JSON objects within the byte limit may become move arguments. */-async function readBody(req) {- if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new Refused('BAD_REQUEST', 'send an application/json object as the request body');- const chunks = [];- let size = 0;- for await (const chunk of req) {- size += chunk.length;- if (size > BODY_BYTES) throw new Refused('BAD_REQUEST', `the body exceeds ${BODY_BYTES} bytes; send one move or request at a time`);- chunks.push(chunk);- }- let body;- try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { throw new Refused('BAD_REQUEST', 'the body is not JSON; send an application/json object'); }- if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Refused('BAD_REQUEST', 'the body needs a JSON object; send one move or request at a time');- return body;-}-/** Resolve an authenticated local caller's agent to its own checkout, never another board. */function agentPath(root, name = COORDINATOR) {if (typeof name !== 'string' || !name) throw new Refused('BAD_REQUEST', 'agent needs a registered name; omit it to act as the coordinator');@@ -163,72 +144,35 @@ function createRequest(root, body) {});}-/** Keep an event stream open and resume from either supported cursor, releasing it on disconnect. */-function streamEvents(root, after, res, streams) {- res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-store', connection: 'keep-alive', 'x-content-type-options': 'nosniff' });- res.write(': API v1\n\n');- let cursor = after;- const send = () => {- try {- for (const event of afterEvents(root, cursor)) {- res.write(`id: ${event.event_id}\ndata: ${JSON.stringify({ version: VERSION, event })}\n\n`);- cursor = event.event_id;- }- } catch (error) {- res.write(`event: error\ndata: ${JSON.stringify(refusalDocument(error))}\n\n`);- res.end();- }- };- const timer = setInterval(send, 200);- timer.unref();- streams.add(res);- res.once('close', () => { clearInterval(timer); streams.delete(res); });- send();-}-/** Serve the RFC 0002 API only on loopback, behind the same session-secret boundary as the view. */-export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand } = {}) {+export function serveApi({ port = 0, secret = randomBytes(18).toString('base64url'), runCommand, projects = listProjects } = {}) {if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');const key = Buffer.from(secret);- const streams = new Set();let bound;- const json = (res, status, body) => {- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' });- res.end(JSON.stringify(body));- };- const server = createServer(async (req, res) => {- try {- const url = new URL(req.url ?? '/', `http://${ADDRESS}`);+ const handler = createApiHandler({+ authenticate: (req) => {+ const url = new URL(req.url ?? '/', 'http://' + ADDRESS);const authorization = String(req.headers.authorization ?? '');const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? (authorization.startsWith('Bearer ') ? authorization.slice(7) : url.searchParams.get('k') ?? '')));- const ownHost = req.headers.host === `${ADDRESS}:${bound}` || req.headers.host === `localhost:${bound}`;- if (!ownHost || given.length !== key.length || !timingSafeEqual(given, key)) return json(res, 401, refusalDocument(new Refused('AUTH_REQUIRED', 'this API needs its session secret and own host; use the address pullboard serve printed')));- if (req.method === 'GET' && url.pathname === '/api/v1/boards') return json(res, 200, { version: VERSION, boards: apiBoards() });- const route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests)$/.exec(url.pathname);- if (!route) return json(res, 404, refusalDocument(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, events, moves or requests path')));- const board = findBoard(route[1]);- if (req.method === 'GET' && route[2] === 'state') {- const state = projectState(board.root);- state.requests = withBoard(board.root, (db) => store.openRequests(db));- return json(res, 200, { version: VERSION, state });- }- if (req.method === 'GET' && route[2] === 'events') {- const after = eventCursor(req.headers['last-event-id'] ?? url.searchParams.get('after'));- if (String(req.headers.accept ?? '').includes('text/event-stream')) return streamEvents(board.root, after, res, streams);- return json(res, 200, { version: VERSION, events: afterEvents(board.root, after) });- }- if (req.method === 'POST' && route[2] === 'moves') {- const moved = await executeMove(board.root, await readBody(req), runCommand);- return json(res, moved.status, moved.body);- }- if (req.method === 'POST' && route[2] === 'requests') return json(res, 200, createRequest(board.root, await readBody(req)));- return json(res, 400, refusalDocument(new Refused('BAD_REQUEST', `use the documented method for ${route[2]}; reads use GET and moves and requests use POST`)));- } catch (error) {- const status = error.code === 'NO_BOARD' ? 404 : error instanceof Refused ? 400 : 500;- if (!res.headersSent) json(res, status, refusalDocument(error));- else res.end();- }+ const ownHost = req.headers.host === ADDRESS + ':' + bound || req.headers.host === 'localhost:' + bound;+ if (!ownHost || given.length !== key.length || !timingSafeEqual(given, key)) throw new Refused('AUTH_REQUIRED', 'this API needs its session secret and own host; use the address pullboard serve printed');+ if (req.headers.origin && req.headers.origin !== 'http://' + req.headers.host) throw new Refused('API_ORIGIN', 'use the API from its own origin');+ return { local: true };+ },+ boards: () => apiBoards(projects),+ board: (id) => findBoard(id, projects),+ state: (board) => {+ const state = projectState(board.root);+ state.board = board.id;+ state.requests = withBoard(board.root, (db) => store.openRequests(db));+ return state;+ },+ events: (board, after) => afterEvents(board.root, after),+ move: (board, body) => executeMove(board.root, body, runCommand),+ request: (board, body) => createRequest(board.root, body),});+ const server = createServer(handler);+ server.requestTimeout = 15_000;return new Promise((ready, fail) => {server.once('error', (error) => fail(new Refused(error.code === 'EADDRINUSE' ? 'PORT_BUSY' : 'API_LISTEN', `cannot listen on ${ADDRESS}:${port}: ${error.message}; run pullboard serve --port 0 to choose a free port`)));server.listen(port, ADDRESS, () => {@@ -236,7 +180,7 @@ export function serveApi({ port = 0, secret = randomBytes(18).toString('base64urready({url: `http://${ADDRESS}:${bound}/api/v1/boards?k=${secret}`,port: bound,- close: () => new Promise((closed) => { for (const stream of streams) stream.end(); server.close(() => closed()); server.closeIdleConnections(); }),+ close: () => new Promise((closed) => { handler.close(); server.close(() => closed()); server.closeIdleConnections(); }),});});});diff --git a/test/api-http.test.js b/test/api-http.test.jsnew file mode 100644index 00000000..11df37cd--- /dev/null+++ b/test/api-http.test.js@@ -0,0 +1,282 @@+/** Real HTTP calls against an isolated Git repo and the actual board engine (A2). */+import assert from 'node:assert/strict';+import { execFileSync, spawnSync } from 'node:child_process';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { createServer, request as httpRequest } from 'node:http';+import { join, resolve } from 'node:path';+import { test } from 'node:test';+import { serveApi } from '../src/api.js';+import { main } from '../src/cli.js';+import { createApiHandler } from '../src/api-http.js';+import { Refused } from '../src/refused.js';+import * as store from '../src/board.js';++const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');++/** Quote an executable path literally for the fixture's source-bin hook shim. */+function shellWord(value) {+ return "'" + value.replace(/'/g, "'\\''") + "'";+}++/** Create a private, committed project, with an exact-build hook shim and no personal Git config. */+function fixture(t) {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-http-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const root = join(dir, 'repo');+ const bin = join(dir, 'bin');+ mkdirSync(root);+ mkdirSync(bin);+ writeFileSync(join(bin, 'pullboard'), `#!/bin/sh\nexec ${shellWord(process.execPath)} ${shellWord(BIN)} "$@"\n`);+ chmodSync(join(bin, 'pullboard'), 0o755);+ const env = {+ ...process.env, HOME: join(dir, 'home'), PULLBOARD_HOME: join(dir, 'home'),+ PATH: bin + ':' + process.env.PATH, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'HTTP Agent', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'HTTP Agent', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ mkdirSync(env.HOME);+ /** Run Git only inside the private fixture. */+ const git = (...args) => execFileSync('git', args, { cwd: root, env, stdio: 'pipe', encoding: 'utf8' });+ /** Exercise this worktree's real CLI with a private environment. */+ const run = (cwd, ...args) => spawnSync(process.execPath, [BIN, ...args], { cwd, env, encoding: 'utf8' });+ /** Decode one successful versioned CLI invocation without printing session links. */+ function cli(cwd, ...args) {+ const result = run(cwd, ...args, '--json');+ assert.equal(result.status, 0, result.stderr);+ return JSON.parse(result.stdout);+ }+ git('init', '-q', '-b', 'main');+ cli(root, 'init');+ const config = JSON.parse(readFileSync(join(root, 'pullboard.json'), 'utf8'));+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ ...config, gate: 'true', lanes: { app: { owns: ['app/'] }, review: { owns: [] } } }));+ writeFileSync(join(root, 'SPEC.md'), '# HTTP fixture\n\n## Goals\n- G1 [approved, must] Keep the board. | gate: true\n');+ writeFileSync(join(root, 'PRACTICE.md'), '');+ git('add', '-A');+ git('commit', '-q', '-m', 'chore: private HTTP fixture');+ return { root, dir, cli, run };+}++/** Serve this fixture's explicit project, avoiding any registry outside its private home. */+async function httpBox(t, { includeMissing = false } = {}) {+ const box = fixture(t);+ const api = await serveApi({ runCommand: main, projects: () => [...(includeMissing ? [{ root: join(box.dir, 'gone'), name: 'Missing fixture' }] : []), { root: box.root, name: 'HTTP fixture' }] });+ t.after(() => api.close());+ const url = new URL(api.url);+ const key = url.searchParams.get('k');+ const origin = url.origin;+ /** Make a real HTTP call and decode its single versioned response. */+ async function call(path, value, headers = {}) {+ const response = await fetch(origin + path, {+ method: value === undefined ? 'GET' : 'POST',+ headers: { 'x-pullboard-key': key, ...(value === undefined ? {} : { 'content-type': 'application/json' }), ...headers },+ ...(value === undefined ? {} : { body: JSON.stringify(value) }),+ });+ const document = await response.json();+ assert.equal(document.version, 1);+ return { status: response.status, document };+ }+ 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.match(id, /^[0-9a-f]{32}$/);+ return { ...box, api, origin, key, id, call, path: '/api/v1/boards/' + id };+}++test('[A2] a stale registered folder does not hide another readable board', async (t) => {+ const box = await httpBox(t, { includeMissing: true });+ const state = await box.call(box.path + '/state');+ assert.equal(state.status, 200);+ assert.equal(state.document.state.board, box.id);+});++test('[A2] real HTTP state, moves and refusals use the CLI and exact committed events', async (t) => {+ const box = await httpBox(t);+ const one = box.cli(box.root, 'worktree', 'app');+ const two = box.cli(box.root, 'worktree', 'app');+ const added = await box.call(box.path + '/moves', { verb: 'add', args: { lane: 'app', title: 'HTTP item', criterion: 'complete', specs: 'G1' } });+ assert.equal(added.status, 200);+ assert.equal(added.document.event.event_kind, 'add');+ const id = added.document.result.item.item_id;+ const claimed = await box.call(box.path + '/moves', { verb: 'claim', item: id, agent: one.agent });+ assert.equal(claimed.status, 200);+ assert.equal(claimed.document.event.event_by, one.agent);+ assert.equal(claimed.document.event.event_kind, 'claim');+ const refused = await box.call(box.path + '/moves', { verb: 'claim', item: id, agent: two.agent });+ const terminal = box.run(two.path, 'claim', String(id), '--json');+ assert.equal(refused.status, 409);+ assert.equal(terminal.status, 1);+ assert.equal(refused.document.error.code, JSON.parse(terminal.stdout).error.code);+ assert.deepEqual(refused.document.error, JSON.parse(terminal.stdout).error, 'the original CLI refusal keeps its message and next step');+ const state = await box.call(box.path + '/state');+ assert.equal(state.document.state.board, box.id);+ assert.equal(state.document.state.items.find((item) => item.id === id).owner, one.agent);+ const events = await box.call(box.path + '/events?after=' + added.document.event.event_id);+ assert.deepEqual(events.document.events, [claimed.document.event]);+ const badAgent = await box.call(box.path + '/moves', { verb: 'release', item: id, agent: 'absent-agent' });+ assert.equal(badAgent.status, 409);+ assert.equal(badAgent.document.error.code, 'NO_AGENT');+});++test('[A2, H12, R2] requests and shouts append events and requests stay outside decisions', async (t) => {+ const box = await httpBox(t);+ const requested = await box.call(box.path + '/requests', { text: 'Please approve the fixture row.' });+ assert.equal(requested.status, 200);+ assert.equal(requested.document.result.request, true);+++ assert.equal(requested.document.event.event_kind, 'shout');+ const shout = await box.call(box.path + '/moves', { verb: 'shout', args: { to: 'app', text: 'new work' } });+ assert.equal(shout.document.event.event_kind, 'shout');+ const state = await box.call(box.path + '/state');+ assert.equal(state.document.state.requests.length, 1);+ assert.equal(state.document.state.decisions.length, 0);+ const premature = await box.call(box.path + '/moves', { verb: 'answer', item: requested.document.result.id, args: { text: 'I am working on it' } });+ assert.equal(premature.status, 409);+ assert.equal(premature.document.error.code, 'REQUEST_OUTCOME');+ assert.equal((await box.call(box.path + '/state')).document.state.requests.length, 1);+ const answer = await box.call(box.path + '/moves', { verb: 'answer', item: requested.document.result.id, args: { text: 'done checked and recorded' } });+ assert.equal(answer.status, 200);+ assert.equal(answer.document.event.event_kind, 'answer');+ assert.equal((await box.call(box.path + '/state')).document.state.requests.length, 0);+});++test('[A2] a live HTTP stream follows CLI writes and reconnects after Last-Event-ID', async (t) => {+ const box = await httpBox(t);+ const initial = await box.call(box.path + '/events');+ const after = initial.document.events.at(-1).event_id;+ const controller = new AbortController();+ const response = await fetch(box.origin + box.path + '/events?after=' + after, { headers: { 'x-pullboard-key': box.key, accept: 'text/event-stream' }, signal: controller.signal });+ assert.match(response.headers.get('content-type'), /text\/event-stream/);+ const reader = response.body.getReader();+ let buffered = '';+ /** Read a complete live event with a bounded timeout. */+ async function frame() {+ const timeout = setTimeout(() => controller.abort(), 10_000);+ try {+ while (!/\ndata: .+\n\n/.test(buffered)) {+ const { value, done } = await reader.read();+ assert.equal(done, false, 'stream stays open until its event arrives');+ buffered += new TextDecoder().decode(value);+ }+ const match = /id: (\d+)\ndata: (.+)\n\n/.exec(buffered);+ assert.ok(match);+ buffered = buffered.slice(match.index + match[0].length);+ return { id: Number(match[1]), document: JSON.parse(match[2]) };+ } finally { clearTimeout(timeout); }+ }+ const added = box.cli(box.root, 'add', 'app', 'Terminal event', '--criterion', 'done', '--specs', 'G1');+ const live = await frame();+ assert.equal(live.document.version, 1);+ assert.equal(live.document.event.event_kind, 'add');+ assert.equal(live.document.event.item_id, added.item.item_id);+ assert.equal(live.id, live.document.event.event_id);+ await reader.cancel();+ controller.abort();+ const replay = await fetch(box.origin + box.path + '/events?after=0', { headers: { 'x-pullboard-key': box.key, 'last-event-id': String(live.id) } });+ assert.deepEqual((await replay.json()).events, []);+ const invalid = await box.call(box.path + '/events?after=1.5');+ assert.equal(invalid.status, 400);+ assert.equal(invalid.document.error.code, 'BAD_CURSOR');+});++test('[A2] local auth, origin, unknown board and malformed calls refuse without moving', async (t) => {+ const box = await httpBox(t);+ const unauthenticated = await fetch(box.origin + '/api/v1/boards');+ assert.equal(unauthenticated.status, 401);+ assert.equal((await unauthenticated.json()).error.code, 'AUTH_REQUIRED');+ const badSecret = await box.call('/api/v1/boards', undefined, { 'x-pullboard-key': 'incorrect-private-fixture-key' });+ assert.equal(badSecret.status, 401);+ const badOrigin = await box.call(box.path + '/requests', { text: 'blocked' }, { origin: 'https://different.invalid' });+ assert.equal(badOrigin.status, 403);+ const unknown = await box.call('/api/v1/boards/' + '0'.repeat(32) + '/state');+ assert.equal(unknown.status, 404);+ const unknownStream = await box.call('/api/v1/boards/' + '0'.repeat(32) + '/events', undefined, { accept: 'text/event-stream' });+ assert.equal(unknownStream.status, 404);+ const malformed = await fetch(box.origin + box.path + '/moves', { method: 'POST', headers: { 'x-pullboard-key': box.key, 'content-type': 'application/json' }, body: '{broken' });+ assert.equal(malformed.status, 400);+ assert.equal((await malformed.json()).error.code, 'BAD_REQUEST');+ const unsupported = await box.call(box.path + '/moves', { verb: 'run', args: { agent: 'unsafe' } });+ assert.equal(unsupported.status, 400);+ assert.equal(unsupported.document.error.code, 'BAD_REQUEST');+ const state = await box.call(box.path + '/state');+ assert.deepEqual(state.document.state.items, []);+ assert.deepEqual(state.document.state.requests, []);+});++test('[A2] move text stays literal and invalid bodies cannot produce a partial event', async (t) => {+ const box = await httpBox(t);+ const literal = await box.call(box.path + '/moves', { verb: 'shout', args: { to: 'app', text: '--help' } });+ assert.equal(literal.status, 200);+ assert.equal(literal.document.event.event_kind, 'shout');+ const state = await box.call(box.path + '/state');+ assert.equal(state.document.state.shouts.at(-1).shout_text, '--help');+ const oversized = await box.call(box.path + '/requests', { text: 'x'.repeat(110_000) });+ assert.equal(oversized.status, 400);+ assert.equal(oversized.document.error.code, 'BAD_REQUEST');+ const wrongType = await box.call(box.path + '/requests', { text: 'refused' }, { 'content-type': 'text/plain' });+ assert.equal(wrongType.status, 400);+ const wrongHost = await new Promise((done, reject) => {+ const request = httpRequest(box.origin + '/api/v1/boards', { headers: { host: 'foreign.invalid', 'x-pullboard-key': box.key } }, (response) => {+ let text = '';+ response.on('data', (chunk) => { text += chunk; });+ response.on('end', () => done({ status: response.statusCode, document: JSON.parse(text) }));+ });+ request.on('error', reject);+ request.end();+ });+ assert.equal(wrongHost.status, 401);+ assert.equal(wrongHost.document.error.code, 'AUTH_REQUIRED');+ const after = await box.call(box.path + '/state');+ assert.deepEqual(after.document.state.events, state.document.state.events);+ assert.deepEqual(after.document.state.requests, []);+});++test('[A2] shared transport stops a live stream when its caller loses access', async (t) => {+ const box = fixture(t);+ const file = join(box.root, '.git', 'pullboard', 'board.sqlite');+ let authorized = true;+ let checks = 0;+ /** Read this fixture's real event records and always close its connection. */+ function records(after = 0) {+ const board = store.openBoard(file);+ try { return store.events(board).filter((event) => event.event_id > after); }+ finally { store.closeBoard(board); }+ }+ const board = store.openBoard(file);+ const id = store.boardId(board);+ store.closeBoard(board);+ const handler = createApiHandler({+ authenticate: () => {+ checks += 1;+ if (!authorized) throw new Refused('AUTH_REQUIRED', 'the fixture session was revoked; sign in again');+ return { user: 'fixture-user' };+ },+ board: () => ({ id }),+ events: (known, after) => records(after),+ }, { pollMs: 20 });+ const server = createServer(handler);+ await new Promise((done) => server.listen(0, '127.0.0.1', done));+ t.after(() => new Promise((done) => { handler.close(); server.close(done); server.closeIdleConnections(); }));+ const controller = new AbortController();+ t.after(() => controller.abort());+ const timeout = setTimeout(() => controller.abort(), 10_000);+ t.after(() => clearTimeout(timeout));+ const response = await fetch('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/events?after=' + records().at(-1).event_id, { headers: { accept: 'text/event-stream' }, signal: controller.signal });+ const reader = response.body.getReader();+ await reader.read();+ authorized = false;+ box.cli(box.root, 'add', 'app', 'Hidden after revocation', '--criterion', 'complete', '--specs', 'G1');+ let text = '';+ while (true) {+ const { value, done } = await reader.read();+ if (done) break;+ text += new TextDecoder().decode(value);+ }+ assert.match(text, /event: error/);+ assert.match(text, /"version":1/);+ assert.match(text, /"code":"AUTH_REQUIRED"/);+ assert.doesNotMatch(text, /"event_kind":"add"/);+ assert.ok(checks >= 3, 'access is checked at entry and on live polls');+});