269 lines · 12.3 KBRaw
| 1 | export interface DecisionRecord { |
| 2 | readonly decisionId: string; |
| 3 | readonly decision: string; |
| 4 | readonly reason: readonly string[]; |
| 5 | /** What a later change of this decision costs, and who pays. Empty in records written before the field existed. */ |
| 6 | readonly toReverse: string; |
| 7 | readonly alternativesConsidered: readonly string[]; |
| 8 | readonly rejected: Readonly<Record<string, string>>; |
| 9 | readonly assumptions: readonly string[]; |
| 10 | readonly affectedComponents: readonly string[]; |
| 11 | readonly evidence: readonly string[]; |
| 12 | readonly supersedes: readonly string[]; |
| 13 | } |
| 14 | |
| 15 | export interface DecisionProblem { |
| 16 | /** Zero-based index of the `decision` block within the commit message. */ |
| 17 | readonly block: number; |
| 18 | readonly field?: string; |
| 19 | readonly message: string; |
| 20 | } |
| 21 | |
| 22 | export interface PushProblem { |
| 23 | /** Position of the offending record in the list passed to `checkDecisions`. */ |
| 24 | readonly index: number; |
| 25 | readonly decisionId: string; |
| 26 | readonly field: "decision_id" | "supersedes"; |
| 27 | readonly message: string; |
| 28 | } |
| 29 | |
| 30 | export const DECISION_ID = /^DEC-[0-9A-HJKMNP-TV-Z]{26}$/; |
| 31 | |
| 32 | type Value = string | string[] | Record<string, string>; |
| 33 | |
| 34 | const LISTS = { |
| 35 | reason: "reason", |
| 36 | alternatives_considered: "alternativesConsidered", |
| 37 | assumptions: "assumptions", |
| 38 | affected_components: "affectedComponents", |
| 39 | evidence: "evidence", |
| 40 | supersedes: "supersedes", |
| 41 | } as const; |
| 42 | |
| 43 | /** Fields refs still accepts in old commits but no longer reads. Records once named a task with `task: <n>`. */ |
| 44 | const IGNORED = new Set(["task"]); |
| 45 | |
| 46 | const FIELDS = new Set(["decision_id", "decision", "to_reverse", "rejected", ...IGNORED, ...Object.keys(LISTS)]); |
| 47 | |
| 48 | const BLOCK = /^```decision[ \t]*\r?\n([\s\S]*?)^```[ \t]*$/gm; |
| 49 | const OPENING = /^```decision[ \t]*$/gm; |
| 50 | const NONE = /^Decision:[ \t]*none[ \t]*$/im; |
| 51 | const MAX_BLOCKS = 32; |
| 52 | const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; |
| 53 | |
| 54 | /** |
| 55 | * The id of a record that does not name one: `DEC-`, the first 125 bits of the commit hash in Crockford |
| 56 | * base32, and the block's position. Pushed commits never change, so anyone with the repository gets the same id. |
| 57 | */ |
| 58 | export function decisionIdFor(commit: string, block: number): string { |
| 59 | let bits = BigInt(`0x${commit.padEnd(40, "0").slice(0, 40)}`) >> 35n; |
| 60 | let id = ""; |
| 61 | for (let i = 0; i < 25; i++, bits >>= 5n) id = CROCKFORD[Number(bits & 31n)] + id; |
| 62 | return `DEC-${id}${CROCKFORD[block]}`; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Reads every fenced `decision` block in a commit message. Blocks use a strict YAML subset: |
| 67 | * `key: scalar`, `key:` followed by `- item` lines, or `key:` followed by `name: scalar` lines. |
| 68 | */ |
| 69 | export function parseDecisions(message: string, commit: string): { decisions: DecisionRecord[]; problems: DecisionProblem[] } { |
| 70 | const decisions: DecisionRecord[] = []; |
| 71 | const problems: DecisionProblem[] = []; |
| 72 | const bodies = [...message.matchAll(BLOCK)].map((match) => match[1]); |
| 73 | const openings = message.match(OPENING)?.length ?? 0; |
| 74 | if (openings > bodies.length) problems.push({ block: bodies.length, message: "Decision block is not closed with ```." }); |
| 75 | if (bodies.length > MAX_BLOCKS) problems.push({ block: MAX_BLOCKS, message: `A commit may carry at most ${MAX_BLOCKS} decision blocks.` }); |
| 76 | |
| 77 | bodies.slice(0, MAX_BLOCKS).forEach((body, block) => { |
| 78 | const parsed = parseBlock(body); |
| 79 | if ("problem" in parsed) return problems.push({ block, message: parsed.problem }); |
| 80 | const found = toRecord(parsed.fields, block, commit); |
| 81 | if ("problems" in found) problems.push(...found.problems); |
| 82 | else decisions.push(found.record); |
| 83 | }); |
| 84 | return { decisions, problems }; |
| 85 | } |
| 86 | |
| 87 | /** A git trailer line, such as `Co-Authored-By: …` or `Signed-off-by: …`. */ |
| 88 | const TRAILER = /^[A-Za-z][A-Za-z0-9-]*: \S.*$/; |
| 89 | |
| 90 | /** The commit body as prose: no subject line, no decision blocks, no trailing git trailers, at most one blank line between paragraphs. */ |
| 91 | export function narrative(message: string): string { |
| 92 | const lines = message.replace(BLOCK, "").replace(new RegExp(NONE.source, "gim"), "").split(/\r?\n/).slice(1); |
| 93 | let end = lines.length; |
| 94 | while (end > 0 && (lines[end - 1].trim() === "" || TRAILER.test(lines[end - 1].trim()))) end--; |
| 95 | return lines.slice(0, end).join("\n").replace(/\n{3,}/g, "\n\n").trim(); |
| 96 | } |
| 97 | |
| 98 | /** |
| 99 | * Checks every decision in a push, in commit order, against the decision ids the origin already holds. |
| 100 | * A decision may supersede one made earlier in the same push. |
| 101 | */ |
| 102 | export function checkDecisions(decisions: readonly DecisionRecord[], context: { readonly known: ReadonlySet<string> }): PushProblem[] { |
| 103 | const problems: PushProblem[] = []; |
| 104 | const seen = new Set<string>(); |
| 105 | decisions.forEach(({ decisionId, supersedes }, index) => { |
| 106 | if (context.known.has(decisionId) || seen.has(decisionId)) problems.push({ index, decisionId, field: "decision_id", message: `${decisionId} already exists.` }); |
| 107 | for (const id of supersedes) { |
| 108 | if (!context.known.has(id) && !seen.has(id)) problems.push({ index, decisionId, field: "supersedes", message: `${decisionId} supersedes ${id}, which does not exist.` }); |
| 109 | } |
| 110 | seen.add(decisionId); |
| 111 | }); |
| 112 | return problems; |
| 113 | } |
| 114 | |
| 115 | function parseBlock(body: string): { fields: Map<string, Value> } | { problem: string } { |
| 116 | const fields = new Map<string, Value>(); |
| 117 | let open: { key: string; value: Value | null } | null = null; |
| 118 | const lines = body.split(/\r?\n/); |
| 119 | |
| 120 | for (const [index, raw] of lines.entries()) { |
| 121 | const line = index + 1; |
| 122 | if (!raw.trim()) continue; |
| 123 | if (raw.includes("\t")) return { problem: `Line ${line}: use spaces, not tabs.` }; |
| 124 | |
| 125 | if (!raw.startsWith(" ")) { |
| 126 | const pair = splitPair(raw); |
| 127 | if (!pair) return { problem: `Line ${line}: expected "key: value".` }; |
| 128 | if (fields.has(pair.key)) return { problem: `Line ${line}: ${pair.key} appears twice.` }; |
| 129 | if (open && open.value === null) return { problem: `Line ${line}: ${open.key} has no value.` }; |
| 130 | if (pair.value) { |
| 131 | fields.set(pair.key, scalar(pair.value)); |
| 132 | open = null; |
| 133 | } else { |
| 134 | open = { key: pair.key, value: null }; |
| 135 | } |
| 136 | continue; |
| 137 | } |
| 138 | |
| 139 | if (!open) return { problem: `Line ${line}: unexpected indentation.` }; |
| 140 | const item = raw.trim(); |
| 141 | if (item.startsWith("- ") || item === "-") { |
| 142 | if (open.value !== null && !Array.isArray(open.value)) return { problem: `Line ${line}: ${open.key} mixes list items and keys.` }; |
| 143 | const value = scalar(item.slice(1).trim()); |
| 144 | if (!value) return { problem: `Line ${line}: empty list item.` }; |
| 145 | open.value = [...((open.value as string[] | null) ?? []), value]; |
| 146 | } else { |
| 147 | if (Array.isArray(open.value)) return { problem: `Line ${line}: ${open.key} mixes list items and keys.` }; |
| 148 | const pair = splitPair(item); |
| 149 | if (!pair || !pair.value) return { problem: `Line ${line}: expected "name: value" under ${open.key}.` }; |
| 150 | const map: Record<string, string> = (open.value as Record<string, string> | null) ?? {}; |
| 151 | if (Object.hasOwn(map, pair.key)) return { problem: `Line ${line}: ${pair.key} appears twice under ${open.key}.` }; |
| 152 | map[pair.key] = scalar(pair.value); |
| 153 | open.value = map; |
| 154 | } |
| 155 | fields.set(open.key, open.value); |
| 156 | } |
| 157 | if (open && open.value === null) return { problem: `${open.key} has no value.` }; |
| 158 | return { fields }; |
| 159 | } |
| 160 | |
| 161 | function splitPair(text: string): { key: string; value: string } | null { |
| 162 | const match = text.match(/^([A-Za-z0-9_.-]+):(?:\s+(.*))?$/); |
| 163 | return match ? { key: match[1], value: (match[2] ?? "").trim() } : null; |
| 164 | } |
| 165 | |
| 166 | function scalar(text: string): string { |
| 167 | if (text.length >= 2 && text.startsWith('"') && text.endsWith('"')) { |
| 168 | try { |
| 169 | return JSON.parse(text); |
| 170 | } catch { |
| 171 | return text; |
| 172 | } |
| 173 | } |
| 174 | if (text.length >= 2 && text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replaceAll("''", "'"); |
| 175 | return text; |
| 176 | } |
| 177 | |
| 178 | function toRecord(fields: Map<string, Value>, block: number, commit: string): { record: DecisionRecord } | { problems: DecisionProblem[] } { |
| 179 | const problems: DecisionProblem[] = []; |
| 180 | const fail = (field: string, message: string) => problems.push({ block, field, message }); |
| 181 | |
| 182 | for (const key of fields.keys()) if (!FIELDS.has(key)) fail(key, `Unknown field ${key}.`); |
| 183 | |
| 184 | const text = (key: string): string => { |
| 185 | const value = fields.get(key); |
| 186 | if (value === undefined) fail(key, `${key} is required.`); |
| 187 | else if (typeof value !== "string") fail(key, `${key} must be a single value.`); |
| 188 | else return value; |
| 189 | return ""; |
| 190 | }; |
| 191 | const list = (key: string, required = false): string[] => { |
| 192 | const value = fields.get(key); |
| 193 | if (value === undefined) { |
| 194 | if (required) fail(key, `${key} is required.`); |
| 195 | return []; |
| 196 | } |
| 197 | if (!Array.isArray(value)) fail(key, `${key} must be a list of "- item" lines.`); |
| 198 | else return value; |
| 199 | return []; |
| 200 | }; |
| 201 | |
| 202 | const optional = (key: string): string | null => (fields.has(key) ? text(key) : null); |
| 203 | const decisionId = optional("decision_id") ?? decisionIdFor(commit, block); |
| 204 | if (decisionId && !DECISION_ID.test(decisionId)) fail("decision_id", "decision_id must be DEC- followed by 26 Crockford base32 characters."); |
| 205 | const decision = text("decision"); |
| 206 | const toReverse = optional("to_reverse") ?? ""; |
| 207 | const rejected = fields.get("rejected") ?? {}; |
| 208 | if (typeof rejected === "string" || Array.isArray(rejected)) fail("rejected", 'rejected must be "name: reason" lines.'); |
| 209 | const lists = Object.fromEntries(Object.entries(LISTS).map(([key, name]) => [name, list(key, key === "reason")])) as Record<(typeof LISTS)[keyof typeof LISTS], string[]>; |
| 210 | lists.supersedes = lists.supersedes.map((id) => { |
| 211 | const step = id.match(/^([0-9a-f]{40})#([1-9][0-9]?)$/); |
| 212 | if (step && Number(step[2]) <= MAX_BLOCKS) return decisionIdFor(step[1], Number(step[2]) - 1); |
| 213 | if (!DECISION_ID.test(id)) fail("supersedes", `${id} is not a decision id, or a full commit hash and block number such as <commit>#1.`); |
| 214 | return id; |
| 215 | }); |
| 216 | |
| 217 | if (problems.length) return { problems }; |
| 218 | return { record: { decisionId, decision, toReverse, rejected: rejected as Record<string, string>, ...lists } }; |
| 219 | } |
| 220 | |
| 221 | export interface ReviewedCommit { |
| 222 | readonly hash: string; |
| 223 | readonly message: string; |
| 224 | readonly parents?: readonly string[]; |
| 225 | } |
| 226 | |
| 227 | export interface CommitReview { |
| 228 | readonly records: readonly { readonly commit: string; readonly record: DecisionRecord }[]; |
| 229 | readonly problems: readonly { readonly commit: string; readonly message: string }[]; |
| 230 | } |
| 231 | |
| 232 | 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."; |
| 233 | |
| 234 | /** |
| 235 | * Reads the decision records in newly pushed commits, oldest first. Valid records are returned for |
| 236 | * indexing; anything else is a problem. A commit needs no record. With `strict`, as for an agent's |
| 237 | * push, each record must also say what it costs to reverse. |
| 238 | */ |
| 239 | export function reviewCommits(commits: readonly ReviewedCommit[], context: { readonly known: ReadonlySet<string>; readonly strict?: boolean }): CommitReview { |
| 240 | const parsed = commits.map((commit) => ({ commit, ...parseDecisions(commit.message, commit.hash) })); |
| 241 | const problems = parsed.flatMap(({ commit, decisions, problems }) => [ |
| 242 | ...problems.map((problem) => ({ commit: commit.hash, message: describe(problem) })), |
| 243 | ...(context.strict ? decisions.filter((record) => !record.toReverse.trim()).map((record) => ({ commit: commit.hash, message: `"${record.decision}": ${MISSING_COST}` })) : []), |
| 244 | ]); |
| 245 | const candidates = parsed.flatMap(({ commit, decisions }) => decisions.map((record) => ({ commit: commit.hash, record }))); |
| 246 | const pushProblems = checkDecisions( |
| 247 | candidates.map(({ record }) => record), |
| 248 | context, |
| 249 | ); |
| 250 | const rejected = new Set(pushProblems.map((problem) => problem.index)); |
| 251 | return { |
| 252 | records: candidates.filter((_, index) => !rejected.has(index)), |
| 253 | problems: [...problems, ...pushProblems.map((problem) => ({ commit: candidates[problem.index].commit, message: problem.message }))], |
| 254 | }; |
| 255 | } |
| 256 | |
| 257 | /** |
| 258 | * The decisions that still hold at the end of a list in commit order: none that a later one |
| 259 | * supersedes, and no repeat of an earlier sentence. |
| 260 | */ |
| 261 | export function netDecisions<T extends { readonly record: DecisionRecord }>(entries: readonly T[]): T[] { |
| 262 | const superseded = new Set(entries.flatMap(({ record }) => record.supersedes)); |
| 263 | const seen = new Set<string>(); |
| 264 | return entries.filter(({ record }) => !superseded.has(record.decisionId) && !seen.has(record.decision) && seen.add(record.decision)); |
| 265 | } |
| 266 | |
| 267 | function describe(problem: DecisionProblem): string { |
| 268 | return `decision block ${problem.block + 1}: ${problem.message}`; |
| 269 | } |