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
fix(view): a code reference is a whole word; its own words decide [B23]
Corey Olsondab2b0236a4c
diff --git a/src/cockpit.js b/src/cockpit.jsindex 7aed8e28..4f111a4e 100644--- a/src/cockpit.js+++ b/src/cockpit.js@@ -386,13 +386,22 @@ const stateOf = (i) => i.status === 'claimed' ? 'building' : i.status === 'submiconst 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];+// was at that commit, with its line numbers. The words before it go with it, so the view can refuse+// a reference they may make part of a path with a space.+const codeRef = (ref, before) => {+ const c = view.code[view.root + '\\n' + before + '\\n' + 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;+ return '<button class="ref" data-code="' + esc(ref) + '"' + (before ? ' data-before="' + esc(before) + '"' : '') + ' type="button" aria-expanded="' + open + '">' + esc(ref) + '</button>' + shown;+};+// The words written just before a reference that could be part of a path, nearest last, up to four:+// a path with a space would start among them.+const wordsBefore = (prior) => {+ const words = /[ \\t]$/.test(prior) ? prior.split('\\n').pop().trim().split(/[ \\t]+/) : [];+ const kept = [];+ while (words.length && kept.length < 4 && /^[^:@()[\\]{}"'\`]+$/.test(words.at(-1))) kept.unshift(words.pop());+ return kept.join(' ');};const tone = (s) => s === 'approved' ? 'ok' : s === 'pending' ? 'no' : s === 'draft' ? 'warn' : '';const count = (n, one, many = one) => n + ' ' + (n === 1 ? one : many);@@ -699,12 +708,12 @@ 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 ' is never read as one;- // a number that names no item stays text. A path:lines@commit reference opens that code (B23): it- // is the whole run of path characters before the colon, never a tail of it, so what it opens is- // what it says, and the view refuses what is no path in the repo.+ // a number that names no item stays text. A path:lines@commit reference opens that code (B23). It+ // counts only as a whole word, never as the tail of one, so what it opens is what it says, and the+ // view refuses what is no path in the repo.const titles = new Map(p.items.map((i) => [String(i.id), i.title]));- 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 linked = (text) => String(text ?? '').split(/(#\\d+|(?<![^\\s([{"'\`])[^\\s:@()[\\]{}"'\`]+:\\d+(?:-\\d+)?@[0-9a-f]{7,40}(?![^\\s)\\]}"'\`.,;:!?]))/).map((part, n, parts) => {+ if (n % 2 && part[0] !== '#') return codeRef(part, wordsBefore(parts.slice(0, n).join('')));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('');@@ -810,14 +819,14 @@ function search() {* 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 });+async function code(ref, before) {+ const c = (view.code[view.root + '\\n' + before + '\\n' + 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)));+ Object.assign(c, await api('/api/code?root=' + encodeURIComponent(view.root) + '&ref=' + encodeURIComponent(ref) + '&before=' + encodeURIComponent(before)));} catch (error) {c.error = String(error.message || error);}@@ -899,7 +908,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.code) code(t.dataset.code, t.dataset.before || '');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.jsindex d0b6c677..c6dbcf88 100644--- a/src/serve.js+++ b/src/serve.js@@ -141,15 +141,15 @@ 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, never lines past the file's end, and never more- * than CODE_LINES lines. A path cannot hold a space, so when the commit holds a path with one that- * ends in this one, the words before the reference may be its start, and it is refused rather than- * opened as a different file.+ * than CODE_LINES lines. A path cannot hold a space, so the words written just before a reference+ * may be the start of one: when they and the path make a file the commit holds, the reference may+ * mean that file, and it is refused rather than opened as a different one.** @param {string} root- * @param {{ path: string, from: number, to: number, commit: string }} ref+ * @param {{ path: string, from: number, to: number, commit: string, before?: string }} ref* @returns {{ path: string, commit: string, from: number, to: number, lines: string[], more: boolean }}*/-export function codeAt(root, { path, from, to, commit }) {+export function codeAt(root, { path, from, to, commit, before = '' }) {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}")`);@@ -160,9 +160,13 @@ export function codeAt(root, { path, from, to, commit }) {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 names = spawnSync('git', ['ls-tree', '-r', '-z', '--name-only', full], { cwd: root, encoding: 'utf8', maxBuffer: 64_000_000 }).stdout.split('\0');- const longer = names.find((name) => name.endsWith(` ${path}`));- if (longer) throw new Refused('AMBIGUOUS', `${path} may be the end of "${longer}" at ${commit}, a path with a space, which a reference cannot name`);+ const words = String(before).split(' ').filter(Boolean).slice(-4);+ for (let k = 1; k <= words.length; k += 1) {+ const longer = `${words.slice(-k).join(' ')} ${path}`;+ if (spawnSync('git', ['cat-file', '-e', `${full}:${longer}`], { cwd: root }).status === 0) {+ throw new Refused('AMBIGUOUS', `the words before it may make it "${longer}", a path with a space, which a reference cannot name`);+ }+ }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');@@ -259,7 +263,8 @@ export function serveView({ port = 0, secret = randomBytes(18).toString('base64uconst 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] }));+ const before = (url.searchParams.get('before') ?? '').slice(-200);+ 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;diff --git a/test/cockpit.test.js b/test/cockpit.test.jsindex f42c02cc..2aea9e4a 100644--- a/test/cockpit.test.js+++ b/test/cockpit.test.js@@ -1317,7 +1317,7 @@ test("a shout's code reference opens that code as it was at that commit [B23]",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');- // A path with a space ends in another file's path: text naming it must never open the other.+ // A path with a space ends in another file's path: text that may name it must not open the other.writeFileSync(join(alpha.web, 'web', 'note.txt'), 'plain note\n');mkdirSync(join(alpha.web, 'web', 'my web'));writeFileSync(join(alpha.web, 'web', 'my web', 'note.txt'), 'spaced note\n');@@ -1330,44 +1330,55 @@ test("a shout's code reference opens that code as it was at that commit [B23]",box.run(alpha.web, 'shout', 'all', `#1 was ${was}, is ${now}; see ${long}.`);const spaced = `web/note.txt:1@${second.slice(0, 7)}`;box.run(alpha.web, 'shout', 'all', `absolute /${was} and spaced web/my ${spaced}`);+ box.run(alpha.web, 'shout', 'all', `plus x+${spaced}`);+ box.run(alpha.web, 'shout', 'all', spaced);// 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');+ // A button carries the words just before it that could be part of a path.+ const button = (ref, open, before = '') => `<button class="ref" data-code="${ref}"${before ? ` data-before="${before}"` : ''} type="button" aria-expanded="${open}">${ref}</button>`;+ assert.ok(page.show('feed').includes(`#1</button> was ${button(was, false, '#1 was')}, is ${button(now, false, 'is')}; see ${button(long, false, 'see')}.`), 'each reference is a button in the text');- await page.click({ code: was });- await page.click({ code: now });+ await page.click({ code: was, before: '#1 was' });+ await page.click({ code: now, before: 'is' });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 <b>there</b></span><span><i>2</i> second line</span></span>'), 'escaped, every indent kept');+ assert.ok(feed.includes(button(was, true, '#1 was') + '<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, 'is') + '<span class="code"><span><i>1</i> hello <b>there</b></span><span><i>2</i> second line</span></span>'), 'escaped, every indent kept');- await page.click({ code: long });+ await page.click({ code: long, before: 'see' });feed = page.show('feed');- const shown = feed.slice(feed.indexOf(button(long, true)));+ const shown = feed.slice(feed.indexOf(button(long, true, 'see')));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');-- // A reference is the whole path the text gives, never a tail of it; what is no path in the repo,- // or may be the end of a path with a space, says so rather than open another file.- assert.ok(page.show('feed').includes(`absolute ${button('/' + was, false)} and spaced web/my ${button(spaced, false)}`));- await page.click({ code: '/' + was });+ assert.ok(page.show('feed').includes(button(was, true, '#1 was') + '<span class="code">'), 'a refresh keeps it open');+ await page.click({ code: was, before: '#1 was' });+ assert.ok(page.show('feed').includes(button(was, false, '#1 was') + ', is'), 'a second click closes it');++ // A reference is a whole word, never the tail of one: what is no path in the repo says so, and so+ // does one the words before it may make part of a path with a space, rather than open another file.+ feed = page.show('feed');+ assert.ok(feed.includes(`absolute ${button('/' + was, false, 'absolute')} and spaced web/my ${button(spaced, false, 'and spaced web/my')}`));+ assert.ok(feed.includes(`plus ${button('x+' + spaced, false, 'plus')}`));+ await page.click({ code: '/' + was, before: 'absolute' });+ await page.click({ code: spaced, before: 'and spaced web/my' });+ await page.click({ code: 'x+' + spaced, before: 'plus' });await page.click({ code: spaced });feed = page.show('feed');- assert.ok(feed.includes(button('/' + was, true) + `<span class="code no">[BAD_REF] name a file inside the repo by its path from the top, such as src/serve.js (saw "/web/greeting.html")</span>`), 'escaped, as every refusal');- assert.ok(feed.includes(button(spaced, true) + `<span class="code no">[AMBIGUOUS] web/note.txt may be the end of "web/my web/note.txt" at ${second.slice(0, 7)}, a path with a space, which a reference cannot name</span>`));+ assert.ok(feed.includes(button('/' + was, true, 'absolute') + '<span class="code no">[BAD_REF] name a file inside the repo by its path from the top, such as src/serve.js (saw "/web/greeting.html")</span>'), 'escaped, as every refusal');+ assert.ok(feed.includes(button('x+' + spaced, true, 'plus') + '<span class="code no">[BAD_REF] name a file inside the repo by its path from the top, such as src/serve.js (saw "x+web/note.txt")</span>'));+ assert.ok(feed.includes(button(spaced, true, 'and spaced web/my') + '<span class="code no">[AMBIGUOUS] the words before it may make it "web/my web/note.txt", a path with a space, which a reference cannot name</span>'));+ assert.ok(feed.includes(button(spaced, true) + '<span class="code"><span><i>1</i>plain note</span></span>'), 'a reference standing alone opens, whatever other files there are');- 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 } });+ const ask = async (ref, { root = alpha.repo, key = view.key, before = '' } = {}) => {+ const res = await fetch(`${view.base}/api/code?root=${encodeURIComponent(root)}&ref=${encodeURIComponent(ref)}&before=${encodeURIComponent(before)}`, { headers: { 'x-pullboard-key': key } });return [res.status, (await res.json()).error ?? ''];};+ assert.deepEqual(await ask(spaced, { before: 'web/my' }), [400, '[AMBIGUOUS] the words before it may make it "web/my web/note.txt", a path with a space, which a reference cannot name']);+ assert.deepEqual(await ask(spaced, { before: 'see the' }), [200, ''], 'words that make no file leave it be');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`);