@nikovirtala/adr 0.5.4 → 0.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"search-Ciix0IwS.js","names":["compiled","compiled","SOURCE_NAME","decoder","decoder"],"sources":["../src/commit-actions.ts","../src/config.ts","../src/log.ts","../src/log-index.ts","../src/sources.ts","../src/templates/builtin.ts","../src/write.ts","../src/views.ts","../src/scope.ts","../src/search.ts"],"sourcesContent":["/**\n * `{action}` of a commit that writes one event of each type (design §4.3), and what the title slot\n * names: the decision's title for the events that change whether it is decided, else its display.\n */\nexport const ACTIONS = {\n proposed: { action: \"propose to\", names: \"title\" },\n accepted: { action: \"decide to\", names: \"title\" },\n rejected: { action: \"decide not to\", names: \"title\" },\n withdrawn: { action: \"withdraw the proposal to\", names: \"title\" },\n deprecated: { action: \"deprecate\", names: \"display\" },\n superseded: { action: \"supersede\", names: \"display\" },\n noted: { action: \"add a note to\", names: \"display\" },\n linked: { action: \"link\", names: \"display\" },\n scoped: { action: \"set the scope of\", names: \"display\" },\n} as const satisfies Record<string, { action: string; names: \"title\" | \"display\" }>;\n\n/**\n * The verb of each display-named event type in a batch subject (?6, design §4.4), and the order\n * they are joined in: `link and scope ADR-0003`, `add a note to` last so it reads before the name.\n */\nexport const BATCH_ACTIONS = {\n deprecated: \"deprecate\",\n superseded: \"supersede\",\n linked: \"link\",\n scoped: \"scope\",\n noted: \"add a note to\",\n} as const;\nexport const BATCH_ORDER: readonly string[] = [\n \"deprecated\",\n \"superseded\",\n \"linked\",\n \"scoped\",\n \"noted\",\n];\n\n/** `{action}` of a batch of more than three verbs. */\nexport const UPDATE_ACTION = \"update\";\n\n/** The longest batch action, `deprecate, supersede and add a note to`. */\nexport const LONGEST_BATCH = \"deprecate, supersede and add a note to\".length;\n\n/** `{action}` of `adr index --commit`, whose title slot holds `the decision index`. */\nexport const INDEX_ACTION = \"regenerate\";\n\n/** What `adr index --commit`'s title slot holds. */\nexport const INDEX_TITLE = \"the decision index\";\n\n/** `{action}` of a draft update (`adr_update_draft`), whose title slot holds the display. */\nexport const DRAFT_ACTION = \"update the draft of\";\n\n/**\n * The longest `{action}` that goes with a title, which `[commit] subject` must leave a title room\n * for. A batch action (up to `LONGEST_BATCH`) only ever goes with a display, so `COMMIT_NAMES`\n * covers it instead.\n */\nexport const LONGEST_ACTION: number = Math.max(\n ...Object.values(ACTIONS).map((a) => a.action.length),\n INDEX_ACTION.length,\n DRAFT_ACTION.length,\n);\n\n/** The longest display: `ADR-` and up to 9 digits (`formatDecisionNumber`, kind/project.ts). */\nexport const DISPLAY_LENGTH = 13;\n\n/** What a link's title slot names after the display when the target is in another log. */\nexport const CROSS_LOG_LINK = \"to a decision in another log\";\n\n/** adr's commit-subject placeholders, each with its longest value (design §4.2). */\nexport const COMMIT_VARS = Object.freeze({\n action: LONGEST_ACTION,\n id: 8,\n display: DISPLAY_LENGTH,\n command: 9,\n});\n\n/**\n * The names the title placeholder holds instead of a title, which are never shortened, each with\n * its action: supersede's `<display> with <display>` and a link's `<display> to <display>` or\n * `<display> to a decision in another log` (`planLink` in write.ts), and `adr index`'s\n * `the decision index`. The shorter names (a display, at most 13 characters) always fit in the\n * room a title gets.\n */\nexport const COMMIT_NAMES = Object.freeze([\n {\n length: DISPLAY_LENGTH * 2 + \" with \".length,\n vars: { action: ACTIONS.superseded.action.length },\n },\n {\n length: DISPLAY_LENGTH + 1 + CROSS_LOG_LINK.length,\n vars: { action: ACTIONS.linked.action.length },\n },\n { length: INDEX_TITLE.length, vars: { action: INDEX_ACTION.length } },\n // A batch names the decision by its display, never shortened; where the joined verbs don't fit\n // the template, the batch says `update <display>`, so every template that fits that still parses.\n { length: DISPLAY_LENGTH, vars: { action: UPDATE_ACTION.length } },\n]);\n","import {\n type CommitTemplate,\n ConfigError,\n parseCommitTemplate,\n parseGlob,\n readCommitTemplate,\n type Severity,\n type ToolConfig,\n} from \"@nikovirtala/ledger\";\nimport { COMMIT_NAMES, COMMIT_VARS } from \"./commit-actions.js\";\nimport { adrKind } from \"./kind.js\";\n\n/** The default `[commit] subject`. */\nexport const DEFAULT_COMMIT_SUBJECT = \"docs(adr): {action} {title}\";\n\n/** adr's settings from `adr.toml` (design §5.3); every key is optional. */\nexport interface AdrConfig {\n /** `[log] default_template`: the template `adr new` uses without `--template`. */\n readonly defaultTemplate: string;\n /** `[log] main_branch`: the ref numbers come from; `null` resolves it automatically. */\n readonly mainBranch: string | null;\n /** `[log] index`: `committed` keeps a generated `<root>/index.md` fresh and verified. */\n readonly index: \"committed\" | \"none\";\n /** `[policy] accept_requires_human`. */\n readonly acceptRequiresHuman: boolean;\n /** `[policy] auto_commit`: commit writes without `--commit`. */\n readonly autoCommit: boolean;\n /** `[policy] mcp_can_decide`: validated now, used in phase 3. */\n readonly mcpCanDecide: boolean;\n /** `[verify] fail_on`. */\n readonly failOn: Severity;\n /** `[verify] governed_by_inactive`: the severity of `decision/governed-by-inactive`. */\n readonly governedByInactive: Severity;\n /** `[hooks] scope_follow_renames`: what the pre-commit hook does with renames of covered files. */\n readonly scopeFollowRenames: \"stage\" | \"warn\" | \"off\";\n /** `[hooks] index`: whether the pre-commit hook only checks `index.md` or regenerates it. */\n readonly hookIndex: \"check\" | \"stage\";\n /** `[commit] subject`: the template of `--commit` subjects. */\n readonly commitSubject: CommitTemplate;\n /** `[scope] anchor_keyword`: the code-anchor keyword, `adr` in `// adr:<id>`. */\n readonly anchorKeyword: string;\n /** `[scope] anchor_exclude`: globs of files whose anchors are ignored (docs that show examples). */\n readonly anchorExclude: readonly string[];\n}\n\nexport const DEFAULT_ADR_CONFIG: AdrConfig = Object.freeze({\n defaultTemplate: \"nygard\",\n mainBranch: null,\n index: \"none\",\n acceptRequiresHuman: true,\n autoCommit: false,\n mcpCanDecide: false,\n failOn: \"error\",\n governedByInactive: \"warning\",\n scopeFollowRenames: \"stage\",\n hookIndex: \"check\",\n commitSubject: parseCommitTemplate(DEFAULT_COMMIT_SUBJECT, {\n vars: COMMIT_VARS,\n where: \"commit.subject\",\n names: COMMIT_NAMES,\n }),\n anchorKeyword: adrKind.anchorKeyword,\n anchorExclude: Object.freeze([]),\n});\n\nconst TEMPLATE = /^[a-z][a-z0-9-]*$/;\nconst KEYWORD = /^[a-z][a-z0-9-]{0,31}$/;\nconst MAX_ANCHOR_EXCLUDE = 100;\n\nfunction isTable(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v) && !(v instanceof Date);\n}\n\n/**\n * Validates `adr.toml` (ledger's parsed `ToolConfig`; `null` when there is none). A wrong type or\n * value throws `ConfigError` naming the file and key. Unknown keys are ignored, so newer files\n * still load. `[log] root` is ledger's (`openToolLog` already checked it).\n */\nexport function parseAdrConfig(config: ToolConfig | null, file: string | null): AdrConfig {\n if (config === null) return DEFAULT_ADR_CONFIG;\n const where = file ?? config.file ?? \"adr.toml\";\n const fail = (message: string) => new ConfigError(`${where}: ${message}`, { file: where });\n const table = (name: string): Record<string, unknown> => {\n const t = config.raw[name];\n if (t === undefined) return {};\n if (!isTable(t)) throw fail(`${name} must be a table`);\n return t;\n };\n const log = table(\"log\");\n const policy = table(\"policy\");\n const verify = table(\"verify\");\n const scope = table(\"scope\");\n const hooks = table(\"hooks\");\n const bool = (t: Record<string, unknown>, section: string, key: string, fallback: boolean) => {\n const v = t[key];\n if (v === undefined) return fallback;\n if (typeof v !== \"boolean\") throw fail(`${section}.${key} must be true or false`);\n return v;\n };\n const oneOf = <T extends string>(\n t: Record<string, unknown>,\n section: string,\n key: string,\n values: readonly T[],\n fallback: T,\n ): T => {\n const v = t[key];\n if (v === undefined) return fallback;\n if (typeof v !== \"string\" || !(values as readonly string[]).includes(v)) {\n throw fail(`${section}.${key} must be ${values.map((x) => JSON.stringify(x)).join(\" or \")}`);\n }\n return v as T;\n };\n\n const template = log.default_template;\n if (\n template !== undefined &&\n (typeof template !== \"string\" || template.length > 64 || !TEMPLATE.test(template))\n ) {\n throw fail(`log.default_template must be a template name matching ${TEMPLATE.source}`);\n }\n const main = log.main_branch;\n if (\n main !== undefined &&\n (typeof main !== \"string\" || main.trim() === \"\" || main.startsWith(\"-\") || main.includes(\"\\0\"))\n ) {\n throw fail(\"log.main_branch must be a ref name that doesn't start with -\");\n }\n const keyword = scope.anchor_keyword;\n if (keyword !== undefined && (typeof keyword !== \"string\" || !KEYWORD.test(keyword))) {\n throw fail(`scope.anchor_keyword must match ${KEYWORD.source}`);\n }\n const exclude = scope.anchor_exclude;\n if (exclude !== undefined) {\n if (!Array.isArray(exclude) || exclude.length > MAX_ANCHOR_EXCLUDE) {\n throw fail(`scope.anchor_exclude must be an array of at most ${MAX_ANCHOR_EXCLUDE} globs`);\n }\n exclude.forEach((g: unknown, i) => {\n if (typeof g !== \"string\") throw fail(`scope.anchor_exclude[${i}] must be a string`);\n const parsed = parseGlob(g);\n if (!parsed.ok) throw fail(`scope.anchor_exclude[${i}]: ${parsed.message}`);\n });\n }\n return {\n defaultTemplate: typeof template === \"string\" ? template : DEFAULT_ADR_CONFIG.defaultTemplate,\n mainBranch: typeof main === \"string\" ? main : null,\n index: oneOf(log, \"log\", \"index\", [\"committed\", \"none\"] as const, \"none\"),\n acceptRequiresHuman: bool(policy, \"policy\", \"accept_requires_human\", true),\n autoCommit: bool(policy, \"policy\", \"auto_commit\", false),\n mcpCanDecide: bool(policy, \"policy\", \"mcp_can_decide\", false),\n failOn: oneOf(verify, \"verify\", \"fail_on\", [\"error\", \"warning\"] as const, \"error\"),\n governedByInactive: oneOf(\n verify,\n \"verify\",\n \"governed_by_inactive\",\n [\"warning\", \"error\"] as const,\n \"warning\",\n ),\n scopeFollowRenames: oneOf(\n hooks,\n \"hooks\",\n \"scope_follow_renames\",\n [\"stage\", \"warn\", \"off\"] as const,\n \"stage\",\n ),\n hookIndex: oneOf(hooks, \"hooks\", \"index\", [\"check\", \"stage\"] as const, \"check\"),\n commitSubject: readCommitTemplate(config, {\n file: where,\n vars: COMMIT_VARS,\n defaultSubject: DEFAULT_COMMIT_SUBJECT,\n names: COMMIT_NAMES,\n }),\n anchorKeyword: typeof keyword === \"string\" ? keyword : DEFAULT_ADR_CONFIG.anchorKeyword,\n anchorExclude: Array.isArray(exclude) ? (exclude as string[]) : [],\n };\n}\n","import {\n type CheckContext,\n classifyPath,\n compileKind,\n diffTrees,\n type Finding,\n type FoldedLogOf,\n foldLog,\n type GitOptions,\n invariantsCheck,\n type LogLayout,\n loadFindings,\n loadLog,\n type Numbering,\n numberLog,\n openToolLog,\n type Projection,\n parseEventFileName,\n projectLog,\n readIndexNumbers,\n refReader,\n relateCheck,\n resolveSubjectInput,\n sortFindings,\n sortInLogOrder,\n type ToolLog,\n type TreeReader,\n transitions,\n UsageError,\n withGitOperation,\n} from \"@nikovirtala/ledger\";\nimport { type AdrConfig, parseAdrConfig } from \"./config.js\";\nimport { adrKind, type DecisionView } from \"./kind.js\";\n\n/** A decision log opened for the CLI or MCP: ledger's tool log plus adr's config. */\nexport interface DecisionLog extends ToolLog {\n readonly adr: AdrConfig;\n}\n\n/**\n * Opens the decision log (design D3): `--root`, else `adr.toml`'s `[log] root`, else `docs/adr`;\n * read from the `ref` tree, the index or the work tree.\n */\nexport async function openDecisionLog(o: {\n readonly cwd: string;\n readonly root?: string | null;\n readonly ref?: string | null;\n readonly reader?: \"worktree\" | \"index\";\n readonly gitOptions?: GitOptions;\n}): Promise<DecisionLog> {\n const log = await openToolLog({ ...o, tool: \"adr\", kind: adrKind });\n return { ...log, adr: parseAdrConfig(log.config, log.configPath) };\n}\n\n/** One read of a decision log: everything list, show and the write plans need. */\nexport interface DecisionsRead {\n /** The tree that was read, its layout and config; no `Git`, so plans can run on a MemoryTree. */\n readonly tree: TreeReader;\n readonly layout: LogLayout;\n readonly adr: AdrConfig;\n readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly folded: FoldedLogOf<typeof adrKind>;\n readonly projection: Projection<DecisionView>;\n readonly numbering: Numbering;\n /** Load, transition, invariant and relate findings; no diff-based checks. */\n readonly findings: readonly Finding[];\n /** How the log was located (`ToolLog.notes`); `[]` for a MemoryTree read. */\n readonly notes: readonly string[];\n /** The `[[sources]]` names in the config; listings read them only with `--source`. */\n readonly sources: readonly string[];\n /** The `[[sources]]` entry this read is of (`--source`), or `null` for the local log. */\n readonly source: string | null;\n}\n\n/**\n * `numberLog` on the repository, then `readDecisionsFrom(log.tree, …)`. In a shallow clone of a\n * log with `[log] index = \"committed\"`, the numbers come from `<root>/index.md` in the commit\n * being read (`--ref`, else HEAD, resolved when the numbers are needed), never from the work tree's\n * copy, which may number acceptances that exist only there (design 2b D1, §4.6).\n */\nexport async function readDecisions(log: DecisionLog): Promise<DecisionsRead> {\n return withGitOperation(async () => {\n return readDecisionsFrom(log.tree, {\n layout: log.layout,\n adr: log.adr,\n numbering: await numberDecisions(log),\n ref: log.ref,\n commit: log.commit,\n notes: log.notes,\n sources: (log.config?.sources ?? []).map((s) => s.name),\n });\n });\n}\n\n/** The display numbers `readDecisions` uses, with its shallow-clone fallback to `index.md`. */\nexport async function numberDecisions(log: DecisionLog): Promise<Numbering> {\n return numberLog(log.git, {\n kind: adrKind,\n layout: log.layout,\n mainRef: log.adr.mainBranch,\n ...(log.adr.index === \"committed\"\n ? {\n fallback: async () => {\n const c = await log.git.resolveCommit(log.ref ?? \"HEAD\");\n return c === null\n ? null\n : readIndexNumbers(await refReader(log.git, c), `${log.layout.root}/index.md`);\n },\n }\n : {}),\n });\n}\n\nconst compiled = compileKind(adrKind);\n\n/** The git-free core of `readDecisions`; tests pass a MemoryTree and a hand-made `Numbering`. */\nexport async function readDecisionsFrom(\n tree: TreeReader,\n o: {\n readonly layout: LogLayout;\n readonly adr: AdrConfig;\n readonly numbering: Numbering;\n readonly ref?: string | null;\n readonly commit?: string | null;\n readonly notes?: readonly string[];\n readonly sources?: readonly string[];\n readonly source?: string | null;\n },\n): Promise<DecisionsRead> {\n const { layout, adr, numbering } = o;\n const snapshot = await loadLog(tree, { kind: compiled, layout });\n const folded = foldLog(adrKind, snapshot);\n const ctx: CheckContext = {\n kind: compiled,\n layout,\n base: null,\n head: snapshot,\n changes: [],\n scope: \"all\",\n inScope: new Set(snapshot.subjects.keys()),\n folded: { head: folded, base: null },\n };\n const options = { acceptRequiresHuman: adr.acceptRequiresHuman, sources: null };\n const findings: Finding[] = [];\n for (const check of [loadFindings, transitions, invariantsCheck(options), relateCheck(options)]) {\n findings.push(...(await check.run(ctx)));\n }\n return {\n tree,\n layout,\n adr,\n root: layout.root,\n ref: o.ref ?? null,\n commit: o.commit ?? null,\n folded,\n projection: projectLog(adrKind, folded, { numbering }),\n numbering,\n findings: sortFindings(findings.map((f) => ({ ...f, kind: adrKind.name }))),\n notes: o.notes ?? [],\n sources: o.sources ?? [],\n source: o.source ?? null,\n };\n}\n\n/**\n * The note listing reads add for a log with `[[sources]]`: the other logs are listed with\n * `--source`, from cached copies. `null` without sources, and for a `--source` read.\n */\nexport function sourcesNote(read: DecisionsRead): string | null {\n if (read.sources.length === 0 || read.source !== null) return null;\n return `the logs in [[sources]] (${read.sources.join(\", \")}) are listed with --source <name>, from cached copies; run adr sources fetch to update them`;\n}\n\n/** `read.notes`, then the sources note when there is one. */\nexport function listingNotes(read: DecisionsRead): readonly string[] {\n const note = sourcesNote(read);\n return note === null ? read.notes : [...read.notes, note];\n}\n\n/**\n * The note a read command adds about where numbers come from: the shallow-clone index, or why\n * they are unavailable (`unavailable: false` leaves that one out); `null` for none.\n */\nexport function numberingNote(\n read: DecisionsRead,\n o: { readonly unavailable: boolean },\n): string | null {\n const n = read.numbering;\n if (n.reason === \"index\") return `numbers come from ${read.root}/index.md (shallow clone)`;\n if (n.available || !o.unavailable) return null;\n return n.reason === \"shallow\"\n ? 'numbers are unavailable (shallow clone); run git fetch --unshallow, or commit an index with [log] index = \"committed\"'\n : `numbers are unavailable (${unavailableReason(n)}); decisions display by id`;\n}\n\n/** Why numbers are unavailable, in words: `shallow clone` or `no main branch`. */\nexport function unavailableReason(n: Numbering): string {\n return n.reason === \"shallow\" ? \"shallow clone\" : \"no main branch\";\n}\n\n/**\n * The id a decision argument names: an id, or a number in any form `parseDecisionNumber` takes.\n * Throws `UsageError` (exit 2) naming the reason when it names nothing.\n */\nexport function resolveDecision(read: DecisionsRead, input: string): string {\n const r = resolveSubjectInput(input, {\n subjects: new Set(read.folded.subjects.keys()),\n kind: adrKind,\n numbering: read.numbering,\n });\n if (r.ok) return r.id;\n const shown = JSON.stringify(input.trim());\n switch (r.reason) {\n case \"malformed\":\n throw new UsageError(`invalid decision ${JSON.stringify(input)}`);\n case \"qualified\":\n throw new UsageError(\n `decision ${shown} is in another log; cross-log references aren't supported yet`,\n );\n case \"numbers-unavailable\":\n throw new UsageError(\n `decision numbers are unavailable (${unavailableReason(read.numbering)}); use the decision's id instead of ${shown}`,\n );\n case \"not-found\":\n throw new UsageError(`unknown decision ${input.trim()}`);\n }\n}\n\n/** The `since` key of `adr list --since <rev>` (design 2b D7). */\nexport interface ChangedSince {\n /** The revision as given, such as `ORIG_HEAD`. */\n readonly rev: string;\n readonly commit: string;\n /** Event files added since `rev`, in log order (`(at, id)`, then path; `sortInLogOrder`). */\n readonly events: readonly {\n readonly subject: string;\n readonly type: string;\n readonly path: string;\n }[];\n}\n\n/**\n * The event files in `--ref`'s tree (else HEAD's) that `rev`'s tree lacks (design 2b D7). Diffing\n * trees answers \"what did this pull bring\" for fast-forwards and merges (`ORIG_HEAD` is the tip\n * before them), and lists nothing for a rebase of your own work, whose events are in both trees.\n * Throws `RefNotFoundError` when either revision doesn't resolve.\n */\nexport async function changedSince(log: DecisionLog, rev: string): Promise<ChangedSince> {\n return withGitOperation(async () => {\n const base = await refReader(log.git, rev);\n const head = await refReader(log.git, log.ref ?? \"HEAD\");\n const changes = await diffTrees(base, head, `${log.layout.root}/${log.layout.events}`);\n const events = changes.flatMap((c) => {\n if (c.status !== \"added\") return [];\n const p = classifyPath(log.layout, c.path);\n if (p.area !== \"event\" || p.subject === null || p.file.includes(\"/\")) return [];\n const name = parseEventFileName(p.file);\n return name === null ? [] : [{ subject: p.subject, type: name.type, path: c.path }];\n });\n return { rev, commit: base.commit ?? \"\", events: await sortInLogOrder(head, events) };\n });\n}\n","import { posix } from \"node:path\";\nimport {\n type Check,\n ConfigError,\n classifyPath,\n commitWithRecovery,\n escapeMarkdown,\n type Finding,\n firstLine,\n type Git,\n headBytes,\n headTree,\n holdsText,\n type IndexSpec,\n indexCheck,\n type LogLayout,\n projectNumbering,\n readIndexNumbers,\n refReader,\n renderCommitMessage,\n renderIndex,\n type TreeReader,\n UsageError,\n verifyLog,\n withGitOperation,\n worktreeReader,\n writeIndexCopy,\n} from \"@nikovirtala/ledger\";\nimport { INDEX_ACTION, INDEX_TITLE } from \"./commit-actions.js\";\nimport type { AdrConfig } from \"./config.js\";\nimport { adrKind, type DecisionView } from \"./kind.js\";\nimport { type DecisionLog, readDecisionsFrom } from \"./log.js\";\nimport type { WriteOptions } from \"./write.js\";\n\n/** `adr index --json` (design 2b §4.5). */\nexport interface IndexResultJson {\n readonly format: \"adr-index/v1\";\n /** The index file, repo-relative: `<root>/index.md`. */\n readonly path: string;\n readonly check: boolean;\n /**\n * `--check`: no finding. Otherwise: the copies the command compares (the work tree and the\n * index, or HEAD's when committing) already held the render.\n */\n readonly fresh: boolean;\n /** Repo-relative paths this command wrote. */\n readonly written: readonly string[];\n readonly commit: string | null;\n /** `--check`'s findings; `[]` otherwise. */\n readonly findings: readonly Finding[];\n readonly notes: readonly string[];\n}\n\n/**\n * What the recovery hint says about rerunning `adr index --commit` after `git commit` failed\n * (design 2b D5). It names the file, not the path, which the hint lists above it.\n */\nexport const INDEX_RERUN =\n \"You can also run adr index --commit again once git accepts the commit; it commits index.md while it differs from HEAD's.\";\n\n/**\n * The step before the manual commit when a write's second index render failed after staging\n * (design 2b §4.5 step 4).\n */\nexport const INDEX_BEFORE = (root: string): string =>\n `Run adr index --no-commit first; it writes and stages ${root}/index.md from the work tree. If other decisions in ${root} have uncommitted changes, the work tree's index includes them; append their paths after -- in the command below, so the commit matches the index.`;\n\n/**\n * The step after the manual commit when the commit carried the index: the commit's render leaves\n * out other decisions' uncommitted entries (design 2b D5, §4.5 step 5).\n */\nexport const INDEX_AFTER = (root: string): string =>\n `Then run adr index --no-commit to restore other decisions' entries in ${root}/index.md.`;\n\n/** The repo-relative path of a log's generated index. */\nexport const indexPath = (layout: LogLayout): string => `${layout.root}/index.md`;\n\nconst GROUPS: readonly { readonly heading: string; readonly statuses: readonly string[] }[] = [\n { heading: \"Accepted\", statuses: [\"accepted\"] },\n { heading: \"Proposed\", statuses: [\"proposed\"] },\n { heading: \"Superseded and deprecated\", statuses: [\"superseded\", \"deprecated\"] },\n { heading: \"Rejected and withdrawn\", statuses: [\"rejected\", \"withdrawn\"] },\n];\n\nconst cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);\n\n/**\n * adr's index spec (01:209: active decisions first), built per render so that a superseded\n * decision's status can name its successor's display from `views`.\n */\nexport const DECISION_INDEX = (\n root: string,\n views: ReadonlyMap<string, DecisionView>,\n): IndexSpec<DecisionView> => ({\n tool: \"adr\",\n title: \"Architecture decisions\",\n groups: GROUPS.map((g) => ({\n heading: g.heading,\n filter: (v: DecisionView) => g.statuses.includes(v.status),\n })),\n columns: [\n { heading: \"Decision\", cell: (v) => escapeMarkdown(v.display) },\n {\n heading: \"Title\",\n cell: (v) =>\n v.body_path === null\n ? escapeMarkdown(v.title)\n : `[${escapeMarkdown(v.title)}](${encodeURI(posix.relative(root, v.body_path))})`,\n },\n {\n heading: \"Status\",\n cell: (v) =>\n v.status === \"superseded\" && v.superseded_by !== null\n ? `superseded by ${escapeMarkdown(views.get(v.superseded_by)?.display ?? v.superseded_by)}`\n : v.status,\n },\n { heading: \"Since\", cell: (v) => v.status_at.slice(0, 10) },\n ],\n order: (a, b) =>\n (a.number ?? Number.POSITIVE_INFINITY) - (b.number ?? Number.POSITIVE_INFINITY) ||\n cmp(a.status_at, b.status_at) ||\n cmp(a.id, b.id),\n});\n\n/**\n * The index `tree` must hold: its decisions, numbered as they will be once the commit holding\n * `tree` (which builds on `history`: HEAD, a commit, or null on an unborn HEAD) is on main\n * (design 2b D2), with `[log] main_branch`'s numbers first. A tree that isn't a commit's (the work\n * tree, the index) also merges `MERGE_HEAD` while a merge is in progress. In a shallow clone the\n * numbers continue from those `history`'s index recorded; `null` when there are none, so the\n * numbers can't be projected.\n */\nexport async function renderDecisionIndex(\n git: Git,\n o: {\n readonly layout: LogLayout;\n readonly adr: AdrConfig;\n readonly tree: TreeReader;\n readonly history: string | null;\n },\n): Promise<string | null> {\n return withGitOperation(async () => {\n const { layout, history } = o;\n const mergeHead =\n o.tree.commit === null && history !== null ? await git.resolveCommit(\"MERGE_HEAD\") : null;\n const numbering = await projectNumbering(git, {\n kind: adrKind,\n layout,\n history,\n tree: o.tree,\n mainRef: o.adr.mainBranch,\n merging: mergeHead === null ? [] : [mergeHead],\n recorded: async () =>\n history === null\n ? null\n : readIndexNumbers(await refReader(git, history), indexPath(layout)),\n });\n if (!numbering.available) return null;\n const read = await readDecisionsFrom(o.tree, { layout, adr: o.adr, numbering });\n const views = read.projection.views;\n return renderIndex(DECISION_INDEX(layout.root, views), [...views.values()], numbering);\n });\n}\n\n/** At most this many paths are named in the unstaged-files `index/stale` message. */\nconst UNSTAGED_NAMED = 5;\n\n/**\n * What the unstaged-files `index/stale` finding and the matching write note both start with:\n * `path` lists `files` (some of them), which aren't staged.\n */\nexport function unstagedIndexText(path: string, files: readonly string[]): string {\n const named = files.slice(0, UNSTAGED_NAMED).join(\", \");\n const more = files.length > UNSTAGED_NAMED ? \", …\" : \"\";\n return `${path} lists decision files that aren't staged (${named}${more})`;\n}\n\n/**\n * The log's event and body files whose work-tree content isn't staged (untracked or modified),\n * sorted: the cause of a staged `index.md` that only the work tree's render matches.\n */\nexport async function unstagedLogFiles(git: Git, layout: LogLayout): Promise<string[]> {\n const paths = [\n ...(await git.unstagedPaths([layout.root])),\n ...(await git.untrackedPaths([layout.root])),\n ];\n return [...new Set(paths)]\n .filter((p) => {\n const area = classifyPath(layout, p).area;\n return area === \"event\" || area === \"body\";\n })\n .sort();\n}\n\n/**\n * The verify check that `<root>/index.md` is current (design 2b §4.5, \"Freshness in verify\"). In\n * staged mode (the pre-commit hook), a stale staged copy that equals the work tree's render\n * means another decision's files aren't staged: writes stage the work tree's render (D2), and\n * `adr index` would change nothing. The finding then names those files and says to stage them.\n */\nexport function decisionIndexCheck(log: DecisionLog): Check {\n const path = indexPath(log.layout);\n const check = indexCheck({\n path,\n fix: \"run adr index\",\n async expected(ctx) {\n const head = ctx.repo?.head;\n const history =\n head === undefined\n ? null\n : typeof head === \"object\"\n ? head.commit\n : await log.git.resolveCommit(\"HEAD\");\n return renderDecisionIndex(log.git, {\n layout: log.layout,\n adr: log.adr,\n tree: ctx.head.tree,\n history,\n });\n },\n });\n return {\n id: check.id,\n async run(ctx) {\n const findings = await check.run(ctx);\n const stale = findings.find((f) => f.rule === \"index/stale\");\n if (stale === undefined || ctx.repo?.head !== \"index\") return findings;\n const files = await unstagedLogFiles(log.git, log.layout);\n if (files.length === 0) return findings;\n const worktree = await renderDecisionIndex(log.git, {\n layout: log.layout,\n adr: log.adr,\n tree: worktreeReader(log.git),\n history: await log.git.resolveCommit(\"HEAD\"),\n });\n if (worktree === null || !holdsText(await ctx.head.tree.read(path), worktree)) {\n return findings;\n }\n const message = `${unstagedIndexText(path, files)}; git add them and commit again, or move them out of the work tree and run adr index`;\n return findings.map((f) => (f === stale ? { ...f, message } : f));\n },\n };\n}\n\n/** `adr index`'s result and whether the work-tree refresh after a commit changed a copy. */\nexport interface IndexRun {\n readonly doc: IndexResultJson;\n /** With a commit requested: step 5 wrote or staged the work tree's render. */\n readonly refreshed: boolean;\n}\n\n/**\n * `adr index` (design 2b §4.5) with what the text output needs; `indexDecisionLog` is the\n * library entry.\n */\nexport async function runDecisionIndex(\n log: DecisionLog,\n o: WriteOptions & { readonly check?: boolean } = {},\n): Promise<IndexRun> {\n return withGitOperation(async () => {\n const path = indexPath(log.layout);\n const root = log.layout.root;\n const check = o.check === true;\n const notes = [...log.notes, ...(o.notes ?? [])];\n if (log.adr.index !== \"committed\") {\n throw new UsageError('adr index needs [log] index = \"committed\" in adr.toml');\n }\n if (check) {\n if (o.commit === true || (o.message !== undefined && o.message !== null)) {\n throw new UsageError(\"--check writes nothing; drop --commit and --message\");\n }\n const findings = await verifyLog({\n git: log.git,\n kind: adrKind,\n layout: log.layout,\n mode: { type: \"full\", ...(log.ref === null ? {} : { head: log.ref }) },\n checks: [decisionIndexCheck(log)],\n });\n const doc: IndexResultJson = {\n format: \"adr-index/v1\",\n path,\n check: true,\n fresh: findings.length === 0,\n written: [],\n commit: null,\n findings,\n notes,\n };\n return { doc, refreshed: false };\n }\n if (log.ref !== null || log.tree.label !== \"worktree\") {\n throw new UsageError(\"adr index writes the work tree; use --ref only with --check\");\n }\n const { git } = log;\n const commit = o.commit ?? log.adr.autoCommit;\n if (commit && ((await git.identity()) === null || (await git.committerIdentity()) === null)) {\n throw new ConfigError(\"--commit needs a git identity; set git user.name and user.email\");\n }\n const head = await git.resolveCommit(\"HEAD\");\n const render = (tree: TreeReader, history: string | null) =>\n renderDecisionIndex(git, { layout: log.layout, adr: log.adr, tree, history });\n const shallow = () =>\n new UsageError(\"numbers need history in this shallow clone; run git fetch --unshallow\");\n let written = false;\n const place = async (text: string): Promise<boolean> => {\n const r = await writeIndexCopy(git, path, text);\n if (r.stage) await git.add([path]);\n written ||= r.wrote;\n return r.wrote || r.stage;\n };\n\n if (!commit) {\n const text = await render(worktreeReader(git), head);\n if (text === null) throw shallow();\n const changed = await place(text);\n const doc: IndexResultJson = {\n format: \"adr-index/v1\",\n path,\n check: false,\n fresh: !changed,\n written: written ? [path] : [],\n commit: null,\n findings: [],\n notes,\n };\n return { doc, refreshed: false };\n }\n\n // The commit's only path is index.md, which the render doesn't read, so it renders HEAD's tree;\n // HEAD's copy decides whether there is anything to commit.\n const text = await render(await headTree(git, head), head);\n if (text === null) throw shallow();\n const fresh = holdsText(await headBytes(git, path), text);\n let sha: string | null = null;\n if (!fresh) {\n await place(text);\n const message =\n o.message ??\n renderCommitMessage(log.adr.commitSubject, {\n title: INDEX_TITLE,\n vars: { action: INDEX_ACTION, id: \"index.md\", display: \"index.md\", command: \"index\" },\n }).message;\n sha = await commitWithRecovery(git, {\n message,\n only: [path],\n rerun: INDEX_RERUN,\n after: INDEX_AFTER(root),\n });\n }\n // Step 5: other decisions' uncommitted entries go back into the work tree and the index.\n let refreshed = false;\n try {\n const again = await render(worktreeReader(git), sha ?? head);\n if (again !== null) refreshed = await place(again);\n } catch (err) {\n notes.push(`${path} may be stale: ${firstLine(err)}; run adr index`);\n }\n const doc: IndexResultJson = {\n format: \"adr-index/v1\",\n path,\n check: false,\n fresh,\n written: written ? [path] : [],\n commit: sha,\n findings: [],\n notes,\n };\n return { doc, refreshed };\n });\n}\n\n/**\n * `adr index [--check] [--commit | --no-commit] [-m <message>]` (design 2b §4.5): renders\n * `<root>/index.md` and writes and stages it where the work tree or the index differ. With\n * `commit` (default `[policy] auto_commit`) it renders HEAD's tree and commits the file alone when\n * HEAD's copy differs, then refreshes the work tree's copy, which may include other decisions'\n * uncommitted entries. `check` writes nothing and reports `index/*` findings.\n */\nexport async function indexDecisionLog(\n log: DecisionLog,\n o: WriteOptions & { readonly check?: boolean } = {},\n): Promise<IndexResultJson> {\n return (await runDecisionIndex(log, o)).doc;\n}\n","import {\n compileKind,\n foldLog,\n loadLog,\n MemoryTree,\n NO_NUMBERING,\n type Numbering,\n projectLog,\n readIndexNumbers,\n readSources,\n type SourceConfig,\n type SourceStatus,\n sourceLogRef,\n sourcesOfKinds,\n UsageError,\n withGitOperation,\n} from \"@nikovirtala/ledger\";\nimport { type AdrSource, adrKind, type ForeignDecision } from \"./kind.js\";\nimport { type DecisionLog, type DecisionsRead, readDecisionsFrom } from \"./log.js\";\n\nexport type { AdrSource, ForeignDecision };\n\nexport interface DecisionSources {\n /** Every `kind = \"adr\"` entry by name, for `AdrOptions.sources`. */\n readonly logs: ReadonlyMap<string, AdrSource>;\n /** What each `kind = \"adr\"` entry resolved to, for the report's `sources` field. */\n readonly statuses: readonly SourceStatus[];\n readonly notes: readonly string[];\n}\n\n/** The kinds adr reads from `[[sources]]`: only decision logs. */\nexport const DECISION_SOURCE_KINDS: readonly string[] = [\"adr\"];\n\nconst compiled = compileKind(adrKind);\n\n/** Numbers recorded in a source's committed index, as a `Numbering`. */\nfunction indexNumbering(byId: ReadonlyMap<string, number> | null): Numbering {\n if (byId === null) return NO_NUMBERING;\n return {\n available: true,\n reason: \"index\",\n ref: null,\n commit: null,\n byId,\n byNumber: new Map([...byId].map(([id, n]) => [n, id])),\n };\n}\n\n/** The `[[sources]]` entries adr reads and the ones it skips, in config order. */\nexport function decisionSourceConfigs(log: DecisionLog): {\n readonly sources: readonly SourceConfig[];\n readonly skipped: readonly SourceConfig[];\n} {\n const all = log.config?.sources ?? [];\n const sources = sourcesOfKinds(all, DECISION_SOURCE_KINDS);\n return { sources, skipped: all.filter((s) => !sources.includes(s)) };\n}\n\n/**\n * Reads the decision logs of the `kind = \"adr\"` `[[sources]]` entries (other kinds are never\n * fetched): from the local cache only with `fetch: \"cache\"` (the default), else fetched first\n * (`readSources`; a failed fetch throws `SourceFetchError`). A cached source's decisions are folded\n * with adr's kind and numbered from its committed `index.md` (the cache is a depth-1 clone, so\n * history numbering can't work), else shown by id.\n */\nexport async function readDecisionSources(\n log: DecisionLog,\n o: { readonly fetch?: \"cache\" | \"network\" } = {},\n): Promise<DecisionSources> {\n const { sources } = decisionSourceConfigs(log);\n const reads = await readSources(log.git, sources, { fetch: o.fetch ?? \"cache\" });\n const logs = new Map<string, AdrSource>();\n const notes: string[] = [];\n for (const r of reads) {\n if (r.source === null) {\n logs.set(r.config.name, { subjects: null, commit: null });\n continue;\n }\n const ref = sourceLogRef(r.source, {\n layout: adrKind.def.layout,\n defaultRoot: adrKind.def.defaultRoot,\n });\n const snapshot = await loadLog(ref.tree, { kind: compiled, layout: ref.layout });\n if (snapshot.subjects.size === 0) {\n notes.push(\n `source ${r.config.name} has no decision log at ${ref.layout.root} in ${r.source.commit.slice(0, 12)}`,\n );\n }\n const numbering = indexNumbering(\n await readIndexNumbers(ref.tree, `${ref.layout.root}/index.md`),\n );\n const projected = projectLog(adrKind, foldLog(adrKind, snapshot), { numbering }).views;\n logs.set(r.config.name, {\n commit: r.source.commit,\n subjects: new Map(\n [...projected].map(([id, v]) => [\n id,\n { status: v.status, display: v.display, title: v.title },\n ]),\n ),\n });\n }\n return { logs, statuses: reads.map((r) => r.status), notes };\n}\n\nconst SOURCE_NAME = /^[a-z][a-z0-9-]{0,31}$/;\n\n/**\n * The cached decision log of the `[[sources]]` entry `name`, as a `DecisionsRead` for `adr list\n * --source` and `adr search --source` (cache only, never the network). An uncached source reads as\n * an empty log with the note `<name> not fetched; run adr sources fetch`. Throws `UsageError` for a\n * name that isn't configured or whose kind adr doesn't read.\n */\nexport async function readSourceDecisions(log: DecisionLog, name: string): Promise<DecisionsRead> {\n return withGitOperation(async () => {\n if (!SOURCE_NAME.test(name)) {\n throw new UsageError(`--source must match ${SOURCE_NAME.source}: ${name}`);\n }\n const { sources, skipped } = decisionSourceConfigs(log);\n const other = skipped.find((s) => s.name === name);\n if (other !== undefined) {\n throw new UsageError(`source ${name} has kind ${other.kind}, which adr doesn't read`);\n }\n const config = sources.find((s) => s.name === name);\n if (config === undefined) {\n const known = [...sources, ...skipped].map((s) => s.name);\n throw new UsageError(\n known.length === 0\n ? `unknown source ${name}; there are no sources`\n : `unknown source ${name}; the sources are ${known.join(\", \")}`,\n );\n }\n const [r] = await readSources(log.git, [config], { fetch: \"cache\" });\n const base = { adr: log.adr, notes: [...log.notes], source: name };\n if (r?.source === undefined || r.source === null) {\n return readDecisionsFrom(new MemoryTree({}), {\n ...base,\n layout: adrKind.layoutAt(config.root ?? adrKind.def.defaultRoot),\n numbering: NO_NUMBERING,\n notes: [...base.notes, `${name} not fetched; run adr sources fetch`],\n });\n }\n const ref = sourceLogRef(r.source, {\n layout: adrKind.def.layout,\n defaultRoot: adrKind.def.defaultRoot,\n });\n return readDecisionsFrom(ref.tree, {\n ...base,\n layout: ref.layout,\n numbering: indexNumbering(await readIndexNumbers(ref.tree, `${ref.layout.root}/index.md`)),\n commit: r.source.commit,\n });\n });\n}\n","/**\n * The built-in decision templates, version 1 (design §5.7). `adr new` copies the one it uses into\n * `<root>/templates/<name>.md` on first use, so the team owns it and its versions live in git\n * (D4). Every section is required unless marked optional, and each has a required Scope section\n * (01:311).\n */\n\nconst NYGARD = `---\ntemplate: nygard\nversion: 1\nsections:\n - id: context\n heading: Context\n required: true\n guidance: What is the issue that motivates this decision? Describe the forces at play.\n - id: decision\n heading: Decision\n required: true\n guidance: What is the change that we're proposing or doing? Write it in the active voice.\n - id: scope\n heading: Scope\n required: true\n guidance: What does this decision govern? Name the systems, code paths or teams it applies to.\n - id: consequences\n heading: Consequences\n required: true\n guidance: What becomes easier or harder because of this change? Include the risks.\n---\n# {{title}}\n\n## Context\n{{context}}\n\n## Decision\n{{decision}}\n\n## Scope\n{{scope}}\n\n## Consequences\n{{consequences}}\n`;\n\nconst MADR = `---\ntemplate: madr\nversion: 1\nsections:\n - id: context\n heading: Context and Problem Statement\n required: true\n guidance: Describe the context and the problem in two or three sentences, or as a question.\n - id: drivers\n heading: Decision Drivers\n required: false\n guidance: List the forces and concerns that shape the decision.\n - id: options\n heading: Considered Options\n required: true\n guidance: List the options that were considered, one per line.\n - id: decision\n heading: Decision Outcome\n required: true\n guidance: Name the chosen option and say why it was chosen.\n - id: scope\n heading: Scope\n required: true\n guidance: What does this decision govern? Name the systems, code paths or teams it applies to.\n - id: consequences\n heading: Consequences\n required: true\n guidance: Describe the good and the bad consequences of the chosen option.\n---\n# {{title}}\n\n## Context and Problem Statement\n{{context}}\n\n## Decision Drivers\n{{drivers}}\n\n## Considered Options\n{{options}}\n\n## Decision Outcome\n{{decision}}\n\n## Scope\n{{scope}}\n\n## Consequences\n{{consequences}}\n`;\n\nconst Y_STATEMENT = `---\ntemplate: y-statement\nversion: 1\nsections:\n - id: statement\n heading: Statement\n required: true\n guidance: In the context of <use case>, facing <concern>, we decided for <option>, to achieve <quality>, accepting <downside>.\n - id: scope\n heading: Scope\n required: true\n guidance: What does this decision govern? Name the systems, code paths or teams it applies to.\n---\n# {{title}}\n\n## Statement\n{{statement}}\n\n## Scope\n{{scope}}\n`;\n\n/** The built-in templates by name: the file text `adr new` materializes. */\nexport const BUILTIN_TEMPLATES: Readonly<Record<string, string>> = Object.freeze({\n nygard: NYGARD,\n madr: MADR,\n \"y-statement\": Y_STATEMENT,\n});\n","import { readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n type Actor,\n applySetOp,\n bodyFileName,\n bodySha256,\n CommitFailedError,\n ConfigError,\n classifyPath,\n commitWithRecovery,\n compileKind,\n ENVELOPE_VERSION,\n type EventEnvelope,\n EventExistsError,\n type EventRef,\n eventDir,\n eventPath,\n eventTrailers,\n extractSections,\n FileExistsError,\n type Finding,\n finding,\n firstLine,\n followRenames,\n globMatcher,\n headBytes,\n headTree,\n historyTemplates,\n holdsText,\n InvalidArgumentError,\n indexReader,\n invalidateGitOperation,\n isSubjectId,\n joinActions,\n type LogLayout,\n lintDocument,\n lintTemplate,\n newSubjectId,\n nextEventIdentity,\n overlayTree,\n parseEventFileName,\n parseGlob,\n parseTemplate,\n type Rename,\n type RenderedCommit,\n refReader,\n renderCommitMessage,\n renderTemplate,\n replaceFile,\n replaceSections,\n type SetOp,\n saveCommitRecovery,\n serializeEvent,\n slugify,\n stagedRenames,\n type Template,\n type TemplateSource,\n type Trailer,\n type TreeReader,\n templateHistoryRef,\n UsageError,\n withGitOperation,\n withoutPaths,\n worktreeReader,\n writeEvents,\n writeIndexCopy,\n writeNewFile,\n} from \"@nikovirtala/ledger\";\nimport {\n ACTIONS,\n BATCH_ACTIONS,\n BATCH_ORDER,\n CROSS_LOG_LINK,\n DRAFT_ACTION,\n UPDATE_ACTION,\n} from \"./commit-actions.js\";\nimport { type AdrSource, adrKind, type DecisionView, type LinkRel } from \"./kind.js\";\nimport {\n type DecisionLog,\n type DecisionsRead,\n readDecisions,\n readDecisionsFrom,\n resolveDecision,\n} from \"./log.js\";\nimport {\n INDEX_AFTER,\n INDEX_BEFORE,\n indexPath,\n renderDecisionIndex,\n unstagedIndexText,\n unstagedLogFiles,\n} from \"./log-index.js\";\nimport { readDecisionSources } from \"./sources.js\";\nimport { BUILTIN_TEMPLATES } from \"./templates/builtin.js\";\n\n/** `adr <write command> --json` (design §5.5, §6.1). */\nexport interface WriteResultJson {\n readonly format: \"adr-write/v1\";\n readonly command:\n | \"new\"\n | \"accept\"\n | \"supersede\"\n | \"reject\"\n | \"withdraw\"\n | \"deprecate\"\n | \"note\"\n | \"link\"\n | \"scope\"\n | \"update\";\n readonly ok: boolean;\n /**\n * The decision after the write; before it when `ok` is false (`null` for a refused `new`).\n * After a commit it is read again from the log, so an acceptance committed on the main ref\n * carries its number; otherwise `number` is `null` until the acceptance lands on main. In a\n * shallow clone with a committed index, the number comes from HEAD's `index.md`, which on a\n * branch is the number the decision will get once the branch merges.\n */\n readonly decision: DecisionView | null;\n /** Each decision superseded by this write, after it (read again after a commit, like `decision`). */\n readonly affected: readonly DecisionView[];\n /** Repo-relative paths this command wrote, in write order. */\n readonly written: readonly string[];\n readonly commit: string | null;\n /** Refusal findings when `ok` is false; the draft's template lint for `new` (informational). */\n readonly findings: readonly Finding[];\n /**\n * How the log was located (`ToolLog.notes`), then the caller's notes (attribution), then the\n * write's own (a shortened commit subject, …).\n */\n readonly notes: readonly string[];\n}\n\n/** What every write function takes besides its input (design §6.1). */\nexport interface WriteOptions {\n /** Commit the write; default `[policy] auto_commit`. */\n readonly commit?: boolean;\n /** The commit message to use instead of the `[commit] subject` one; used only when committing. */\n readonly message?: string | null;\n /** Notes to report before the write's own, such as the attribution notes. */\n readonly notes?: readonly string[];\n /**\n * With `[log] index = \"committed\"`: `\"refresh\"` (the default) keeps `<root>/index.md` fresh;\n * `\"skip\"` leaves it alone (the pre-commit hook's rename following, design 2b D8).\n */\n readonly index?: \"refresh\" | \"skip\";\n}\n\nexport interface ProposeInput {\n readonly title: string;\n /** Default `[log] default_template`. */\n readonly template?: string;\n /** Section id → markdown. */\n readonly sections?: Readonly<Record<string, string>>;\n /** Decisions this one is meant to replace, as ids or numbers. */\n readonly supersedes?: readonly string[];\n readonly actor: Actor;\n}\n\n/** What a plan needs besides the read: a clock, randomness and templates. */\nexport interface PlanContext {\n /** Clock for `nextEventIdentity`. */\n readonly now: () => number;\n /** ULID and subject-id randomness. */\n readonly random?: (buf: Uint8Array) => void;\n /** Drafts' recorded template versions. */\n readonly templates: TemplateSource;\n /** Built-in template texts by name (§5.7), for `new`. */\n readonly builtins: Readonly<Record<string, string>>;\n}\n\n/** Everything one write command does, computed without touching git or the disk. */\nexport interface WritePlan {\n readonly command: \"new\" | \"accept\" | \"supersede\" | \"event\";\n readonly subject: string;\n /** New files, repo-relative path → bytes, in write order: body, materialized template, events. */\n readonly files: Readonly<Record<string, Uint8Array>>;\n /**\n * Existing files to replace, path → the new bytes and the bytes the plan read; written only if\n * the file still holds `expected` (a draft update).\n */\n readonly replace?: Readonly<\n Record<string, { readonly bytes: Uint8Array; readonly expected: Uint8Array }>\n >;\n readonly events: readonly EventEnvelope[];\n /** Paths to stage: every new file, plus the existing body for accept. */\n readonly stage: readonly string[];\n /** Subject ids involved (D6): the subject, every superseded target, and `by` for supersede. Sorted. */\n readonly involved: readonly string[];\n /** Per involved subject: its body, its events dir and its recorded template. Sorted, deduplicated. */\n readonly commitScope: readonly string[];\n /** The events directories in `commitScope`, sorted; the rest of `commitScope` are file paths. */\n readonly eventDirs: readonly string[];\n /** For new: the body path, the rendered bytes and the template, for the editor step. */\n readonly draft: {\n readonly path: string;\n readonly rendered: Uint8Array;\n readonly template: Template;\n } | null;\n /** What the commit message is made of; `write()` renders it with `[commit] subject`. */\n readonly commit: CommitParts | null;\n /** One `ADR`/`ADR-Event` pair per plan event, in write order. */\n readonly trailers: readonly Trailer[];\n /** Views after the write, computed on `overlayTree(read.tree, files)`. */\n readonly decision: DecisionView | null;\n readonly affected: readonly DecisionView[];\n /** Informational (new: the draft's template lint). */\n readonly findings: readonly Finding[];\n /** The write's own notes for the result (an already existing link, …). */\n readonly notes?: readonly string[];\n}\n\n/** The parts of a commit message (design §4.3): the template's variables and the body. */\nexport interface CommitParts {\n /** `{action}`, the verb phrase, e.g. `propose to` or `set the scope of`. */\n readonly action: string;\n /**\n * The text after `{action}`, which `{title}` and `{raw_title}` come from: the decision's title\n * as recorded for propose, accept, reject and withdraw, else its display (`ADR-0006`, or\n * `ADR-0006 with ADR-0007` for supersede).\n */\n readonly title: string;\n readonly id: string;\n readonly display: string;\n /** Body paragraphs, each wrapped at 72. */\n readonly body: readonly string[];\n}\n\nexport type PlanResult =\n | { readonly ok: true; readonly plan: WritePlan }\n | {\n readonly ok: false;\n readonly decision: DecisionView | null;\n readonly findings: readonly Finding[];\n };\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst compiled = compileKind(adrKind);\nconst TEMPLATE_NAME = /^[a-z][a-z0-9-]*$/;\nconst MAX_TEXT_BYTES = 64 * 1024;\nconst SUBJECT_ATTEMPTS = 5;\nconst QUALIFIED_SUPERSESSION = \"cross-log supersession isn't supported yet\";\n\nconst sorted = (xs: Iterable<string>): string[] => [...new Set(xs)].sort();\nconst templatePath = (read: DecisionsRead, name: string) => `${read.root}/templates/${name}.md`;\n\n/** A text argument within the 64 KiB cap and without NUL characters, else `UsageError`. */\nfunction checkText(what: string, text: string): void {\n if (text.includes(\"\\0\")) throw new UsageError(`${what} must not contain NUL characters`);\n const size = encoder.encode(text).byteLength;\n if (size > MAX_TEXT_BYTES) {\n throw new UsageError(`${what} is ${size} bytes; the limit is ${MAX_TEXT_BYTES} (64 KiB)`);\n }\n}\n\nfunction checkReason(reason: string | null | undefined): string | null {\n if (reason === undefined || reason === null) return null;\n const r = reason.trim();\n if (r === \"\") throw new UsageError(\"--reason must not be empty\");\n checkText(\"--reason\", r);\n return r;\n}\n\n/** The view of a folded decision, else `UsageError` naming why it can't be used. */\nfunction viewOf(read: DecisionsRead, id: string): DecisionView {\n const view = read.projection.views.get(id);\n if (view !== undefined) return view;\n if (read.projection.unreadable.includes(id)) {\n throw new UsageError(`decision ${id} uses a newer format; upgrade adr`);\n }\n throw new UsageError(`decision ${id} can't be read; run adr verify`);\n}\n\n/** A refusal finding about decision `subject`, on its body (or events directory). */\nfunction refusal(read: DecisionsRead, rule: string, message: string, subject: string): Finding {\n const loaded = read.folded.subjects.get(subject)?.loaded;\n return finding({\n severity: \"error\",\n rule,\n message,\n file: loaded?.bodyPaths[0] ?? eventDir(read.layout, subject),\n subject,\n kind: adrKind.name,\n });\n}\n\n/** `\"<type> is not allowed while <status>[; <status> is terminal]\"`, as the fold words it. */\nfunction illegal(type: string, status: string): string {\n const terminal = adrKind.machine.terminal.includes(status as never)\n ? `; ${status} is terminal`\n : \"\";\n return `${type} is not allowed while ${status}${terminal}`;\n}\n\n/** A new event of `subject`, sorting after its existing ones. */\nfunction newEvent(\n read: DecisionsRead,\n c: PlanContext,\n o: {\n readonly subject: string;\n readonly type: string;\n readonly data: Record<string, unknown>;\n readonly reason?: string | null;\n readonly actor: Actor;\n readonly after?: readonly EventEnvelope[];\n },\n): EventEnvelope {\n const existing = (read.folded.subjects.get(o.subject)?.loaded.events ?? []).flatMap((e) =>\n e.event === null ? [] : [e.event],\n );\n const { at, id } = nextEventIdentity([...existing, ...(o.after ?? [])], {\n now: c.now,\n ...(c.random === undefined ? {} : { random: c.random }),\n });\n return {\n envelope: ENVELOPE_VERSION,\n kind: adrKind.name,\n schema: adrKind.schema,\n id,\n subject: o.subject,\n type: o.type,\n at,\n actor: o.actor,\n ...(o.reason === undefined || o.reason === null ? {} : { reason: o.reason }),\n data: o.data,\n };\n}\n\n/** Body, events directory and recorded template of each involved subject (D6). */\nfunction commitScope(\n read: DecisionsRead,\n involved: readonly string[],\n extra: { readonly body?: string; readonly template?: string } = {},\n): { scope: string[]; eventDirs: string[] } {\n const paths: string[] = [];\n const dirs: string[] = [];\n for (const id of involved) {\n const view = read.projection.views.get(id);\n if (view?.body_path !== null && view?.body_path !== undefined) paths.push(view.body_path);\n if (view !== undefined) paths.push(templatePath(read, view.template.name));\n dirs.push(eventDir(read.layout, id));\n }\n if (extra.body !== undefined) paths.push(extra.body);\n if (extra.template !== undefined) paths.push(extra.template);\n return { scope: sorted([...paths, ...dirs]), eventDirs: sorted(dirs) };\n}\n\nconst findingKey = (f: Finding) => [f.rule, f.subject ?? \"\", f.file ?? \"\", f.message].join(\"\\0\");\n\n/**\n * The precheck (§6.3): folds the would-be log and refuses when the write adds any finding. Problems\n * that were already there don't block; the write can only add findings about what it touches.\n */\nasync function precheck(\n read: DecisionsRead,\n files: Readonly<Record<string, Uint8Array>>,\n replace: Readonly<Record<string, Uint8Array>> = {},\n): Promise<{ after: DecisionsRead; added: Finding[] }> {\n const after = await readDecisionsFrom(overlayTree(read.tree, { ...files, ...replace }), {\n layout: read.layout,\n adr: read.adr,\n numbering: read.numbering,\n ref: read.ref,\n commit: read.commit,\n notes: read.notes,\n sources: read.sources,\n });\n const before = new Set(read.findings.map(findingKey));\n return { after, added: after.findings.filter((f) => !before.has(findingKey(f))) };\n}\n\nfunction filesOf(\n events: readonly EventEnvelope[],\n read: DecisionsRead,\n): Record<string, Uint8Array> {\n return Object.fromEntries(\n events.map((e) => [eventPath(read.layout, e), encoder.encode(serializeEvent(e))]),\n );\n}\n\nconst pairsOf = (events: readonly EventEnvelope[]): Trailer[] =>\n events.flatMap((e): Trailer[] => [\n [\"ADR\", e.subject],\n [\"ADR-Event\", e.type],\n ]);\n\n/** The template `new` uses: the repo's `<root>/templates/<name>.md`, else a built-in to copy. */\nasync function chooseTemplate(\n read: DecisionsRead,\n name: string,\n c: PlanContext,\n): Promise<\n | { ok: true; template: Template; materialize: string | null; path: string }\n | { ok: false; findings: Finding[] }\n> {\n if (name.length > 64 || !TEMPLATE_NAME.test(name)) {\n throw new UsageError(`invalid template name ${JSON.stringify(name)}`);\n }\n const path = templatePath(read, name);\n const bytes = await read.tree.read(path);\n let text: string;\n let materialize: string | null = null;\n if (bytes !== null) {\n text = decoder.decode(bytes);\n } else {\n const builtin = Object.hasOwn(c.builtins, name) ? c.builtins[name] : undefined;\n if (builtin === undefined) {\n const known = Object.keys(c.builtins).sort().join(\", \");\n throw new UsageError(`unknown template ${name}; add ${path} or use one of ${known}`);\n }\n text = builtin;\n materialize = builtin;\n }\n const parsed = parseTemplate(text, { path });\n if (!parsed.ok) return { ok: false, findings: parsed.findings };\n const lint = lintTemplate(parsed.template, {\n requireSections: adrKind.def.templates?.requireSections ?? [],\n });\n if (lint.length > 0) return { ok: false, findings: lint };\n return { ok: true, template: parsed.template, materialize, path };\n}\n\n/**\n * Plans `adr new`: a rendered body, a materialized template if needed, and `proposed`. With\n * `refuseIncomplete` (a commit with no editor to fill the draft in, design §7.2), a draft that\n * fails the template lint is refused with those findings before any file is planned.\n */\nexport async function planPropose(\n read: DecisionsRead,\n input: ProposeInput,\n c: PlanContext,\n o: { readonly refuseIncomplete?: boolean } = {},\n): Promise<PlanResult> {\n const title = input.title.trim();\n if (title === \"\" || title.length > 200 || /[\\r\\n]/.test(title)) {\n throw new UsageError(\"the title must be a single line of 1 to 200 characters\");\n }\n const supersedes = sorted(\n (input.supersedes ?? []).map((s) => {\n if (s.includes(\":\"))\n throw new UsageError(`cannot supersede ${s.trim()}: ${QUALIFIED_SUPERSESSION}`);\n return resolveDecision(read, s);\n }),\n );\n const chosen = await chooseTemplate(read, input.template ?? read.adr.defaultTemplate, c);\n if (!chosen.ok) return { ok: false, decision: null, findings: chosen.findings };\n const t = chosen.template;\n const sections = input.sections ?? {};\n for (const [id, text] of Object.entries(sections)) {\n if (!t.sections.some((s) => s.id === id)) {\n const ids = t.sections.map((s) => s.id).join(\", \");\n throw new UsageError(`template ${t.name} has no section ${id}; its sections are ${ids}`);\n }\n checkText(`section ${id}`, text);\n }\n const rendered = renderTemplate(t, { title, sections }, { missing: \"guidance\" });\n if (!rendered.ok) throw new UsageError(rendered.findings.map((f) => f.message).join(\"; \"));\n\n let id = \"\";\n let bodyPath = \"\";\n for (let attempt = 0; ; attempt++) {\n id = newSubjectId(c.random);\n bodyPath = `${read.root}/${read.layout.bodies}/${bodyFileName(id, slugify(title))}`;\n if (!read.folded.subjects.has(id) && (await read.tree.read(bodyPath)) === null) break;\n if (attempt + 1 >= SUBJECT_ATTEMPTS) throw new FileExistsError(bodyPath);\n }\n const lint = lintDocument(t, rendered.text, { file: bodyPath, subject: id });\n if (o.refuseIncomplete === true && lint.length > 0) {\n return { ok: false, decision: null, findings: lint };\n }\n const event = newEvent(read, c, {\n subject: id,\n type: \"proposed\",\n data: {\n title,\n template: t.name,\n template_version: t.version,\n ...(supersedes.length === 0 ? {} : { supersedes }),\n },\n actor: input.actor,\n });\n const body = encoder.encode(rendered.text);\n const files: Record<string, Uint8Array> = { [bodyPath]: body };\n if (chosen.materialize !== null) files[chosen.path] = encoder.encode(chosen.materialize);\n Object.assign(files, filesOf([event], read));\n\n const { after, added } = await precheck(read, files);\n if (added.length > 0) return { ok: false, decision: null, findings: added };\n const { scope, eventDirs } = commitScope(read, [id], { body: bodyPath, template: chosen.path });\n return {\n ok: true,\n plan: {\n command: \"new\",\n subject: id,\n files,\n events: [event],\n stage: Object.keys(files),\n involved: [id],\n commitScope: scope,\n eventDirs,\n draft: { path: bodyPath, rendered: body, template: t },\n commit: { action: ACTIONS.proposed.action, title, id, display: id, body: [] },\n trailers: pairsOf([event]),\n decision: viewOf(after, id),\n affected: [],\n findings: lint,\n },\n };\n}\n\n/** The draft lint of an `accept`: the body against the template version its proposal recorded. */\nasync function acceptLint(\n read: DecisionsRead,\n view: DecisionView,\n c: PlanContext,\n): Promise<{ findings: Finding[]; bytes: Uint8Array | null }> {\n const body = read.folded.subjects.get(view.id)?.loaded.body ?? null;\n if (body === null) {\n return {\n findings: [refusal(read, \"body/missing\", \"body file is missing\", view.id)],\n bytes: null,\n };\n }\n const { name, version } = view.template;\n const found = await c.templates.get(name, version);\n if (!found.ok) {\n const message =\n found.reason === \"not-found\"\n ? `template ${name} not found at ${found.path}`\n : `template ${name} has no version ${version} at ${found.path}`;\n return {\n findings: [refusal(read, `template/${found.reason}`, message, view.id)],\n bytes: body.bytes,\n };\n }\n let text: string;\n try {\n text = new TextDecoder(\"utf-8\", { fatal: true }).decode(body.bytes);\n } catch {\n return {\n findings: [refusal(read, \"body/not-utf8\", \"body is not valid UTF-8\", view.id)],\n bytes: body.bytes,\n };\n }\n const lint = lintDocument(found.template, text, { file: body.path, subject: view.id });\n return { findings: lint.map((f) => ({ ...f, kind: adrKind.name })), bytes: body.bytes };\n}\n\n/** Input of a draft update: the decision and the sections to replace (section id → markdown). */\nexport interface UpdateDraftInput {\n readonly id: string;\n readonly sections: Readonly<Record<string, string>>;\n}\n\nconst MAX_SECTIONS = 50;\n\n/**\n * Plans a draft update (design §6.6): the given sections of a proposed decision's body replaced in\n * place, every other line kept, written only if the body still holds the bytes read. Refused\n * (`ok: false`) when the decision isn't proposed or its body or template version is missing or\n * unreadable, and with `refuseIncomplete` when the new draft fails its template lint. An unknown\n * section, a missing heading or a heading in the content is a `UsageError`.\n */\nexport async function planUpdateDraft(\n read: DecisionsRead,\n input: UpdateDraftInput,\n c: PlanContext,\n o: { readonly refuseIncomplete?: boolean } = {},\n): Promise<PlanResult> {\n const id = resolveDecision(read, input.id);\n const view = viewOf(read, id);\n const refused = (fs: readonly Finding[]): PlanResult => ({\n ok: false,\n decision: view,\n findings: fs,\n });\n if (view.status !== \"proposed\") {\n return refused([\n refusal(\n read,\n \"decision/not-a-draft\",\n `${namedView(view)} is ${view.status}; only a proposed decision's draft can change`,\n id,\n ),\n ]);\n }\n const ids = Object.keys(input.sections);\n if (ids.length === 0 || ids.length > MAX_SECTIONS) {\n throw new UsageError(`a draft update takes 1 to ${MAX_SECTIONS} sections`);\n }\n for (const [section, text] of Object.entries(input.sections))\n checkText(`section ${section}`, text);\n const { findings: problems, template, text, body } = await draftOf(read, view, c);\n if (problems.length > 0 || template === null || text === null || body === null) {\n return refused(problems);\n }\n const r = replaceSections(template, text, input.sections);\n if (!r.ok) {\n const [first] = r.findings;\n if (first?.rule === \"render/unknown-section\") {\n const known = template.sections.map((s) => s.id).join(\", \");\n const unknown = ids.find((s) => !template.sections.some((t) => t.id === s)) ?? \"\";\n throw new UsageError(\n `template ${template.name} has no section ${unknown}; its sections are ${known}`,\n );\n }\n if (first?.rule === \"render/section-missing\") {\n const gone = new Set(extractSections(template, text).missing);\n const missing = template.sections.find((s) => ids.includes(s.id) && gone.has(s.id));\n throw new UsageError(\n `${body.path} has no '${missing?.heading ?? \"\"}' heading; edit the file by hand`,\n );\n }\n throw new UsageError(r.findings.map((f) => f.message).join(\"; \"));\n }\n if (r.text === text) {\n return emptyPlan(id, view, [\"the draft already has this content; nothing written\"]);\n }\n const bytes = encoder.encode(r.text);\n const lint = lintDocument(template, r.text, { file: body.path, subject: id }).map((f) => ({\n ...f,\n kind: adrKind.name,\n }));\n if (o.refuseIncomplete === true && lint.length > 0) return refused(lint);\n const { after, added } = await precheck(read, {}, { [body.path]: bytes });\n if (added.length > 0) return refused(added);\n const { scope, eventDirs } = commitScope(read, [id]);\n const order = template.sections.map((s) => s.id).filter((s) => ids.includes(s));\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject: id,\n files: {},\n replace: { [body.path]: { bytes, expected: body.bytes } },\n events: [],\n stage: [body.path],\n involved: [id],\n commitScope: scope,\n eventDirs,\n draft: null,\n commit: {\n action: DRAFT_ACTION,\n title: view.display,\n id,\n display: view.display,\n body: [`Sections: ${order.join(\", \")}.`],\n },\n trailers: [[\"ADR\", id]],\n decision: after.projection.views.get(id) ?? view,\n affected: [],\n findings: lint,\n },\n };\n}\n\n/**\n * A proposed decision's body, its text and the template version its proposal recorded, or the\n * refusal findings when one of them is missing or the body isn't UTF-8.\n */\nasync function draftOf(\n read: DecisionsRead,\n view: DecisionView,\n c: PlanContext,\n): Promise<{\n findings: Finding[];\n template: Template | null;\n text: string | null;\n body: { readonly path: string; readonly bytes: Uint8Array } | null;\n}> {\n const none = { template: null, text: null, body: null };\n const body = read.folded.subjects.get(view.id)?.loaded.body ?? null;\n if (body === null) {\n return { findings: [refusal(read, \"body/missing\", \"body file is missing\", view.id)], ...none };\n }\n const { name, version } = view.template;\n const found = await c.templates.get(name, version);\n if (!found.ok) {\n const message =\n found.reason === \"not-found\"\n ? `template ${name} not found at ${found.path}`\n : `template ${name} has no version ${version} at ${found.path}`;\n return { findings: [refusal(read, `template/${found.reason}`, message, view.id)], ...none };\n }\n try {\n const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(body.bytes);\n return { findings: [], template: found.template, text, body };\n } catch {\n return {\n findings: [refusal(read, \"body/not-utf8\", \"body is not valid UTF-8\", view.id)],\n ...none,\n };\n }\n}\n\n/** Plans `adr accept`: `accepted` with the body hash, and `superseded` on each declared target. */\nexport async function planAccept(\n read: DecisionsRead,\n input: { readonly id: string; readonly actor: Actor },\n c: PlanContext,\n o: { readonly copyGlobs?: readonly string[]; readonly tracked?: readonly string[] } = {},\n): Promise<PlanResult> {\n const id = resolveDecision(read, input.id);\n const view = viewOf(read, id);\n const refused = (findings: readonly Finding[]): PlanResult => ({\n ok: false,\n decision: view,\n findings,\n });\n const findings: Finding[] = [];\n if (view.status !== \"proposed\") {\n findings.push(refusal(read, \"transition/illegal\", illegal(\"accepted\", view.status), id));\n }\n const lint = await acceptLint(read, view, c);\n findings.push(...lint.findings);\n if (read.adr.acceptRequiresHuman && input.actor.kind === \"agent\") {\n findings.push(\n refusal(\n read,\n \"decision/agent-accepted\",\n `accepted by agent ${input.actor.name}; accept_requires_human needs a human`,\n id,\n ),\n );\n }\n const targets: string[] = [];\n for (const target of view.declared_supersedes) {\n if (target.includes(\":\")) {\n findings.push(\n refusal(\n read,\n \"decision/reference-missing\",\n `supersedes ${target}: ${QUALIFIED_SUPERSESSION}`,\n id,\n ),\n );\n continue;\n }\n const t = read.projection.views.get(target);\n if (t === undefined) {\n findings.push(\n refusal(\n read,\n \"decision/reference-missing\",\n `supersedes ${target}, which is not in the log`,\n id,\n ),\n );\n } else if (target === id) {\n findings.push(\n refusal(read, \"decision/supersession-cycle\", `supersession cycle: ${id} → ${id}`, id),\n );\n } else if (t.status !== \"accepted\" && t.status !== \"deprecated\") {\n findings.push(refusal(read, \"transition/illegal\", illegal(\"superseded\", t.status), target));\n } else {\n targets.push(target);\n }\n }\n if (findings.length > 0 || lint.bytes === null) return refused(findings);\n\n const accepted = newEvent(read, c, {\n subject: id,\n type: \"accepted\",\n data: { body_sha256: bodySha256(lint.bytes) },\n actor: input.actor,\n });\n const cascade = targets.map((target) =>\n newEvent(read, c, {\n subject: target,\n type: \"superseded\",\n data: { by: id },\n actor: input.actor,\n }),\n );\n // Copying the superseded scope (design §6.10): one `scoped` event with the union, in the same\n // batch. `scoped` is allowed while proposed and accepted, so its order against `accepted`\n // doesn't change the fold.\n const copyGlobs = o.copyGlobs ?? [];\n const copied =\n copyGlobs.length === 0\n ? null\n : newEvent(read, c, {\n subject: id,\n type: \"scoped\",\n data: {\n set: [\n ...applySetOp(view.applies_to, { add: copyGlobs }, { what: \"glob\", maxItems: 200 })\n .set,\n ],\n },\n actor: input.actor,\n after: [accepted],\n });\n if (copied !== null) {\n const valid = compiled.validate(copied, { file: null });\n if (!valid.ok) {\n return refused(valid.findings.map((f) => ({ ...f, subject: id, kind: adrKind.name })));\n }\n }\n const sources = copied === null ? [] : scopeToCopy(read, id).sources;\n const events = [accepted, ...(copied === null ? [] : [copied]), ...cascade];\n const files = filesOf(events, read);\n const { after, added } = await precheck(read, files);\n if (added.length > 0) return refused(added);\n const involved = sorted([id, ...targets]);\n const { scope, eventDirs } = commitScope(read, involved);\n const bodyPath = view.body_path ?? \"\";\n // Accepted, the decision's globs must match (?7): say so for each one that doesn't yet.\n const globs = copied === null ? view.applies_to : (copied.data.set as readonly string[]);\n const unmatched = o.tracked === undefined ? [] : unmatchedGlobs(globs, o.tracked);\n return {\n ok: true,\n plan: {\n ...(unmatched.length === 0\n ? {}\n : {\n notes: unmatched.map(\n (g) =>\n `${g} matches no tracked file; from this commit verify reports scope/glob-unmatched until a file matches, so commit the files with it or change the scope`,\n ),\n }),\n command: \"accept\",\n subject: id,\n files,\n events,\n stage: [...Object.keys(files), bodyPath],\n involved,\n commitScope: scope,\n eventDirs,\n draft: null,\n commit: {\n action: ACTIONS.accepted.action,\n title: view.title,\n id,\n display: view.display,\n body: [\n ...targets.map((t) => {\n const v = viewOf(read, t);\n return `Supersedes ${v.display}: ${sentenceTitle(v.title)}.`;\n }),\n ...sources.map((t) => `Copies the scope of ${viewOf(read, t).display}.`),\n ],\n },\n trailers: pairsOf(events),\n decision: viewOf(after, id),\n affected: targets.map((t) => viewOf(after, t)),\n findings: [],\n },\n };\n}\n\n/** The scope an `accept` can copy from the decisions it supersedes (design §6.10). */\nexport interface ScopeOffer {\n /** The decision being accepted. */\n readonly id: string;\n /** The superseded decisions with globs the accepted one lacks, sorted by id. */\n readonly sources: readonly string[];\n /** Their displays (`ADR-0002`, or the id), in `sources` order. */\n readonly displays: readonly string[];\n /** The globs to add: the union of their scopes minus the accepted decision's own, sorted. */\n readonly globs: readonly string[];\n}\n\n/**\n * Whether `accept` copies the superseded decisions' scope: always, never, never but with a note\n * naming the `adr scope` command that would (the default), or as a function decides.\n */\nexport type CopyScope = \"copy\" | \"skip\" | \"suggest\" | ((offer: ScopeOffer) => Promise<boolean>);\n\n/**\n * What accepting `id` could copy: the declared targets it will supersede (accepted or\n * deprecated, as `planAccept` selects them) and the globs of theirs it doesn't have yet.\n */\nexport function scopeToCopy(read: DecisionsRead, id: string): ScopeOffer {\n const own = new Set(viewOf(read, id).applies_to);\n const sources: string[] = [];\n const globs = new Set<string>();\n for (const target of sorted(viewOf(read, id).declared_supersedes)) {\n const t = target === id ? undefined : read.projection.views.get(target);\n if (t === undefined || (t.status !== \"accepted\" && t.status !== \"deprecated\")) continue;\n const extra = t.applies_to.filter((g) => !own.has(g));\n if (extra.length === 0) continue;\n sources.push(target);\n for (const g of extra) globs.add(g);\n }\n return {\n id,\n sources,\n displays: sources.map((t) => viewOf(read, t).display),\n globs: sorted(globs),\n };\n}\n\nconst shQuote = (s: string) => `'${s.replaceAll(\"'\", \"'\\\\''\")}'`;\nconst andList = (xs: readonly string[]) =>\n xs.length <= 1 ? xs.join(\"\") : `${xs.slice(0, -1).join(\", \")} and ${xs.at(-1)}`;\n\n/** The note of an offer not taken: the `adr scope` command that copies it. */\nfunction copyScopeNote(id: string, offer: ScopeOffer): string {\n const n = offer.globs.length;\n const adds = offer.globs.map((g) => `--add ${shQuote(g)}`).join(\" \");\n return `not copying the scope of ${andList(offer.displays)} (${n} ${n === 1 ? \"glob\" : \"globs\"}); to copy it: adr scope ${id} ${adds}`;\n}\n\n/** Plans `adr supersede <id> --by <by>`: one `superseded` event on `id`. */\nexport async function planSupersede(\n read: DecisionsRead,\n input: {\n readonly id: string;\n readonly by: string;\n readonly reason?: string | null;\n readonly actor: Actor;\n },\n c: PlanContext,\n): Promise<PlanResult> {\n if (input.by.includes(\":\")) {\n throw new UsageError(`--by ${input.by.trim()}: ${QUALIFIED_SUPERSESSION}`);\n }\n const reason = checkReason(input.reason);\n const id = resolveDecision(read, input.id);\n const by = resolveDecision(read, input.by);\n const view = viewOf(read, id);\n const target = viewOf(read, by);\n const findings: Finding[] = [];\n if (view.status !== \"accepted\" && view.status !== \"deprecated\") {\n findings.push(refusal(read, \"transition/illegal\", illegal(\"superseded\", view.status), id));\n }\n if (by === id || target.chain.includes(id)) {\n const cycle =\n by === id ? [id, id] : [id, ...target.chain.slice(0, target.chain.indexOf(id) + 1)];\n findings.push(\n refusal(read, \"decision/supersession-cycle\", `supersession cycle: ${cycle.join(\" → \")}`, id),\n );\n } else if (target.status !== \"accepted\") {\n findings.push(\n refusal(\n read,\n \"decision/superseded-by-unaccepted\",\n `superseded by ${by}, which is not accepted`,\n id,\n ),\n );\n }\n const refused = (fs: readonly Finding[]): PlanResult => ({\n ok: false,\n decision: view,\n findings: fs,\n });\n if (findings.length > 0) return refused(findings);\n\n const event = newEvent(read, c, {\n subject: id,\n type: \"superseded\",\n data: { by },\n reason,\n actor: input.actor,\n });\n const files = filesOf([event], read);\n const { after, added } = await precheck(read, files);\n if (added.length > 0) return refused(added);\n const involved = sorted([id, by]);\n const { scope, eventDirs } = commitScope(read, involved);\n return {\n ok: true,\n plan: {\n command: \"supersede\",\n subject: id,\n files,\n events: [event],\n stage: Object.keys(files),\n involved,\n commitScope: scope,\n eventDirs,\n draft: null,\n commit: {\n action: ACTIONS.superseded.action,\n title: `${view.display} with ${target.display}`,\n id,\n display: view.display,\n body: [`Superseded by ${target.display}: ${sentenceTitle(target.title)}.`],\n },\n trailers: pairsOf([event]),\n decision: viewOf(after, id),\n affected: [viewOf(after, id)],\n findings: [],\n },\n };\n}\n\nconst actionOf = (type: string): { action: string; names: \"title\" | \"display\" } =>\n Object.hasOwn(ACTIONS, type)\n ? ACTIONS[type as keyof typeof ACTIONS]\n : { action: type, names: \"display\" };\n\n/** A title in a body sentence: whitespace collapsed and trailing dots removed, as in a subject. */\nconst sentenceTitle = (title: string) =>\n title\n .replace(/\\s+/g, \" \")\n .replace(/[. ]+$/, \"\")\n .trim();\n\n/**\n * Plans any one event on an existing decision: the state machine and the event's validation\n * decide, then the precheck. Phase 2's reject, withdraw, deprecate, note, link and scope wrap it.\n */\nexport async function planEvent(\n read: DecisionsRead,\n input: {\n readonly subject: string;\n readonly type: string;\n readonly data: Record<string, unknown>;\n readonly reason?: string | null;\n readonly actor: Actor;\n },\n c: PlanContext,\n): Promise<PlanResult> {\n const id = resolveDecision(read, input.subject);\n const view = viewOf(read, id);\n if (!adrKind.machine.types.has(input.type) || input.type === adrKind.machine.initial.type) {\n throw new InvalidArgumentError(`planEvent can't write a ${input.type} event`);\n }\n const reason = checkReason(input.reason);\n const refused = (fs: readonly Finding[]): PlanResult => ({\n ok: false,\n decision: view,\n findings: fs,\n });\n if (!adrKind.machine.allowed(view.status, input.type)) {\n return refused([refusal(read, \"transition/illegal\", illegal(input.type, view.status), id)]);\n }\n const event = newEvent(read, c, {\n subject: id,\n type: input.type,\n data: input.data,\n reason,\n actor: input.actor,\n });\n const valid = compiled.validate(event, { file: null });\n if (!valid.ok) {\n return refused(valid.findings.map((f) => ({ ...f, subject: id, kind: adrKind.name })));\n }\n const files = filesOf([event], read);\n const { after, added } = await precheck(read, files);\n if (added.length > 0) return refused(added);\n const by = input.type === \"superseded\" ? String(input.data.by) : null;\n const involved = sorted([id, ...(by !== null && isSubjectId(by) ? [by] : [])]);\n const { scope, eventDirs } = commitScope(read, involved);\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject: id,\n files,\n events: [event],\n stage: Object.keys(files),\n involved,\n commitScope: scope,\n eventDirs,\n draft: null,\n commit: {\n action: actionOf(input.type).action,\n title: actionOf(input.type).names === \"title\" ? view.title : view.display,\n id,\n display: view.display,\n body: reason === null ? [] : [`Reason: ${reason}`],\n },\n trailers: pairsOf([event]),\n decision: viewOf(after, id),\n affected: input.type === \"superseded\" ? [viewOf(after, id)] : [],\n findings: [],\n },\n };\n}\n\n/** Input of the lifecycle exits: the decision and the envelope's `reason`. */\nexport interface ReasonInput {\n readonly id: string;\n readonly reason?: string | null;\n readonly actor: Actor;\n}\n\n/** Plans `adr reject`: `rejected` with its required reason, while proposed. */\nexport function planReject(read: DecisionsRead, input: ReasonInput, c: PlanContext) {\n return planEvent(read, { ...input, subject: input.id, type: \"rejected\", data: {} }, c);\n}\n\n/** Plans `adr withdraw`: `withdrawn`, with a reason when given, while proposed. */\nexport function planWithdraw(read: DecisionsRead, input: ReasonInput, c: PlanContext) {\n return planEvent(read, { ...input, subject: input.id, type: \"withdrawn\", data: {} }, c);\n}\n\n/** Plans `adr deprecate`: `deprecated` with its required reason, while accepted. */\nexport function planDeprecate(read: DecisionsRead, input: ReasonInput, c: PlanContext) {\n return planEvent(read, { ...input, subject: input.id, type: \"deprecated\", data: {} }, c);\n}\n\n/** Plans `adr note`: `noted` with the text as given, in every state. */\nexport function planNote(\n read: DecisionsRead,\n input: { readonly id: string; readonly text: string; readonly actor: Actor },\n c: PlanContext,\n): Promise<PlanResult> {\n if (input.text.trim() === \"\") throw new UsageError(\"the note text must not be empty\");\n checkText(\"the note text\", input.text);\n return planEvent(\n read,\n { subject: input.id, type: \"noted\", data: { text: input.text }, actor: input.actor },\n c,\n );\n}\n\nconst LINK_RELS: readonly LinkRel[] = [\"relates-to\", \"refines\", \"depends-on\"];\nconst SOURCE_NAME = /^[a-z][a-z0-9-]{0,31}$/;\n\nexport interface LinkInput {\n readonly id: string;\n /** A local id or number, or `<source>:<id>` naming a configured `[[sources]]` entry. */\n readonly to: string;\n /** Default `relates-to`. */\n readonly rel?: string;\n readonly actor: Actor;\n}\n\n/**\n * Plans `adr link` (design §6.7): `linked` in every state. A qualified target must name one of\n * `o.sources` (the log's `[[sources]]` names) of kind `adr` (`o.logs`, from the local cache): a\n * cached source must hold the id, else `UsageError`; into an uncached one the link is written with\n * a note that it isn't checked. A link that already exists plans nothing, with a note.\n */\nexport async function planLink(\n read: DecisionsRead,\n input: LinkInput,\n c: PlanContext,\n o: {\n readonly sources?: readonly string[];\n readonly logs?: ReadonlyMap<string, AdrSource>;\n readonly kinds?: ReadonlyMap<string, string>;\n } = {},\n): Promise<PlanResult> {\n const rel = input.rel ?? \"relates-to\";\n if (!(LINK_RELS as readonly string[]).includes(rel)) {\n throw new UsageError(`unknown --rel ${rel}; use relates-to, refines or depends-on`);\n }\n const id = resolveDecision(read, input.id);\n const view = viewOf(read, id);\n const target = input.to.trim();\n let to: string;\n let shown: string;\n let described: string;\n let named: string;\n let foreignNote: string | null = null;\n const at = target.indexOf(\":\");\n if (at >= 0) {\n const source = target.slice(0, at);\n const local = target.slice(at + 1);\n if (!SOURCE_NAME.test(source) || !isSubjectId(local)) {\n throw new UsageError(`invalid decision ${JSON.stringify(input.to)}`);\n }\n if (!(o.sources ?? []).includes(source)) {\n throw new UsageError(`unknown source ${source}; add a [[sources]] entry named ${source}`);\n }\n const kind = o.kinds?.get(source);\n if (kind !== undefined && kind !== \"adr\") {\n throw new UsageError(`source ${source} has kind ${kind}, which adr doesn't read`);\n }\n const cached = o.logs?.get(source);\n if (cached?.subjects !== null && cached?.subjects !== undefined) {\n if (!cached.subjects.has(local)) {\n throw new UsageError(\n `${target} is not in source ${source} (pinned at ${(cached.commit ?? \"\").slice(0, 12)})`,\n );\n }\n } else if (o.logs !== undefined) {\n foreignNote = `${source} not fetched; the reference isn't checked`;\n }\n to = target;\n shown = target;\n described = `${rel} ${target}.`;\n named = `${view.display} ${CROSS_LOG_LINK}`;\n } else {\n to = resolveDecision(read, target);\n if (to === id) throw new UsageError(\"a decision can't link to itself\");\n const t = viewOf(read, to);\n shown = t.display;\n described = `${rel} ${t.display}: ${sentenceTitle(t.title)}.`;\n named = `${view.display} to ${t.display}`;\n }\n if (view.links.some((l) => l.to === to && l.rel === rel)) {\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject: id,\n files: {},\n events: [],\n stage: [],\n involved: [id],\n commitScope: [],\n eventDirs: [],\n draft: null,\n commit: null,\n trailers: [],\n decision: view,\n affected: [],\n findings: [],\n notes: [`already linked: ${view.display} ${rel} ${shown}; nothing written`],\n },\n };\n }\n const r = await planEvent(\n read,\n { subject: id, type: \"linked\", data: { to, rel }, actor: input.actor },\n c,\n );\n if (!r.ok || r.plan.commit === null) return r;\n return {\n ok: true,\n plan: {\n ...r.plan,\n commit: { ...r.plan.commit, title: named, body: [described] },\n notes: [...(r.plan.notes ?? []), ...(foreignNote === null ? [] : [foreignNote])],\n },\n };\n}\n\nexport interface ScopeInput {\n readonly id: string;\n /** Replace (`set`, `[]` clears), or `add` and `remove` globs (design §3.2). */\n readonly op: SetOp;\n readonly actor: Actor;\n /** How the caller names `set`, `add`, `remove` and `clear` in messages; default the field names. */\n readonly names?: {\n readonly set: string;\n readonly add: string;\n readonly remove: string;\n readonly clear?: string;\n };\n}\n\n/** `ADR-0003 (k3f9q8a1)`, or the id alone when the decision has no number. */\nconst namedView = (v: DecisionView) => (v.display === v.id ? v.id : `${v.display} (${v.id})`);\n\n/** The globs of `globs` that match none of `files`. */\nfunction unmatchedGlobs(globs: readonly string[], files: readonly string[]): string[] {\n const matches = globMatcher(globs);\n const hit = new Set(files.flatMap((f) => matches(f)));\n return globs.filter((g) => !hit.has(g));\n}\n\n/**\n * Plans `adr scope` with a set operation (design §6.8): one `scoped` event with the whole new set\n * while proposed, accepted or deprecated, or nothing when the set doesn't change. Invalid globs,\n * conflicting operations and more than 200 globs are `UsageError`s. Notes name removed globs that\n * weren't there, added ones that were, resulting globs matching none of `o.tracked` (when given)\n * and a narrowed accepted scope.\n */\nexport async function planScope(\n read: DecisionsRead,\n input: ScopeInput,\n c: PlanContext,\n o: { readonly tracked?: readonly string[] } = {},\n): Promise<PlanResult> {\n const id = resolveDecision(read, input.id);\n const view = viewOf(read, id);\n const result = applySetOp(view.applies_to, input.op, {\n what: \"glob\",\n validate: (g) => {\n const parsed = parseGlob(g);\n return parsed.ok ? null : parsed.message;\n },\n maxItems: 200,\n ...(input.names === undefined ? {} : { names: input.names }),\n });\n if (!adrKind.machine.allowed(view.status, \"scoped\")) {\n return {\n ok: false,\n decision: view,\n findings: [refusal(read, \"transition/illegal\", illegal(\"scoped\", view.status), id)],\n };\n }\n const named = namedView(view);\n const notes = [\n ...result.absent.map((g) => `${g} is not in the scope of ${named}`),\n ...result.present.map((g) => `${g} is already in the scope of ${named}`),\n ];\n if (!result.changed) {\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject: id,\n files: {},\n events: [],\n stage: [],\n involved: [id],\n commitScope: [],\n eventDirs: [],\n draft: null,\n commit: null,\n trailers: [],\n decision: view,\n affected: [],\n findings: [],\n notes,\n },\n };\n }\n if (o.tracked !== undefined) {\n // Verify's scope/glob-unmatched applies to the statuses in requireMatchIn (?7): accepted\n // decisions; a proposed one may name code that doesn't exist yet.\n const checked = (adrKind.def.scope?.requireMatchIn ?? []).includes(view.status)\n ? \"; verify (hooks and CI) reports scope/glob-unmatched until a file matches\"\n : view.status === \"proposed\"\n ? `; verify reports scope/glob-unmatched once ${view.display} is accepted, until a file matches`\n : \"\";\n notes.push(\n ...unmatchedGlobs(result.set, o.tracked).map((g) => `${g} matches no tracked file${checked}`),\n );\n }\n if (result.removed.length > 0 && (view.status === \"accepted\" || view.status === \"deprecated\")) {\n notes.push(\n \"this narrows the scope of an accepted decision; if its Scope section no longer reads true, propose a superseding decision instead\",\n );\n }\n const r = await planEvent(\n read,\n { subject: id, type: \"scoped\", data: { set: [...result.set] }, actor: input.actor },\n c,\n );\n return r.ok ? { ok: true, plan: { ...r.plan, notes } } : r;\n}\n\n/**\n * Plans one `scoped` event per change, in one batch (design §6.8 step 4): each decision's status\n * must allow `scoped` and each event must validate, else the first failing decision is refused.\n * The plan has no commit message, because `--follow-renames` never commits. `decision` is\n * `input.id`'s view after the write, or `null` without one; `affected` are the changed views.\n */\nasync function planScopeEvents(\n read: DecisionsRead,\n changes: readonly { readonly id: string; readonly set: readonly string[] }[],\n input: { readonly id: string | null; readonly actor: Actor },\n c: PlanContext,\n): Promise<PlanResult> {\n const given = input.id === null ? null : viewOf(read, input.id);\n const events: EventEnvelope[] = [];\n for (const change of changes) {\n const view = viewOf(read, change.id);\n const refused = (findings: readonly Finding[]): PlanResult => ({\n ok: false,\n decision: given,\n findings,\n });\n if (!adrKind.machine.allowed(view.status, \"scoped\")) {\n return refused([\n refusal(read, \"transition/illegal\", illegal(\"scoped\", view.status), change.id),\n ]);\n }\n const event = newEvent(read, c, {\n subject: change.id,\n type: \"scoped\",\n data: { set: [...change.set] },\n actor: input.actor,\n });\n const valid = compiled.validate(event, { file: null });\n if (!valid.ok) {\n return refused(valid.findings.map((f) => ({ ...f, subject: change.id, kind: adrKind.name })));\n }\n events.push(event);\n }\n const files = filesOf(events, read);\n const { after, added } = await precheck(read, files);\n if (added.length > 0) return { ok: false, decision: given, findings: added };\n const involved = sorted(changes.map((ch) => ch.id));\n const { scope, eventDirs } = commitScope(read, involved);\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject: input.id ?? involved[0] ?? \"\",\n files,\n events,\n stage: Object.keys(files),\n involved,\n commitScope: scope,\n eventDirs,\n draft: null,\n commit: null,\n trailers: pairsOf(events),\n decision: input.id === null ? null : viewOf(after, input.id),\n affected: changes.map((ch) => viewOf(after, ch.id)),\n findings: [],\n },\n };\n}\n\n/** A plan that writes nothing: the views as they are, and `notes`. */\nfunction emptyPlan(\n subject: string,\n decision: DecisionView | null,\n notes: readonly string[],\n): PlanResult {\n return {\n ok: true,\n plan: {\n command: \"event\",\n subject,\n files: {},\n events: [],\n stage: [],\n involved: decision === null ? [] : [decision.id],\n commitScope: [],\n eventDirs: [],\n draft: null,\n commit: null,\n trailers: [],\n decision,\n affected: [],\n findings: [],\n notes,\n },\n };\n}\n\n/** The renamed files and the tracked files before and after them (design §3.4). */\ninterface StagedRenames {\n readonly renames: readonly Rename[];\n readonly before: readonly string[];\n readonly after: readonly string[];\n}\n\n/**\n * Plans `adr scope [<decision>] --follow-renames` (design §6.8 steps 1–4): the given decision's\n * globs, or every decision's, rewritten by `followRenames`. Decisions whose status forbids\n * `scoped` are skipped, with a note when the renames would have changed their scope; an explicit\n * one is refused.\n */\nasync function planFollowRenames(\n read: DecisionsRead,\n input: { readonly id: string | null; readonly actor: Actor },\n staged: StagedRenames,\n c: PlanContext,\n): Promise<PlanResult> {\n const id = input.id === null ? null : resolveDecision(read, input.id);\n const given = id === null ? null : viewOf(read, id);\n if (staged.renames.length === 0) return emptyPlan(id ?? \"\", given, []);\n if (given !== null && !adrKind.machine.allowed(given.status, \"scoped\")) {\n return {\n ok: false,\n decision: given,\n findings: [refusal(read, \"transition/illegal\", illegal(\"scoped\", given.status), given.id)],\n };\n }\n const views = given !== null ? [given] : [...read.projection.views.values()];\n const notes: string[] = [];\n const changes: { id: string; set: readonly string[] }[] = [];\n for (const view of [...views].sort((a, b) => (a.id < b.id ? -1 : 1))) {\n const result = followRenames({ globs: view.applies_to, ...staged });\n if (!result.changed) continue;\n const named = namedView(view);\n if (!adrKind.machine.allowed(view.status, \"scoped\")) {\n const covers = globMatcher(view.applies_to);\n const leaving = staged.renames.filter((r) => covers(r.from).length > 0).length;\n notes.push(\n `${named} is ${view.status}; its scope can't follow renames (${leaving} renamed files leave it)`,\n );\n continue;\n }\n if (result.globs.length > 200) {\n throw new UsageError(\n `following the renames gives ${named} ${result.globs.length} globs; the limit is 200`,\n );\n }\n for (const s of result.skipped) {\n notes.push(\n `${s.to} can't be written as a scope glob (${s.problem}); ${named} no longer covers it`,\n );\n }\n for (const path of result.gained) {\n notes.push(\n `${path} is now covered by ${named}'s scope but wasn't before the rename; check it`,\n );\n }\n changes.push({ id: view.id, set: result.globs });\n }\n if (changes.length === 0) return emptyPlan(id ?? \"\", given, notes);\n const r = await planScopeEvents(read, changes, { id, actor: input.actor }, c);\n return r.ok ? { ok: true, plan: { ...r.plan, notes } } : r;\n}\n\n/** The paths of every file in `tree`. */\nasync function filePaths(tree: TreeReader): Promise<string[]> {\n return (await tree.list(\"\")).filter((e) => e.type === \"file\").map((e) => e.path);\n}\n\n/** Every tracked file in the index, for the \"matches no tracked file\" notes. */\nasync function trackedFiles(log: DecisionLog): Promise<string[]> {\n return filePaths(await indexReader(log.git));\n}\n\n/** What the editor step decided (§5.4 step 4a). */\nexport interface AfterStage {\n /** Draft lint findings to report instead of `plan.findings`; `null` keeps `plan.findings`. */\n readonly findings: readonly Finding[] | null;\n /** `false` skips the commit: the files stay written and staged, and `commit` is `null`. */\n readonly commit: boolean;\n}\n\nconst isYaml = (path: string) => /\\.ya?ml$/.test(path);\n\n/** What `applyPlan` did. */\nexport interface AppliedPlan {\n /** Repo-relative paths written: the plan's files, then `<root>/index.md` when it was written. */\n readonly written: string[];\n readonly commit: string | null;\n readonly findings: readonly Finding[];\n /** Notes about the index (\"not updated\", \"may be stale\"); `[]` when none. */\n readonly notes: readonly string[];\n /** The message `compose` rendered, or `null` without `compose` or a commit. */\n readonly rendered: RenderedCommit | null;\n}\n\n/**\n * What the recovery hint says about rerunning a write command after `git commit` failed (design\n * 2b D5): the batch is already in the log, so a rerun is refused, writes nothing or duplicates it.\n */\nexport const WRITE_RERUN =\n \"Don't run the command again: the log already holds the change, so a rerun would be refused, do nothing, or write it a second time.\";\n\n/**\n * A write leaves the work tree's render of `index.md` (`staged`) staged, and it lists decision\n * files that may not be staged. When some aren't and the index's own render differs, the next\n * plain commit's hook fails; the note says so, as its `index/stale` finding does. `null`\n * otherwise, or when that render fails.\n */\nasync function unstagedIndexNote(\n log: DecisionLog,\n at: string,\n staged: string,\n history: string | null,\n render: (tree: TreeReader, history: string | null) => Promise<string | null>,\n): Promise<string | null> {\n const files = await unstagedLogFiles(log.git, log.layout);\n if (files.length === 0) return null;\n const own = await render(await indexReader(log.git), history).catch(() => null);\n if (own === null || own === staged) return null;\n return `${unstagedIndexText(at, files)}; git add them before you commit, or move them out of the work tree and run adr index`;\n}\n\n/**\n * Applies a plan (§5.4): refuses a commit whose scope has unstaged or needed untracked paths,\n * writes the files (removing them again if a write fails), stages them, runs `afterStage`, and\n * commits `plan.stage` plus the involved subjects' already-staged files with exact trailers. A\n * failed `git commit` throws `CommitFailedError` with the manual command (design 2b D5) and the\n * notes made so far.\n */\nexport async function applyPlan(\n log: DecisionLog,\n plan: WritePlan,\n o: {\n readonly commit: boolean;\n /** The commit message, without trailers; required when committing. */\n readonly message?: string;\n /** `message` is the user's own: append the trailers to its own trailer block, if it ends in one. */\n readonly mergeTrailers?: boolean;\n /**\n * Renders the commit message once the extra staged events are known (?6), instead of\n * `message`: `plan` holds the plan's own events, `extra` the other staged event files the\n * commit sweeps in (by file name, deduplicated by subject and type), and `tree` is the\n * commit's tree. Exclusive with `message`.\n */\n readonly compose?: (c: {\n readonly plan: readonly EventRef[];\n readonly extra: readonly EventRef[];\n readonly tree: TreeReader;\n }) => RenderedCommit;\n readonly afterStage?: () => Promise<AfterStage>;\n /**\n * Renders the log's index for `tree`, which builds on `history` (HEAD, the new commit, or\n * null on an unborn HEAD); `null` when the numbers can't be projected. Given only when the log\n * keeps a committed index (design 2b D2, §4.5).\n */\n readonly index?: (tree: TreeReader, history: string | null) => Promise<string | null>;\n },\n): Promise<AppliedPlan> {\n const { git } = log;\n if (o.commit && o.message === undefined && o.compose === undefined) {\n throw new InvalidArgumentError(\"applyPlan needs a message to commit\");\n }\n if (o.message !== undefined && o.compose !== undefined) {\n throw new InvalidArgumentError(\"applyPlan takes a message or compose, not both\");\n }\n const stage = new Set(plan.stage);\n // This check runs before anything is written. It stays correct with an editor in between for\n // the body, which is in `plan.stage` and is re-staged after a successful edit; every other path\n // in the scope (a materialized template, say) is checked again by the editor step once the\n // editor has closed, because `--only` would commit its work-tree content.\n if (o.commit) {\n const unstaged = new Set(await git.unstagedPaths(plan.commitScope));\n const dirs = new Set(plan.eventDirs);\n const untracked = new Set([\n ...(await git.untrackedPaths(plan.commitScope.filter((p) => !dirs.has(p)))),\n ...(await git.untrackedPaths(plan.eventDirs)).filter(isYaml),\n ]);\n const dirty = sorted([...unstaged, ...untracked]).filter((p) => !stage.has(p));\n const [first] = dirty;\n if (first !== undefined) {\n throw new UsageError(\n unstaged.has(first)\n ? `${first} has unstaged changes; stage or discard them, or run without --commit`\n : `${first} is not tracked; git add it, or run without --commit`,\n );\n }\n }\n\n // The index (design 2b §4.5) is rendered before anything is written, so a projection error\n // leaves nothing behind. A committing write renders the tree `git commit --only` builds: HEAD\n // (or nothing) with every `only` path's work-tree bytes, which are `plan.files`' for new files.\n const root = log.layout.root;\n const at = indexPath(log.layout);\n const notes: string[] = [];\n const head = await git.resolveCommit(\"HEAD\");\n const extraOf = async () =>\n (await git.stagedPaths(plan.commitScope)).filter((p) => !stage.has(p));\n const commitTree = async (extra: readonly string[]): Promise<TreeReader> => {\n const work = worktreeReader(git);\n const files: Record<string, Uint8Array> = {};\n const gone = new Set<string>();\n for (const p of sorted([...plan.stage, ...extra])) {\n const bytes = plan.files[p] ?? plan.replace?.[p]?.bytes ?? (await work.read(p));\n if (bytes === null) gone.add(p);\n else files[p] = bytes;\n }\n return withoutPaths(overlayTree(await headTree(git, head), files), gone);\n };\n const extra0 = o.commit && o.index !== undefined ? await extraOf() : [];\n let text: string | null = null;\n if (o.index !== undefined) {\n const tree = o.commit\n ? await commitTree(extra0)\n : overlayTree(worktreeReader(git), { ...plan.files, ...replaceBytes(plan) });\n text = await o.index(tree, head);\n if (text === null) {\n notes.push(\n `${at} not updated: numbers need history in this shallow clone; run git fetch --unshallow, then adr index`,\n );\n }\n }\n\n const toStage: string[] = [];\n // Assigned in the closures below, so typed without narrowing.\n let indexWritten = false as boolean;\n let indexOld = null as Uint8Array | null;\n let indexInCommit = false as boolean;\n /** Brings the work-tree copy to `t` and stages it (now, or with the batch) where they differ. */\n const refresh = async (t: string, now: boolean): Promise<boolean> => {\n const r = await writeIndexCopy(git, at, t);\n if (r.wrote && !indexWritten) indexOld = r.old;\n indexWritten ||= r.wrote;\n if (r.stage) {\n if (now) await git.add([at]);\n else toStage.push(at);\n }\n return r.wrote || r.stage;\n };\n /** Step 3's rules: committing, HEAD's copy decides; otherwise the work tree and the index. */\n const place = async (t: string, committing: boolean, now: boolean): Promise<void> => {\n if (!committing) {\n await refresh(t, now);\n return;\n }\n indexInCommit = !holdsText(await headBytes(git, at), t);\n if (indexInCommit) await refresh(t, now);\n };\n\n const eventPaths = new Set(plan.events.map((e) => eventPath(log.layout, e)));\n const written: string[] = [];\n const replaced: string[] = [];\n try {\n for (const [path, r] of Object.entries(plan.replace ?? {})) {\n await replaceFile(git, path, r.bytes, { expected: r.expected });\n replaced.push(path);\n }\n for (const [path, bytes] of Object.entries(plan.files)) {\n if (eventPaths.has(path)) continue;\n await writeNewFile(git, path, bytes, { stage: false });\n written.push(path);\n }\n if (text !== null) await place(text, o.commit, false);\n await writeEvents(git, log.layout, plan.events, { kind: log.compiled, stage: false });\n } catch (err) {\n const top = git.root ?? \"\";\n if (indexWritten) {\n if (indexOld === null) await rm(join(top, at), { force: true });\n else await writeFile(join(top, at), indexOld);\n }\n for (const path of written) await rm(join(top, path), { force: true });\n for (const path of replaced) {\n const r = plan.replace?.[path];\n if (r !== undefined)\n await replaceFile(git, path, r.expected, { expected: r.bytes }).catch(() => {});\n }\n throw err;\n }\n await git.add([...plan.stage, ...toStage]);\n /** The work tree's render that ends up staged, and the commit it builds on. */\n let stagedIndex: { readonly text: string; readonly history: string | null } | null =\n !o.commit && text !== null ? { text, history: head } : null;\n\n let findings = plan.findings;\n let commit = o.commit;\n if (o.afterStage !== undefined) {\n const after = await o.afterStage();\n findings = after.findings ?? plan.findings;\n commit = commit && after.commit;\n }\n\n const stale = (err: unknown) => `${at} may be stale: ${firstLine(err)}; run adr index`;\n let sha: string | null = null;\n let rendered: RenderedCommit | null = null;\n if (commit) {\n const extra = await extraOf();\n const extraRefs = stagedEventRefs(log.layout, extra);\n const planRefs = plan.events.map((e) => ({ subject: e.subject, type: e.type }));\n rendered =\n o.compose === undefined\n ? null\n : o.compose({ plan: planRefs, extra: extraRefs, tree: await commitTree(extra) });\n const message = rendered?.message ?? o.message ?? \"\";\n const mergeTrailers = o.mergeTrailers === true;\n // One pair per (decision, type): a staged event of a type the plan writes too adds nothing.\n const pairs = eventTrailers([...extraRefs, ...planRefs], TRAILER_KEYS);\n const named = new Set(pairs.filter(([k]) => k === \"ADR\").map(([, v]) => v));\n const trailers = [\n ...pairs,\n ...(plan.events.length === 0\n ? plan.trailers.filter(([k, v]) => k !== \"ADR\" || !named.has(v))\n : []),\n ];\n const sameEvents =\n sorted(extra.filter(isYaml)).join(\"\\0\") === sorted(extra0.filter(isYaml)).join(\"\\0\");\n if (text !== null && o.index !== undefined && o.afterStage !== undefined && !sameEvents) {\n // Step 4: the editor step ran while other events were staged; render the new tree.\n try {\n const again = await o.index(await commitTree(extra), head);\n if (again !== null) await place(again, true, true);\n } catch (err) {\n const recovery = await saveCommitRecovery(git, {\n message,\n mergeTrailers,\n trailers,\n only: sorted([...plan.stage, ...extra, at]),\n });\n throw new CommitFailedError(\n {\n recovery,\n headline: `${at} couldn't be refreshed: ${firstLine(err)}`,\n detail: \"\",\n rerun: WRITE_RERUN,\n before: INDEX_BEFORE(root),\n after: null,\n notes,\n },\n { cause: err },\n );\n }\n }\n try {\n sha = await commitWithRecovery(git, {\n message,\n mergeTrailers,\n trailers,\n only: sorted([...plan.stage, ...extra, ...(indexInCommit ? [at] : [])]),\n rerun: WRITE_RERUN,\n after: indexInCommit ? INDEX_AFTER(root) : null,\n });\n } catch (err) {\n // The notes made so far (an index not updated, say) explain the state the hint describes.\n throw err instanceof CommitFailedError ? err.withNotes(notes) : err;\n }\n // Step 5: the commit's render leaves out other decisions' uncommitted entries; the work tree\n // and the index get them back.\n if (text !== null && o.index !== undefined) {\n try {\n const again = await o.index(worktreeReader(git), sha);\n if (again !== null) {\n await refresh(again, true);\n stagedIndex = { text: again, history: sha };\n }\n } catch (err) {\n notes.push(stale(err));\n }\n }\n } else if (o.commit && text !== null && o.index !== undefined) {\n // Step 4: the editor step turned the commit off, so the index must match the work tree.\n try {\n const again = await o.index(worktreeReader(git), head);\n if (again !== null) {\n await refresh(again, true);\n stagedIndex = { text: again, history: head };\n }\n } catch (err) {\n notes.push(stale(err));\n }\n }\n if (stagedIndex !== null && o.index !== undefined) {\n const { text: t, history } = stagedIndex;\n const note = await unstagedIndexNote(log, at, t, history, o.index);\n if (note !== null) notes.push(note);\n }\n return {\n written: [\n ...Object.keys(plan.replace ?? {}),\n ...Object.keys(plan.files),\n ...(indexWritten ? [at] : []),\n ],\n commit: sha,\n findings,\n notes,\n rendered,\n };\n}\n\n/** The `ADR`/`ADR-Event` trailer keys. */\nconst TRAILER_KEYS = { subject: \"ADR\", event: \"ADR-Event\" } as const;\n\n/**\n * The staged event files among `paths` as (decision, type) refs, in path order (by decision,\n * then event time), deduplicated by decision and type.\n */\nfunction stagedEventRefs(layout: LogLayout, paths: readonly string[]): EventRef[] {\n const found: EventRef[] = [];\n for (const p of sorted(paths.filter(isYaml))) {\n const c = classifyPath(layout, p);\n if (c.area !== \"event\" || c.subject === null || c.file.includes(\"/\")) continue;\n const name = parseEventFileName(c.file);\n if (name !== null) found.push({ subject: c.subject, type: name.type });\n }\n const seen = new Set<string>();\n return found.filter((r) => {\n const key = `${r.subject}\\0${r.type}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** The new bytes of each file a plan replaces. */\nconst replaceBytes = (plan: WritePlan): Record<string, Uint8Array> =>\n Object.fromEntries(Object.entries(plan.replace ?? {}).map(([p, r]) => [p, r.bytes]));\n\n/**\n * The clock, the randomness and `applyPlan` the write functions use. Only tests pass their own\n * (for example an `apply` that fails once); the default is the real ones.\n */\nexport interface WriteDeps {\n readonly now: () => number;\n readonly random?: (buf: Uint8Array) => void;\n readonly apply: typeof applyPlan;\n}\nconst DEFAULT_DEPS: WriteDeps = { now: Date.now, apply: applyPlan };\n\n/**\n * The views `adr-write/v1` reports. Without a commit they are the plan's, folded on the overlay.\n * After a commit they come from a new read of the log, so a commit on the main ref shows the\n * numbers it assigned, as the CLI text and phase 3's MCP tools do. A commit that failed threw in\n * `applyPlan`, so nothing is read for it.\n */\nasync function viewsAfter(\n log: DecisionLog,\n plan: WritePlan,\n sha: string | null,\n): Promise<{ decision: DecisionView | null; affected: readonly DecisionView[] }> {\n if (sha === null) return { decision: plan.decision, affected: plan.affected };\n const read = await readDecisions({ ...log, commit: sha });\n const view = (v: DecisionView) => read.projection.views.get(v.id) ?? v;\n return {\n decision: plan.decision === null ? null : view(plan.decision),\n affected: plan.affected.map(view),\n };\n}\n\n/**\n * `--commit` needs an author and a committer identity; checked before anything is written, since\n * `GIT_AUTHOR_*` alone satisfies the author while `git commit` still fails on the committer.\n */\nasync function checkCommitIdentity(log: DecisionLog): Promise<void> {\n if ((await log.git.identity()) === null || (await log.git.committerIdentity()) === null) {\n throw new ConfigError(\"--commit needs a git identity; set git user.name and user.email\");\n }\n}\n\nconst STATUS_TYPES: ReadonlySet<string> = new Set([\n \"proposed\",\n \"accepted\",\n \"rejected\",\n \"withdrawn\",\n]);\n\n/**\n * The commit's action and title slot (ADR-0008, ?6), chosen once the staged events the commit\n * sweeps in are known: when `plan` or `extra` holds a status event (proposed, accepted, rejected,\n * withdrawn), the title form of the last one, since that is what the commit decides. Otherwise\n * the plan's own subject when the extra events add no other verb; with two or three verbs those\n * joined (`link and scope ADR-0003`), and beyond three (or where the joined verbs don't fit a\n * custom template) `update ADR-0003`. Every single-action subject stays the plan's own, byte for\n * byte.\n */\nexport function composeSubject(\n read: DecisionsRead,\n parts: CommitParts,\n c: { readonly plan: readonly EventRef[]; readonly extra: readonly EventRef[] },\n): { readonly action: string; readonly title: string } {\n const all = [...c.extra, ...c.plan];\n const status = all.filter((e) => STATUS_TYPES.has(e.type)).at(-1);\n if (status !== undefined) {\n const own = c.plan.some((e) => e.subject === status.subject && e.type === status.type);\n if (own) return { action: parts.action, title: parts.title };\n const action = ACTIONS[status.type as keyof typeof ACTIONS].action;\n return { action, title: read.projection.views.get(status.subject)?.title ?? status.subject };\n }\n const primary = c.plan[0]?.type;\n const verbs = new Set<string>();\n for (const t of [primary, ...c.extra.map((e) => e.type)]) {\n if (t !== undefined && Object.hasOwn(BATCH_ACTIONS, t)) verbs.add(t);\n }\n if (verbs.size <= 1 || primary === undefined || !verbs.has(primary)) {\n return { action: parts.action, title: parts.title };\n }\n const ordered = BATCH_ORDER.filter((t) => verbs.has(t)).map(\n (t) => BATCH_ACTIONS[t as keyof typeof BATCH_ACTIONS],\n );\n return {\n action: ordered.length > 3 ? UPDATE_ACTION : joinActions(ordered),\n title: parts.display,\n };\n}\n\n/** The plan's commit message from `[commit] subject` (design §4), with `composeSubject`'s slot. */\nfunction commitMessage(\n log: DecisionLog,\n command: string,\n read: DecisionsRead,\n plan: WritePlan,\n c: { readonly plan: readonly EventRef[]; readonly extra: readonly EventRef[] },\n): RenderedCommit {\n const parts = plan.commit;\n if (parts === null) throw new InvalidArgumentError(\"this write can't be committed\");\n const { action, title } = composeSubject(read, parts, c);\n const render = (a: string) =>\n renderCommitMessage(log.adr.commitSubject, {\n title,\n vars: { action: a, id: parts.id, display: parts.display, command },\n body: parts.body,\n });\n const r = render(action);\n // A batch names the display, which is never shortened: a custom template too long for the\n // joined verbs gets `update <display>`.\n return r.shortened && title === parts.display && action !== parts.action\n ? render(UPDATE_ACTION)\n : r;\n}\n\n/**\n * Plan, then apply, with the single `EventExistsError` retry (§5.4 steps 1–5). `o.message`\n * replaces the rendered commit message; `o.notes` come before the write's own notes. A plan with\n * no files and no events is reported as written without touching the repository, and so is\n * every plan with `dryRun` (its views are the plan's).\n */\nasync function write(\n log: DecisionLog,\n command: WriteResultJson[\"command\"],\n plan: (read: DecisionsRead, c: PlanContext) => Promise<PlanResult>,\n o: WriteOptions & { readonly dryRun?: boolean },\n deps: WriteDeps,\n afterStage?: (plan: WritePlan, commit: boolean) => () => Promise<AfterStage>,\n): Promise<WriteResultJson> {\n return withGitOperation(async () => {\n if (log.ref !== null) {\n throw new InvalidArgumentError(\"writes read the work tree; open the log without a ref\");\n }\n if (log.tree.label !== \"worktree\") {\n throw new InvalidArgumentError(\n \"writes read the work tree; open the log with the worktree reader\",\n );\n }\n const commit = o.commit ?? log.adr.autoCommit;\n if (commit) await checkCommitIdentity(log);\n const notes = [...log.notes, ...(o.notes ?? [])];\n for (let attempt = 0; ; attempt++) {\n const read = await readDecisions(log);\n const ref = await templateHistoryRef(log.git, { type: \"full\" });\n const c: PlanContext = {\n now: deps.now,\n ...(deps.random === undefined ? {} : { random: deps.random }),\n templates: historyTemplates(log.git, log.tree, `${read.root}/templates`, { ref }),\n builtins: BUILTIN_TEMPLATES,\n };\n const r = await plan(read, c);\n if (!r.ok) {\n return {\n format: \"adr-write/v1\",\n command,\n ok: false,\n decision: r.decision,\n affected: [],\n written: [],\n commit: null,\n findings: r.findings,\n notes,\n };\n }\n const empty =\n r.plan.events.length === 0 &&\n Object.keys(r.plan.files).length === 0 &&\n Object.keys(r.plan.replace ?? {}).length === 0;\n if (empty || o.dryRun === true) {\n return {\n format: \"adr-write/v1\",\n command,\n ok: true,\n decision: r.plan.decision,\n affected: r.plan.affected,\n written: [],\n commit: null,\n findings: r.plan.findings,\n notes: [...notes, ...(r.plan.notes ?? [])],\n };\n }\n if (commit && r.plan.commit === null) {\n throw new InvalidArgumentError(\"this write can't be committed\");\n }\n const given = o.message ?? null;\n try {\n const applied = await deps.apply(log, r.plan, {\n commit,\n ...(!commit\n ? {}\n : given !== null\n ? { message: given, mergeTrailers: true }\n : { compose: (c) => commitMessage(log, command, read, r.plan, c) }),\n ...(afterStage === undefined ? {} : { afterStage: afterStage(r.plan, commit) }),\n ...(log.adr.index === \"committed\" && o.index !== \"skip\"\n ? {\n index: (tree: TreeReader, history: string | null) =>\n renderDecisionIndex(log.git, { layout: log.layout, adr: log.adr, tree, history }),\n }\n : {}),\n });\n const views = await viewsAfter(log, r.plan, applied.commit);\n const own = [\n ...(r.plan.notes ?? []),\n ...applied.notes,\n ...(applied.commit !== null && applied.rendered?.note != null\n ? [applied.rendered.note]\n : []),\n ];\n return {\n format: \"adr-write/v1\",\n command,\n ok: true,\n decision: views.decision,\n affected: views.affected,\n written: applied.written,\n commit: applied.commit,\n findings: applied.findings,\n notes: [...notes, ...own],\n };\n } catch (err) {\n // A refused commit keeps the notes a successful write would report, before applyPlan's.\n if (err instanceof CommitFailedError)\n throw err.withNotes([...notes, ...(r.plan.notes ?? [])]);\n // Another process wrote the same event path in the same instant: writeEvents removed this\n // batch and applyPlan the new body and template, so plan again with a fresh clock, once.\n if (!(err instanceof EventExistsError) || attempt > 0) throw err;\n }\n }\n });\n}\n\nconst sameBytes = (a: Uint8Array, b: Uint8Array) =>\n a.byteLength === b.byteLength && a.every((x, i) => x === b[i]);\n\nasync function readIfPresent(path: string): Promise<Uint8Array | null> {\n try {\n return await readFile(path);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return null;\n throw err;\n }\n}\n\n/**\n * The editor step (§5.4): runs `edit` on the staged draft, re-stages the edited body when the\n * editor exited 0, and skips the commit when committing would take content nobody confirmed: the\n * body changed while the editor failed, the body is gone, or another path in the commit scope (a\n * materialized template, say) changed while the editor was open (design review NIT 2). The\n * findings are the lint of the draft as it now is.\n */\nfunction editorStep(\n log: DecisionLog,\n edit: (absBodyPath: string) => Promise<string | null>,\n onNote: ((note: string) => void) | undefined,\n): (plan: WritePlan, commitRequested: boolean) => () => Promise<AfterStage> {\n return (plan, commitRequested) => async () => {\n const d = plan.draft;\n if (d === null) return { findings: null, commit: true };\n const abs = join(log.git.root ?? \"\", d.path);\n const note = await edit(abs);\n // The editor may run other processes or wait on a person: drop what the operation cached.\n invalidateGitOperation();\n const bytes = await readIfPresent(abs);\n let commit: boolean;\n if (bytes === null) {\n commit = false;\n onNote?.(\n `${d.path} was removed while editing; the rendered draft is still staged. Restore it with \\`git checkout -- ${d.path}\\``,\n );\n } else if (note === null) {\n await log.git.add([d.path]);\n commit = true;\n } else if (sameBytes(bytes, d.rendered)) {\n commit = true;\n } else {\n commit = false;\n if (commitRequested) {\n onNote?.(\n `${d.path} changed while the editor failed; review it, then git add it and commit`,\n );\n }\n }\n if (commit && commitRequested) {\n const late = (await log.git.unstagedPaths(plan.commitScope)).filter((p) => p !== d.path);\n const [first] = late;\n if (first !== undefined) {\n commit = false;\n onNote?.(\n `${first} changed while the editor was open; review it, then git add it and commit`,\n );\n }\n }\n const text = decoder.decode(bytes ?? d.rendered);\n const findings = lintDocument(d.template, text, { file: d.path, subject: plan.subject });\n // Never commit a draft that `adr verify` then fails (design §7.2); it stays staged.\n if (commit && commitRequested && findings.length > 0) {\n commit = false;\n onNote?.(`${d.path} still has unfilled required sections; fill them in, then commit`);\n }\n return { findings, commit };\n };\n}\n\n/**\n * `adr new`: renders a draft, writes the body, any materialized template and the `proposed`\n * event, stages them, and commits with `commit` (default `[policy] auto_commit`).\n *\n * `edit` (CLI only; MCP never passes it) runs between staging and committing, on the absolute\n * body path. It resolves to `null` when the editor exited 0, else to a note for the user (spawn\n * error, exit status). `onNote` receives the notes about a skipped commit or a removed body,\n * without the \"not committed: \" prefix the CLI adds when a commit was requested.\n *\n * A draft with unfilled sections is never committed (design §7.2): without `edit` a commit is\n * refused (`ok: false`, nothing written); after `edit` the commit is skipped with a note.\n */\nexport async function proposeDecision(\n log: DecisionLog,\n input: ProposeInput,\n o: WriteOptions & {\n readonly edit?: (absBodyPath: string) => Promise<string | null>;\n readonly onNote?: (note: string) => void;\n } = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return withGitOperation(async () => {\n return write(\n log,\n \"new\",\n (read, c) =>\n planPropose(read, input, c, {\n refuseIncomplete: (o.commit ?? log.adr.autoCommit) && o.edit === undefined,\n }),\n o,\n deps,\n o.edit === undefined ? undefined : editorStep(log, o.edit, o.onNote),\n );\n });\n}\n\n/**\n * `adr accept`: lints the draft, hashes the body, writes `accepted` and a `superseded` event on\n * each declared target, stages them with the body, and commits with `commit`. When the targets\n * have globs the decision lacks, `copyScope` decides whether a `scoped` event copies them\n * (default `\"suggest\"`: no copy, and a note with the `adr scope` command that would).\n */\nexport async function acceptDecision(\n log: DecisionLog,\n input: { readonly id: string; readonly actor: Actor },\n o: WriteOptions & { readonly copyScope?: CopyScope } = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n const copyScope = o.copyScope ?? \"suggest\";\n // Decided once per command: the EventExistsError retry plans again without asking again.\n let copy: boolean | null = null;\n const tracked = await trackedFiles(log);\n return write(\n log,\n \"accept\",\n async (read, c) => {\n const plain = await planAccept(read, input, c, { tracked });\n if (!plain.ok) return plain;\n const id = plain.plan.subject;\n const offer = scopeToCopy(read, id);\n if (offer.globs.length === 0) return plain;\n if (copy === null) {\n if (typeof copyScope === \"function\") {\n copy = await copyScope(offer);\n // The callback may prompt a person or run other processes: drop what was cached.\n invalidateGitOperation();\n } else {\n copy = copyScope === \"copy\";\n }\n }\n if (copy) return planAccept(read, input, c, { copyGlobs: offer.globs, tracked });\n if (copyScope === \"skip\") return plain;\n const notes = [...(plain.plan.notes ?? []), copyScopeNote(id, offer)];\n return { ok: true, plan: { ...plain.plan, notes } };\n },\n o,\n deps,\n );\n}\n\n/** `adr supersede <id> --by <by>`: writes `superseded`, stages it, and commits with `commit`. */\nexport async function supersedeDecision(\n log: DecisionLog,\n input: {\n readonly id: string;\n readonly by: string;\n readonly reason?: string | null;\n readonly actor: Actor;\n },\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return write(log, \"supersede\", (read, c) => planSupersede(read, input, c), o, deps);\n}\n\n/**\n * `adr reject <id> --reason <text>`: writes `rejected`, stages it, and commits with `commit`. The\n * kind requires the reason; without one the write is refused (findings, nothing written).\n */\nexport async function rejectDecision(\n log: DecisionLog,\n input: ReasonInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return write(log, \"reject\", (read, c) => planReject(read, input, c), o, deps);\n}\n\n/** `adr withdraw <id> [--reason <text>]`: writes `withdrawn`, stages it, and commits with `commit`. */\nexport async function withdrawDecision(\n log: DecisionLog,\n input: ReasonInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return write(log, \"withdraw\", (read, c) => planWithdraw(read, input, c), o, deps);\n}\n\n/**\n * `adr deprecate <id> --reason <text>`: writes `deprecated`, stages it, and commits with `commit`.\n * The kind requires the reason, as for `rejectDecision`.\n */\nexport async function deprecateDecision(\n log: DecisionLog,\n input: ReasonInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return write(log, \"deprecate\", (read, c) => planDeprecate(read, input, c), o, deps);\n}\n\n/** `adr note <id> <text>`: writes `noted`, stages it, and commits with `commit`. */\nexport async function noteDecision(\n log: DecisionLog,\n input: { readonly id: string; readonly text: string; readonly actor: Actor },\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return write(log, \"note\", (read, c) => planNote(read, input, c), o, deps);\n}\n\n/**\n * `adr link <id> <target> [--rel <rel>]`: writes `linked`, stages it, and commits with `commit`.\n * Qualified targets name the log's `[[sources]]`; a link that exists already writes nothing.\n */\nexport async function linkDecision(\n log: DecisionLog,\n input: LinkInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n const configs = log.config?.sources ?? [];\n const sources = configs.map((s) => s.name);\n const kinds = new Map(configs.map((s) => [s.name, s.kind]));\n const logs = input.to.includes(\":\")\n ? (await readDecisionSources(log, { fetch: \"cache\" })).logs\n : undefined;\n return write(\n log,\n \"link\",\n (read, c) =>\n planLink(read, input, c, { sources, kinds, ...(logs === undefined ? {} : { logs }) }),\n o,\n deps,\n );\n}\n\n/**\n * `adr scope <id> --set|--add|--remove …`: writes one `scoped` event with the new set, stages it,\n * and commits with `commit`. An unchanged set writes nothing.\n */\nexport async function scopeDecision(\n log: DecisionLog,\n input: ScopeInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n const tracked = await trackedFiles(log);\n return write(log, \"scope\", (read, c) => planScope(read, input, c, { tracked }), o, deps);\n}\n\n/**\n * Replaces sections of a proposed decision's draft (design §6.6), stages the body, and commits\n * with `commit` (default `[policy] auto_commit`). A body with unstaged changes is a `UsageError`,\n * so nobody's unsaved edit is folded into this write; a body changed between plan and write is\n * `FileChangedError`. A commit is never made of a draft that fails its template lint: it is\n * refused (`ok: false`, nothing written), as for `proposeDecision` without an editor.\n */\nexport async function updateDraft(\n log: DecisionLog,\n input: UpdateDraftInput,\n o: WriteOptions = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return withGitOperation(async () => {\n const read = await readDecisions(log);\n const view = viewOf(read, resolveDecision(read, input.id));\n if (view.body_path !== null && (await log.git.unstagedPaths([view.body_path])).length > 0) {\n throw new UsageError(\n `${view.body_path} has unstaged changes; stage or discard them, or edit the draft by hand`,\n );\n }\n return write(\n log,\n \"update\",\n (read, c) =>\n planUpdateDraft(read, input, c, { refuseIncomplete: o.commit ?? log.adr.autoCommit }),\n o,\n deps,\n );\n });\n}\n\nconst FOLLOW_NO_COMMIT_NOTE =\n \"--follow-renames never commits; commit the scoped events with the renames\";\n\n/**\n * `adr scope [<decision>] --follow-renames` (design §6.8): rewrites the scope globs of the given\n * decision, or of every decision, after the renames staged against `HEAD`, and stages one\n * `scoped` event per changed decision. It never commits, whatever `[policy] auto_commit` says\n * (the events belong in the commit with the renames), so `o.commit: true` and a message are\n * `InvalidArgumentError`s. `dryRun` plans the same events and notes without writing anything.\n */\nexport async function followScopeRenames(\n log: DecisionLog,\n input: { readonly id?: string; readonly actor: Actor },\n o: WriteOptions & { readonly dryRun?: boolean } = {},\n deps: WriteDeps = DEFAULT_DEPS,\n): Promise<WriteResultJson> {\n return withGitOperation(async () => {\n if (o.commit === true) {\n throw new InvalidArgumentError(\"followScopeRenames never commits; don't pass commit: true\");\n }\n if (o.message !== undefined && o.message !== null) {\n throw new InvalidArgumentError(\"followScopeRenames never commits, so it takes no message\");\n }\n const renames = await stagedRenames(log.git);\n const staged: StagedRenames =\n renames.length === 0\n ? { renames, before: [], after: [] }\n : {\n renames,\n before: await filePaths(await refReader(log.git, \"HEAD\")),\n after: await filePaths(await indexReader(log.git)),\n };\n const doc = await write(\n log,\n \"scope\",\n (read, c) => planFollowRenames(read, { id: input.id ?? null, actor: input.actor }, staged, c),\n { ...o, commit: false },\n deps,\n );\n return log.adr.autoCommit && doc.ok && doc.affected.length > 0\n ? { ...doc, notes: [...doc.notes, FOLLOW_NO_COMMIT_NOTE] }\n : doc;\n });\n}\n","import {\n compareEvents,\n type EventEnvelope,\n type Finding,\n type StateHeader,\n UsageError,\n withGitOperation,\n} from \"@nikovirtala/ledger\";\nimport type { DecisionStatus, DecisionView } from \"./kind.js\";\nimport { type ChangedSince, type DecisionsRead, listingNotes } from \"./log.js\";\n\n/** The `numbering` key of the read documents. */\nexport interface NumberingJson {\n readonly available: boolean;\n readonly reason: \"shallow\" | \"no-main-ref\" | \"index\" | null;\n readonly ref: string | null;\n}\n\n/** `adr list --json` (design §5.5). */\nexport interface DecisionListJson {\n readonly format: \"adr-list/v1\";\n /** The `[[sources]]` entry listed (`--source`), or `null` for the local log. */\n readonly source: string | null;\n readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly numbering: NumberingJson;\n readonly decisions: readonly DecisionView[];\n /** With `--since <rev>`: the event files added since `rev`; `null` without it. */\n readonly since: ChangedSince | null;\n /** Newer envelope or schema versions; upgrade adr. */\n readonly unreadable: readonly string[];\n /** First event not `proposed`, or a body with no events; run adr verify. */\n readonly unfoldable: readonly string[];\n readonly findings: readonly Finding[];\n readonly notes: readonly string[];\n}\n\n/** `adr show <decision> --json` (design §5.5). */\nexport interface DecisionShowJson {\n readonly format: \"adr-show/v1\";\n readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly numbering: NumberingJson;\n readonly header: StateHeader;\n readonly decision: DecisionView;\n readonly body: string | null;\n /** Every valid event in fold order with `history`, else `null`. */\n readonly events: readonly EventEnvelope[] | null;\n readonly findings: readonly Finding[];\n readonly notes: readonly string[];\n}\n\n/** The `numbering` key of `adr-list/v1`, `adr-show/v1` and `adr-for/v1`. */\nexport const numberingJson = (read: DecisionsRead): NumberingJson => ({\n available: read.numbering.available,\n reason: read.numbering.reason,\n ref: read.numbering.ref,\n});\n\n/** Numbered decisions by number, then unnumbered ones by `proposed_at`, then id. */\nexport function compareViews(a: DecisionView, b: DecisionView): number {\n if (a.number !== null || b.number !== null) {\n if (a.number === null) return 1;\n if (b.number === null) return -1;\n return a.number - b.number;\n }\n if (a.proposed_at !== b.proposed_at) return a.proposed_at < b.proposed_at ? -1 : 1;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n\n/**\n * The `adr-list/v1` document: decisions in list order, filtered by `status` and by `since` (only\n * the decisions with event files added since its revision, from `changedSince`), and truncated to\n * `limit` after ordering. `findings` are those of the listed decisions and of the log as a whole.\n */\nexport function listDecisions(\n read: DecisionsRead,\n o: {\n readonly status?: readonly DecisionStatus[];\n readonly since?: ChangedSince | null;\n readonly limit?: number;\n } = {},\n): DecisionListJson {\n const statuses = o.status === undefined || o.status.length === 0 ? null : new Set(o.status);\n const since = o.since ?? null;\n const changed = since === null ? null : new Set(since.events.map((e) => e.subject));\n const decisions = [...read.projection.views.values()]\n .filter((v) => statuses === null || statuses.has(v.status))\n .filter((v) => changed === null || changed.has(v.id))\n .sort(compareViews)\n .slice(0, o.limit ?? Number.POSITIVE_INFINITY);\n const listed = new Set(decisions.map((v) => v.id));\n return {\n format: \"adr-list/v1\",\n source: read.source,\n root: read.root,\n ref: read.ref,\n commit: read.commit,\n numbering: numberingJson(read),\n decisions,\n since,\n unreadable: read.projection.unreadable,\n unfoldable: read.projection.unfoldable,\n findings: read.findings.filter((f) => f.subject === null || listed.has(f.subject)),\n notes: listingNotes(read),\n };\n}\n\nconst decoder = new TextDecoder();\n\n/**\n * The `adr-show/v1` document of the decision `id` (resolve it with `resolveDecision` first).\n * Throws `UsageError` for an unknown, unreadable or unfoldable decision.\n */\nexport async function showDecision(\n read: DecisionsRead,\n id: string,\n o: { readonly history?: boolean } = {},\n): Promise<DecisionShowJson> {\n return withGitOperation(async () => {\n const view = read.projection.views.get(id);\n if (view === undefined) {\n if (read.projection.unreadable.includes(id)) {\n throw new UsageError(`decision ${id} uses a newer format; upgrade adr`);\n }\n if (read.projection.unfoldable.includes(id)) {\n throw new UsageError(`decision ${id} can't be read; run adr verify`);\n }\n throw new UsageError(`unknown decision ${id}`);\n }\n const loaded = read.folded.subjects.get(id)?.loaded;\n const body = loaded?.body ?? null;\n const events =\n o.history === true\n ? (loaded?.events ?? [])\n .flatMap((e) => (e.event === null ? [] : [{ path: e.path, event: e.event }]))\n .sort((a, b) =>\n compareEvents({ ...a.event, path: a.path }, { ...b.event, path: b.path }),\n )\n .map((e) => e.event)\n : null;\n return {\n format: \"adr-show/v1\",\n root: read.root,\n ref: read.ref,\n commit: read.commit,\n numbering: numberingJson(read),\n header: stateHeader(view, read),\n decision: view,\n body: body === null ? null : decoder.decode(body.bytes),\n events,\n findings: read.findings.filter((f) => f.subject === id),\n notes: read.notes,\n };\n });\n}\n\nconst day = (at: string | null) => (at ?? \"\").slice(0, 10);\n\n/** The reason on the applied event that produced the decision's current status, if any. */\nfunction statusReason(read: DecisionsRead, id: string): string | null {\n const applied = read.folded.subjects.get(id)?.applied ?? [];\n const last = applied.findLast((a) => a.from !== a.to);\n const reason = last?.event.reason;\n return typeof reason === \"string\" && reason.trim() !== \"\" ? reason.trim() : null;\n}\n\n/**\n * The state header (01:258–259): `<display> (<id>) · <status>`, and for a decision that isn't in\n * force a warning saying what to read instead. `refer` names where to read another decision. CLI\n * default: `display(id)`. Phase 3 MCP passes `id => \"adr://decision/\" + display(id)`, e.g.\n * `adr://decision/ADR-0012`, or the id when unnumbered.\n */\nexport function stateHeader(\n view: DecisionView,\n read: DecisionsRead,\n o: { readonly refer?: (id: string) => string } = {},\n): StateHeader {\n const display = (id: string) => read.projection.views.get(id)?.display ?? id;\n const refer = o.refer ?? display;\n const line =\n view.number === null\n ? `${view.id} · ${view.status}`\n : `${view.display} (${view.id}) · ${view.status}`;\n const parts: string[] = [];\n const reason = statusReason(read, view.id);\n const when = day(view.status_at);\n switch (view.status) {\n case \"superseded\": {\n const target = view.effective ?? view.superseded_by ?? view.id;\n const accepted = read.projection.views.get(target)?.decided_at ?? null;\n const date = accepted === null ? \"\" : ` (accepted ${day(accepted)})`;\n parts.push(\n `SUPERSEDED by ${display(target)}${date}. Do not apply this decision; read ${refer(target)} instead.`,\n );\n if (view.chain.length > 2) parts.push(`Chain: ${view.chain.map(display).join(\" → \")}.`);\n break;\n }\n case \"deprecated\":\n parts.push(`DEPRECATED on ${when}: ${reason ?? \"no reason given\"}. No decision replaces it.`);\n break;\n case \"rejected\":\n parts.push(\n `REJECTED on ${when}: ${reason ?? \"no reason given\"}. This decision was never in force.`,\n );\n break;\n case \"withdrawn\":\n parts.push(\n `WITHDRAWN on ${when}${reason === null ? \"\" : `: ${reason}`}. This decision was never in force.`,\n );\n break;\n default:\n break;\n }\n if (view.body_intact === false) {\n parts.push(\"WARNING: the body changed after acceptance; run adr verify.\");\n }\n return { line, warning: parts.length === 0 ? null : parts.join(\" \") };\n}\n","import { lstat, realpath } from \"node:fs/promises\";\nimport { isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport {\n type Finding,\n indexReader,\n type ScopeVia,\n scanAnchors,\n scopeLookup,\n type TreeReader,\n UsageError,\n withGitOperation,\n} from \"@nikovirtala/ledger\";\nimport type { DecisionStatus, DecisionView } from \"./kind.js\";\nimport { type DecisionLog, type DecisionsRead, listingNotes } from \"./log.js\";\nimport { type NumberingJson, numberingJson, stateHeader } from \"./views.js\";\n\n/** One decision that governs a path in `adr-for/v1` (design §6.9). */\nexport interface DecisionForJson {\n readonly id: string;\n readonly display: string;\n readonly title: string;\n readonly status: DecisionStatus;\n readonly effective: string | null;\n /** What to know before applying it: superseded, deprecated, never in force; `null` if nothing. */\n readonly warning: string | null;\n /** The globs that matched, then the anchor lines. */\n readonly via: readonly ScopeVia[];\n}\n\n/** An anchor naming no decision of this log. */\nexport interface UnresolvedAnchorJson {\n /** The id, or `<source>:<id>` for a qualified anchor. */\n readonly ref: string;\n readonly line: number;\n readonly reason: \"not-found\" | \"other-log\";\n}\n\n/** `adr for <path>… --json` (design §6.9). */\nexport interface DecisionsForJson {\n readonly format: \"adr-for/v1\";\n readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly numbering: NumberingJson;\n readonly paths: readonly {\n readonly path: string;\n /** In the index, or in the `--ref` tree. */\n readonly tracked: boolean;\n readonly decisions: readonly DecisionForJson[];\n readonly unresolved: readonly UnresolvedAnchorJson[];\n }[];\n /** The read's findings of the listed decisions and of the log as a whole. */\n readonly findings: readonly Finding[];\n readonly notes: readonly string[];\n}\n\nconst MAX_PATHS = 100;\nconst MAX_PATH_LENGTH = 4096;\n/** Statuses whose globs govern code; rejected and withdrawn decisions were never in force. */\nconst GLOBS_APPLY: ReadonlySet<DecisionStatus> = new Set([\n \"proposed\",\n \"accepted\",\n \"deprecated\",\n \"superseded\",\n]);\n/** The order `adr for` and `adr search` list statuses in: in force first. */\nexport const STATUS_ORDER: readonly DecisionStatus[] = [\n \"accepted\",\n \"proposed\",\n \"deprecated\",\n \"superseded\",\n \"rejected\",\n \"withdrawn\",\n];\n\n/** Accepted first (design §6.9 step 5); within a status by number, then by id. */\nfunction compareFor(a: DecisionView, b: DecisionView): number {\n const s = STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status);\n if (s !== 0) return s;\n if (a.number !== null || b.number !== null) {\n if (a.number === null) return 1;\n if (b.number === null) return -1;\n return a.number - b.number;\n }\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n\n/** `path` (relative to `cwd`) as a repo-relative POSIX path; `UsageError` outside the work tree. */\nasync function repoPath(root: string, cwd: string, path: string): Promise<string> {\n if (path.length > MAX_PATH_LENGTH) {\n throw new UsageError(`a path can be at most ${MAX_PATH_LENGTH} characters`);\n }\n const base = await realpath(cwd).catch(() => cwd);\n const rel = relative(root, resolve(base, path));\n if (rel === \"..\" || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {\n throw new UsageError(`${path} is outside the repository`);\n }\n return rel.split(sep).join(\"/\");\n}\n\n/**\n * Which decisions govern each path (design §6.9): globs of decisions that were ever in force, and\n * comment anchors of any decision, read from the work tree or, with a `--ref` log, that commit.\n * Paths are relative to `o.cwd` (default the repository root); directories and paths outside the\n * repository are `UsageError`s. Paths need not be tracked.\n */\nexport async function decisionsFor(\n read: DecisionsRead,\n log: DecisionLog,\n o: { readonly paths: readonly string[]; readonly cwd?: string },\n): Promise<DecisionsForJson> {\n return withGitOperation(async () => {\n const root = log.git.root;\n if (root === null) throw new UsageError(\"adr for needs a work tree\");\n if (o.paths.length === 0 || o.paths.length > MAX_PATHS) {\n throw new UsageError(`adr for takes 1 to ${MAX_PATHS} paths`);\n }\n let index: Promise<TreeReader> | null = null;\n const indexed = () => {\n index ??= indexReader(log.git);\n return index;\n };\n const hasUnder = async (tree: TreeReader, path: string) =>\n (await tree.list(path)).some((e) => e.path !== path);\n const paths: string[] = [];\n for (const given of o.paths) {\n const path = await repoPath(root, o.cwd ?? root, given);\n // A work-tree directory is found with lstat, before anything is listed or hashed (a symlink\n // is a file); a path missing from the work tree is a directory when the index has paths under\n // it. At a ref, the commit's tree is listed, which hashes nothing.\n let directory = path === \"\";\n if (!directory && read.ref === null) {\n const st = await lstat(join(root, path)).catch(() => null);\n directory = st === null ? await hasUnder(await indexed(), path) : st.isDirectory();\n } else if (!directory) {\n directory = await hasUnder(read.tree, path);\n }\n if (directory) {\n throw new UsageError(\n `${given} is a directory; adr for takes file paths, for example adr for $(git ls-files ${given})`,\n );\n }\n if (!paths.includes(path)) paths.push(path);\n }\n\n const atRef = read.ref !== null && read.commit !== null;\n const trackedIn = atRef ? read.tree : await indexed();\n const tracked = new Set<string>();\n for (const p of paths) {\n if ((await trackedIn.list(p)).some((e) => e.path === p)) tracked.add(p);\n }\n const anchors = await scanAnchors(log.git, {\n keyword: read.adr.anchorKeyword,\n tree: atRef ? { commit: read.commit as string } : \"worktree\",\n paths,\n excludeDirs: [read.layout.root],\n exclude: read.adr.anchorExclude,\n });\n const views = read.projection.views;\n const lookup = scopeLookup({\n subjects: [...views.values()]\n .filter((v) => GLOBS_APPLY.has(v.status))\n .map((v) => ({ id: v.id, globs: v.applies_to })),\n anchors,\n });\n\n const listed = new Set<string>();\n const out = paths.map((path) => {\n const decisions: { view: DecisionView; via: readonly ScopeVia[] }[] = [];\n const unresolved: UnresolvedAnchorJson[] = [];\n for (const m of lookup(path)) {\n const view = m.source === null ? views.get(m.id) : undefined;\n if (view === undefined) {\n for (const v of m.via) {\n if (v.type !== \"anchor\") continue;\n unresolved.push({\n ref: m.source === null ? m.id : `${m.source}:${m.id}`,\n line: v.line,\n reason: m.source === null ? \"not-found\" : \"other-log\",\n });\n }\n continue;\n }\n decisions.push({ view, via: m.via });\n listed.add(view.id);\n }\n decisions.sort((a, b) => compareFor(a.view, b.view));\n unresolved.sort((a, b) => a.line - b.line);\n return {\n path,\n tracked: tracked.has(path),\n decisions: decisions.map(\n ({ view: v, via }): DecisionForJson => ({\n id: v.id,\n display: v.display,\n title: v.title,\n status: v.status,\n effective: v.effective,\n warning: stateHeader(v, read).warning,\n via,\n }),\n ),\n unresolved,\n };\n });\n return {\n format: \"adr-for/v1\",\n root: read.root,\n ref: read.ref,\n commit: read.commit,\n numbering: numberingJson(read),\n paths: out,\n findings: read.findings.filter((f) => f.subject === null || listed.has(f.subject)),\n notes: listingNotes(read),\n };\n });\n}\n","import {\n countOccurrences,\n type Finding,\n foldText,\n type StateHeader,\n searchExcerpt,\n searchTerms,\n UsageError,\n} from \"@nikovirtala/ledger\";\nimport type { DecisionStatus, DecisionView } from \"./kind.js\";\nimport { type DecisionsRead, listingNotes } from \"./log.js\";\nimport { STATUS_ORDER } from \"./scope.js\";\nimport { compareViews, type NumberingJson, numberingJson, stateHeader } from \"./views.js\";\n\n/** ledger's `foldText`, the folding `adr search` compares. */\nexport { foldText as fold } from \"@nikovirtala/ledger\";\n\nexport type SearchField = \"id\" | \"title\" | \"body\" | \"notes\";\n\n/** One decision `adr search` found. */\nexport interface DecisionSearchResultJson {\n readonly decision: DecisionView;\n /** `stateHeader(view, read)`: the CLI's wording. */\n readonly header: StateHeader;\n readonly score: number;\n /** The fields with a hit, in the order id, title, body, notes (the display number is `id`). */\n readonly matched: readonly SearchField[];\n /** The best matching line of the body or a note, cut to about 160 characters; `null` if none. */\n readonly excerpt: string | null;\n}\n\n/** `adr search <query>… --json` and `adr_search` (design §6.4). */\nexport interface DecisionSearchJson {\n readonly format: \"adr-search/v1\";\n /** The `[[sources]]` entry searched (`--source`), or `null` for the local log. */\n readonly source: string | null;\n readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly numbering: NumberingJson;\n /** As given, trimmed. */\n readonly query: string;\n /** Folded, deduplicated, in query order. */\n readonly terms: readonly string[];\n readonly include_inactive: boolean;\n /** Matching decisions before `limit`. */\n readonly total: number;\n /** Decisions that match but aren't active; `0` with `include_inactive`. */\n readonly inactive_omitted: number;\n readonly results: readonly DecisionSearchResultJson[];\n /** The read's findings of the listed decisions and of the log as a whole. */\n readonly findings: readonly Finding[];\n /** `read.notes`, then the sources note. */\n readonly notes: readonly string[];\n}\n\nconst ACTIVE: ReadonlySet<DecisionStatus> = new Set([\"proposed\", \"accepted\"]);\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** The body text without its first `# ` title line; `\"\"` when missing or not UTF-8. */\nfunction bodyText(read: DecisionsRead, id: string): string {\n const bytes = read.folded.subjects.get(id)?.loaded?.body?.bytes;\n if (bytes === undefined) return \"\";\n let text: string;\n try {\n text = decoder.decode(bytes).replace(/\\r\\n/g, \"\\n\");\n } catch {\n return \"\";\n }\n const lines = text.split(\"\\n\");\n const title = lines.findIndex((l) => l.startsWith(\"# \"));\n if (title >= 0) lines.splice(title, 1);\n return lines.join(\"\\n\");\n}\n\nfunction noteTexts(read: DecisionsRead, id: string): string[] {\n return (read.folded.subjects.get(id)?.applied ?? []).flatMap((a) => {\n const text = (a.event.data as { text?: unknown } | null)?.text;\n return a.event.type === \"noted\" && typeof text === \"string\" ? [text] : [];\n });\n}\n\n/**\n * Full-text search of the log (design §8.1): a decision matches when every term of the folded\n * query is a substring of its folded id, display number, title, body or note texts. Ranked by\n * score (10 for a term equal to the id or number, 5 in the title, up to 3 for body hits and 2\n * for note hits), then status as `adr for` orders them, then list order. Only proposed and\n * accepted decisions unless `includeInactive`. Throws `UsageError` for an invalid query.\n */\nexport function searchDecisions(\n read: DecisionsRead,\n o: { readonly query: string; readonly includeInactive?: boolean; readonly limit?: number },\n): DecisionSearchJson {\n const terms = searchTerms(o.query);\n if (o.limit !== undefined && (!Number.isInteger(o.limit) || o.limit < 1)) {\n throw new UsageError(\"the search limit must be a positive integer\");\n }\n const includeInactive = o.includeInactive === true;\n const found: (DecisionSearchResultJson & { readonly view: DecisionView })[] = [];\n let inactive = 0;\n for (const view of read.projection.views.values()) {\n const body = bodyText(read, view.id);\n const notes = noteTexts(read, view.id);\n const id = foldText(view.id).text;\n const display = foldText(view.display).text;\n const title = foldText(view.title).text;\n const foldedBody = foldText(body).text;\n const foldedNotes = notes.map((n) => foldText(n).text).join(\"\\n\");\n const hit = new Set<SearchField>();\n let score = 0;\n let all = true;\n for (const t of terms) {\n const inId = id.includes(t) || display.includes(t);\n const inTitle = title.includes(t);\n const inBody = countOccurrences(foldedBody, t);\n const inNotes = countOccurrences(foldedNotes, t);\n if (!inId && !inTitle && inBody === 0 && inNotes === 0) {\n all = false;\n break;\n }\n if (inId) hit.add(\"id\");\n if (inTitle) hit.add(\"title\");\n if (inBody > 0) hit.add(\"body\");\n if (inNotes > 0) hit.add(\"notes\");\n score +=\n (t === id || t === display ? 10 : 0) +\n (inTitle ? 5 : 0) +\n Math.min(3, inBody) +\n Math.min(2, inNotes);\n }\n if (!all) continue;\n if (!includeInactive && !ACTIVE.has(view.status)) {\n inactive++;\n continue;\n }\n const lines = [\n ...body.split(\"\\n\").filter((l) => l.trim() !== \"\" && !l.startsWith(\"#\")),\n ...notes.flatMap((n) => n.split(\"\\n\")),\n ];\n found.push({\n view,\n decision: view,\n header: stateHeader(view, read),\n score,\n matched: ([\"id\", \"title\", \"body\", \"notes\"] as const).filter((f) => hit.has(f)),\n excerpt: searchExcerpt(lines, terms),\n });\n }\n found.sort(\n (a, b) =>\n b.score - a.score ||\n STATUS_ORDER.indexOf(a.view.status) - STATUS_ORDER.indexOf(b.view.status) ||\n compareViews(a.view, b.view),\n );\n const results = found.slice(0, o.limit ?? Number.POSITIVE_INFINITY).map(({ view: _, ...r }) => r);\n const listed = new Set(results.map((r) => r.decision.id));\n return {\n format: \"adr-search/v1\",\n source: read.source,\n root: read.root,\n ref: read.ref,\n commit: read.commit,\n numbering: numberingJson(read),\n query: o.query.trim(),\n terms,\n include_inactive: includeInactive,\n total: found.length,\n inactive_omitted: inactive,\n results,\n findings: read.findings.filter((f) => f.subject === null || listed.has(f.subject)),\n notes: listingNotes(read),\n };\n}\n"],"mappings":";;;;;;;;;AAIA,MAAa,UAAU;CACrB,UAAU;EAAE,QAAQ;EAAc,OAAO;CAAQ;CACjD,UAAU;EAAE,QAAQ;EAAa,OAAO;CAAQ;CAChD,UAAU;EAAE,QAAQ;EAAiB,OAAO;CAAQ;CACpD,WAAW;EAAE,QAAQ;EAA4B,OAAO;CAAQ;CAChE,YAAY;EAAE,QAAQ;EAAa,OAAO;CAAU;CACpD,YAAY;EAAE,QAAQ;EAAa,OAAO;CAAU;CACpD,OAAO;EAAE,QAAQ;EAAiB,OAAO;CAAU;CACnD,QAAQ;EAAE,QAAQ;EAAQ,OAAO;CAAU;CAC3C,QAAQ;EAAE,QAAQ;EAAoB,OAAO;CAAU;AACzD;;;;;AAMA,MAAa,gBAAgB;CAC3B,YAAY;CACZ,YAAY;CACZ,QAAQ;CACR,QAAQ;CACR,OAAO;AACT;AACA,MAAa,cAAiC;CAC5C;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,gBAAgB;;AAY7B,MAAa,eAAe;;;;;;AAO5B,MAAa,iBAAyB,KAAK,IACzC,GAAG,OAAO,OAAO,OAAO,CAAC,CAAC,KAAK,MAAM,EAAE,OAAO,MAAM,GACpD,IACA,EACF;;AAMA,MAAa,iBAAiB;;AAG9B,MAAa,cAAc,OAAO,OAAO;CACvC,QAAQ;CACR,IAAI;CACJ,SAAA;CACA,S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ecisionLog, N as readDecisions, S as DECISION_INDEX, _ as withdrawDecision, a as stateHeader, d as proposeDecision, f as rejectDecision, g as updateDraft, h as supersedeDecision, i as showDecision, l as linkDecision, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions } from "./search-DLUlAP11.js";
1
+ import { F as resolveDecision, M as openDecisionLog, N as readDecisions, S as DECISION_INDEX, _ as withdrawDecision, a as stateHeader, d as proposeDecision, f as rejectDecision, g as updateDraft, h as supersedeDecision, i as showDecision, l as linkDecision, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions } from "./search-Ciix0IwS.js";
2
2
  import { n as DECISION_STATUSES, t as adrKind } from "./kind-C3DiBuUp.js";
3
- import { t as listTemplates } from "./list-qsuw1oAL.js";
3
+ import { t as listTemplates } from "./list-BnLU8Mis.js";
4
4
  import { MAX_GLOB_LENGTH, UsageError, eventDir, parseOnBehalfOf, renderIndex, renderStateHeader, resolveSubjectInput } from "@nikovirtala/ledger";
5
5
  import { mcpAttribution, serveMcp } from "@nikovirtala/ledger/mcp";
6
6
  // src/mcp/policy.ts
@@ -947,4 +947,4 @@ async function serveAdrMcp(o) {
947
947
  }
948
948
  export { serveAdrMcp };
949
949
 
950
- //# sourceMappingURL=server-WidFQzlx.js.map
950
+ //# sourceMappingURL=server-BA8WZ9Jq.js.map