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(view): use the public API for reads and moves [A3,N26,N27]

Corey Olsonb349482dffb7
diff --git a/src/cockpit.js b/src/cockpit.js
index 6f6b8413..8fd2337b 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -406,17 +406,78 @@ function flowSvg(p) {
return '<svg viewBox="0 0 ' + W + ' ' + f(H) + '" role="img" aria-label="The item lifecycle, with counts from this board"><defs>' + head('pb-head', '') + head('pb-head-back', 'back') + '</defs>' + routes.join('') + boxes.join('') + '</svg>';
}
+/** Read or move through API v1, retaining the rule and repair guidance in a refusal. */
async function api(path, body) {
const res = await fetch(path, { method: body ? 'POST' : 'GET', headers: { 'x-pullboard-key': key, ...(body ? { 'content-type': 'application/json' } : {}) }, body: body ? JSON.stringify(body) : undefined });
const json = await res.json();
- if (!res.ok) throw new Error(json.error || res.status);
+ if (!res.ok) {
+ const refusal = json.error;
+ const message = refusal && typeof refusal === 'object' ? '[' + refusal.code + '] ' + refusal.message : refusal || res.status;
+ throw new Error(message);
+ }
return json;
}
+/** A board's sidebar counts, derived from the same API state the page displays. */
+function boardSummary(board, state) {
+ /** Count one item state for the sidebar. */
+ const count = (test) => state.items.filter(test).length;
+ return {
+ ...board, ok: true,
+ building: count((item) => item.status === 'claimed'),
+ awaiting: count((item) => item.status === 'submitted'),
+ sentBack: count((item) => item.status === 'open' && item.verdict && item.verdict.decision === 'REJECT'),
+ open: count((item) => item.status === 'open'),
+ verified: count((item) => item.status === 'verified'),
+ pending: state.spec.filter((row) => row.status === 'pending').length,
+ drafts: state.spec.filter((row) => row.status === 'draft').length,
+ holds: state.holds.length,
+ decisions: state.decisions.length,
+ };
+}
+
+/** Resolve a displayed repo to the persistent board identity supplied by API v1. */
+function boardPath(root) {
+ const board = data && data.projects.find((entry) => entry.root === root && entry.ok);
+ if (!board) throw new Error('This board is unavailable; choose a readable project and retry.');
+ return '/api/v1/boards/' + encodeURIComponent(board.id);
+}
+
+/** Compose the multi-repo page from the public board list and each board's public state. */
+async function boardState(root, mark) {
+ const listed = await api('/api/v1/boards');
+ const states = new Map();
+ const cursor = mark !== null && mark !== undefined && /^\\d+$/.test(String(mark)) && Number.isSafeInteger(Number(mark)) ? Number(mark) : null;
+ const projects = await Promise.all(listed.boards.map(async (board) => {
+ try {
+ const query = board.root === root && cursor !== null ? '?seen=' + encodeURIComponent(cursor) : '';
+ const reply = await api('/api/v1/boards/' + encodeURIComponent(board.id) + '/state' + query);
+ states.set(board.root, reply.state);
+ return boardSummary(board, reply.state);
+ } catch (error) {
+ return { ...board, ok: false, error: String(error.message || error) };
+ }
+ }));
+ projects.push(...(listed.warnings || []).map((warning) => ({ ...warning, ok: false, error: warning.error.error.message })));
+ const grouped = new Map();
+ for (const project of projects) {
+ if (!project.project) continue;
+ if (!grouped.has(project.project)) grouped.set(project.project, []);
+ grouped.get(project.project).push(project);
+ }
+ const groups = [...grouped].map(([name, repos]) => ({ name, key: 'group:' + name, repos }));
+ const group = groups.find((entry) => entry.key === root);
+ return {
+ projects, groups, project: states.get(root) || null,
+ group: group ? { name: group.name, repos: group.repos.filter((repo) => repo.ok).map((repo) => ({ root: repo.root, name: repo.name, board: states.get(repo.root) })) } : null,
+ };
+}
+
+/** Refresh from API v1 and discard a response for a project the person already left. */
async function refresh() {
const root = view.root;
const mark = root ? view.seen['pb.seen.' + root] ?? keep('pb.seen.' + root) : null;
- const next = await api('/api/state' + (root ? '?root=' + encodeURIComponent(root) + (mark === null || mark === undefined ? '' : '&seen=' + encodeURIComponent(mark)) : ''));
+ const next = await boardState(root, mark);
// The person switched projects while this answer was on its way: the switch's own refresh shows it.
if (root !== view.root) return;
if (!next.project && !next.group && next.projects.some((p) => p.ok)) {
@@ -744,19 +805,40 @@ async function code(ref, before) {
if (!c.open || c.lines) return;
c.error = null;
try {
- Object.assign(c, await api('/api/code?root=' + encodeURIComponent(view.root) + '&ref=' + encodeURIComponent(ref) + '&before=' + encodeURIComponent(before)));
+ const reply = await api(boardPath(view.root) + '/code?ref=' + encodeURIComponent(ref) + '&before=' + encodeURIComponent(before));
+ Object.assign(c, reply.code);
} catch (error) {
c.error = String(error.message || error);
}
render();
}
-/**
- * Run an action as its CLI command on the server, show what the command said, and redraw from the
- * board. The console belongs to the latest action: one that answers after a later one has started
- * writes nothing there and sets no close, and a close fires only while its action is still the
- * latest, so a success can never hide a refusal that came after it.
- */
+/** Translate the page's five actions into the public move shape and a familiar command label. */
+function pageMove(command, args = {}) {
+ /** Trim form values before constructing the move and its display label. */
+ const text = (value) => String(value || '').trim();
+ if (command === 'add') {
+ const fields = { lane: text(args.lane), title: text(args.title) };
+ const label = ['add', fields.lane, fields.title];
+ for (const name of ['criterion', 'specs', 'brief']) if (text(args[name])) { fields[name] = text(args[name]); label.push('--' + name, fields[name]); }
+ return { body: { verb: 'add', args: fields }, label: label.join(' ') };
+ }
+ if (command === 'shout') return { body: { verb: 'shout', args: { to: text(args.to), text: text(args.text) } }, label: ['shout', text(args.to), text(args.text)].join(' ') };
+ if (command === 'answer') return { body: { verb: 'answer', item: Number(args.id), args: { text: text(args.text), as: 'person' } }, label: ['answer', text(args.id), text(args.text), '--as', 'person'].join(' ') };
+ if (command === 'hold') return { body: { verb: 'hold', args: { lane: text(args.lane), reason: text(args.reason) } }, label: ['hold', text(args.lane), '--reason', text(args.reason)].join(' ') };
+ if (command === 'release') return { body: { verb: 'hold', args: { lane: text(args.lane), off: true } }, label: ['hold', text(args.lane), '--off'].join(' ') };
+ throw new Error('No view action ' + String(command) + '; choose add, shout, answer, hold or release.');
+}
+
+/** Describe an API-confirmed move without exposing its transport document in the page. */
+function moveMessage(move, result) {
+ if (move.verb === 'add') return 'added #' + result.id;
+ if (move.verb === 'shout') return 'shouted to ' + move.args.to;
+ if (move.verb === 'answer') return 'answered #' + move.item;
+ return move.args.off ? 'released the ' + move.args.lane + ' lane' : 'holding the ' + move.args.lane + ' lane: ' + move.args.reason;
+}
+
+/** Run a public API move and let only the latest action own the console and its close timer. */
async function act(command, args) {
const out = $('console');
const run = (view.acting = (view.acting || 0) + 1);
@@ -766,15 +848,16 @@ async function act(command, args) {
out.className = 'console';
out.textContent = 'running…';
try {
- const result = await api('/api/act', { root: view.root, command, args });
+ const move = pageMove(command, args);
+ const result = await api(boardPath(view.root) + '/moves', move.body);
if (latest()) {
- out.className = 'console ' + (result.code === 0 ? 'ok' : 'no');
- out.textContent = '$ ' + result.command + '\\n' + (result.out + result.err).trim();
+ out.className = 'console ok';
+ out.textContent = '$ pullboard ' + move.label + '\\n' + moveMessage(move.body, result.result);
// What went through says so and then steps aside; a refusal stays until the person closes it.
- if (result.code === 0) view.closing = setTimeout(() => { if (latest()) out.hidden = true; }, 6000);
+ view.closing = setTimeout(() => { if (latest()) out.hidden = true; }, 6000);
}
await refresh();
- return result.code === 0;
+ return true;
} catch (error) {
if (latest()) {
out.className = 'console no';
diff --git a/src/serve.js b/src/serve.js
index d9f4188b..c7651f7c 100644
--- a/src/serve.js
+++ b/src/serve.js
@@ -1,18 +1,17 @@
/**
* `pullboard view` (N26, N27): the person's micro site. One page on this machine shows every
* registered project: items by state, what needs the person, shouts, doctrine, agents and activity,
- * refreshing itself. Its actions run the real CLI in the project, so every rule and refusal applies
- * exactly as at a terminal.
+ * refreshing itself. Reads and actions use the shared local API v1 handler (A3); actions run the
+ * real CLI in the project, so every rule and refusal applies exactly as at a terminal.
*
* It listens on the loopback address only and answers nothing without the session's secret and its
* own Host, so another site in the browser cannot reach it. It opens no outbound connection (P5).
*/
-import { spawn, spawnSync } from 'node:child_process';
+import { spawnSync } from 'node:child_process';
import { randomBytes, timingSafeEqual } from 'node:crypto';
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
import * as store from './board.js';
import { cockpitPage } from './cockpit.js';
import { COORDINATOR, loadConfig } from './config.js';
@@ -22,7 +21,6 @@ import { listProjects, registryFile } from './projects.js';
import { Refused } from './refused.js';
import { loadSpec } from './spec.js';
-const BIN = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
/** The page's styles (N26), read once: the page links them, so it needs no inline style. */
const VIEW_CSS = readFileSync(new URL('./view.css', import.meta.url), 'utf8');
export const LOOPBACK = '127.0.0.1';
@@ -79,60 +77,6 @@ function withProject(root, read) {
}
}
-/**
- * One project in the sidebar: its counts, or why it cannot be read (moved, no config).
- *
- * @param {{ root: string, name: string }} project
- * @returns {any}
- */
-function summary(project) {
- try {
- return withProject(project.root, (board, info, config) => {
- const items = store.listItems(board, { all: true });
- const count = (test) => items.filter(test).length;
- const spec = loadSpec(info.root, config).rows;
- return {
- ...project,
- ok: true,
- building: count((item) => item.item_status === 'claimed'),
- awaiting: count((item) => item.item_status === 'submitted'),
- sentBack: count((item) => item.item_status === 'open' && item.item_verdict === 'REJECT'),
- open: count((item) => item.item_status === 'open'),
- verified: count((item) => item.item_status === 'verified'),
- // What the person decides (B26): rows waiting for their call, held lanes, and the decisions
- // passed up to them. An agent's ask goes to its coordinator, and stays off this count.
- pending: spec.filter((row) => row.status === 'pending').length,
- drafts: spec.filter((row) => row.status === 'draft').length,
- holds: store.laneHolds(board).length,
- decisions: store.openDecisions(board, store.PERSON).length,
- };
- });
- } catch (error) {
- const reason = !existsSync(project.root) ? 'The folder is missing.'
- : error?.code === 'NO_CONFIG' ? 'pullboard.json is missing.'
- : error?.code === 'BAD_CONFIG' ? 'pullboard.json is invalid.'
- : error?.code === 'NOT_A_REPO' ? 'The folder is not a Git repository.'
- : 'Repository settings or its board cannot be read.';
- return { ...project, ok: false, error: `${reason} Run pullboard forget "${project.root}" to remove it.` };
- }
-}
-
-/**
- * Group registered repositories by their configured project name for the sidebar and group view.
- *
- * @param {any[]} projects
- * @returns {{ name: string, key: string, repos: any[] }[]}
- */
-function projectGroups(projects) {
- const grouped = new Map();
- for (const repo of projects) {
- if (!repo.project) continue;
- if (!grouped.has(repo.project)) grouped.set(repo.project, []);
- grouped.get(repo.project).push(repo);
- }
- return [...grouped].map(([name, repos]) => ({ name, key: `group:${name}`, repos }));
-}
-
/**
* Everything the page shows for one project. Given the newest shout the person has seen there,
* it also counts every shout since, which the forty it sends cannot always show.
@@ -240,57 +184,20 @@ export function codeAt(root, { path, from, to, commit, before = '' }) {
return { path, commit: full, from, to: last, lines: lines.slice(from - 1, last), more: last < to };
}
-/**
- * The CLI command an action from the page stands for, or null for one it does not offer.
- *
- * @param {string} command
- * @param {any} args
- * @returns {string[] | null}
- */
-export function actionArgs(command, args = {}) {
- const text = (value) => String(value ?? '').trim();
- if (command === 'add') {
- return ['add', text(args.lane), text(args.title), ...(text(args.criterion) ? ['--criterion', text(args.criterion)] : []), ...(text(args.specs) ? ['--specs', text(args.specs)] : []), ...(text(args.brief) ? ['--brief', text(args.brief)] : [])];
- }
- if (command === 'shout') return ['shout', text(args.to), text(args.text)];
- // The view is the person's, so it answers as the person (B26).
- if (command === 'answer') return ['answer', text(args.id), text(args.text), '--as', 'person'];
- if (command === 'hold') return ['hold', text(args.lane), '--reason', text(args.reason)];
- if (command === 'release') return ['hold', text(args.lane), '--off'];
- return null;
-}
-
-/**
- * Run the CLI in a folder, as the person would at a terminal there.
- *
- * @param {string} cwd
- * @param {string[]} args
- * @returns {Promise<{ code: number | null, out: string, err: string }>}
- */
-function runCli(cwd, args) {
- return new Promise((done) => {
- const child = spawn(process.execPath, [BIN, ...args], { cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] });
- let out = '';
- let err = '';
- child.stdout.on('data', (chunk) => { out += chunk; });
- child.stderr.on('data', (chunk) => { err += chunk; });
- const timer = setTimeout(() => child.kill(), 120_000);
- child.on('close', (code) => {
- clearTimeout(timer);
- done({ code, out, err });
- });
- });
-}
-
/**
* Serve the view until stopped.
*
* @param {{ port?: number, secret?: string }} [options]
* @returns {Promise<{ url: string, port: number, close: () => Promise<void> }>}
*/
-export function serveView({ port = 0, secret = randomBytes(18).toString('base64url') } = {}) {
+export async function serveView({ port = 0, secret = randomBytes(18).toString('base64url') } = {}) {
const key = Buffer.from(secret);
let bound = 0;
+ // The API reads projectState and codeAt from this module. Load its factory after our exports
+ // initialize, and use the real CLI entry point without adding a second move implementation.
+ const { createLocalApiHandler } = await import('./api.js');
+ const { main } = await import('./cli.js');
+ const apiHandler = createLocalApiHandler({ secret, getPort: () => bound, runCommand: main, projects: listProjects });
const reply = (res, code, type, body) => {
res.writeHead(code, {
'content-type': type,
@@ -311,60 +218,19 @@ export function serveView({ port = 0, secret = randomBytes(18).toString('base64u
} catch {
return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });
}
+ if (url.pathname.startsWith('/api/')) return apiHandler(req, res);
const given = Buffer.from(String(req.headers['x-pullboard-key'] ?? url.searchParams.get('k') ?? ''));
const isOwnHost = req.headers.host === `${LOOPBACK}:${bound}` || req.headers.host === `localhost:${bound}`;
if (!isOwnHost || given.length !== key.length || !timingSafeEqual(given, key)) return json(res, 403, { error: 'this view needs its own address and secret: open the link pullboard view printed' });
try {
if (req.method === 'GET' && url.pathname === '/') return reply(res, 200, 'text/html; charset=utf-8', cockpitPage(secret));
if (req.method === 'GET' && url.pathname === '/view.css') return reply(res, 200, 'text/css; charset=utf-8', VIEW_CSS);
- if (req.method === 'GET' && url.pathname === '/api/state') {
- const projects = listProjects().map(summary);
- const groups = projectGroups(projects);
- const root = url.searchParams.get('root');
- const known = projects.find((project) => project.root === root && project.ok);
- const group = root?.startsWith('group:') ? groups.find((entry) => entry.name === root.slice('group:'.length)) : null;
- const seen = /^\d+$/.test(url.searchParams.get('seen') ?? '') ? Number(url.searchParams.get('seen')) : null;
- return json(res, 200, {
- projects,
- groups,
- project: known ? projectState(known.root, { seen }) : null,
- group: group ? {
- name: group.name,
- repos: group.repos.filter((repo) => repo.ok).map((repo) => ({ root: repo.root, name: repo.name, board: projectState(repo.root) })),
- } : null,
- });
- }
- if (req.method === 'GET' && url.pathname === '/api/code') {
- const root = url.searchParams.get('root');
- if (!listProjects().some((project) => project.root === root)) return json(res, 400, { error: 'not a project on this machine' });
- const ref = /^([^:@]+):(\d+)(?:-(\d+))?@([^@]+)$/.exec(url.searchParams.get('ref') ?? '');
- if (!ref) return json(res, 400, { error: 'a code reference reads path:lines@commit, such as src/serve.js:12-30@be4356b' });
- try {
- const before = (url.searchParams.get('before') ?? '').slice(-2000);
- return json(res, 200, codeAt(root, { path: ref[1], from: Number(ref[2]), to: Number(ref[3] ?? ref[2]), commit: ref[4], before }));
- } catch (error) {
- if (error instanceof Refused) return json(res, 400, { error: error.message });
- throw error;
- }
- }
- if (req.method === 'POST' && url.pathname === '/api/act' && String(req.headers['content-type']).startsWith('application/json')) {
- let raw = '';
- for await (const chunk of req) {
- raw += chunk;
- if (raw.length > 100_000) return json(res, 413, { error: 'too large' });
- }
- const { root, command, args } = JSON.parse(raw || '{}');
- const argv = actionArgs(command, args);
- if (!argv) return json(res, 400, { error: `no action "${command}"` });
- // An action runs only inside a project this machine already knows; agents start boards.
- if (!listProjects().some((project) => project.root === root)) return json(res, 400, { error: 'not a project on this machine' });
- return json(res, 200, { command: `pullboard ${argv.join(' ')}`, ...(await runCli(root, argv)) });
- }
return json(res, 404, { error: 'no such page' });
} catch (error) {
return json(res, 500, { error: error.message });
}
});
+ server.requestTimeout = 15_000;
// Asked for any port, the view tries the one it last served from first, and takes any free one
// when that is busy; a port the person names is used as named, and a busy one is refused with the
// way out rather than a stack trace.
@@ -385,7 +251,7 @@ export function serveView({ port = 0, secret = randomBytes(18).toString('base64u
ready({
url: `http://${LOOPBACK}:${bound}/?k=${secret}`,
port: bound,
- close: () => new Promise((closed) => server.close(() => closed())),
+ close: () => new Promise((closed) => { apiHandler.close(); server.close(() => closed()); server.closeIdleConnections(); }),
});
});
};