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): a shout's code reference opens that code [B23]

Corey Olsoncceead307887
diff --git a/src/cockpit.js b/src/cockpit.js
index af482e82..dd3deca2 100644
--- a/src/cockpit.js
+++ b/src/cockpit.js
@@ -225,6 +225,11 @@ input, select, textarea { border: 1px solid var(--line-strong); background: var(
.feed .day { margin: 0; padding: 12px 0 4px; font: 600 11px/1 var(--mono); letter-spacing: .07em; text-transform: uppercase; color: var(--ink-faint); }
.feed .day:first-child { padding-top: 6px; }
.feed button.ref { border: 0; background: none; padding: 0; color: var(--accent-strong); cursor: pointer; text-decoration: underline; text-underline-offset: 2px; }
+.code { display: block; margin: 6px 0 2px; padding: 6px 0; border: 1px solid var(--line); border-radius: 8px; background: var(--surface-2); font: 12px/1.55 var(--mono); white-space: pre; overflow-x: auto; overflow-wrap: normal; }
+.code > span { display: block; padding-right: 12px; }
+.code i { display: inline-block; min-width: 3.2em; padding: 0 10px 0 6px; text-align: right; font-style: normal; color: var(--ink-faint); user-select: none; }
+.code .more, .code.no { padding: 2px 10px; white-space: normal; color: var(--ink-muted); }
+.code.no { color: var(--reject); }
.feed .act { display: flex; gap: 0 5px; align-items: baseline; min-width: 0; }
.feed .act .what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink-muted); }
.agent { display: grid; gap: 2px; padding: 7px 0; border-top: 1px solid var(--line); font-size: 13px; }
@@ -343,7 +348,7 @@ input, select, textarea { border: 1px solid var(--line-strong); background: var(
<script>
const key = new URLSearchParams(location.search).get('k') || '';
const keep = (name, value) => { try { if (value === undefined) return localStorage.getItem(name); localStorage.setItem(name, value); } catch { return null; } return value; };
-const view = { root: keep('pb.project'), tab: keep('pb.tab') || 'items', seen: {}, item: null, adding: false, state: 'active', rows: { spec: 'decide', doctrine: 'all' }, row: { spec: null, doctrine: null } };
+const view = { root: keep('pb.project'), tab: keep('pb.tab') || 'items', seen: {}, code: {}, item: null, adding: false, state: 'active', rows: { spec: 'decide', doctrine: 'all' }, row: { spec: null, doctrine: null } };
let data = null;
let seen = '';
const $ = (id) => document.getElementById(id);
@@ -380,6 +385,15 @@ const verdictHtml = (v) => '<div class="verdict ' + (v.decision === 'ACCEPT' ? '
const stateOf = (i) => i.status === 'claimed' ? 'building' : i.status === 'submitted' ? 'verify' : i.status === 'verified' ? 'verified' : i.status === 'withdrawn' ? 'withdrawn' : i.verdict && i.verdict.decision === 'REJECT' ? 'back' : 'open';
const STATES = { building: ['building', 'busy'], verify: ['to verify', 'warn'], back: ['sent back', 'no'], verified: ['verified', 'ok'], open: ['open', ''], withdrawn: ['withdrawn', ''] };
const chip = (s) => '<span class="chip ' + STATES[s][1] + '">' + STATES[s][0] + '</span>';
+// A shout's path:lines@commit reference (B23): a button, and under it, once opened, that code as it
+// was at that commit, with its line numbers.
+const codeRef = (ref) => {
+ const c = view.code[view.root + ' ' + ref];
+ const open = Boolean(c && c.open);
+ const shown = !open ? '' : c.error ? '<span class="code no">' + esc(c.error) + '</span>' : !c.lines ? '<span class="code more">loading…</span>'
+ : '<span class="code">' + c.lines.map((line, n) => '<span><i>' + (c.from + n) + '</i>' + esc(line) + '</span>').join('') + (c.more ? '<span class="more">the first ' + c.lines.length + ' lines</span>' : '') + '</span>';
+ return '<button class="ref" data-code="' + esc(ref) + '" type="button" aria-expanded="' + open + '">' + esc(ref) + '</button>' + shown;
+};
const tone = (s) => s === 'approved' ? 'ok' : s === 'pending' ? 'no' : s === 'draft' ? 'warn' : '';
const count = (n, one, many = one) => n + ' ' + (n === 1 ? one : many);
// What needs the person in a project, as its Needs-you list counts it: work sent back or waiting for a
@@ -685,9 +699,10 @@ function render() {
// Every #id in a shout that names an item opens it, whatever stands next to it. The ids are found in
// the raw text and each piece is escaped on its own, so an apostrophe's &#39; is never read as one;
- // a number that names no item stays text.
+ // a number that names no item stays text. A path:lines@commit reference opens that code (B23).
const titles = new Map(p.items.map((i) => [String(i.id), i.title]));
- const linked = (text) => String(text ?? '').split(/(#\\d+)/).map((part) => {
+ const linked = (text) => String(text ?? '').split(/(#\\d+|[\\w.-]+(?:\\/[\\w.-]+)*:\\d+(?:-\\d+)?@[0-9a-f]{7,40}(?!\\w))/).map((part, n) => {
+ if (n % 2 && part[0] !== '#') return codeRef(part);
const id = /^#\\d+$/.test(part) ? String(Number(part.slice(1))) : '';
return titles.has(id) ? '<button class="ref" data-go="item:' + id + '" title="' + esc(titles.get(id)) + '" type="button">' + esc(part) + '</button>' : esc(part);
}).join('');
@@ -788,6 +803,25 @@ function search() {
render();
}
+/**
+ * Open or close the code a path:lines@commit reference names (B23). The first open asks the view for
+ * those lines as they were at that commit; the answer stays with the page, so every refresh redraws
+ * it, and a failed ask is tried again on the next open.
+ */
+async function code(ref) {
+ const c = (view.code[view.root + ' ' + ref] ??= { open: false });
+ c.open = !c.open;
+ render();
+ if (!c.open || c.lines) return;
+ c.error = null;
+ try {
+ Object.assign(c, await api('/api/code?root=' + encodeURIComponent(view.root) + '&ref=' + encodeURIComponent(ref)));
+ } 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
@@ -851,7 +885,7 @@ function switchTo(root) {
}
document.addEventListener('click', (event) => {
- const t = event.target.closest('[data-root],[data-tab],[data-go],[data-item],[data-state],[data-rows],[data-row],[data-release],[data-shout],[data-new],#proj-switch,#console');
+ const t = event.target.closest('[data-root],[data-tab],[data-go],[data-item],[data-state],[data-rows],[data-row],[data-release],[data-shout],[data-new],[data-code],#proj-switch,#console');
if (!event.target.closest('.side')) fold(false);
if (!t) return;
if (t.id === 'proj-switch') { fold(!$('side').classList.contains('open')); return; }
@@ -863,6 +897,7 @@ document.addEventListener('click', (event) => {
else if (t.dataset.state) { view.state = t.dataset.state; render(); }
else if (t.dataset.rows) { const [kind, f] = t.dataset.rows.split(':'); view.rows[kind] = f; render(); }
else if (t.dataset.row) { const [kind, id] = t.dataset.row.split(':'); view.row[kind] = id; render(); }
+ else if (t.dataset.code) code(t.dataset.code);
else if (t.dataset.release) act('release', { lane: t.dataset.release });
else if (t.dataset.shout) { $('shout-to').value = t.dataset.shout; $('shout-text').value = '#' + t.dataset.about + ': '; view.tab = 'shouts'; showTab(); $('shout-text').focus(); }
else if (t.dataset.new !== undefined) { view.adding = true; render(); $('add-title').focus(); }
diff --git a/src/serve.js b/src/serve.js
index 837fa9a2..894554b7 100644
--- a/src/serve.js
+++ b/src/serve.js
@@ -7,7 +7,7 @@
* 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 } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';
import { join } from 'node:path';
@@ -15,9 +15,10 @@ import { fileURLToPath } from 'node:url';
import * as store from './board.js';
import { cockpitPage } from './cockpit.js';
import { COORDINATOR, loadConfig } from './config.js';
-import { repoInfo } from './git.js';
+import { repoInfo, resolveCommit } from './git.js';
import { productSummaries } from './products.js';
import { listProjects } from './projects.js';
+import { Refused } from './refused.js';
import { loadSpec } from './spec.js';
const BIN = fileURLToPath(new URL('../bin/pullboard.js', import.meta.url));
@@ -131,6 +132,40 @@ export function projectState(root, { seen = null } = {}) {
});
}
+/** The most lines one code reference shows (B23). */
+export const CODE_LINES = 60;
+/** The largest file a code reference reads, in bytes. */
+const CODE_BYTES = 2_000_000;
+
+/**
+ * The lines a shout's path:lines@commit reference names, as they were at that commit (B23). Git
+ * alone reads them, from the commit's own tree: never the working tree, never a path outside the
+ * repo, never a revision that is not a plain SHA, and never more than CODE_LINES lines.
+ *
+ * @param {string} root
+ * @param {{ path: string, from: number, to: number, commit: string }} ref
+ * @returns {{ path: string, commit: string, from: number, to: number, lines: string[], more: boolean }}
+ */
+export function codeAt(root, { path, from, to, commit }) {
+ if (!/^[0-9a-f]{7,40}$/.test(commit)) throw new Refused('BAD_REF', `name the commit by its SHA, 7 to 40 hex digits (saw "${commit}")`);
+ if (!/^[\w.-]+(?:\/[\w.-]+)*$/.test(path) || path.split('/').some((part) => part === '.' || part === '..')) {
+ throw new Refused('BAD_REF', `name a file inside the repo by its path from the top, such as src/serve.js (saw "${path}")`);
+ }
+ if (!(Number.isInteger(from) && Number.isInteger(to) && from >= 1 && to >= from)) throw new Refused('BAD_REF', 'name the lines as 12, or 12-30');
+ const full = resolveCommit(root, commit);
+ if (!full) throw new Refused('NO_COMMIT', `no commit ${commit} in this repo`);
+ const object = `${full}:${path}`;
+ const type = spawnSync('git', ['cat-file', '-t', object], { cwd: root, encoding: 'utf8' });
+ if (type.status !== 0 || type.stdout.trim() !== 'blob') throw new Refused('NO_FILE', `no file ${path} at ${commit}`);
+ const size = Number(spawnSync('git', ['cat-file', '-s', object], { cwd: root, encoding: 'utf8' }).stdout);
+ if (!(size <= CODE_BYTES)) throw new Refused('TOO_LARGE', `${path} is over ${CODE_BYTES / 1_000_000} MB, too large to show`);
+ const lines = spawnSync('git', ['cat-file', 'blob', object], { cwd: root, encoding: 'utf8', maxBuffer: CODE_BYTES + 1 }).stdout.split('\n');
+ if (lines.at(-1) === '') lines.pop();
+ if (from > lines.length) throw new Refused('NO_LINES', `${path} has ${lines.length} lines at ${commit}`);
+ const last = Math.min(to, lines.length, from + CODE_LINES - 1);
+ return { path, commit: full, from, to: last, lines: lines.slice(from - 1, last), more: last < Math.min(to, lines.length) };
+}
+
/**
* The CLI command an action from the page stands for, or null for one it does not offer.
*
@@ -212,6 +247,18 @@ export function serveView({ port = 0, secret = randomBytes(18).toString('base64u
const seen = /^\d+$/.test(url.searchParams.get('seen') ?? '') ? Number(url.searchParams.get('seen')) : null;
return json(res, 200, { projects, project: known ? projectState(known.root, { seen }) : 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 {
+ return json(res, 200, codeAt(root, { path: ref[1], from: Number(ref[2]), to: Number(ref[3] ?? ref[2]), commit: ref[4] }));
+ } 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) {
diff --git a/test/cockpit.test.js b/test/cockpit.test.js
index 6636d11d..111f397c 100644
--- a/test/cockpit.test.js
+++ b/test/cockpit.test.js
@@ -1309,6 +1309,74 @@ test('spec rows read across a phone [N26]', async () => {
}
});
+test("a shout's code reference opens that code as it was at that commit [B23]", async () => {
+ const box = machine();
+ const alpha = project(box, 'alpha');
+ box.run(alpha.repo, 'add', 'web', 'Greeting', '--specs', 'G1', '--criterion', 'greets');
+ build(box, alpha, 1, 'greeting.html');
+ const first = box.git(alpha.web, 'rev-parse', 'HEAD');
+ writeFileSync(join(alpha.web, 'web', 'greeting.html'), ' hello <b>there</b>\n second line\n');
+ writeFileSync(join(alpha.web, 'web', 'long.txt'), Array.from({ length: 100 }, (_, n) => `line ${n + 1}`).join('\n') + '\n');
+ box.git(alpha.web, 'add', '-A');
+ box.git(alpha.web, 'commit', '-q', '-m', 'feat(web): a warmer greeting [G1]');
+ const second = box.git(alpha.web, 'rev-parse', 'HEAD');
+ const was = `web/greeting.html:1@${first.slice(0, 7)}`;
+ const now = `web/greeting.html:1-2@${second.slice(0, 12)}`;
+ const long = `web/long.txt:1-100@${second}`;
+ box.run(alpha.web, 'shout', 'all', `#1 was ${was}, is ${now}; see ${long}.`);
+ // A file only the working tree has, which no commit holds.
+ writeFileSync(join(alpha.repo, 'draft.txt'), 'not committed\n');
+ const view = await startView(box);
+ try {
+ const page = await openPage(view);
+ const button = (ref, open) => `<button class="ref" data-code="${ref}" type="button" aria-expanded="${open}">${ref}</button>`;
+ assert.ok(page.show('feed').includes(`, is ${button(now, false)}; see ${button(long, false)}.`), 'each reference is a button in the text');
+
+ await page.click({ code: was });
+ await page.click({ code: now });
+ let feed = page.show('feed');
+ assert.ok(feed.includes(button(was, true) + '<span class="code"><span><i>1</i>greeting.html</span></span>'), 'the code as it was at that commit');
+ assert.ok(feed.includes(button(now, true) + '<span class="code"><span><i>1</i> hello &lt;b&gt;there&lt;/b&gt;</span><span><i>2</i> second line</span></span>'), 'escaped, every indent kept');
+
+ await page.click({ code: long });
+ feed = page.show('feed');
+ const shown = feed.slice(feed.indexOf(button(long, true)));
+ assert.equal([...shown.matchAll(/<span><i>(\d+)<\/i>line \1<\/span>/g)].length, 60, 'at most sixty lines');
+ assert.match(shown, /<i>60<\/i>line 60<\/span><span class="more">the first 60 lines<\/span><\/span>/);
+
+ await page.run('seen = ""; refresh()');
+ assert.ok(page.show('feed').includes(button(was, true) + '<span class="code">'), 'a refresh keeps it open');
+ await page.click({ code: was });
+ assert.ok(page.show('feed').includes(button(was, false) + ', is'), 'a second click closes it');
+
+ const ask = async (ref, { root = alpha.repo, key = view.key } = {}) => {
+ const res = await fetch(`${view.base}/api/code?root=${encodeURIComponent(root)}&ref=${encodeURIComponent(ref)}`, { headers: { 'x-pullboard-key': key } });
+ return [res.status, (await res.json()).error ?? ''];
+ };
+ const sha = first.slice(0, 7);
+ for (const ref of [`../outside.txt:1@${sha}`, `/etc/passwd:1@${sha}`, `web/../../outside.txt:1@${sha}`, `./web/greeting.html:1@${sha}`]) {
+ assert.deepEqual(await ask(ref), [400, `[BAD_REF] name a file inside the repo by its path from the top, such as src/serve.js (saw "${ref.split(':')[0]}")`], `${ref} is refused`);
+ }
+ for (const commit of ['HEAD', 'main', '--output=x', 'abc']) assert.match((await ask(`web/greeting.html:1@${commit}`)).join(' '), /^400 \[BAD_REF\] name the commit by its SHA/, `${commit} is no SHA`);
+ assert.deepEqual(await ask('web/greeting.html:1@deadbee'), [400, '[NO_COMMIT] no commit deadbee in this repo']);
+ assert.deepEqual(await ask(`draft.txt:1@${second}`), [400, `[NO_FILE] no file draft.txt at ${second}`], 'the working tree is never read');
+ assert.deepEqual(await ask(`web:1@${sha}`), [400, `[NO_FILE] no file web at ${sha}`], 'nor a folder');
+ assert.deepEqual(await ask(`web/greeting.html:0@${sha}`), [400, '[BAD_REF] name the lines as 12, or 12-30']);
+ assert.deepEqual(await ask(`web/greeting.html:3-2@${sha}`), [400, '[BAD_REF] name the lines as 12, or 12-30']);
+ assert.deepEqual(await ask(`web/greeting.html:9@${sha}`), [400, `[NO_LINES] web/greeting.html has 1 lines at ${sha}`]);
+ assert.deepEqual(await ask(`web/greeting.html@${sha}`), [400, 'a code reference reads path:lines@commit, such as src/serve.js:12-30@be4356b']);
+ assert.deepEqual(await ask(was, { root: box.dir }), [400, 'not a project on this machine']);
+ assert.equal((await ask(was, { key: 'wrong' }))[0], 403, 'and nothing without the secret');
+
+ // A refused reference says why where its code would be.
+ box.run(alpha.web, 'shout', 'all', `gone: web/greeting.html:7@${sha}`);
+ await page.run('refresh()');
+ await page.click({ code: `web/greeting.html:7@${sha}` });
+ assert.ok(page.show('feed').includes(`<span class="code no">[NO_LINES] web/greeting.html has 1 lines at ${sha}</span>`));
+ } finally {
+ await view.stop();
+ }
+});
test('an empty feed says so on one line [N26]', async () => {
const box = machine();
project(box, 'alpha');