Files
PIKKIE/server/src/changes.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

531 lines
31 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Code changes: testers (and their bots, via MCP) submit patches; admins review them and take a whole batch
* in one go, as a single mbox for `git am`, then accept / decline / bounce the batch with one call.
*/
import { db, now, tx } from './db.js';
import { wrapHtml, e } from './mail.js';
import { notify, adminIds } from './notify.js';
import { HttpError, ref as itemRef, setStatus, siteUrl, resolveProject, avatarUrl } from './services.js';
export const CHANGE_STATUSES = ['pending', 'needs_work', 'accepted', 'declined', 'withdrawn'];
export const CHANGE_LABEL = { pending: 'Pending review', needs_work: 'Needs work', accepted: 'Accepted', declined: 'Declined', withdrawn: 'Withdrawn' };
/** what an admin can set; "withdrawn" belongs to the author */
export const REVIEW_STATUSES = ['pending', 'needs_work', 'accepted', 'declined'];
export const MAX_PATCH = 2_000_000; // bytes of patch text per change
export const MAX_BUNDLE = 60; // changes per bundle
const MAX_BUNDLE_BYTES = 25_000_000; // patch text per bundle, so one download can't balloon the server's memory
export const cref = (id) => `CH-${id}`;
/** single line, no control / invisible / direction characters (titles end up in mail and commit subjects) */
const oneLine = (v, max) =>
String(v ?? '')
.replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, ' ')
.replace(/[​‎‏‪-‮⁠⁦-⁩؜]/g, '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, max);
const multiLine = (v, max) => String(v ?? '').replace(/\r\n?/g, '\n').replace(/[\0-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '').trim().slice(0, max);
/* ---------- patch analysis ---------- */
const FP_SEP = /^From [0-9a-f]{40} Mon Sep 17 00:00:00 2001$/;
/** Validates a unified diff / `git format-patch` series and counts what it touches. */
export function analyzePatch(raw) {
if (typeof raw !== 'string' || !raw.trim()) throw new HttpError(400, 'patch is empty. Send the output of `git diff` or `git format-patch --stdout`.');
let text = raw.replace(/^/, '');
if (Buffer.byteLength(text) > MAX_PATCH) throw new HttpError(400, `patch is too large (max ${MAX_PATCH / 1_000_000} MB). Split it into smaller changes.`);
if (text.includes('\0')) throw new HttpError(400, 'patch contains raw binary data. Use `git diff --binary` for binary files.');
if (!text.endsWith('\n')) text += '\n';
const lines = text.split('\n');
lines.pop(); // the empty string after the final newline
const files = new Set();
let add = 0, del = 0, oldLeft = 0, newLeft = 0, git = false, hunks = 0, binary = 0, minus = null;
const clean = (p) => {
p = p.split('\t')[0].trim();
if (p.startsWith('"') && p.endsWith('"')) p = p.slice(1, -1);
return p === '/dev/null' ? null : p.replace(/^[ab]\//, '');
};
for (const l of lines) {
if (oldLeft > 0 || newLeft > 0) {
const c = l[0];
if (c === '+') { add++; newLeft--; continue; }
if (c === '-') { del++; oldLeft--; continue; }
if (c === ' ' || l === '') { oldLeft--; newLeft--; continue; }
if (c === '\\') continue; // "\ No newline at end of file"
oldLeft = newLeft = 0; // malformed hunk: fall through and treat as a header line
}
const hk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(l);
if (hk) { hunks++; oldLeft = hk[1] === undefined ? 1 : Number(hk[1]); newLeft = hk[2] === undefined ? 1 : Number(hk[2]); continue; }
if (l.startsWith('diff --git ')) {
git = true; minus = null;
const m = /^diff --git "?a\/(.+?)"? "?b\/(.+?)"?$/.exec(l);
if (m) files.add(m[2]);
continue;
}
if (l.startsWith('--- ')) { minus = clean(l.slice(4)); continue; }
if (l.startsWith('+++ ')) { const p = clean(l.slice(4)) ?? minus; if (p) files.add(p); continue; }
if (l === 'GIT binary patch') binary++;
}
if (!hunks && !binary && !git) throw new HttpError(400, "That doesn't look like a diff. Send the output of `git diff` or `git format-patch --stdout`.");
if (files.size > 1000) throw new HttpError(400, 'patch touches more than 1000 files. Split it into smaller changes.');
const series = FP_SEP.test(lines[0]);
let commits = 1;
if (series) {
const msgs = splitSeries(text);
commits = msgs.length;
for (const [i, m] of msgs.entries()) {
const head = m.slice(0, m.indexOf('\n\n') + 1 || m.length);
if (!/^Subject: /m.test(head) || !/^From: /m.test(head)) throw new HttpError(400, `commit ${i + 1} of the format-patch series has no From: or Subject: header`);
}
}
return { text, files: [...files], additions: add, deletions: del, commits, series };
}
/** "From <sha> …" separated messages of a `git format-patch --stdout` series (separator lines dropped) */
function splitSeries(text) {
const out = [];
let cur = null;
for (const l of text.split('\n')) {
if (FP_SEP.test(l)) { if (cur) out.push(cur.join('\n')); cur = []; continue; }
cur?.push(l);
}
if (cur) out.push(cur.join('\n'));
return out;
}
/* ---------- code without a diff ---------- */
export const MAX_SNIPPETS = 50;
/** a pasted block that is really a diff gets treated as the change's patch */
export const looksLikeDiff = (t) =>
FP_SEP.test(String(t).split('\n', 1)[0]) || /^diff --git /m.test(t) || (/^--- \S/m.test(t) && /^\+\+\+ \S/m.test(t) && /^@@ -\d/m.test(t));
/** [{ path?, language?, note?, content }]: a function, a whole file, a suggested fix. Paths are hints, never touched on disk. */
export function normSnippets(list) {
if (list === undefined || list === null || list === '') return [];
if (typeof list === 'string') {
try { list = JSON.parse(list); } catch { throw new HttpError(400, 'snippets must be a JSON array of { path, content }'); }
}
if (!Array.isArray(list)) throw new HttpError(400, 'snippets must be an array of { path, content }');
if (list.length > MAX_SNIPPETS) throw new HttpError(400, `at most ${MAX_SNIPPETS} snippets per change`);
const out = list
.map((s) => {
if (typeof s === 'string') s = { content: s };
if (!s || typeof s !== 'object') throw new HttpError(400, 'each snippet needs content');
const content = String(s.content ?? '').replace(/\r\n?/g, '\n').replace(/\0/g, '');
if (!content.trim()) return null; // empty blocks from a form
return {
path: oneLine(s.path, 300).replace(/^\.?\/+/, ''),
language: oneLine(s.language, 30).toLowerCase().replace(/[^a-z0-9+#.-]/g, ''),
note: multiLine(s.note, 2000),
content: content.endsWith('\n') ? content : content + '\n',
};
})
.filter(Boolean);
if (Buffer.byteLength(JSON.stringify(out)) > MAX_PATCH) throw new HttpError(400, `code is too large (max ${MAX_PATCH / 1_000_000} MB). Split it into smaller changes.`);
return out;
}
/** patch and/or snippets → what we store. At least one is required. */
function prepareCode(patch, snippets) {
const sn = normSnippets(snippets);
let p = patch !== undefined && patch !== null && String(patch).trim() ? String(patch) : null;
if (!p) {
// from the web/app form: a pasted diff without a path becomes the patch
const i = sn.findIndex((s) => !s.path && looksLikeDiff(s.content));
if (i >= 0) p = sn.splice(i, 1)[0].content;
}
if (!p && !sn.length) throw new HttpError(400, 'Send some code: a patch (git diff) if you have the repository, or snippets: the code you wrote, with the file it belongs in if you know it.');
const a = p ? analyzePatch(p) : { text: '', files: [], additions: 0, deletions: 0, commits: 0 };
return { ...a, files: [...new Set([...a.files, ...sn.map((s) => s.path).filter(Boolean)])], snippets: sn };
}
/* ---------- reading ---------- */
const COLS = `c.*, u.name author_name, u.avatar author_avatar, p.name project_name, p.color project_color,
(SELECT COUNT(*) FROM change_notes n WHERE n.change_id=c.id AND n.body<>'') note_count`;
const FROM = 'FROM changes c JOIN users u ON u.id=c.user_id JOIN projects p ON p.id=c.project_id';
function fixesOf(changeId) {
return db
.prepare('SELECT i.id,i.text,i.status FROM change_items ci JOIN items i ON i.id=ci.item_id WHERE ci.change_id=? ORDER BY i.id')
.all(changeId)
.map((i) => ({ id: i.id, ref: itemRef(i.id), text: i.text, status: i.status }));
}
function base(r) {
const files = JSON.parse(r.files || '[]');
const snippets = JSON.parse(r.snippets || '[]');
return {
id: r.id,
ref: cref(r.id),
title: r.title,
status: r.status,
status_label: CHANGE_LABEL[r.status],
revision: r.revision,
project: { id: r.project_id, name: r.project_name, color: r.project_color },
author: { id: r.user_id, name: r.author_name, avatar: avatarUrl(r.user_id, r.author_avatar) },
base: r.base,
files_count: files.length,
additions: r.additions,
deletions: r.deletions,
commits: r.commits,
// "patch" (a diff for git am), "code" (snippets someone applies by hand or with an agent), or "mixed"
kind: r.patch ? (snippets.length ? 'mixed' : 'patch') : 'code',
has_patch: !!r.patch,
snippet_count: snippets.length,
snippet_lines: snippets.reduce((n, s) => n + s.content.split('\n').length - 1, 0),
fixes: fixesOf(r.id),
note_count: r.note_count ?? 0,
via: r.via,
via_label: r.via_label,
created: r.created,
updated: r.updated,
};
}
/** files touched by more than one of these changes: apply those with care (or in the listed order) */
function overlapsOf(rows) {
const by = new Map();
for (const r of rows) for (const f of JSON.parse(r.files || '[]')) by.set(f, [...(by.get(f) || []), cref(r.id)]);
return [...by].filter(([, refs]) => refs.length > 1).map(([file, refs]) => ({ file, changes: refs })).slice(0, 200);
}
export function listChanges({ projectId, status, userId, q, limit = 50, offset = 0, itemId } = {}) {
const where = [];
const args = [];
if (projectId) { where.push('c.project_id=?'); args.push(Number(projectId)); }
if (status) {
const list = String(status).split(',').map((s) => s.trim()).filter((s) => CHANGE_STATUSES.includes(s));
if (list.length) { where.push(`c.status IN (${list.map(() => '?').join(',')})`); args.push(...list); }
}
if (userId) { where.push('c.user_id=?'); args.push(Number(userId)); }
if (itemId) { where.push('c.id IN (SELECT change_id FROM change_items WHERE item_id=?)'); args.push(Number(itemId)); }
if (q) {
const like = `%${String(q).replace(/[\\%_]/g, '\\$&')}%`;
where.push(`(c.title LIKE ? ESCAPE '\\' OR c.description LIKE ? ESCAPE '\\' OR c.files LIKE ? ESCAPE '\\' OR u.name LIKE ? ESCAPE '\\')`);
args.push(like, like, like, like);
}
const w = where.length ? 'WHERE ' + where.join(' AND ') : '';
const total = db.prepare(`SELECT COUNT(*) n ${FROM} ${w}`).get(...args).n;
const rows = db.prepare(`SELECT ${COLS} ${FROM} ${w} ORDER BY c.updated DESC, c.id DESC LIMIT ? OFFSET ?`).all(...args, Math.min(Number(limit) || 50, 200), Math.max(Number(offset) || 0, 0));
const counts = Object.fromEntries(CHANGE_STATUSES.map((s) => [s, 0]));
for (const r of db.prepare(`SELECT status, COUNT(*) n FROM changes ${projectId ? 'WHERE project_id=?' : ''} GROUP BY status`).all(...(projectId ? [Number(projectId)] : []))) counts[r.status] = r.n;
const pending = rows.filter((r) => r.status === 'pending');
return { total, counts, changes: rows.map(base), overlaps: overlapsOf(pending) };
}
export function getChange(id, { withPatch = true } = {}) {
const r = db.prepare(`SELECT ${COLS} ${FROM} WHERE c.id=?`).get(Number(id));
if (!r) return null;
const notes = db
.prepare(`SELECT n.*, u.name author_name, u.role author_role, u.avatar author_avatar FROM change_notes n JOIN users u ON u.id=n.user_id WHERE n.change_id=? ORDER BY n.id`)
.all(r.id)
.map((n) => ({
id: n.id, body: n.body, status_to: n.status_to, revision: n.revision, via: n.via, via_label: n.via_label, created: n.created,
author: { id: n.user_id, name: n.author_name, role: n.author_role, avatar: avatarUrl(n.user_id, n.author_avatar) },
}));
return { ...base(r), description: r.description, commit_author: r.author, files: JSON.parse(r.files || '[]'), notes, ...(withPatch ? { patch: r.patch, snippets: JSON.parse(r.snippets || '[]') } : {}) };
}
/* ---------- writing ---------- */
const AUTHOR_RE = /^([^<>\r\n"]{1,100}) <([^<>\s@]{1,64}@[^<>\s@]{1,190})>$/;
function parseFixes(list) {
if (list === undefined || list === null || list === '') return [];
const arr = Array.isArray(list) ? list : String(list).split(/[\s,]+/);
const ids = [...new Set(arr.map((x) => Number(String(x).trim().replace(/^PK-/i, ''))).filter((n) => Number.isInteger(n) && n > 0))].slice(0, 50);
for (const id of ids) if (!db.prepare('SELECT 1 FROM items WHERE id=?').get(id)) throw new HttpError(400, `fixes: ${itemRef(id)} does not exist`);
return ids;
}
function fields(a) {
const out = {};
if (a.title !== undefined) { out.title = oneLine(a.title, 150); if (!out.title) throw new HttpError(400, 'title is required: one line saying what the change does'); }
if (a.description !== undefined) out.description = multiLine(a.description, 20_000);
if (a.base !== undefined) out.base = oneLine(a.base, 120);
if (a.author !== undefined && a.author !== null && a.author !== '') {
const s = oneLine(a.author, 260);
if (!AUTHOR_RE.test(s)) throw new HttpError(400, 'author must look like "Name <email@example.com>"');
out.author = s;
} else if (a.author === '') out.author = '';
return out;
}
export function submitChange({ userId, project, title, description, base: baseRef, author, patch, snippets, fixes, via = 'web', viaLabel = '' }) {
const f = fields({ title, description, base: baseRef, author });
if (!f.title) throw new HttpError(400, 'title is required: one line saying what the change does');
const p = prepareCode(patch, snippets);
const fixIds = parseFixes(fixes);
// default project: the one the linked bullets live in, then the user's last one
const linkedProject = fixIds.length ? db.prepare('SELECT project_id FROM items WHERE id=?').get(fixIds[0])?.project_id : null;
const proj = resolveProject(project ?? linkedProject ?? undefined, userId);
if (!proj) throw new HttpError(400, 'No active project. Ask an admin to create one.');
const id = tx(() => {
const t = now();
const r = db
.prepare('INSERT INTO changes(project_id,user_id,title,description,base,author,patch,snippets,files,additions,deletions,commits,via,via_label,created,updated) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
.run(proj.id, userId, f.title, f.description || '', f.base || '', f.author || '', p.text, JSON.stringify(p.snippets), JSON.stringify(p.files), p.additions, p.deletions, p.commits, via, viaLabel, t, t);
const cid = Number(r.lastInsertRowid);
for (const iid of fixIds) db.prepare('INSERT INTO change_items(change_id,item_id) VALUES(?,?)').run(cid, iid);
return cid;
});
const who = db.prepare('SELECT name FROM users WHERE id=?').get(userId)?.name;
const stat = [p.text && `+${p.additions} −${p.deletions}`, p.snippets.length && `${p.snippets.length} code snippet${p.snippets.length === 1 ? '' : 's'}`, p.files.length && `${p.files.length} file${p.files.length === 1 ? '' : 's'}`].filter(Boolean).join(', ');
const viaNote = via === 'mcp' ? ' (via MCP)' : '';
for (const to of adminIds()) {
notify({
to, event: 'new_changes', actorId: userId, title: `${who} submitted ${cref(id)} in ${proj.name}${viaNote}`, body: `${f.title} · ${stat}`, link: `#/change/${id}`,
mail: {
subject: `[PIKKIE] [${proj.name}] ${cref(id)}: ${f.title}${viaNote}`,
text: `${who} submitted a code change: ${f.title}\n${stat}\n\n${f.description || ''}\n\n${siteUrl()}/#/change/${id}`,
html: wrapHtml(`${cref(id)} from ${who}`, `<p><b>${e(f.title)}</b></p><p style="color:#bbb">${e(stat)}</p><p style="white-space:pre-wrap">${e(f.description || '')}</p>`, `${siteUrl()}/#/change/${id}`),
},
});
}
return getChange(id, { withPatch: false });
}
/** A new revision (author only, while pending or bounced): goes back into the review queue.
* New code (patch and/or snippets) replaces ALL code of the previous revision. */
export function reviseChange({ id, userId, patch, snippets, title, description, base: baseRef, author, fixes, note, via = 'web', viaLabel = '' }) {
const c = db.prepare('SELECT * FROM changes WHERE id=?').get(Number(id));
if (!c) throw new HttpError(404, 'Code change not found');
if (c.user_id !== userId) throw new HttpError(403, 'Only the person who submitted a change can revise it. Submit your own change instead.');
if (!['pending', 'needs_work'].includes(c.status)) throw new HttpError(409, `${cref(c.id)} is ${CHANGE_LABEL[c.status].toLowerCase()} and can no longer be revised. Submit a new change.`);
const f = fields({ title, description, base: baseRef, author });
const newCode = (patch !== undefined && patch !== null && patch !== '') || (snippets !== undefined && snippets !== null && snippets !== '');
const p = newCode ? prepareCode(patch, snippets) : null;
const fixIds = fixes !== undefined ? parseFixes(fixes) : null;
if (!p && !Object.keys(f).length && !fixIds && !note) throw new HttpError(400, 'Nothing to change: send new code (patch or snippets), title, description, base, author or fixes');
const body = multiLine(note, 10_000);
tx(() => {
const t = now();
const rev = p ? c.revision + 1 : c.revision;
const sets = { ...f, updated: t, status: 'pending', revision: rev };
if (p) Object.assign(sets, { patch: p.text, snippets: JSON.stringify(p.snippets), files: JSON.stringify(p.files), additions: p.additions, deletions: p.deletions, commits: p.commits });
const keys = Object.keys(sets);
db.prepare(`UPDATE changes SET ${keys.map((k) => `${k}=?`).join(',')} WHERE id=?`).run(...keys.map((k) => sets[k]), c.id);
if (fixIds) {
db.prepare('DELETE FROM change_items WHERE change_id=?').run(c.id);
for (const iid of fixIds) db.prepare('INSERT INTO change_items(change_id,item_id) VALUES(?,?)').run(c.id, iid);
}
const what = p ? `Revision ${rev}` : 'Updated';
db.prepare('INSERT INTO change_notes(change_id,user_id,body,status_to,revision,via,via_label,created) VALUES(?,?,?,?,?,?,?,?)')
.run(c.id, userId, body, c.status === 'pending' ? null : 'pending', rev, via, viaLabel, t);
return what;
});
if (c.status === 'needs_work') {
const who = db.prepare('SELECT name FROM users WHERE id=?').get(userId)?.name;
for (const to of adminIds()) notify({ to, event: 'new_changes', actorId: userId, title: `${who} revised ${cref(c.id)}`, body: body || f.title || c.title, link: `#/change/${c.id}` });
}
return getChange(c.id, { withPatch: false });
}
export function withdrawChange({ id, userId, note, via = 'web', viaLabel = '' }) {
const c = db.prepare('SELECT * FROM changes WHERE id=?').get(Number(id));
if (!c) throw new HttpError(404, 'Code change not found');
if (c.user_id !== userId) throw new HttpError(403, 'Only the person who submitted a change can withdraw it');
if (!['pending', 'needs_work'].includes(c.status)) throw new HttpError(409, `${cref(c.id)} is already ${CHANGE_LABEL[c.status].toLowerCase()}`);
tx(() => {
const t = now();
db.prepare("UPDATE changes SET status='withdrawn', updated=? WHERE id=?").run(t, c.id);
db.prepare("INSERT INTO change_notes(change_id,user_id,body,status_to,revision,via,via_label,created) VALUES(?,?,?,'withdrawn',?,?,?,?)").run(c.id, userId, multiLine(note, 10_000), c.revision, via, viaLabel, t);
});
return getChange(c.id, { withPatch: false });
}
export function commentChange({ id, userId, body, via = 'web', viaLabel = '' }) {
const c = db.prepare('SELECT * FROM changes WHERE id=?').get(Number(id));
if (!c) throw new HttpError(404, 'Code change not found');
const text = multiLine(body, 10_000);
if (!text) throw new HttpError(400, 'Write something');
const t = now();
const nid = Number(db.prepare('INSERT INTO change_notes(change_id,user_id,body,revision,via,via_label,created) VALUES(?,?,?,?,?,?,?)').run(c.id, userId, text, c.revision, via, viaLabel, t).lastInsertRowid);
db.prepare('UPDATE changes SET updated=? WHERE id=?').run(t, c.id);
const u = db.prepare('SELECT name, role FROM users WHERE id=?').get(userId);
const link = `${siteUrl()}/#/change/${c.id}`;
const mail = { subject: `[PIKKIE] ${u.name} on ${cref(c.id)}: ${c.title}`, text: `${u.name}:\n\n${text}\n\n${link}`, html: wrapHtml(`${u.name} on ${cref(c.id)}`, `<p style="color:#bbb">${e(c.title)}</p><p style="white-space:pre-wrap">${e(text)}</p>`, link) };
notify({ to: c.user_id, event: 'changes', actorId: userId, title: `${u.name} commented on ${cref(c.id)}`, body: text, link: `#/change/${c.id}`, mail });
// the author answering a review: let the admins know
if (userId === c.user_id && u.role !== 'admin' && c.status === 'needs_work') {
for (const to of adminIds()) notify({ to, event: 'new_changes', actorId: userId, title: `${u.name} answered on ${cref(c.id)}`, body: text, link: `#/change/${c.id}`, mail });
}
return nid;
}
/**
* ADMIN: review a whole batch at once. All ids are checked first; then every change gets the same status and
* message in one transaction. With fixIssues, accepted changes also flag the bullets they fix as fixed.
*/
export function reviewChanges({ ids, userId, status, message, fixIssues = false, via = 'web', viaLabel = '' }) {
if (!REVIEW_STATUSES.includes(status)) throw new HttpError(400, `status must be one of ${REVIEW_STATUSES.join(', ')}`);
const list = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => Number(String(x).replace(/^CH-/i, ''))).filter((n) => Number.isInteger(n) && n > 0))];
if (!list.length) throw new HttpError(400, 'ids: give at least one code change id');
if (list.length > 100) throw new HttpError(400, 'ids: at most 100 changes per call');
const rows = list.map((id) => {
const c = db.prepare('SELECT * FROM changes WHERE id=?').get(id);
if (!c) throw new HttpError(404, `${cref(id)} not found`);
if (c.status === 'withdrawn') throw new HttpError(409, `${cref(id)} was withdrawn by its author`);
return c;
});
const body = multiLine(message, 10_000);
tx(() => {
const t = now();
for (const c of rows) {
db.prepare('UPDATE changes SET status=?, updated=? WHERE id=?').run(status, t, c.id);
db.prepare('INSERT INTO change_notes(change_id,user_id,body,status_to,revision,via,via_label,created) VALUES(?,?,?,?,?,?,?,?)').run(c.id, userId, body, status, c.revision, via, viaLabel, t);
}
});
const admin = db.prepare('SELECT name FROM users WHERE id=?').get(userId);
const fixed = [];
for (const c of rows) {
const label = CHANGE_LABEL[status];
const link = `${siteUrl()}/#/change/${c.id}`;
if (c.status !== status) {
notify({
to: c.user_id, event: 'changes', actorId: userId, title: `${cref(c.id)} is now ${label}`, body: body || c.title, link: `#/change/${c.id}`,
mail: {
subject: `[PIKKIE] ${cref(c.id)} is now: ${label}`,
text: `${admin.name} marked your change "${c.title}" as ${label}.\n\n${body}\n\n${link}`,
html: wrapHtml(`${cref(c.id)} → ${label}`, `<p style="color:#bbb">${e(c.title)}</p><p><b>${e(admin.name)}:</b></p><p style="white-space:pre-wrap">${e(body) || '<i>(no message)</i>'}</p>`, link),
},
});
}
if (fixIssues && status === 'accepted') {
for (const it of fixesOf(c.id)) {
if (['fixed', 'finished', 'declined'].includes(it.status)) continue;
setStatus({ itemId: it.id, userId, status: 'fixed', message: `Fixed by ${cref(c.id)}: ${c.title}${body ? `\n\n${body}` : ''}`, via, viaLabel });
fixed.push(it.ref);
}
}
}
return { status, changes: rows.map((c) => cref(c.id)), bullets_fixed: fixed };
}
export function deleteChange(id) {
db.prepare('DELETE FROM changes WHERE id=?').run(Number(id));
}
/* ---------- the batch: one mbox for `git am` ---------- */
const MBOX_SEP = 'From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001';
/** mboxrd: no line inside a message can pose as a message separator (so one change can't smuggle in another) */
const rd = (s) => s.replace(/^(>*From )/gm, '>$1');
const hdr = (s) => (/^[\x20-\x7e]*$/.test(s) ? s : `=?UTF-8?B?${Buffer.from(s).toString('base64')}?=`);
/** lines `git mailinfo` would take as the start of the diff are indented, so a description can't inject patch content */
const safeMsg = (s) => s.split('\n').map((l) => (/^(---|diff -|Index: )/.test(l) ? ' ' + l : l)).join('\n');
function trailers(c, who) {
const fixes = fixesOf(c.id);
return [`PIKKIE-Change: ${cref(c.id)} revision ${c.revision}, submitted by ${who}`, fixes.length && `PIKKIE-Fixes: ${fixes.map((f) => f.ref).join(', ')}`].filter(Boolean);
}
function messagesFor(c, who) {
const tr = trailers(c, who);
if (FP_SEP.test(c.patch.split('\n', 1)[0])) {
// a format-patch series keeps its own authors, dates and messages; we add the PIKKIE trailers
return splitSeries(c.patch).map((m) => {
const lines = m.split('\n');
const headEnd = lines.indexOf('');
let cut = lines.findIndex((l, i) => i > headEnd && (l === '---' || l.startsWith('diff --git ')));
if (cut < 0) cut = lines.length;
const before = lines.slice(0, cut);
while (before.length > headEnd + 1 && before[before.length - 1] === '') before.pop();
// join an existing trailer block (Signed-off-by: …), otherwise start one after a blank line
const trailerBlock = before.length > headEnd + 1 && /^[\w-]+: /.test(before[before.length - 1]) ? tr : ['', ...tr];
return [...before, ...trailerBlock, ...lines.slice(cut)].join('\n');
});
}
const [, name, mail] = AUTHOR_RE.exec(c.author || '') || [null, who, `pikkie-user-${c.user_id}@users.noreply.invalid`];
const desc = safeMsg(c.description || '');
return [
[
`From: ${hdr(name)} <${mail}>`,
`Date: ${new Date(c.created).toUTCString()}`,
`Subject: ${hdr(`[PATCH] ${c.title}`)}`,
'MIME-Version: 1.0',
'Content-Type: text/plain; charset=UTF-8',
'Content-Transfer-Encoding: 8bit',
'',
...(desc ? [desc, ''] : []),
...tr,
'---',
...(c.base ? [`Base: ${c.base}`, ''] : []),
c.patch.replace(/\n$/, ''),
].join('\n'),
];
}
/**
* One mbox with every selected change, oldest first (or in the order of `ids`), ready for
* git am --patch-format=mboxrd -3 <file>
*/
export function bundle({ ids, projectId, status = 'pending' } = {}) {
let rows;
if (ids && (!Array.isArray(ids) || ids.length)) {
const list = [...new Set((Array.isArray(ids) ? ids : String(ids).split(',')).map((x) => Number(String(x).trim().replace(/^CH-/i, ''))).filter((n) => Number.isInteger(n) && n > 0))];
if (list.length > MAX_BUNDLE) throw new HttpError(400, `at most ${MAX_BUNDLE} changes per bundle`);
rows = list.map((id) => {
const c = db.prepare('SELECT c.*, u.name author_name FROM changes c JOIN users u ON u.id=c.user_id WHERE c.id=?').get(id);
if (!c) throw new HttpError(404, `${cref(id)} not found`);
return c;
});
} else {
const st = CHANGE_STATUSES.includes(status) ? status : 'pending';
rows = db
.prepare(`SELECT c.*, u.name author_name FROM changes c JOIN users u ON u.id=c.user_id WHERE c.status=? ${projectId ? 'AND c.project_id=?' : ''} ORDER BY c.id LIMIT ?`)
.all(st, ...(projectId ? [Number(projectId)] : []), MAX_BUNDLE + 1);
if (rows.length > MAX_BUNDLE) throw new HttpError(400, `more than ${MAX_BUNDLE} changes match. Pick a project or ids.`);
}
if (!rows.length) throw new HttpError(404, 'No code changes to bundle');
if (rows.reduce((n, r) => n + r.patch.length + (r.snippets || '').length, 0) > MAX_BUNDLE_BYTES) throw new HttpError(400, `these changes add up to more than ${MAX_BUNDLE_BYTES / 1_000_000} MB of patches. Bundle fewer at a time (pick ids or a project).`);
const projects = [...new Set(rows.map((r) => r.project_id))];
const msgs = rows.filter((c) => c.patch).flatMap((c) => messagesFor(c, c.author_name));
const mbox = msgs.map((m) => `${MBOX_SEP}\n${rd(m).replace(/\n*$/, '\n')}`).join('\n');
const pname = projects.length === 1 ? db.prepare('SELECT name FROM projects WHERE id=?').get(projects[0])?.name || 'project' : 'mixed';
const slug = pname.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'project';
const stem = `pikkie-${slug}-${new Date().toISOString().slice(0, 10)}-${rows.map((r) => r.id).join('-').slice(0, 60)}`;
const coded = rows.filter((r) => JSON.parse(r.snippets || '[]').length);
const sheet = coded.length ? snippetSheet(coded, pname) : '';
return {
filename: `${stem}.mbox`,
sheet_filename: `${stem}-code.md`,
apply: [
msgs.length && `git am --patch-format=mboxrd -3 ${stem}.mbox # the ${msgs.length} commit${msgs.length === 1 ? '' : 's'} from diffs`,
coded.length && `then work through ${stem}-code.md: ${coded.length} change${coded.length === 1 ? '' : 's'} sent as code without a diff, to put in place by hand or by your agent`,
].filter(Boolean),
commits: msgs.length,
changes: rows.map((r) => {
const sn = JSON.parse(r.snippets || '[]');
return { id: r.id, ref: cref(r.id), title: r.title, author: r.author_name, status: r.status, revision: r.revision, base: r.base, kind: r.patch ? (sn.length ? 'mixed' : 'patch') : 'code', commits: r.patch ? r.commits : 0, snippets: sn.length, files_count: JSON.parse(r.files).length, additions: r.additions, deletions: r.deletions };
}),
overlaps: overlapsOf(rows),
mixed_projects: projects.length > 1,
mbox,
sheet,
};
}
const EXT_LANG = { js: 'js', mjs: 'js', cjs: 'js', ts: 'ts', tsx: 'tsx', jsx: 'jsx', kt: 'kotlin', kts: 'kotlin', java: 'java', py: 'python', rb: 'ruby', go: 'go', rs: 'rust', c: 'c', h: 'c', cpp: 'cpp', cs: 'csharp', swift: 'swift', php: 'php', sh: 'bash', css: 'css', scss: 'scss', html: 'html', vue: 'vue', svelte: 'svelte', json: 'json', yml: 'yaml', yaml: 'yaml', toml: 'toml', xml: 'xml', sql: 'sql', md: 'markdown', gradle: 'groovy', dart: 'dart', lua: 'lua' };
/** a fence longer than any backtick run inside, so code can't close it early */
const fenceFor = (s) => '`'.repeat(Math.max(3, ...[...s.matchAll(/`+/g)].map((m) => m[0].length + 1)));
/** One Markdown sheet with every change that came in as code: easy to read, and easy for an agent in the repo to apply. */
function snippetSheet(rows, pname) {
const out = [
`# PIKKIE code snippets · ${pname} · ${new Date().toISOString().slice(0, 10)}`,
'',
'These changes were sent as code without a diff (the submitters may not have the repository). File paths are their hints. Put each one in place, by hand or with your coding agent, then mark the batch with `review_changes` or on the Code page.',
];
for (const r of rows) {
const fx = fixesOf(r.id);
out.push('', '---', '', `## ${cref(r.id)}: ${r.title}`, '');
out.push(`*by ${r.author_name} · revision ${r.revision}${r.base ? ` · made against \`${r.base.replace(/`/g, "'")}\`` : ''}${fx.length ? ` · fixes ${fx.map((f) => f.ref).join(', ')}` : ''}*`);
for (const f of fx) out.push(`- ${f.ref}: ${f.text.split('\n')[0].slice(0, 200)}`);
if (r.description) out.push('', r.description);
if (r.patch) out.push('', `*This change also has a diff, which is in the mbox.*`);
JSON.parse(r.snippets || '[]').forEach((sn, i) => {
const lang = sn.language || EXT_LANG[(sn.path.split('.').pop() || '').toLowerCase()] || '';
const fence = fenceFor(sn.content);
out.push('', `### ${sn.path ? `\`${sn.path.replace(/`/g, "'")}\`` : `Snippet ${i + 1} (no file given)`}`);
if (sn.note) out.push('', sn.note);
out.push('', `${fence}${lang}`, sn.content.replace(/\n$/, ''), fence);
});
}
return out.join('\n') + '\n';
}