Files
PIKKIE/server/test/changes.test.js
T
juli 3e50430749 PIKKIE 1.4.0: code changes, reviewed in batches
Testers and their bots can send the code that fixes a bullet, without
access to the repository: code snippets with the file they belong in,
or a git diff / format-patch series when they do have the repo.

- Web (Code), Android (the code button on Bullets) and MCP
  (submit_change, list_changes, get_change, update_change,
  withdraw_change, comment_change).
- Admins take a whole batch at once: one mboxrd file for git am with
  all diffs, plus one Markdown code sheet with every snippet, and a
  warning for files touched by more than one change.
- review_changes accepts, bounces or declines a batch with one
  message and can flag the linked bullets as fixed.
- Revisions, review discussion, opt-in notifications, a tutorial step
  and README docs.
2026-11-11 13:01:22 +01:00

351 lines
19 KiB
JavaScript

import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
process.env.PIKKIE_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-changes-'));
process.env.PIKKIE_KEY_FILE = process.env.PIKKIE_DATA + '.key';
delete process.env.PIKKIE_SECRET_KEY;
const { default: app } = await import('../src/index.js');
let server, base;
before(async () => {
server = app.listen(0);
await new Promise((r) => server.once('listening', r));
base = `http://127.0.0.1:${server.address().port}`;
});
after(() => server.close());
const jar = {};
async function call(who, method, url, body) {
const headers = {};
if (jar[who]) headers.cookie = jar[who];
let payload = body;
if (body && !(body instanceof FormData)) { headers['content-type'] = 'application/json'; payload = JSON.stringify(body); }
const res = await fetch(base + url, { method, headers, body: payload });
const sc = res.headers.get('set-cookie');
if (sc) jar[who] = sc.split(';')[0];
const text = await res.text();
let json;
try { json = JSON.parse(text); } catch { json = text; }
return { status: res.status, json, headers: res.headers };
}
const mcp = (key, name, args) =>
fetch(base + '/mcp', { method: 'POST', headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }) })
.then((r) => r.json())
.then((j) => ({ error: !!j.result?.isError, content: j.result?.content || [], data: (() => { try { return JSON.parse(j.result?.content?.[0]?.text); } catch { return j.result?.content?.[0]?.text; } })() }));
/* ---------- a throwaway git repository ---------- */
const REPO = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-repo-'));
const git = (cwd, ...args) => execFileSync('git', args, { cwd, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_AUTHOR_DATE: '2026-11-11T10:00:00Z', GIT_COMMITTER_DATE: '2026-11-11T10:00:00Z' } });
const write = (cwd, f, s) => { fs.mkdirSync(path.dirname(path.join(cwd, f)), { recursive: true }); fs.writeFileSync(path.join(cwd, f), s); };
function setupRepo() {
git(REPO, 'init', '-q', '-b', 'main');
git(REPO, 'config', 'user.name', 'Maintainer');
git(REPO, 'config', 'user.email', 'maint@example.com');
write(REPO, 'app/a.txt', 'one\ntwo\nthree\n');
write(REPO, 'app/b.txt', 'alpha\nbeta\n');
write(REPO, 'app/c.txt', 'x\n');
git(REPO, 'add', '.');
git(REPO, 'commit', '-qm', 'base');
return git(REPO, 'rev-parse', 'HEAD').trim();
}
let BASE;
/** a plain `git diff` of an edit, without committing it */
function diffOf(edit) {
edit();
const d = git(REPO, 'diff');
git(REPO, 'checkout', '-q', '--', '.');
return d;
}
const PW = 'correct horse battery';
let adminKey, testerKey, otherKey, bulletId, chA, chB, chC;
test('setup: admin, two testers, keys, a bullet', async () => {
BASE = setupRepo();
await call('admin', 'POST', '/api/setup', { email: 'admin@x.io', name: 'Boss', password: PW });
await call('admin', 'PUT', '/api/admin/settings', { signup_enabled: '1' });
await call('tester', 'POST', '/api/signup', { email: 't@x.io', name: 'Tess', password: PW });
await call('other', 'POST', '/api/signup', { email: 'o@x.io', name: 'Otto', password: PW });
adminKey = (await call('admin', 'POST', '/api/keys', { name: 'mergebot' })).json.key;
testerKey = (await call('tester', 'POST', '/api/keys', { name: 'coder' })).json.key;
otherKey = (await call('other', 'POST', '/api/keys', { name: 'otto-bot' })).json.key;
const r = await mcp(testerKey, 'submit_bullets', { bullets: ['two should be TWO'] });
bulletId = r.data.created[0].id;
});
test('submit a plain git diff via MCP, linked to the bullet it fixes', async () => {
const patch = diffOf(() => write(REPO, 'app/a.txt', 'one\nTWO\nthree\n'));
const r = await mcp(testerKey, 'submit_change', { title: 'Capitalise two', description: 'Because PK says so.', patch, fixes: [`PK-${bulletId}`], base: BASE });
assert.equal(r.error, false, JSON.stringify(r.data));
chA = r.data;
assert.match(chA.ref, /^CH-\d+$/);
assert.equal(chA.status, 'pending');
assert.equal(chA.files_count, 1);
assert.equal(chA.additions, 1);
assert.equal(chA.deletions, 1);
assert.equal(chA.via, 'mcp');
assert.deepEqual(chA.fixes.map((f) => f.id), [bulletId]);
// the bullet knows about it
const it = await call('admin', 'GET', `/api/items/${bulletId}`);
assert.deepEqual(it.json.changes.map((c) => c.ref), [chA.ref]);
});
test('rejects things that are not patches, and unknown bullets', async () => {
let r = await mcp(testerKey, 'submit_change', { title: 'nope', patch: 'just some text\nnot a diff\n' });
assert.equal(r.error, true);
assert.match(r.content[0].text, /doesn't look like a diff/);
r = await mcp(testerKey, 'submit_change', { title: '', patch: 'diff --git a/x b/x\n' });
assert.equal(r.error, true);
r = await mcp(testerKey, 'submit_change', { title: 'x', patch: diffOf(() => write(REPO, 'app/c.txt', 'y\n')), fixes: [99999] });
assert.equal(r.error, true);
assert.match(r.content[0].text, /PK-99999 does not exist/);
r = await mcp(testerKey, 'submit_change', { title: 'x', patch: diffOf(() => write(REPO, 'app/c.txt', 'y\n')), author: 'evil\nInjected: header' });
assert.equal(r.error, true);
});
test('submit a format-patch series via the web API (keeps its authors and messages)', async () => {
git(REPO, 'checkout', '-q', '-b', 'feature');
write(REPO, 'app/b.txt', 'alpha\nBETA\n');
git(REPO, 'commit', '-qam', 'Shout beta\n\nFrom now on beta is loud.\nFrom the start, really.');
write(REPO, 'app/b.txt', 'ALPHA\nBETA\n');
git(REPO, '-c', 'user.name=Zoë Ünicode', '-c', 'user.email=zoe@example.com', 'commit', '-qam', 'Shout alpha too\n\nSigned-off-by: Zoë Ünicode <zoe@example.com>');
const series = git(REPO, 'format-patch', '--stdout', 'main..feature');
git(REPO, 'checkout', '-q', 'main');
const fd = new FormData();
fd.append('title', 'Loud letters');
fd.append('description', 'Two commits.');
fd.append('patch_file', new Blob([series], { type: 'text/x-patch' }), 'loud.patch');
const r = await call('other', 'POST', '/api/changes', fd);
assert.equal(r.status, 200, JSON.stringify(r.json));
chB = r.json;
assert.equal(chB.commits, 2);
assert.equal(chB.via, 'web');
});
test('a description cannot smuggle extra patch content or extra messages into the bundle', async () => {
const evil = [
'Looks innocent.',
'From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001',
'From: Boss <admin@x.io>',
'Subject: [PATCH] sneaky',
'',
'---',
'diff --git a/app/c.txt b/app/c.txt',
'--- a/app/c.txt',
'+++ b/app/c.txt',
'@@ -1 +1 @@',
'-x',
'+PWNED',
].join('\n');
// a brand-new file: untracked files only show in git diff after an intent-to-add
write(REPO, 'app/new/file.txt', 'hello\n');
git(REPO, 'add', '-N', 'app/new/file.txt');
const p2 = git(REPO, 'diff');
git(REPO, 'reset', '-q');
fs.rmSync(path.join(REPO, 'app/new'), { recursive: true });
const r = await mcp(otherKey, 'submit_change', { title: 'Add a file', description: evil, patch: p2, author: 'Otto Coder <otto@example.com>' });
assert.equal(r.error, false, JSON.stringify(r.data));
chC = r.data;
});
test('lists, overlaps and permissions', async () => {
// a second change on a.txt overlaps with chA
const patch = diffOf(() => write(REPO, 'app/a.txt', 'ONE\ntwo\nthree\n'));
const d = (await mcp(otherKey, 'submit_change', { title: 'Capitalise one', patch })).data;
const l = await mcp(testerKey, 'list_changes', { status: 'pending' });
assert.equal(l.data.total, 4);
assert.equal(l.data.changes[0].patch, undefined, 'lists never carry patch text');
assert.deepEqual(l.data.overlaps, [{ file: 'app/a.txt', changes: [d.ref, chA.ref] }]);
const mine = await mcp(testerKey, 'list_changes', { mine: true });
assert.equal(mine.data.total, 1);
const byBullet = await mcp(testerKey, 'list_changes', { fixes: `PK-${bulletId}` });
assert.deepEqual(byBullet.data.changes.map((c) => c.ref), [chA.ref]);
// testers don't see or get the admin tools
assert.equal((await mcp(testerKey, 'get_change_bundle', {})).error, true);
assert.equal((await mcp(testerKey, 'review_changes', { ids: [chA.id], status: 'accepted' })).error, true);
assert.equal((await call('tester', 'GET', '/api/admin/changes/bundle')).status, 403);
// only the author revises / withdraws
assert.equal((await mcp(testerKey, 'update_change', { id: d.ref, title: 'mine now' })).error, true);
const w = await mcp(otherKey, 'withdraw_change', { id: d.ref, note: 'dupe of ' + chA.ref });
assert.equal(w.data.status, 'withdrawn');
const again = await mcp(adminKey, 'review_changes', { ids: [d.id], status: 'accepted' });
assert.equal(again.error, true);
assert.match(again.content[0].text, /withdrawn/);
});
test('admin bundles the pending queue into one mbox that git am applies in one go', async () => {
const r = await mcp(adminKey, 'get_change_bundle', {});
assert.equal(r.error, false, JSON.stringify(r.content));
const summary = r.data;
const mbox = r.content[1].text;
assert.deepEqual(summary.changes.map((c) => c.ref), [chA.ref, chB.ref, chC.ref]);
assert.equal(summary.commits, 4);
assert.deepEqual(summary.overlaps, []);
// the only message separators are the ones PIKKIE wrote
assert.equal(mbox.match(/^From [0-9a-f]{40} /gm).length, 4);
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-apply-'));
git(work, 'clone', '-q', REPO, '.');
git(work, 'config', 'user.name', 'Maintainer');
git(work, 'config', 'user.email', 'maint@example.com');
fs.writeFileSync(path.join(work, '..', path.basename(work) + '.mbox'), mbox);
git(work, 'am', '--patch-format=mboxrd', '-3', path.join(work, '..', path.basename(work) + '.mbox'));
const log = git(work, 'log', '--format=%an <%ae>|%s', `${BASE}..HEAD`).trim().split('\n').reverse();
assert.deepEqual(log, [
'Tess <pikkie-user-2@users.noreply.invalid>|Capitalise two',
'Maintainer <maint@example.com>|Shout beta',
'Zoë Ünicode <zoe@example.com>|Shout alpha too',
'Otto Coder <otto@example.com>|Add a file',
]);
assert.equal(fs.readFileSync(path.join(work, 'app/a.txt'), 'utf8'), 'one\nTWO\nthree\n');
assert.equal(fs.readFileSync(path.join(work, 'app/b.txt'), 'utf8'), 'ALPHA\nBETA\n');
assert.equal(fs.readFileSync(path.join(work, 'app/new/file.txt'), 'utf8'), 'hello\n');
assert.equal(fs.readFileSync(path.join(work, 'app/c.txt'), 'utf8'), 'x\n', 'the description must not have patched c.txt');
// messages and trailers survived; mboxrd un-escaped the "From " lines of the commit message
const msgA = git(work, 'log', '-1', '--format=%B', 'HEAD~3');
assert.match(msgA, /Because PK says so\./);
assert.match(msgA, new RegExp(`PIKKIE-Change: ${chA.ref} revision 1, submitted by Tess`));
assert.match(msgA, new RegExp(`PIKKIE-Fixes: PK-${bulletId}`));
const msgB1 = git(work, 'log', '-1', '--format=%B', 'HEAD~2');
assert.match(msgB1, /^From now on beta is loud\.\nFrom the start, really\.$/m);
assert.match(msgB1, new RegExp(`PIKKIE-Change: ${chB.ref}`));
const msgB2 = git(work, 'log', '-1', '--format=%B', 'HEAD~1');
assert.match(msgB2, /Signed-off-by: Zoë Ünicode <zoe@example.com>\nPIKKIE-Change:/);
const msgC = git(work, 'log', '-1', '--format=%B', 'HEAD');
assert.match(msgC, /sneaky/, 'the injected text stays in the commit message, as text');
});
test('the bundle respects the order of ids, and the REST download is an attachment', async () => {
const r = await mcp(adminKey, 'get_change_bundle', { ids: [chC.ref, chA.id] });
assert.deepEqual(r.data.changes.map((c) => c.ref), [chC.ref, chA.ref]);
const d = await call('admin', 'GET', `/api/admin/changes/bundle?ids=${chA.id},${chB.id}`);
assert.equal(d.status, 200);
assert.match(d.headers.get('content-disposition'), /^attachment; filename="pikkie-general-\d{4}-\d\d-\d\d-\d+-\d+\.mbox"$/);
assert.equal(d.headers.get('x-content-type-options'), 'nosniff');
assert.match(d.json, /^From 0{40} Mon Sep 17 00:00:00 2001\nFrom: Tess/);
const one = await call('tester', 'GET', `/api/changes/${chB.id}/patch`);
assert.equal(one.status, 200);
assert.equal(one.json.match(/^From 0{40} /gm).length, 2);
});
test('needs work → revision 2 → accepted in one batch, bullets flagged fixed', async () => {
let r = await mcp(adminKey, 'review_changes', { ids: [chA.id], status: 'needs_work', message: 'Also update the test please' });
assert.equal(r.error, false, JSON.stringify(r.data));
let inbox = await call('tester', 'GET', '/api/notifications');
assert.match(inbox.json.items[0].title, new RegExp(`${chA.ref} is now Needs work`));
const patch = diffOf(() => write(REPO, 'app/a.txt', 'one\nTWO\nTHREE\n'));
r = await mcp(testerKey, 'update_change', { id: chA.ref, patch, note: 'now with three' });
assert.equal(r.data.status, 'pending');
assert.equal(r.data.revision, 2);
assert.equal(r.data.additions, 2);
await mcp(otherKey, 'comment_change', { id: chA.id, message: 'LGTM' });
r = await mcp(adminKey, 'review_changes', { ids: [chA.ref, chB.id, chC.id], status: 'accepted', message: 'Landed in 1.4, thanks!', fix_issues: true });
assert.equal(r.error, false, JSON.stringify(r.data));
assert.deepEqual(r.data.changes, [chA.ref, chB.ref, chC.ref]);
assert.deepEqual(r.data.bullets_fixed, [`PK-${bulletId}`]);
const it = await call('tester', 'GET', `/api/items/${bulletId}`);
assert.equal(it.json.status, 'fixed');
assert.match(it.json.comments.at(-1).body, new RegExp(`Fixed by ${chA.ref}: Capitalise two\\n\\nLanded in 1.4`));
const full = await mcp(testerKey, 'get_change', { id: chA.ref });
assert.equal(full.data.status, 'accepted');
assert.match(full.data.patch, /\+THREE/);
assert.deepEqual(full.data.notes.map((n) => [n.author.name, n.status_to, n.revision]), [
['Boss', 'needs_work', 1], ['Tess', 'pending', 2], ['Otto', null, 2], ['Boss', 'accepted', 2],
]);
// accepted changes are final for the author
assert.equal((await mcp(testerKey, 'update_change', { id: chA.id, title: 'later' })).error, true);
// nothing left to bundle
const empty = await mcp(adminKey, 'get_change_bundle', {});
assert.equal(empty.error, true);
});
test('notification events for code changes exist and are opt-in', async () => {
const p = await call('admin', 'GET', '/api/me/prefs');
assert.ok(p.json.events.some((e) => e.key === 'new_changes'));
assert.deepEqual(p.json.prefs.changes, { email: false, app: false });
const t = await call('tester', 'GET', '/api/me/prefs');
assert.ok(!t.json.events.some((e) => e.key === 'new_changes'), 'testers do not see admin events');
});
test('no repository needed: code snippets via MCP, a pasted diff on the web is recognised', async () => {
const r = await mcp(testerKey, 'submit_change', {
title: 'Retry the save when offline',
description: 'I do not have the repo, but this is what onSave should do.',
fixes: [bulletId],
snippets: [
{ path: 'app/src/Editor.kt', note: 'replace onSave', content: 'fun onSave() {\n retry(3) { save() }\n}' },
{ content: 'Some README note with ``` triple backticks inside\nand ```` four too' },
{ content: ' ' }, // empty blocks are dropped
],
});
assert.equal(r.error, false, JSON.stringify(r.data));
assert.equal(r.data.kind, 'code');
assert.equal(r.data.snippet_count, 2);
assert.equal(r.data.has_patch, false);
assert.equal(r.data.files_count, 1); // only the snippet with a path counts as a file
const full = (await mcp(testerKey, 'get_change', { id: r.data.id })).data;
assert.deepEqual(full.snippets.map((s) => s.path), ['app/src/Editor.kt', '']);
assert.equal(full.snippets[0].content, 'fun onSave() {\n retry(3) { save() }\n}\n');
// nothing at all → a helpful error
const none = await mcp(testerKey, 'submit_change', { title: 'empty' });
assert.equal(none.error, true);
assert.match(none.content[0].text, /snippets/);
// the web form sends every block as a snippet; one that is really a diff becomes the patch
const diff = diffOf(() => write(REPO, 'app/c.txt', 'z\n'));
const fd = new FormData();
fd.append('title', 'Mixed bag');
fd.append('snippets_file', new Blob([JSON.stringify([{ content: diff }, { path: 'docs/notes.md', content: '# hi' }])], { type: 'application/json' }), 'snippets.json');
const w = await call('other', 'POST', '/api/changes', fd);
assert.equal(w.status, 200, JSON.stringify(w.json));
assert.equal(w.json.kind, 'mixed');
assert.equal(w.json.has_patch, true);
assert.equal(w.json.snippet_count, 1);
assert.deepEqual((await call('other', 'GET', `/api/changes/${w.json.id}`)).json.files, ['app/c.txt', 'docs/notes.md']);
// the batch: diffs in the mbox (still git-am-able), code in one Markdown sheet
const b = await mcp(adminKey, 'get_change_bundle', {});
assert.equal(b.error, false, JSON.stringify(b.content));
assert.deepEqual(b.data.changes.map((c) => [c.ref, c.kind]), [[r.data.ref, 'code'], [w.json.ref, 'mixed']]);
assert.equal(b.content.length, 3);
const [mbox, sheet] = [b.content[1].text, b.content[2].text];
assert.equal(mbox.match(/^From 0{40} /gm).length, 1, 'only the change with a diff is in the mbox');
assert.match(sheet, new RegExp(`## ${r.data.ref}: Retry the save when offline`));
assert.match(sheet, /### `app\/src\/Editor\.kt`\n\nreplace onSave\n\n```kotlin\nfun onSave\(\) \{/);
assert.match(sheet, /### Snippet 2 \(no file given\)\n\n`````\nSome README note/, 'the fence is longer than any backtick run inside');
assert.match(sheet, new RegExp(`fixes PK-${bulletId}`));
assert.match(sheet, /This change also has a diff, which is in the mbox/);
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'pikkie-apply2-'));
git(work, 'clone', '-q', REPO, '.');
git(work, 'config', 'user.name', 'M');
git(work, 'config', 'user.email', 'm@example.com');
const f = path.join(os.tmpdir(), path.basename(work) + '.mbox');
fs.writeFileSync(f, mbox);
git(work, 'am', '--patch-format=mboxrd', '-3', f);
assert.equal(fs.readFileSync(path.join(work, 'app/c.txt'), 'utf8'), 'z\n');
// REST: the sheet as .md, and a clear error when a code-only change has no mbox
const md = await call('admin', 'GET', `/api/admin/changes/bundle?ids=${r.data.id}&format=md`);
assert.equal(md.status, 200);
assert.match(md.headers.get('content-disposition'), /-code\.md"$/);
assert.equal((await call('admin', 'GET', `/api/admin/changes/bundle?ids=${r.data.id}`)).status, 404);
assert.equal((await call('tester', 'GET', `/api/changes/${r.data.id}/patch?format=md`)).status, 200);
// a revision replaces all code
const rev = await mcp(testerKey, 'update_change', { id: r.data.id, snippets: [{ path: 'app/src/Editor.kt', content: 'fun onSave() = retry(5) { save() }' }], note: 'five tries' });
assert.equal(rev.data.revision, 2);
assert.equal(rev.data.snippet_count, 1);
});