@nikovirtala/adr 0.0.0 → 0.2.0

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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -0
  3. package/dist/cli.js +1057 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/index.js +3 -0
  6. package/dist/kind-BcHjCHvi.js +415 -0
  7. package/dist/kind-BcHjCHvi.js.map +1 -0
  8. package/dist/kind.js +1 -0
  9. package/dist/types/cli/accept.d.ts +3 -0
  10. package/dist/types/cli/commands.d.ts +3 -0
  11. package/dist/types/cli/deprecate.d.ts +3 -0
  12. package/dist/types/cli/editor.d.ts +12 -0
  13. package/dist/types/cli/for.d.ts +3 -0
  14. package/dist/types/cli/init.d.ts +3 -0
  15. package/dist/types/cli/link.d.ts +3 -0
  16. package/dist/types/cli/list.d.ts +3 -0
  17. package/dist/types/cli/new.d.ts +6 -0
  18. package/dist/types/cli/note.d.ts +3 -0
  19. package/dist/types/cli/open.d.ts +17 -0
  20. package/dist/types/cli/reject.d.ts +3 -0
  21. package/dist/types/cli/scope.d.ts +7 -0
  22. package/dist/types/cli/show.d.ts +3 -0
  23. package/dist/types/cli/supersede.d.ts +3 -0
  24. package/dist/types/cli/text.d.ts +46 -0
  25. package/dist/types/cli/withdraw.d.ts +3 -0
  26. package/dist/types/cli.d.ts +2 -0
  27. package/dist/types/config.d.ts +33 -0
  28. package/dist/types/index.d.ts +8 -0
  29. package/dist/types/init.d.ts +27 -0
  30. package/dist/types/kind/project.d.ts +50 -0
  31. package/dist/types/kind/reduce.d.ts +35 -0
  32. package/dist/types/kind/rules.d.ts +20 -0
  33. package/dist/types/kind/schemas.d.ts +37 -0
  34. package/dist/types/kind.d.ts +18 -0
  35. package/dist/types/log.d.ts +53 -0
  36. package/dist/types/scope.d.ts +51 -0
  37. package/dist/types/templates/builtin.d.ts +8 -0
  38. package/dist/types/verify.d.ts +10 -0
  39. package/dist/types/views.d.ts +65 -0
  40. package/dist/types/write.d.ts +333 -0
  41. package/dist/write-9IaqHRrY.js +1986 -0
  42. package/dist/write-9IaqHRrY.js.map +1 -0
  43. package/package.json +55 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write-9IaqHRrY.js","names":["encoder","compiled","decoder"],"sources":["../src/config.ts","../src/templates/builtin.ts","../src/init.ts","../src/log.ts","../src/views.ts","../src/scope.ts","../src/verify.ts","../src/write.ts"],"sourcesContent":["import {\n type CommitTemplate,\n ConfigError,\n parseCommitTemplate,\n parseGlob,\n readCommitTemplate,\n type Severity,\n type ToolConfig,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\n\n/** adr's commit-subject placeholders, each with its longest value (design §4.2). */\nconst COMMIT_VARS = Object.freeze({ action: 24, id: 8, display: 13, command: 9 });\n/** The default `[commit] subject`. */\nexport const DEFAULT_COMMIT_SUBJECT = \"docs(adr): {action} {title}\";\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). The shorter names (a display,\n * at most 13 characters) always fit in the room a title gets.\n */\nconst COMMIT_NAMES = Object.freeze([\n { length: COMMIT_VARS.display * 2 + \" with \".length, vars: { action: \"supersede\".length } },\n { length: COMMIT_VARS.display + \" to a decision in another log\".length, vars: { action: 4 } },\n]);\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`: validated now, used in phase 2. */\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 /** `[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 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 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 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","/**\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 { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n ConfigError,\n InvalidArgumentError,\n readToolConfig,\n renderCommitMessage,\n UsageError,\n writeNewFile,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\nimport { BUILTIN_TEMPLATES } from \"./templates/builtin.js\";\n\n/** `adr init --json` (design §6.2). */\nexport interface InitResultJson {\n readonly format: \"adr-init/v1\";\n readonly root: string;\n /** The config file of the log after init, repo-relative; `null` if there is none. */\n readonly config: string | null;\n /** Repo-relative paths written, in write order. */\n readonly written: readonly string[];\n /** Files that were already there and were left as they are. */\n readonly kept: readonly string[];\n readonly commit: string | null;\n readonly notes: readonly string[];\n}\n\nconst CONFIG = \"adr.toml\";\nconst DEFAULT_ROOT = adrKind.def.defaultRoot;\nconst encoder = new TextEncoder();\n\n/** The starter config; `root` only for a repo-level file naming a log elsewhere. */\nfunction configText(o: { readonly root: string | null; readonly template: string }): string {\n return [\n \"# adr configuration. Every key is optional: https://github.com/nikovirtala/ark/tree/main/packages/adr#config-adrtoml\",\n \"[log]\",\n ...(o.root === null ? [] : [`root = ${JSON.stringify(o.root)}`]),\n `default_template = ${JSON.stringify(o.template)}`,\n \"\",\n \"[commit]\",\n '# subject = \"docs(adr): {action} {title}\"',\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * `adr init` (design §6.2): writes a config for the log, unless one is found, and each built-in\n * template in `o.templates` (default `nygard`) to `<root>/templates/`, never overwriting a file.\n * A `--root` other than `docs/adr` gets a repo-level `adr.toml` naming it, so later commands find\n * the log without `--root`; when that file exists for another log, the config goes in the root.\n * With `commit` (default `[policy] auto_commit`) the written files are committed on their own;\n * nothing written means nothing committed. No events are written.\n */\nexport async function initDecisionLog(\n log: DecisionLog,\n o: {\n readonly templates?: readonly string[];\n readonly commit?: boolean;\n readonly message?: string | null;\n } = {},\n): Promise<InitResultJson> {\n if (log.ref !== null || log.tree.label !== \"worktree\") {\n throw new InvalidArgumentError(\"init writes the work tree; open the log without a ref\");\n }\n const known = Object.keys(BUILTIN_TEMPLATES);\n const templates = [...new Set(o.templates === undefined ? [\"nygard\"] : o.templates)];\n for (const name of templates) {\n if (!known.includes(name)) {\n throw new UsageError(`unknown built-in template ${name}; use nygard, madr or y-statement`);\n }\n }\n const root = log.layout.root;\n const notes = [...log.notes];\n const files: [string, string][] = [];\n const kept: string[] = [];\n let config = log.configPath;\n if (config !== null) {\n kept.push(config);\n } else {\n const template = templates[0] ?? \"nygard\";\n const repo = await readToolConfig(log.tree, CONFIG);\n if (root === DEFAULT_ROOT) {\n config = `${root}/${CONFIG}`;\n files.push([config, configText({ root: null, template })]);\n } else if (repo === null) {\n config = CONFIG;\n files.push([config, configText({ root, template })]);\n } else {\n // The repo file names another log (openToolLog ignored it with a note); leave it alone.\n const section = repo.raw.log as { root?: unknown } | undefined;\n const other = typeof section?.root === \"string\" ? section.root : DEFAULT_ROOT;\n config = `${root}/${CONFIG}`;\n files.push([config, configText({ root: null, template })]);\n notes.push(`${CONFIG} names ${other}; pass --root ${root} to use this log`);\n }\n }\n for (const name of templates) {\n const path = `${root}/templates/${name}.md`;\n if ((await log.tree.read(path)) !== null) kept.push(path);\n else files.push([path, BUILTIN_TEMPLATES[name] ?? \"\"]);\n }\n\n const commit = files.length > 0 && (o.commit ?? log.adr.autoCommit);\n if (\n commit &&\n ((await log.git.identity()) === null || (await log.git.committerIdentity()) === null)\n ) {\n throw new ConfigError(\"--commit needs a git identity; set git user.name and user.email\");\n }\n const written: string[] = [];\n try {\n for (const [path, text] of files) {\n await writeNewFile(log.git, path, encoder.encode(text));\n written.push(path);\n }\n } catch (err) {\n const top = log.git.root ?? \"\";\n for (const path of written) await rm(join(top, path), { force: true });\n throw err;\n }\n if (written.length > 0) await log.git.add(written);\n let sha: string | null = null;\n if (commit) {\n const message =\n o.message ??\n renderCommitMessage(log.adr.commitSubject, {\n title: \"the decision log\",\n vars: { action: \"set up\", id: \"\", display: \"\", command: \"init\" },\n }).message;\n sha = await log.git.commit({ message, only: written });\n }\n return { format: \"adr-init/v1\", root, config, written, kept, commit: sha, notes };\n}\n","import {\n type CheckContext,\n compileKind,\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 projectLog,\n relateCheck,\n resolveSubjectInput,\n sortFindings,\n type ToolLog,\n type TreeReader,\n transitions,\n UsageError,\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}\n\n/** `numberLog` on the repository, then `readDecisionsFrom(log.tree, …)`. */\nexport async function readDecisions(log: DecisionLog): Promise<DecisionsRead> {\n const numbering = await numberLog(log.git, {\n kind: adrKind,\n layout: log.layout,\n mainRef: log.adr.mainBranch,\n });\n return readDecisionsFrom(log.tree, {\n layout: log.layout,\n adr: log.adr,\n numbering,\n ref: log.ref,\n commit: log.commit,\n notes: log.notes,\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 },\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 };\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 };\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","import {\n compareEvents,\n type EventEnvelope,\n type Finding,\n type StateHeader,\n UsageError,\n} from \"@nikovirtala/ledger\";\nimport type { DecisionStatus, DecisionView } from \"./kind.js\";\nimport type { DecisionsRead } 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\" | 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 readonly root: string;\n readonly ref: string | null;\n readonly commit: string | null;\n readonly numbering: NumberingJson;\n readonly decisions: readonly DecisionView[];\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. */\nfunction 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 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: { readonly status?: readonly DecisionStatus[]; readonly limit?: number } = {},\n): DecisionListJson {\n const statuses = o.status === undefined || o.status.length === 0 ? null : new Set(o.status);\n const decisions = [...read.projection.views.values()]\n .filter((v) => statuses === null || statuses.has(v.status))\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 root: read.root,\n ref: read.ref,\n commit: read.commit,\n numbering: numberingJson(read),\n decisions,\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: read.notes,\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 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) => compareEvents({ ...a.event, path: a.path }, { ...b.event, path: b.path }))\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\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} from \"@nikovirtala/ledger\";\nimport type { DecisionStatus, DecisionView } from \"./kind.js\";\nimport type { DecisionLog, DecisionsRead } 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]);\nconst 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 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: read.notes,\n };\n}\n","import {\n type Check,\n type Finding,\n foldChecks,\n gitTemplates,\n templateHistoryRef,\n type VerifyMode,\n verifyLog,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\n\n/**\n * Every phase-1 check for the log: ledger's mechanical and fold checks with adr's actor policy,\n * and template lint against the templates in the head tree and, for older versions, the history\n * of `historyRef`.\n */\nexport function adrChecks(log: DecisionLog, historyRef: string | null): readonly Check[] {\n return foldChecks(adrKind, {\n options: { acceptRequiresHuman: log.adr.acceptRequiresHuman },\n templates: gitTemplates(log.git, { historyRef }),\n });\n}\n\n/** Verifies the decision log in `mode` (staged, range or full) with `adrChecks`. */\nexport async function verifyDecisions(log: DecisionLog, mode: VerifyMode): Promise<Finding[]> {\n return verifyLog({\n git: log.git,\n kind: adrKind,\n layout: log.layout,\n mode,\n checks: adrChecks(log, await templateHistoryRef(log.git, mode)),\n });\n}\n","import { readFile, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n type Actor,\n applySetOp,\n bodyFileName,\n bodySha256,\n ConfigError,\n classifyPath,\n compileKind,\n ENVELOPE_VERSION,\n type EventEnvelope,\n EventExistsError,\n eventDir,\n eventPath,\n FileExistsError,\n type Finding,\n finding,\n followRenames,\n globMatcher,\n historyTemplates,\n InvalidArgumentError,\n indexReader,\n isSubjectId,\n lintDocument,\n lintTemplate,\n newSubjectId,\n nextEventIdentity,\n overlayTree,\n parseEventFileName,\n parseGlob,\n parseTemplate,\n type Rename,\n refReader,\n renderCommitMessage,\n renderTemplate,\n type SetOp,\n serializeEvent,\n slugify,\n stagedRenames,\n type Template,\n type TemplateSource,\n type Trailer,\n type TreeReader,\n templateHistoryRef,\n UsageError,\n writeEvents,\n writeNewFile,\n} from \"@nikovirtala/ledger\";\nimport { 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 { 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 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.\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\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 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): Promise<{ after: DecisionsRead; added: Finding[] }> {\n const after = await readDecisionsFrom(overlayTree(read.tree, files), {\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 });\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/** 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[] } = {},\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 return {\n ok: true,\n plan: {\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\n/**\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 */\nconst 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\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); it isn't looked up in the other log. A link that\n * already exists plans nothing, with a note.\n */\nexport async function planLink(\n read: DecisionsRead,\n input: LinkInput,\n c: PlanContext,\n o: { readonly sources?: readonly string[] } = {},\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 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 to = target;\n shown = target;\n described = `${rel} ${target}.`;\n named = `${view.display} to a decision in another log`;\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: { ...r.plan, commit: { ...r.plan.commit, title: named, body: [described] } },\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 notes.push(...unmatchedGlobs(result.set, o.tracked).map((g) => `${g} matches no tracked file`));\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/**\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.\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 readonly afterStage?: () => Promise<AfterStage>;\n },\n): Promise<{ written: string[]; commit: string | null; findings: readonly Finding[] }> {\n const { git } = log;\n if (o.commit && o.message === undefined) {\n throw new InvalidArgumentError(\"applyPlan needs a message to commit\");\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 const eventPaths = new Set(plan.events.map((e) => eventPath(log.layout, e)));\n const written: string[] = [];\n try {\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 await writeEvents(git, log.layout, plan.events, { kind: log.compiled, stage: false });\n } catch (err) {\n const root = git.root ?? \"\";\n for (const path of written) await rm(join(root, path), { force: true });\n throw err;\n }\n await git.add(plan.stage);\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 let sha: string | null = null;\n if (commit) {\n const extra = (await git.stagedPaths(plan.commitScope)).filter((p) => !stage.has(p));\n const staged: Trailer[] = extra.filter(isYaml).flatMap((p): Trailer[] => {\n const c = classifyPath(log.layout, p);\n const name = c.area === \"event\" && !c.file.includes(\"/\") ? parseEventFileName(c.file) : null;\n return c.area === \"event\" && c.subject !== null && name !== null\n ? [\n [\"ADR\", c.subject],\n [\"ADR-Event\", name.type],\n ]\n : [];\n });\n sha = await git.commit({\n message: o.message ?? \"\",\n mergeTrailers: o.mergeTrailers === true,\n trailers: [...staged, ...plan.trailers],\n only: sorted([...plan.stage, ...extra]),\n });\n }\n return { written: Object.keys(plan.files), commit: sha, findings };\n}\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\nconst SHORTENED_NOTE =\n \"commit subject shortened to 72 characters; the full title is in the commit body\";\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\n/** The plan's commit message from `[commit] subject` (design §4), and whether it was shortened. */\nfunction commitMessage(\n log: DecisionLog,\n command: string,\n plan: WritePlan,\n): { message: string; shortened: boolean } {\n const parts = plan.commit;\n if (parts === null) throw new InvalidArgumentError(\"this write can't be committed\");\n const r = renderCommitMessage(log.adr.commitSubject, {\n title: parts.title,\n vars: { action: parts.action, id: parts.id, display: parts.display, command },\n body: parts.body,\n });\n return { message: r.message, shortened: r.shortened };\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 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 = r.plan.events.length === 0 && Object.keys(r.plan.files).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 const rendered = commit ? commitMessage(log, command, r.plan) : null;\n const given = o.message ?? null;\n try {\n const applied = await deps.apply(log, r.plan, {\n commit,\n ...(rendered === null\n ? {}\n : { message: given ?? rendered.message, mergeTrailers: given !== null }),\n ...(afterStage === undefined ? {} : { afterStage: afterStage(r.plan, commit) }),\n });\n const views = await viewsAfter(log, r.plan, applied.commit);\n const own = [\n ...(r.plan.notes ?? []),\n ...(applied.commit !== null && given === null && rendered?.shortened === true\n ? [SHORTENED_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 // 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\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 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 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 * `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 return write(\n log,\n \"accept\",\n async (read, c) => {\n const plain = await planAccept(read, input, c);\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 copy = typeof copyScope === \"function\" ? await copyScope(offer) : copyScope === \"copy\";\n }\n if (copy) return planAccept(read, input, c, { copyGlobs: offer.globs });\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 sources = (log.config?.sources ?? []).map((s) => s.name);\n return write(log, \"link\", (read, c) => planLink(read, input, c, { sources }), o, deps);\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\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 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"],"mappings":";;;;;;AAYA,MAAM,cAAc,OAAO,OAAO;CAAE,QAAQ;CAAI,IAAI;CAAG,SAAS;CAAI,SAAS;AAAE,CAAC;;AAEhF,MAAa,yBAAyB;;;;;;;AAOtC,MAAM,eAAe,OAAO,OAAO,CACjC;CAAE,QAAQ,YAAY,UAAU,IAAI;CAAiB,MAAM,EAAE,QAAQ,EAAmB;AAAE,GAC1F;CAAE,QAAQ,YAAY,UAAU;CAAwC,MAAM,EAAE,Q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M,UAAU,MAAM,OAAO,GAAG,EAAE,QAAQ,CAAC,GAAG,GAAG,IAAI;AACzF;AAEA,MAAM,wBACJ;;;;;;;;AASF,eAAsB,mBACpB,KACA,OACA,IAAkD,CAAC,GACnD,OAAkB,cACQ;CAC1B,IAAI,EAAE,WAAW,MACf,MAAM,IAAI,qBAAqB,2DAA2D;CAE5F,IAAI,EAAE,YAAY,KAAA,KAAa,EAAE,YAAY,MAC3C,MAAM,IAAI,qBAAqB,0DAA0D;CAE3F,MAAM,UAAU,MAAM,cAAc,IAAI,GAAG;CAC3C,MAAM,SACJ,QAAQ,WAAW,IACf;EAAE;EAAS,QAAQ,CAAC;EAAG,OAAO,CAAC;CAAE,IACjC;EACE;EACA,QAAQ,MAAM,UAAU,MAAM,UAAU,IAAI,KAAK,MAAM,CAAC;EACxD,OAAO,MAAM,UAAU,MAAM,YAAY,IAAI,GAAG,CAAC;CACnD;CACN,MAAM,MAAM,MAAM,MAChB,KACA,UACC,MAAM,MAAM,kBAAkB,MAAM;EAAE,IAAI,MAAM,MAAM;EAAM,OAAO,MAAM;CAAM,GAAG,QAAQ,CAAC,GAC5F;EAAE,GAAG;EAAG,QAAQ;CAAM,GACtB,IACF;CACA,OAAO,IAAI,IAAI,cAAc,IAAI,MAAM,IAAI,SAAS,SAAS,IACzD;EAAE,GAAG;EAAK,OAAO,CAAC,GAAG,IAAI,OAAO,qBAAqB;CAAE,IACvD;AACN"}
package/package.json CHANGED
@@ -1 +1,55 @@
1
- {"name":"@nikovirtala/adr","version":"0.0.0","description":"placeholder","license":"MIT","repository":{"type":"git","url":"git+https://github.com/nikovirtala/ark.git"}}
1
+ {
2
+ "name": "@nikovirtala/adr",
3
+ "version": "0.2.0",
4
+ "description": "Architecture decision records kept as event logs in git: frozen bodies, computed status and supersession chains. CLI and library.",
5
+ "keywords": [
6
+ "adr",
7
+ "architecture-decision-records",
8
+ "git",
9
+ "event-sourcing",
10
+ "cli"
11
+ ],
12
+ "license": "MIT",
13
+ "homepage": "https://github.com/nikovirtala/ark/tree/main/packages/adr#readme",
14
+ "bugs": "https://github.com/nikovirtala/ark/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/nikovirtala/ark.git",
18
+ "directory": "packages/adr"
19
+ },
20
+ "type": "module",
21
+ "sideEffects": false,
22
+ "bin": {
23
+ "adr": "./dist/cli.js"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/types/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./kind": {
31
+ "types": "./dist/types/kind.d.ts",
32
+ "default": "./dist/kind.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "dist",
38
+ "!dist/**/*.tsbuildinfo"
39
+ ],
40
+ "engines": {
41
+ "node": ">=24"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "provenance": true
46
+ },
47
+ "dependencies": {
48
+ "@nikovirtala/ledger": "^0.4.0"
49
+ },
50
+ "scripts": {
51
+ "build": "tsdown",
52
+ "test": "vitest run",
53
+ "clean": "rm -rf dist"
54
+ }
55
+ }