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(core): extend shared local api [A2,A3]
Corey Olson26e5169df863
diff --git a/docs/api.md b/docs/api.mdindex 40a88392..bb2a2d29 100644--- a/docs/api.md+++ b/docs/api.md@@ -97,16 +97,19 @@ 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.+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 does not hide readable boards: it appears in `warnings` with its registry display fields and a versioned refusal whose `next` field explains how to restore or forget it.| Method and path | Result || --- | --- || `GET /api/v1/boards` | Registered boards with their project details and ids |-| `GET /api/v1/boards/:board/state` | The view's board state, including open coordinator requests |+| `GET /api/v1/boards/:board/state?seen=N` | The view's board state, including open coordinator requests and the unseen shout count since N |+| `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 || `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 |+The boards response keeps `boards` and may include `warnings` for registered entries that could not be opened. State `seen` must be a nonnegative safe integer; omitting it retains the `unseen: null` result. Code previews read only a registered repo's committed tree, use a plain commit SHA and at most 60 lines, and never read the working tree. The shared router lets adapters omit the optional code capability; such adapters return the versioned `CODE_NOT_AVAILABLE` refusal.+<!-- api-http-shapes:start -->| Response | Required top-level fields || --- | --- |diff --git a/docs/api.test.js b/docs/api.test.jsindex 3aeb31d9..569b93a3 100644--- a/docs/api.test.js+++ b/docs/api.test.js@@ -43,4 +43,8 @@ test('[A2] API guide documents the local HTTP response catalog', () => {const documented = readShapeTable('<!-- api-http-shapes:start -->', '<!-- api-http-shapes:end -->');const source = Object.fromEntries(Object.entries(JSON_SHAPES.http).map(([name, shape]) => [name, shape.required]));assert.deepEqual(documented, source);+ assert.match(guide, /`warnings` with its registry display fields and a versioned refusal/);+ 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/);});diff --git a/src/api-http.js b/src/api-http.jsindex a6b5c767..02483780 100644--- a/src/api-http.js+++ b/src/api-http.js@@ -38,6 +38,12 @@ function eventCursor(value) {return Number(value);}+/** A supplied state cursor is an integer, so unlike an omitted events cursor, blank is invalid. */+function seenCursor(value) {+ if (value === '') throw new Refused('BAD_CURSOR', 'seen needs a nonnegative integer; use the last shout id you have seen');+ return eventCursor(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');@@ -90,12 +96,25 @@ export function createApiHandler(adapter, { pollMs = 200 } = {}) {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 route = /^\/api\/v1\/boards\/([^/]+)\/(state|events|moves|requests|code)$/.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')));+ if (req.method === 'GET' && url.pathname === '/api/v1/boards') {+ const listing = await adapter.boards(who);+ return json(res, 200, Array.isArray(listing) ? { boards: listing } : listing);+ }+ if (!route) return json(res, 404, refusal(new Refused('NO_ENDPOINT', 'no API v1 endpoint here; use /api/v1/boards and a board state, code, 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] === 'state') {+ const seen = url.searchParams.has('seen') ? seenCursor(url.searchParams.get('seen')) : null;+ return json(res, 200, { state: await adapter.state(board, who, seen) });+ }+ if (req.method === 'GET' && route[2] === 'code') {+ if (typeof adapter.code !== 'function') throw new Refused('CODE_NOT_AVAILABLE', 'this API adapter does not provide committed-code previews; use the local view or a local API server');+ const ref = /^([^:@]+):(\d+)(?:-(\d+))?@([0-9a-f]{7,40})$/.exec(url.searchParams.get('ref') ?? '');+ if (!ref) throw new Refused('BAD_REF', 'use ref=path:lines@commit, such as src/serve.js:12-30@be4356b');+ const before = (url.searchParams.get('before') ?? '').slice(-2000);+ return json(res, 200, { code: await adapter.code(board, { path: ref[1], from: Number(ref[2]), to: Number(ref[3] ?? ref[2]), commit: ref[4], before }, 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);diff --git a/src/api.js b/src/api.jsindex c7e4ab97..9bd65d90 100644--- a/src/api.js+++ b/src/api.js@@ -1,5 +1,6 @@/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */import { randomBytes, timingSafeEqual } from 'node:crypto';+import { readFileSync } from 'node:fs';import { createServer } from 'node:http';import { join } from 'node:path';import * as store from './board.js';@@ -7,14 +8,24 @@ import { COORDINATOR, loadConfig } from './config.js';import { repoInfo } from './git.js';import { refusalDocument } from './json.js';import { laneNames } from './lanes.js';-import { listProjects } from './projects.js';+import { listProjects, registryFile } from './projects.js';import { Refused } from './refused.js';-import { projectState } from './serve.js';+import { codeAt, projectState } from './serve.js';import { createApiHandler } from './api-http.js';const ADDRESS = '127.0.0.1';const VERSION = 1;+/** Read registry entries without pruning stale roots so the API can report them as warnings. */+function registeredProjects() {+ try {+ const entries = JSON.parse(readFileSync(registryFile(), 'utf8')).projects;+ return Array.isArray(entries) ? entries.filter((project) => typeof project?.root === 'string') : [];+ } catch {+ return [];+ }+}+/** Read a registered board and release its SQLite connection on every path. */function withBoard(root, read) {const info = repoInfo(root);@@ -31,6 +42,21 @@ export function apiBoards(projects = listProjects) {});}+/** List readable registered boards and retain actionable warnings for entries that failed to open. */+function apiBoardListing(projects = registeredProjects) {+ const boards = [];+ const warnings = [];+ for (const project of projects()) {+ try {+ boards.push(withBoard(project.root, (board) => ({ ...project, id: store.boardId(board) })));+ } catch {+ const error = new Refused('BOARD_UNAVAILABLE', `registered project ${project.root} cannot be read; restore the repo or run pullboard forget ${project.root}`);+ warnings.push({ ...project, error: refusalDocument(error) });+ }+ }+ return { boards, warnings };+}+/** Resolve only registered boards, so a request cannot open an arbitrary path on the machine. */function findBoard(id, projects) {const board = apiBoards(projects).find((entry) => entry.id === id);@@ -144,33 +170,42 @@ function createRequest(root, body) {});}-/** 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, projects = listProjects } = {}) {- if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');+/** Create the authenticated local adapter used by the HTTP server and other local transports. */+export function createLocalApiHandler({ secret, getPort, runCommand, projects = registeredProjects } = {}) {+ if (typeof getPort !== 'function') throw new TypeError('createLocalApiHandler needs a bound-port getter');+ if (typeof runCommand !== 'function') throw new TypeError('createLocalApiHandler needs the actual CLI entry point as runCommand');const key = Buffer.from(secret);- let bound;- const handler = createApiHandler({+ return 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 bound = getPort();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),+ boards: () => apiBoardListing(projects),board: (id) => findBoard(id, projects),- state: (board) => {- const state = projectState(board.root);+ state: (board, who, seen) => {+ const state = projectState(board.root, { seen });state.board = board.id;state.requests = withBoard(board.root, (db) => store.openRequests(db));return state;},+ code: (board, ref) => codeAt(board.root, ref),events: (board, after) => afterEvents(board.root, after),move: (board, body) => executeMove(board.root, body, runCommand),request: (board, body) => createRequest(board.root, body),});+}++/** 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, projects = registeredProjects } = {}) {+ if (typeof runCommand !== 'function') throw new TypeError('serveApi needs the actual CLI entry point as runCommand');+ let bound;+ const handler = createLocalApiHandler({ secret, getPort: () => bound, runCommand, projects });const server = createServer(handler);server.requestTimeout = 15_000;return new Promise((ready, fail) => {diff --git a/test/api-http.test.js b/test/api-http.test.jsindex 11df37cd..54f3261d 100644--- a/test/api-http.test.js+++ b/test/api-http.test.js@@ -54,7 +54,7 @@ function fixture(t) {writeFileSync(join(root, 'PRACTICE.md'), '');git('add', '-A');git('commit', '-q', '-m', 'chore: private HTTP fixture');- return { root, dir, cli, run };+ return { root, dir, cli, run, commit: git('rev-parse', 'HEAD').trim() };}/** Serve this fixture's explicit project, avoiding any registry outside its private home. */@@ -86,11 +86,49 @@ async function httpBox(t, { includeMissing = false } = {}) {test('[A2] a stale registered folder does not hide another readable board', async (t) => {const box = await httpBox(t, { includeMissing: true });+ const listed = await box.call('/api/v1/boards');+ assert.equal(listed.document.boards.length, 1);+ assert.equal(listed.document.warnings.length, 1);+ assert.equal(listed.document.warnings[0].name, 'Missing fixture');+ assert.equal(listed.document.warnings[0].error.version, 1);+ assert.equal(listed.document.warnings[0].error.error.code, 'BOARD_UNAVAILABLE');+ assert.match(listed.document.warnings[0].error.error.next, /pullboard forget/);const state = await box.call(box.path + '/state');assert.equal(state.status, 200);assert.equal(state.document.state.board, box.id);});+test('[A2] local HTTP state accepts a safe seen cursor and committed code previews', async (t) => {+ const box = await httpBox(t);+ box.cli(box.root, 'shout', 'app', 'state cursor baseline');+ const before = await box.call(box.path + '/state');+ const seen = before.document.state.shouts.at(-1).shout_id;+ box.cli(box.root, 'shout', 'app', 'state cursor event');+ const state = await box.call(box.path + '/state?seen=' + seen);+ assert.equal(state.document.state.unseen.since, seen);+ assert.equal(state.document.state.unseen.count, 1);+ const missing = await box.call(box.path + '/state');+ assert.equal(missing.document.state.unseen, null);+ for (const cursor of ['', '-1', '1.5', '9007199254740992']) {+ const invalid = await box.call(box.path + '/state?seen=' + cursor);+ assert.equal(invalid.status, 400);+ assert.equal(invalid.document.error.code, 'BAD_CURSOR');+ }++ writeFileSync(join(box.root, 'SPEC.md'), '# changed working tree\n');+ const preview = await box.call(box.path + '/code?ref=' + encodeURIComponent('SPEC.md:1-4@' + box.commit) + '&before=' + encodeURIComponent('Please inspect '));+ assert.equal(preview.status, 200);+ assert.deepEqual(preview.document.code.lines, ['# HTTP fixture', '', '## Goals', '- G1 [approved, must] Keep the board. | gate: true']);+ assert.equal(preview.document.code.path, 'SPEC.md');+ assert.equal(preview.document.code.from, 1);+ assert.equal(preview.document.code.to, 4);+ for (const ref of ['../outside:1@' + box.commit, 'SPEC.md:0@' + box.commit, 'SPEC.md:1@HEAD']) {+ const invalid = await box.call(box.path + '/code?ref=' + encodeURIComponent(ref));+ assert.equal(invalid.status, 400);+ assert.ok(['BAD_REF', 'NO_COMMIT'].includes(invalid.document.error.code));+ }+});+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');@@ -280,3 +318,23 @@ test('[A2] shared transport stops a live stream when its caller loses access', aassert.doesNotMatch(text, /"event_kind":"add"/);assert.ok(checks >= 3, 'access is checked at entry and on live polls');});++test('[A2] adapters without a committed-code capability return a versioned refusal', async (t) => {+ const handler = createApiHandler({+ authenticate: () => ({ user: 'fixture-user' }),+ boards: () => [],+ board: (id) => ({ id }),+ state: () => ({}),+ events: () => [],+ });+ 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); }));+ const id = 'fixture-board';+ const response = await fetch('http://127.0.0.1:' + server.address().port + '/api/v1/boards/' + id + '/code?ref=secret.txt%3A1%40abcdef0');+ const document = await response.json();+ assert.equal(response.status, 400);+ assert.equal(document.version, 1);+ assert.equal(document.error.code, 'CODE_NOT_AVAILABLE');+ assert.match(document.error.next, /local view|local API/);+});