export interface DecisionRecord { readonly decisionId: string; readonly decision: string; readonly reason: readonly string[]; /** What a later change of this decision costs, and who pays. Empty in records written before the field existed. */ readonly toReverse: string; readonly alternativesConsidered: readonly string[]; readonly rejected: Readonly>; readonly assumptions: readonly string[]; readonly affectedComponents: readonly string[]; readonly evidence: readonly string[]; readonly supersedes: readonly string[]; } export interface DecisionProblem { /** Zero-based index of the `decision` block within the commit message. */ readonly block: number; readonly field?: string; readonly message: string; } export interface PushProblem { /** Position of the offending record in the list passed to `checkDecisions`. */ readonly index: number; readonly decisionId: string; readonly field: "decision_id" | "supersedes"; readonly message: string; } export const DECISION_ID = /^DEC-[0-9A-HJKMNP-TV-Z]{26}$/; type Value = string | string[] | Record; const LISTS = { reason: "reason", alternatives_considered: "alternativesConsidered", assumptions: "assumptions", affected_components: "affectedComponents", evidence: "evidence", supersedes: "supersedes", } as const; /** Fields refs still accepts in old commits but no longer reads. Records once named a task with `task: `. */ const IGNORED = new Set(["task"]); const FIELDS = new Set(["decision_id", "decision", "to_reverse", "rejected", ...IGNORED, ...Object.keys(LISTS)]); const BLOCK = /^```decision[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm; const OPENING = /^```decision[ \t]*$/gm; const NONE = /^Decision:[ \t]*none[ \t]*$/im; const MAX_BLOCKS = 32; const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; /** * The id of a record that does not name one: `DEC-`, the first 125 bits of the commit hash in Crockford * base32, and the block's position. Pushed commits never change, so anyone with the repository gets the same id. */ export function decisionIdFor(commit: string, block: number): string { let bits = BigInt(`0x${commit.padEnd(40, "0").slice(0, 40)}`) >> 35n; let id = ""; for (let i = 0; i < 25; i++, bits >>= 5n) id = CROCKFORD[Number(bits & 31n)] + id; return `DEC-${id}${CROCKFORD[block]}`; } /** * Reads every fenced `decision` block in a commit message. Blocks use a strict YAML subset: * `key: scalar`, `key:` followed by `- item` lines, or `key:` followed by `name: scalar` lines. */ export function parseDecisions(message: string, commit: string): { decisions: DecisionRecord[]; problems: DecisionProblem[] } { const decisions: DecisionRecord[] = []; const problems: DecisionProblem[] = []; const bodies = [...message.matchAll(BLOCK)].map((match) => match[1]); const openings = message.match(OPENING)?.length ?? 0; if (openings > bodies.length) problems.push({ block: bodies.length, message: "Decision block is not closed with ```." }); if (bodies.length > MAX_BLOCKS) problems.push({ block: MAX_BLOCKS, message: `A commit may carry at most ${MAX_BLOCKS} decision blocks.` }); bodies.slice(0, MAX_BLOCKS).forEach((body, block) => { const parsed = parseBlock(body); if ("problem" in parsed) return problems.push({ block, message: parsed.problem }); const found = toRecord(parsed.fields, block, commit); if ("problems" in found) problems.push(...found.problems); else decisions.push(found.record); }); return { decisions, problems }; } /** A git trailer line, such as `Co-Authored-By: …` or `Signed-off-by: …`. */ const TRAILER = /^[A-Za-z][A-Za-z0-9-]*: \S.*$/; /** The commit body as prose: no subject line, no decision blocks, no trailing git trailers, at most one blank line between paragraphs. */ export function narrative(message: string): string { const lines = message.replace(BLOCK, "").replace(new RegExp(NONE.source, "gim"), "").split(/\r?\n/).slice(1); let end = lines.length; while (end > 0 && (lines[end - 1].trim() === "" || TRAILER.test(lines[end - 1].trim()))) end--; return lines.slice(0, end).join("\n").replace(/\n{3,}/g, "\n\n").trim(); } /** * Checks every decision in a push, in commit order, against the decision ids the origin already holds. * A decision may supersede one made earlier in the same push. */ export function checkDecisions(decisions: readonly DecisionRecord[], context: { readonly known: ReadonlySet }): PushProblem[] { const problems: PushProblem[] = []; const seen = new Set(); decisions.forEach(({ decisionId, supersedes }, index) => { if (context.known.has(decisionId) || seen.has(decisionId)) problems.push({ index, decisionId, field: "decision_id", message: `${decisionId} already exists.` }); for (const id of supersedes) { if (!context.known.has(id) && !seen.has(id)) problems.push({ index, decisionId, field: "supersedes", message: `${decisionId} supersedes ${id}, which does not exist.` }); } seen.add(decisionId); }); return problems; } function parseBlock(body: string): { fields: Map } | { problem: string } { const fields = new Map(); let open: { key: string; value: Value | null } | null = null; const lines = body.split(/\r?\n/); for (const [index, raw] of lines.entries()) { const line = index + 1; if (!raw.trim()) continue; if (raw.includes("\t")) return { problem: `Line ${line}: use spaces, not tabs.` }; if (!raw.startsWith(" ")) { const pair = splitPair(raw); if (!pair) return { problem: `Line ${line}: expected "key: value".` }; if (fields.has(pair.key)) return { problem: `Line ${line}: ${pair.key} appears twice.` }; if (open && open.value === null) return { problem: `Line ${line}: ${open.key} has no value.` }; if (pair.value) { fields.set(pair.key, scalar(pair.value)); open = null; } else { open = { key: pair.key, value: null }; } continue; } if (!open) return { problem: `Line ${line}: unexpected indentation.` }; const item = raw.trim(); if (item.startsWith("- ") || item === "-") { if (open.value !== null && !Array.isArray(open.value)) return { problem: `Line ${line}: ${open.key} mixes list items and keys.` }; const value = scalar(item.slice(1).trim()); if (!value) return { problem: `Line ${line}: empty list item.` }; open.value = [...((open.value as string[] | null) ?? []), value]; } else { if (Array.isArray(open.value)) return { problem: `Line ${line}: ${open.key} mixes list items and keys.` }; const pair = splitPair(item); if (!pair || !pair.value) return { problem: `Line ${line}: expected "name: value" under ${open.key}.` }; const map: Record = (open.value as Record | null) ?? {}; if (Object.hasOwn(map, pair.key)) return { problem: `Line ${line}: ${pair.key} appears twice under ${open.key}.` }; map[pair.key] = scalar(pair.value); open.value = map; } fields.set(open.key, open.value); } if (open && open.value === null) return { problem: `${open.key} has no value.` }; return { fields }; } function splitPair(text: string): { key: string; value: string } | null { const match = text.match(/^([A-Za-z0-9_.-]+):(?:\s+(.*))?$/); return match ? { key: match[1], value: (match[2] ?? "").trim() } : null; } function scalar(text: string): string { if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) { try { return JSON.parse(text); } catch { return text; } } if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replaceAll("''", "'"); return text; } function toRecord(fields: Map, block: number, commit: string): { record: DecisionRecord } | { problems: DecisionProblem[] } { const problems: DecisionProblem[] = []; const fail = (field: string, message: string) => problems.push({ block, field, message }); for (const key of fields.keys()) if (!FIELDS.has(key)) fail(key, `Unknown field ${key}.`); const text = (key: string): string => { const value = fields.get(key); if (value === undefined) fail(key, `${key} is required.`); else if (typeof value !== "string") fail(key, `${key} must be a single value.`); else return value; return ""; }; const list = (key: string, required = false): string[] => { const value = fields.get(key); if (value === undefined) { if (required) fail(key, `${key} is required.`); return []; } if (!Array.isArray(value)) fail(key, `${key} must be a list of "- item" lines.`); else return value; return []; }; const optional = (key: string): string | null => (fields.has(key) ? text(key) : null); const decisionId = optional("decision_id") ?? decisionIdFor(commit, block); if (decisionId && !DECISION_ID.test(decisionId)) fail("decision_id", "decision_id must be DEC- followed by 26 Crockford base32 characters."); const decision = text("decision"); const toReverse = optional("to_reverse") ?? ""; const rejected = fields.get("rejected") ?? {}; if (typeof rejected === "string" || Array.isArray(rejected)) fail("rejected", 'rejected must be "name: reason" lines.'); const lists = Object.fromEntries(Object.entries(LISTS).map(([key, name]) => [name, list(key, key === "reason")])) as Record<(typeof LISTS)[keyof typeof LISTS], string[]>; lists.supersedes = lists.supersedes.map((id) => { const step = id.match(/^([0-9a-f]{40})#([1-9][0-9]?)$/); if (step && Number(step[2]) <= MAX_BLOCKS) return decisionIdFor(step[1], Number(step[2]) - 1); if (!DECISION_ID.test(id)) fail("supersedes", `${id} is not a decision id, or a full commit hash and block number such as #1.`); return id; }); if (problems.length) return { problems }; return { record: { decisionId, decision, toReverse, rejected: rejected as Record, ...lists } }; } export interface ReviewedCommit { readonly hash: string; readonly message: string; readonly parents?: readonly string[]; } export interface CommitReview { readonly records: readonly { readonly commit: string; readonly record: DecisionRecord }[]; readonly problems: readonly { readonly commit: string; readonly message: string }[]; } export const MISSING_COST = "to_reverse is required. Say what a later change of this decision costs, and who pays. If the answer is a small edit, delete the block."; /** * Reads the decision records in newly pushed commits, oldest first. Valid records are returned for * indexing; anything else is a problem. A commit needs no record. With `strict`, as for an agent's * push, each record must also say what it costs to reverse. */ export function reviewCommits(commits: readonly ReviewedCommit[], context: { readonly known: ReadonlySet; readonly strict?: boolean }): CommitReview { const parsed = commits.map((commit) => ({ commit, ...parseDecisions(commit.message, commit.hash) })); const problems = parsed.flatMap(({ commit, decisions, problems }) => [ ...problems.map((problem) => ({ commit: commit.hash, message: describe(problem) })), ...(context.strict ? decisions.filter((record) => !record.toReverse.trim()).map((record) => ({ commit: commit.hash, message: `"${record.decision}": ${MISSING_COST}` })) : []), ]); const candidates = parsed.flatMap(({ commit, decisions }) => decisions.map((record) => ({ commit: commit.hash, record }))); const pushProblems = checkDecisions( candidates.map(({ record }) => record), context, ); const rejected = new Set(pushProblems.map((problem) => problem.index)); return { records: candidates.filter((_, index) => !rejected.has(index)), problems: [...problems, ...pushProblems.map((problem) => ({ commit: candidates[problem.index].commit, message: problem.message }))], }; } /** * The decisions that still hold at the end of a list in commit order: none that a later one * supersedes, and no repeat of an earlier sentence. */ export function netDecisions(entries: readonly T[]): T[] { const superseded = new Set(entries.flatMap(({ record }) => record.supersedes)); const seen = new Set(); return entries.filter(({ record }) => !superseded.has(record.decisionId) && !seen.has(record.decision) && seen.add(record.decision)); } function describe(problem: DecisionProblem): string { return `decision block ${problem.block + 1}: ${problem.message}`; }