@nikovirtala/adr 0.4.0 → 0.5.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.
- package/README.md +15 -9
- package/dist/cli.js +47 -16
- package/dist/cli.js.map +1 -1
- package/dist/index.js +5 -5
- package/dist/{init-YgW7g9Fx.js → init-CaKKCINh.js} +79 -16
- package/dist/init-CaKKCINh.js.map +1 -0
- package/dist/{kind-DjvA3dyA.js → kind-C3DiBuUp.js} +44 -11
- package/dist/kind-C3DiBuUp.js.map +1 -0
- package/dist/kind.js +1 -1
- package/dist/{list-Dt4KGxvj.js → list-CJi9vZqJ.js} +3 -3
- package/dist/{list-Dt4KGxvj.js.map → list-CJi9vZqJ.js.map} +1 -1
- package/dist/{search-CwIPlNGd.js → search-CTspg2pd.js} +290 -88
- package/dist/search-CTspg2pd.js.map +1 -0
- package/dist/{server-CXCO5zfp.js → server-D3ySzyj6.js} +20 -8
- package/dist/server-D3ySzyj6.js.map +1 -0
- package/dist/types/cli/list.d.ts +4 -1
- package/dist/types/cli/search.d.ts +4 -1
- package/dist/types/commit-actions.d.ts +21 -1
- package/dist/types/hooks.d.ts +3 -2
- package/dist/types/index.d.ts +2 -1
- package/dist/types/kind/rules.d.ts +23 -2
- package/dist/types/kind.d.ts +1 -1
- package/dist/types/log-index.d.ts +0 -18
- package/dist/types/log.d.ts +6 -3
- package/dist/types/search.d.ts +2 -0
- package/dist/types/sources.d.ts +35 -0
- package/dist/types/verify.d.ts +20 -4
- package/dist/types/views.d.ts +2 -0
- package/dist/types/write.d.ts +37 -4
- package/package.json +2 -2
- package/dist/init-YgW7g9Fx.js.map +0 -1
- package/dist/kind-DjvA3dyA.js.map +0 -1
- package/dist/search-CwIPlNGd.js.map +0 -1
- package/dist/server-CXCO5zfp.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"init-YgW7g9Fx.js","names":[],"sources":["../src/verify.ts","../src/hooks.ts","../src/skill.ts","../src/init.ts"],"sourcesContent":["import {\n anchorCheck,\n type Check,\n type CheckContext,\n type Finding,\n type FoldedLogOf,\n finding,\n foldChecks,\n type GovernedChange,\n gitTemplates,\n governedChanges,\n narrowedScopes,\n projectLog,\n scopeGlobCheck,\n templateHistoryRef,\n type VerifyMode,\n verifyLog,\n} from \"@nikovirtala/ledger\";\nimport { adrKind, type DecisionView } from \"./kind.js\";\nimport { type DecisionLog, numberDecisions } from \"./log.js\";\nimport { decisionIndexCheck } from \"./log-index.js\";\n\n/** At most this many paths are named in a `decision/scope-narrowed` message. */\nconst NARROWED_PATHS = 3;\n\n/** The head's decision views with the read's numbering, for the displays in messages. */\nasync function headViews(\n log: DecisionLog,\n ctx: CheckContext,\n): Promise<ReadonlyMap<string, DecisionView>> {\n const head = ctx.folded?.head;\n if (head === undefined) return new Map();\n return projectLog(adrKind, head as FoldedLogOf<typeof adrKind>, {\n numbering: await numberDecisions(log),\n }).views;\n}\n\n/**\n * `decision/governed-by-inactive` (`[verify] governed_by_inactive`, default warning): a changed\n * code file that a superseded or deprecated decision governs, by glob or anchor (01:366).\n */\nfunction governedByInactive(log: DecisionLog): Check {\n return {\n id: \"decision-governed-by-inactive\",\n async run(ctx) {\n const changes = await governedChanges(ctx, {\n keyword: log.adr.anchorKeyword,\n exclude: log.adr.anchorExclude,\n statuses: [\"superseded\", \"deprecated\"],\n });\n if (changes.length === 0) return [];\n const views = await headViews(log, ctx);\n const display = (id: string) => views.get(id)?.display ?? id;\n const message = (c: GovernedChange): string => {\n const what = `${c.path} is governed by ${display(c.subject)}`;\n if (c.status === \"deprecated\") {\n return `${what}, which is deprecated; check whether the change still needs it`;\n }\n const next = views.get(c.subject)?.superseded_by ?? null;\n return next === null\n ? `${what}, which is superseded; check the change against its successor`\n : `${what}, which is superseded by ${display(next)}; check the change against ${display(next)}`;\n };\n return changes.map((c) =>\n finding({\n severity: log.adr.governedByInactive,\n rule: \"decision/governed-by-inactive\",\n message: message(c),\n file: c.path,\n subject: c.subject,\n }),\n );\n },\n };\n}\n\n/**\n * `decision/scope-narrowed` (warning): an accepted decision whose new scope stops covering files\n * that still exist (01:367), which calls for a check against its Scope section.\n */\nfunction scopeNarrowed(log: DecisionLog): Check {\n return {\n id: \"decision-scope-narrowed\",\n async run(ctx) {\n const narrowed = await narrowedScopes(ctx, { statuses: [\"accepted\"] });\n if (narrowed.length === 0) return [];\n const views = await headViews(log, ctx);\n return narrowed.map((n) => {\n const count = n.lost.length;\n const files = count === 1 ? \"1 file that still exists\" : `${count} files that still exist`;\n const named = n.lost.slice(0, NARROWED_PATHS).join(\", \");\n const more = count > NARROWED_PATHS ? \", …\" : \"\";\n return finding({\n severity: \"warning\",\n rule: \"decision/scope-narrowed\",\n message: `${views.get(n.subject)?.display ?? n.subject}'s scope no longer covers ${files} (${named}${more}); check the change against its Scope section`,\n file: n.file,\n subject: n.subject,\n });\n });\n },\n };\n}\n\n/**\n * Every check for the log: ledger's mechanical and fold checks with adr's actor policy, template\n * lint against the templates in the head tree and, for older versions, the history of\n * `historyRef`, the scope-glob and anchor checks, and the decision checks over code\n * (`decision/governed-by-inactive`, `decision/scope-narrowed`). With `[log] index = \"committed\"`,\n * also the freshness of `<root>/index.md`.\n */\nexport function adrChecks(log: DecisionLog, historyRef: string | null): readonly Check[] {\n return [\n ...foldChecks(adrKind, {\n options: { acceptRequiresHuman: log.adr.acceptRequiresHuman },\n templates: gitTemplates(log.git, { historyRef }),\n }),\n scopeGlobCheck(),\n anchorCheck({ keyword: log.adr.anchorKeyword, exclude: log.adr.anchorExclude }),\n governedByInactive(log),\n scopeNarrowed(log),\n ...(log.adr.index === \"committed\" ? [decisionIndexCheck(log)] : []),\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 { access, constants } from \"node:fs/promises\";\nimport { relative, resolve, sep } from \"node:path\";\nimport {\n assertNoHookConflicts,\n classifyPath,\n exitCode,\n type Finding,\n type Git,\n type HookInstallResult,\n type HookManager,\n type HookName,\n hookSnippet,\n installHooks,\n parseEventFileName,\n resolveAttribution,\n type Severity,\n stagedRenames,\n type Trailer,\n UsageError,\n uninstallHooks,\n writeIndexFile,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\nimport { holdsText, indexPath, renderDecisionIndex } from \"./log-index.js\";\nimport { verifyDecisions } from \"./verify.js\";\nimport { followScopeRenames } from \"./write.js\";\n\n/** The hooks adr registers, in the order the text output lists them. */\nconst HOOKS: readonly HookName[] = [\"pre-commit\", \"commit-msg\", \"pre-push\", \"post-merge\"];\n\n/** `adr hooks … --json` (design 2b §4.3); `hooks run` prints `ledger-findings/v1` instead. */\nexport interface HooksResultJson {\n readonly format: \"adr-hooks/v1\";\n readonly action: \"install\" | \"uninstall\" | \"print\" | \"trailers\";\n /** Repo-relative shim paths written or removed. */\n readonly written: readonly string[];\n readonly unchanged: readonly string[];\n readonly registrations: readonly { readonly hook: HookName; readonly argv: readonly string[] }[];\n /** `print` only. */\n readonly snippet: string | null;\n /** `trailers` only: the trailers added, in order. */\n readonly trailers: readonly (readonly [string, string])[];\n}\n\n/**\n * adr's command per hook (design 2b D4), after `adr`. `--root <root>` comes first only when the\n * root can't be found without it: no `<repo>/adr.toml` names it and it isn't `docs/adr`. So the\n * hooks see the same config as a plain `adr` run, and never print the root-override note.\n */\nexport function decisionHookCommands(\n log: DecisionLog,\n): Partial<Record<HookName, readonly string[]>> {\n const r =\n log.configPath === \"adr.toml\" || log.layout.root === adrKind.def.defaultRoot\n ? []\n : [\"--root\", log.layout.root];\n return {\n \"pre-commit\": [...r, \"hooks\", \"run\", \"pre-commit\"],\n \"commit-msg\": [...r, \"hooks\", \"trailers\", \"{args}\"],\n \"pre-push\": [...r, \"verify\", \"--base\", \"@{upstream}\", \"--ref\", \"HEAD\"],\n \"post-merge\": [...r, \"list\", \"--since\", \"ORIG_HEAD\"],\n };\n}\n\nfunction registrations(log: DecisionLog): HooksResultJson[\"registrations\"] {\n const commands = decisionHookCommands(log);\n return HOOKS.flatMap((hook) => {\n const argv = commands[hook];\n return argv === undefined ? [] : [{ hook, argv }];\n });\n}\n\n/** A shim path as the user sees it: repo-relative, with `/`. */\nfunction shown(git: Git, path: string): string {\n return relative(git.root ?? git.gitDir, path)\n .split(sep)\n .join(\"/\");\n}\n\n/** The shims in hook order: `HOOKS`' order, as the text output lists them. */\nfunction inHookOrder(git: Git, paths: readonly string[]): string[] {\n const rank = (p: string) => HOOKS.findIndex((h) => p.endsWith(`/${h}`));\n return paths.map((p) => shown(git, p)).sort((a, b) => rank(a) - rank(b));\n}\n\nfunction result(\n log: DecisionLog,\n action: HooksResultJson[\"action\"],\n r: HookInstallResult | null,\n extra: Partial<Pick<HooksResultJson, \"snippet\" | \"trailers\">> = {},\n): HooksResultJson {\n return {\n format: \"adr-hooks/v1\",\n action,\n written: r === null ? [] : inHookOrder(log.git, r.written),\n unchanged: r === null ? [] : inHookOrder(log.git, r.unchanged),\n registrations: registrations(log),\n snippet: extra.snippet ?? null,\n trailers: extra.trailers ?? [],\n };\n}\n\n/**\n * Registers adr's four commands in ledger's shims, one per hook and shared with other ark tools\n * (design 2b D4). With `core.hooksPath` set or a foreign hook file present, it writes the rest and\n * then throws `HookConflictError` (exit 2), naming each conflict and the `print` command.\n */\nexport async function installDecisionHooks(log: DecisionLog): Promise<HooksResultJson> {\n const r = await installHooks(log.git, { tool: \"adr\", commands: decisionHookCommands(log) });\n assertNoHookConflicts(r, { tool: \"adr\" });\n return result(log, \"install\", r);\n}\n\n/** Removes adr from every shim; a shim left with no tool is deleted. */\nexport async function uninstallDecisionHooks(log: DecisionLog): Promise<HooksResultJson> {\n return result(log, \"uninstall\", await uninstallHooks(log.git, { tool: \"adr\" }));\n}\n\n/** The config to paste into a hook manager instead of installing shims. */\nexport function printDecisionHooks(log: DecisionLog, manager: HookManager): HooksResultJson {\n const regs = registrations(log).map((r) => ({ tool: \"adr\", ...r }));\n return result(log, \"print\", null, { snippet: hookSnippet(manager, regs) });\n}\n\n/** The `ADR-Event` trailer key as git compares keys: case-insensitively. */\nconst ADR_EVENT = /^adr-event[ \\t]*:/im;\n\n/**\n * The `commit-msg` step (P1 §7.1): appends one `ADR`/`ADR-Event` pair per staged added event file\n * of the log, by path, keeping repeats (`ifExists: \"add\"`). It does nothing for a message that\n * already has an `ADR-Event:` trailer (an `adr … --commit` message), or during a merge, whose\n * events came with their own commits' trailers. Throws `UsageError` when the file is missing.\n */\nexport async function addHookTrailers(\n log: DecisionLog,\n messageFile: string,\n): Promise<HooksResultJson> {\n const { git, layout } = log;\n const file = resolve(git.root ?? git.gitDir, messageFile);\n try {\n await access(file, constants.R_OK | constants.W_OK);\n } catch {\n throw new UsageError(`no commit message file at ${messageFile}`);\n }\n const parsed = await git.run([\"interpret-trailers\", \"--parse\", \"--\", file]);\n if (ADR_EVENT.test(Buffer.from(parsed.stdout).toString(\"utf8\"))) {\n return result(log, \"trailers\", null);\n }\n if ((await git.resolveCommit(\"MERGE_HEAD\")) !== null) return result(log, \"trailers\", null);\n const added = await git.stagedPaths([`${layout.root}/${layout.events}`], { addedOnly: true });\n const trailers = added.flatMap((p): Trailer[] => {\n const c = classifyPath(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 await git.appendTrailers(file, trailers, { ifExists: \"add\" });\n return result(log, \"trailers\", null, { trailers });\n}\n\n/**\n * Whether the hook may stage: only into the commit's real index (design 2b D8). `git commit\n * <paths>` and `--only`, adr's own `--commit` included, run hooks on a temporary index, and\n * staging there leaves the user's index showing the file as deleted.\n */\nfunction stagingSafe(git: Git, env: NodeJS.ProcessEnv): boolean {\n const file = env.GIT_INDEX_FILE;\n if (file === undefined || file === \"\") return true;\n const at = resolve(git.root ?? git.gitDir, file);\n return at === resolve(git.gitDir, \"index\") || at === resolve(git.gitDir, \"index.lock\");\n}\n\n/** `ADR-0003, ADR-0004` for the decisions a rename following changes. */\nconst displays = (views: readonly { readonly display: string }[]) =>\n views.map((v) => v.display).join(\", \");\n\n/**\n * `adr hooks run pre-commit` (design 2b D8): rename following, then the index, then `verify\n * --staged`, stopping at the first step that fails. `worktree` must be opened with the work-tree\n * reader, because rename following writes through `write()`; `index` with the index reader, for\n * the config as staged, the index render and verify. Only the index step stages `index.md`, and\n * only with `[hooks] index = \"stage\"`; rename following passes `index: \"skip\"`. Neither stages\n * into a temporary index (`stagingSafe`). A step that can't run throws (exit 2).\n */\nexport async function runPreCommitHook(o: {\n readonly worktree: DecisionLog;\n readonly index: DecisionLog;\n readonly env: NodeJS.ProcessEnv;\n}): Promise<{\n readonly exit: 0 | 1;\n readonly findings: readonly Finding[];\n readonly notes: readonly string[];\n readonly failOn: Severity;\n}> {\n const { worktree, index, env } = o;\n const config = index.adr;\n const failOn = config.failOn;\n const notes: string[] = [...index.notes];\n const done = (exit: 0 | 1, findings: readonly Finding[]) => ({\n exit,\n findings,\n notes: [...new Set(notes)],\n failOn,\n });\n const safe = stagingSafe(index.git, env);\n\n // 1. Renames, on the work-tree log.\n if (config.scopeFollowRenames !== \"off\" && (await stagedRenames(worktree.git)).length > 0) {\n const { actor, notes: attribution } = await resolveAttribution(worktree.git, { env });\n if (config.scopeFollowRenames === \"warn\") {\n const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });\n for (const v of dry.affected) {\n notes.push(\n `${v.display}'s globs don't follow the renames in this commit (scope_follow_renames = \"warn\"); run adr scope --follow-renames`,\n );\n }\n } else if (safe) {\n const doc = await followScopeRenames(\n worktree,\n { actor },\n { index: \"skip\", notes: attribution },\n );\n notes.push(...doc.notes);\n if (!doc.ok) return done(1, doc.findings);\n } else {\n const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });\n if (dry.affected.length > 0) {\n notes.push(\n `the renames in this commit change the scope of ${displays(dry.affected)}; git commit <paths> can't take the scoped events. Run adr scope --follow-renames, then commit again including the files it lists, or set [hooks] scope_follow_renames = \"warn\"`,\n );\n return done(1, []);\n }\n }\n }\n\n // 2. The index, on the index log: regenerated only with [hooks] index = \"stage\".\n if (config.index === \"committed\" && config.hookIndex === \"stage\" && safe) {\n const path = indexPath(index.layout);\n const text = await renderDecisionIndex(index.git, {\n layout: index.layout,\n adr: config,\n tree: index.tree,\n history: await index.git.resolveCommit(\"HEAD\"),\n });\n if (text !== null && !holdsText(await index.tree.read(path), text)) {\n await writeIndexFile(index.git, path, text);\n await index.git.add([path]);\n notes.push(`regenerated and staged ${path}`);\n }\n }\n\n // 3. verify --staged, which also reports a stale index.md in check mode.\n const findings = await verifyDecisions(index, { type: \"staged\" });\n return done(exitCode(findings, { failOn }), findings);\n}\n","/**\n * The agent skill `adr init --skill` writes (01, \"Agent skill (SKILL.md)\"): the judgment of when\n * to use adr's MCP tools. `skill.test.ts` keeps it equal to the block in docs/01-adr-v1.md.\n */\nexport const SKILL_MD = `---\nname: adr\ndescription: Use before changing architecture, data stores, integration patterns, dependencies or cross-cutting conventions, and whenever asked to record, propose or look up an architectural decision.\n---\n\n# Architectural decisions (adr)\n\nDecisions in this repo are managed by adr. Decision files do not\nshow their own status, so never judge from the raw files whether a\ndecision applies.\n\n## Before changing architecture\n\n1. Call adr_for_path for the files you will touch, and adr_search\n for the area you are about to change. adr_search returns active\n decisions only; adr_for_path also lists inactive ones, each with\n a warning.\n2. If your change conflicts with an accepted decision, stop and tell\n the user which ADR it conflicts with. Do not work around it silently.\n3. If the user still wants the change, propose a superseding ADR.\n\n## Reading decisions\n\n- Use adr_get or adr://decision/{id}, never docs/adr/decisions/*.md.\n- If a response says SUPERSEDED or DEPRECATED, follow it to the\n effective decision before acting.\n- If it says REJECTED or WITHDRAWN, the decision was never in force;\n do not apply it.\n\n## Proposing decisions\n\n1. Call adr_templates and fill every required section.\n2. Use only facts from the conversation and the code. Mark unknowns\n as open questions instead of inventing them.\n3. List at least two options considered when the template has that section.\n4. Set supersedes when the proposal replaces an existing decision.\n5. Do not accept your own proposal. Tell the user the ADR id and\n that they can review it and run: adr accept <id>\n6. If the user decides against your proposal, withdraw it with\n adr_withdraw and give their reason. Don't withdraw other\n people's proposals; tell the user instead.\n\n## Changing scope\n\n- When you move or rename code covered by a decision, let the\n pre-commit hook update its globs (adr hooks install). For your\n own proposals, you can use adr_scope. Rescoping an accepted\n decision needs mcp_can_decide; otherwise tell the user and\n suggest adr scope <id> ….\n- Before any scope change, read the decision's Scope section. If it\n would no longer read true after the change, do not rescope: tell\n the user the decision itself is changing and propose a\n superseding ADR.\n\n## Never\n\n- Edit an accepted decision body, any file under docs/adr/events/,\n or index.md by hand.\n- Use adr_note to change the meaning of a decision. Notes clarify;\n changed decisions need a superseding ADR.\n\n## Without the MCP server\n\nUse the CLI with --json: adr search, adr for, adr show, adr new,\nadr note. Set ARK_AGENT=<your name> and ARK_ON_BEHALF_OF=<the user's\nemail> so your writes are attributed.\n`;\n","import { rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n ConfigError,\n commitWithRecovery,\n InvalidArgumentError,\n overlayTree,\n readToolConfig,\n renderCommitMessage,\n replaceFile,\n UsageError,\n worktreeReader,\n writeNewFile,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\nimport {\n firstLine,\n headTree,\n INDEX_AFTER,\n indexPath,\n renderDecisionIndex,\n writeIndexCopy,\n} from \"./log-index.js\";\nimport { SKILL_MD } from \"./skill.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 /** With `--skill`, the SKILL.md path (written or kept); else `null`. */\n readonly skill: string | null;\n readonly commit: string | null;\n readonly notes: readonly string[];\n}\n\n/**\n * What the recovery hint says about rerunning `adr init` after `git commit` failed (design 2b D5):\n * init keeps existing files, so it would commit nothing.\n */\nexport const INIT_RERUN =\n \"Running adr init again won't commit them: the files exist now, so it keeps them and commits nothing.\";\n\nconst CONFIG = \"adr.toml\";\nconst DEFAULT_ROOT = adrKind.def.defaultRoot;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\nconst AGENTS = \"AGENTS.md\";\n\n/** The line `adr init --skill` adds to AGENTS.md for tools that don't load skills. */\nexport const agentsPointer = (skill: string): string =>\n `Architecture decisions in this repository are managed by adr: read ${skill} before changing architecture, and follow it.`;\n\n/** `text` with `line` appended after one blank line, ending with a newline. */\nfunction appendLine(text: string, line: string): string {\n if (text === \"\") return `${line}\\n`;\n const ended = text.endsWith(\"\\n\") ? text : `${text}\\n`;\n return `${ended.endsWith(\"\\n\\n\") ? ended : `${ended}\\n`}${line}\\n`;\n}\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 `[log] index = \"committed\"` it also writes `<root>/index.md` unless one exists. With\n * `commit` (default `[policy] auto_commit`) the written files are committed on their own;\n * nothing written means nothing committed. No events are written. With `o.skill` it also writes\n * the agent skill, unless a SKILL.md is there, and adds the pointer line to `AGENTS.md`, unless a\n * line already names the skill; an AGENTS.md with unstaged changes or not tracked is refused\n * with a commit and left unstaged without one.\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 * Also write `<dir>/SKILL.md` (`dir` repo-relative, `\"\"` for the root) and the AGENTS.md\n * pointer (design §9); `version` is adr's, for the note on a SKILL.md that differs.\n */\n readonly skill?: { readonly dir: string; readonly version: string };\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 const commitRequested = o.commit ?? log.adr.autoCommit;\n const logFiles = files.length;\n\n // The skill (design §9.1): SKILL.md is never overwritten; AGENTS.md gets one pointer line.\n // Checked before anything is written.\n const skill =\n o.skill === undefined ? null : o.skill.dir === \"\" ? \"SKILL.md\" : `${o.skill.dir}/SKILL.md`;\n let agents: {\n readonly bytes: Uint8Array;\n readonly expected: Uint8Array | null;\n readonly stage: boolean;\n } | null = null;\n if (skill !== null) {\n const current = await log.tree.read(skill);\n if (current === null) {\n files.push([skill, SKILL_MD]);\n } else {\n kept.push(skill);\n if (decoder.decode(current) !== SKILL_MD) {\n notes.push(\n `${skill} differs from adr ${o.skill?.version ?? \"\"}'s skill; delete it and run adr init --skill again to replace it`,\n );\n }\n }\n const old = await log.tree.read(AGENTS);\n const text = old === null ? null : decoder.decode(old);\n if ((text ?? \"\").split(\"\\n\").some((l) => l.includes(skill))) {\n kept.push(AGENTS);\n } else {\n let stage = true;\n if (old !== null) {\n const unstaged = (await log.git.unstagedPaths([AGENTS])).length > 0;\n const untracked = (await log.git.untrackedPaths([AGENTS])).length > 0;\n if (commitRequested && unstaged) {\n throw new UsageError(\n `${AGENTS} has unstaged changes; stage or discard them, or run without --commit`,\n );\n }\n if (commitRequested && untracked) {\n throw new UsageError(`${AGENTS} is not tracked; git add it, or run without --commit`);\n }\n if (unstaged || untracked) {\n stage = false;\n notes.push(\n untracked\n ? `${AGENTS} is not tracked, so the pointer is added but not staged; review it and git add it`\n : `${AGENTS} had unstaged changes, so the pointer is added but not staged; review it and git add it`,\n );\n }\n }\n agents = {\n bytes: encoder.encode(appendLine(text ?? \"\", agentsPointer(skill))),\n expected: old,\n stage,\n };\n }\n }\n const at = indexPath(log.layout);\n let indexed = false;\n if (log.adr.index === \"committed\") {\n // Rendered before anything is written, from the tree the commit (or the work tree) will hold.\n if ((await log.tree.read(at)) !== null) {\n kept.push(at);\n } else {\n const head = await log.git.resolveCommit(\"HEAD\");\n const added = Object.fromEntries(files.map(([p, t]) => [p, encoder.encode(t)]));\n const base = commitRequested ? await headTree(log.git, head) : log.tree;\n const text = await renderDecisionIndex(log.git, {\n layout: log.layout,\n adr: log.adr,\n tree: overlayTree(base, added),\n history: head,\n });\n if (text === null) {\n notes.push(\n `${at} not updated: numbers need history in this shallow clone; run git fetch --unshallow, then adr index`,\n );\n } else {\n files.push([at, text]);\n indexed = true;\n }\n }\n }\n\n const commit = (files.length > 0 || agents !== null) && commitRequested;\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 let replaced = false;\n try {\n for (const [path, text] of files) {\n await writeNewFile(log.git, path, encoder.encode(text));\n written.push(path);\n }\n if (agents !== null) {\n if (agents.expected === null) await writeNewFile(log.git, AGENTS, agents.bytes);\n else await replaceFile(log.git, AGENTS, agents.bytes, { expected: agents.expected });\n replaced = agents.expected !== null;\n written.push(AGENTS);\n }\n } catch (err) {\n const top = log.git.root ?? \"\";\n const restore = replaced ? (agents?.expected ?? null) : null;\n for (const path of written) {\n if (path === AGENTS && restore !== null && agents !== null) {\n await replaceFile(log.git, AGENTS, restore, { expected: agents.bytes }).catch(() => {});\n } else {\n await rm(join(top, path), { force: true });\n }\n }\n throw err;\n }\n const staged = written.filter((p) => p !== AGENTS || agents?.stage === true);\n if (staged.length > 0) await log.git.add(staged);\n let sha: string | null = null;\n if (commit) {\n const message =\n o.message ??\n renderCommitMessage(log.adr.commitSubject, {\n title: logFiles > 0 ? \"the decision log\" : \"the adr agent skill\",\n vars: { action: \"set up\", id: \"\", display: \"\", command: \"init\" },\n }).message;\n sha = await commitWithRecovery(log.git, {\n message,\n only: staged,\n rerun: INIT_RERUN,\n after: indexed ? INDEX_AFTER(root) : null,\n });\n if (indexed) {\n // The commit's index leaves out uncommitted log changes; the work tree and the index get\n // them back (design 2b §4.5 step 5).\n try {\n const again = await renderDecisionIndex(log.git, {\n layout: log.layout,\n adr: log.adr,\n tree: worktreeReader(log.git),\n history: sha,\n });\n if (again !== null) {\n const r = await writeIndexCopy(log.git, at, again);\n if (r.stage) await log.git.add([at]);\n }\n } catch (err) {\n notes.push(`${at} may be stale: ${firstLine(err)}; run adr index`);\n }\n }\n }\n return { format: \"adr-init/v1\", root, config, written, kept, skill, commit: sha, notes };\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,iBAAiB;;AAGvB,eAAe,UACb,KACA,KAC4C;CAC5C,MAAM,OAAO,IAAI,QAAQ;CACzB,IAAI,SAAS,KAAA,GAAW,uBAAO,IAAI,IAAI;CACvC,OAAO,WAAW,SAAS,MAAqC,EAC9D,WAAW,MAAM,gBAAgB,GAAG,EACtC,CAAC,CAAC,CAAC;AACL;;;;;AAMA,SAAS,mBAAmB,KAAyB;CACnD,OAAO;EACL,IAAI;EACJ,MAAM,IAAI,KAAK;GACb,MAAM,UAAU,MAAM,gBAAgB,KAAK;IACzC,SAAS,IAAI,IAAI;IACjB,SAAS,IAAI,IAAI;IACjB,UAAU,CAAC,cAAc,YAAY;GACvC,CAAC;GACD,IAAI,QAAQ,WAAW,GAAG,OAAO,CAAC;GAClC,MAAM,QAAQ,MAAM,UAAU,KAAK,GAAG;GACtC,MAAM,WAAW,OAAe,MAAM,IAAI,EAAE,CAAC,EAAE,WAAW;GAC1D,MAAM,WAAW,MAA8B;IAC7C,MAAM,OAAO,GAAG,EAAE,KAAK,kBAAkB,QAAQ,EAAE,OAAO;IAC1D,IAAI,EAAE,WAAW,cACf,OAAO,GAAG,KAAK;IAEjB,MAAM,OAAO,MAAM,IAAI,EAAE,OAAO,CAAC,EAAE,iBAAiB;IACpD,OAAO,SAAS,OACZ,GAAG,KAAK,iEACR,GAAG,KAAK,2BAA2B,QAAQ,IAAI,EAAE,6BAA6B,QAAQ,IAAI;GAChG;GACA,OAAO,QAAQ,KAAK,MAClB,QAAQ;IAC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{"version":3,"file":"kind-DjvA3dyA.js","names":[],"sources":["../src/kind/project.ts","../src/kind/reduce.ts","../src/kind/rules.ts","../src/kind/schemas.ts","../src/kind.ts"],"sourcesContent":["import type { FoldedSubject, ProjectContext } from \"@nikovirtala/ledger\";\nimport type { DecisionState } from \"./reduce.js\";\nimport type { DecisionEvents, DecisionStatus } from \"./schemas.js\";\n\n/** One decision as the CLI, the library and MCP show it (01:173–192, plus the added fields). */\nexport interface DecisionView {\n readonly id: string;\n readonly number: number | null;\n /** `ADR-0007`, or the id when unnumbered. */\n readonly display: string;\n readonly title: string;\n readonly status: DecisionStatus;\n readonly superseded_by: string | null;\n /** Ids whose applied `superseded.by` is this id, sorted. */\n readonly supersedes: readonly string[];\n /** The proposal's intent (01:164). */\n readonly declared_supersedes: readonly string[];\n /** Head of the `superseded_by` chain; `null` only on a cycle. */\n readonly effective: string | null;\n /** `[id, …, effective]`, following `superseded_by` forward. */\n readonly chain: readonly string[];\n readonly template: { readonly name: string; readonly version: number };\n readonly body_path: string | null;\n /** Recorded at acceptance. */\n readonly body_sha256: string | null;\n /** `null` until accepted; whether the current body hash equals the recorded one. */\n readonly body_intact: boolean | null;\n readonly links: readonly { readonly to: string; readonly rel: string }[];\n readonly applies_to: readonly string[];\n readonly notes: number;\n readonly proposed_at: string;\n readonly decided_at: string | null;\n readonly status_at: string;\n /** `proposed 2026-03-12`: state-changing events, in fold order. */\n readonly history: readonly string[];\n}\n\ntype Subject = FoldedSubject<DecisionStatus, DecisionState, DecisionEvents>;\ntype Context = ProjectContext<DecisionStatus, DecisionState, DecisionEvents>;\n\nconst NUMBER = /^(?:adr-?)?0*([1-9][0-9]{0,8})$/i;\n\n/** `ADR-0007`: at least 4 digits, growing past 9999. */\nexport function formatDecisionNumber(n: number): string {\n return `ADR-${String(n).padStart(4, \"0\")}`;\n}\n\n/** `7`, `0007`, `ADR-7`, `adr-0007` → 7; `null` for anything else. */\nexport function parseDecisionNumber(s: string): number | null {\n const m = NUMBER.exec(s.trim());\n return m === null ? null : Number(m[1]);\n}\n\n/**\n * Follows `superseded_by` from `id`. A visited set stops on a cycle (`effective: null`); a\n * reference to a subject that isn't folded ends the chain there.\n */\nfunction chainOf(id: string, ctx: Context): { chain: string[]; effective: string | null } {\n const chain = [id];\n let cur = id;\n for (;;) {\n const next = ctx.log.subjects.get(cur)?.state?.supersededBy ?? null;\n if (next === null) return { chain, effective: cur };\n if (chain.includes(next)) return { chain, effective: null };\n chain.push(next);\n cur = next;\n }\n}\n\n/** Pure: the view of one folded decision. */\nexport function project(subject: Subject, ctx: Context): DecisionView {\n const { id } = subject;\n const s = subject.state;\n if (s === null || subject.status === null) {\n throw new Error(`decision ${id} is not folded`);\n }\n const supersedes = [...ctx.log.subjects.values()]\n .filter((o) => o.id !== id && o.state?.supersededBy === id)\n .map((o) => o.id)\n .sort();\n const { chain, effective } = chainOf(id, ctx);\n const current = ctx.bodySha256(id);\n return {\n id,\n number: ctx.number(id),\n display: ctx.display(id),\n title: s.title,\n status: subject.status,\n superseded_by: s.supersededBy,\n supersedes,\n declared_supersedes: s.declaredSupersedes,\n effective,\n chain,\n template: s.template,\n body_path: subject.loaded.body?.path ?? subject.loaded.bodyPaths[0] ?? null,\n body_sha256: s.bodySha256,\n body_intact: s.bodySha256 === null ? null : current === s.bodySha256,\n links: s.links,\n applies_to: s.appliesTo,\n notes: s.notes,\n proposed_at: s.proposedAt,\n decided_at: s.decidedAt,\n status_at: s.statusAt,\n history: s.history.map((h) => `${h.type} ${h.at.slice(0, 10)}`),\n };\n}\n","import type { Actor, FoldEvent } from \"@nikovirtala/ledger\";\nimport type { DecisionEvents } from \"./schemas.js\";\n\n/** A decision's own state, maintained by `reduce` over its applied events. */\nexport interface DecisionState {\n readonly title: string;\n readonly template: { readonly name: string; readonly version: number };\n readonly declaredSupersedes: readonly string[];\n /** From the applied `accepted` event. */\n readonly bodySha256: string | null;\n readonly acceptedBy: Actor | null;\n readonly supersededBy: string | null;\n /** In fold order, duplicates kept once. */\n readonly links: readonly { readonly to: string; readonly rel: string }[];\n /** The latest `scoped` set (latest wins). */\n readonly appliesTo: readonly string[];\n readonly notes: number;\n /** State-changing events only, in fold order. */\n readonly history: readonly { readonly type: string; readonly at: string }[];\n readonly proposedAt: string;\n /** `at` of `accepted`, `rejected` or `withdrawn`. */\n readonly decidedAt: string | null;\n /** `at` of the latest state-changing event. */\n readonly statusAt: string;\n}\n\nconst EMPTY: DecisionState = {\n title: \"\",\n template: { name: \"\", version: 0 },\n declaredSupersedes: [],\n bodySha256: null,\n acceptedBy: null,\n supersededBy: null,\n links: [],\n appliesTo: [],\n notes: 0,\n history: [],\n proposedAt: \"\",\n decidedAt: null,\n statusAt: \"\",\n};\n\n/** Pure: the state after one applied event. The fold only passes events the machine allows. */\nexport function reduce(state: DecisionState | null, e: FoldEvent<DecisionEvents>): DecisionState {\n const s = state ?? EMPTY;\n const changed = (extra: Partial<DecisionState> = {}): DecisionState => ({\n ...s,\n ...extra,\n history: [...s.history, { type: e.type, at: e.at }],\n statusAt: e.at,\n });\n switch (e.type) {\n case \"proposed\":\n return changed({\n title: e.data.title,\n template: { name: e.data.template, version: e.data.template_version },\n declaredSupersedes: [...(e.data.supersedes ?? [])],\n proposedAt: e.at,\n });\n case \"accepted\":\n return changed({ bodySha256: e.data.body_sha256, acceptedBy: e.actor, decidedAt: e.at });\n case \"rejected\":\n case \"withdrawn\":\n return changed({ decidedAt: e.at });\n case \"deprecated\":\n return changed();\n case \"superseded\":\n return changed({ supersededBy: e.data.by });\n case \"noted\":\n return { ...s, notes: s.notes + 1 };\n case \"linked\": {\n const { to, rel } = e.data;\n const known = s.links.some((l) => l.to === to && l.rel === rel);\n return known ? s : { ...s, links: [...s.links, { to, rel }] };\n }\n case \"scoped\":\n return { ...s, appliesTo: [...e.data.set] };\n }\n}\n","import type { FoldedLog, FoldedSubject, KindFinding } from \"@nikovirtala/ledger\";\nimport type { DecisionState } from \"./reduce.js\";\nimport type { DecisionEvents, DecisionStatus } from \"./schemas.js\";\n\n/** Options of the decision kind's `invariants` and `relate`. */\nexport interface AdrOptions {\n /** Default `true`: an agent may propose, but only a human may accept (01:98). */\n readonly acceptRequiresHuman: boolean;\n}\n\ntype Subject = FoldedSubject<DecisionStatus, DecisionState, DecisionEvents>;\ntype Log = FoldedLog<DecisionStatus, DecisionState, DecisionEvents>;\n\n/** `decision/agent-accepted`: an applied `accepted` event written by an agent under the human policy. */\nexport function invariants(subject: Subject, options: AdrOptions): readonly KindFinding[] {\n if (!options.acceptRequiresHuman) return [];\n return subject.applied.flatMap(({ event }) =>\n event.type === \"accepted\" && event.actor.kind === \"agent\"\n ? [\n {\n severity: \"error\" as const,\n rule: \"decision/agent-accepted\",\n message: `accepted by agent ${event.actor.name}; accept_requires_human needs a human`,\n subject: subject.id,\n event: event.id,\n },\n ]\n : [],\n );\n}\n\n/**\n * Qualified ids (`<source>:<id>`) name decisions in other logs. Phase 1 checks local references\n * only and skips qualified ones, which only hand-written events can hold; CI checks them at the\n * pinned ref in phase 2 (design §E).\n */\nconst isQualified = (ref: string) => ref.includes(\":\");\n\n/**\n * Cross-subject rules: `decision/reference-missing` for a local `supersedes`, `superseded.by` or\n * `linked.to` naming no subject in the log; `decision/superseded-by-unaccepted` when the target of\n * an applied `superseded.by` has no applied `accepted` event in this tree; and\n * `decision/supersession-cycle`, once per cycle on its smallest id.\n */\nexport function relate(log: Log): readonly KindFinding[] {\n const out: KindFinding[] = [];\n const isAccepted = (id: string) =>\n log.subjects.get(id)?.applied.some((a) => a.event.type === \"accepted\") ?? false;\n const missing = (subject: string, event: string, ref: string, what: string) => {\n if (isQualified(ref) || log.subjects.has(ref)) return false;\n out.push({\n severity: \"error\",\n rule: \"decision/reference-missing\",\n message: `${what} ${ref}, which is not in the log`,\n subject,\n event,\n related: [ref],\n });\n return true;\n };\n\n for (const [id, s] of log.subjects) {\n for (const { event } of s.applied) {\n switch (event.type) {\n case \"proposed\":\n for (const ref of event.data.supersedes ?? []) missing(id, event.id, ref, \"supersedes\");\n break;\n case \"superseded\": {\n const by = event.data.by;\n if (missing(id, event.id, by, \"superseded by\") || isQualified(by)) break;\n if (!isAccepted(by)) {\n out.push({\n severity: \"error\",\n rule: \"decision/superseded-by-unaccepted\",\n message: `superseded by ${by}, which is not accepted`,\n subject: id,\n event: event.id,\n related: [by],\n });\n }\n break;\n }\n case \"linked\":\n missing(id, event.id, event.data.to, \"links to\");\n break;\n default:\n break;\n }\n }\n }\n\n const next = (id: string) => log.subjects.get(id)?.state?.supersededBy ?? null;\n const reported = new Set<string>();\n for (const start of log.subjects.keys()) {\n const path: string[] = [];\n let cur: string | null = start;\n while (cur !== null && !path.includes(cur)) {\n path.push(cur);\n cur = next(cur);\n }\n if (cur === null) continue;\n const cycle = path.slice(path.indexOf(cur));\n const smallest = [...cycle].sort()[0];\n if (smallest === undefined || reported.has(smallest)) continue;\n reported.add(smallest);\n const from = cycle.indexOf(smallest);\n const ordered = [...cycle.slice(from), ...cycle.slice(0, from), smallest];\n const event = log.subjects.get(smallest)?.applied.find((a) => a.event.type === \"superseded\")\n ?.event.id;\n out.push({\n severity: \"error\",\n rule: \"decision/supersession-cycle\",\n message: `supersession cycle: ${ordered.join(\" → \")}`,\n subject: smallest,\n ...(event === undefined ? {} : { event }),\n related: [...cycle].sort(),\n });\n }\n return out;\n}\n","import { eventType, setEventType } from \"@nikovirtala/ledger\";\n\n/** A decision's computed status. */\nexport type DecisionStatus =\n | \"proposed\"\n | \"accepted\"\n | \"rejected\"\n | \"withdrawn\"\n | \"deprecated\"\n | \"superseded\";\n\n/** Every status, in lifecycle order. */\nexport const DECISION_STATUSES: readonly DecisionStatus[] = Object.freeze([\n \"proposed\",\n \"accepted\",\n \"rejected\",\n \"withdrawn\",\n \"deprecated\",\n \"superseded\",\n]);\n\n/** A local subject id, or a qualified `<source>:<id>` one. */\nexport const REF = \"^(?:[a-z][a-z0-9-]*:)?[0-9a-hjkmnp-tv-z]{8}$\";\n\nconst ref = { type: \"string\", pattern: REF } as const;\nconst SINGLE_LINE = \"^[^\\\\r\\\\n]*$\";\n\n/** How a `linked` decision relates to its target. */\nexport type LinkRel = \"relates-to\" | \"refines\" | \"depends-on\";\n\n/** The decision kind's event types (01:128–136): data schemas, allowed states and targets. */\nexport const decisionEvents = {\n proposed: eventType<{\n title: string;\n template: string;\n template_version: number;\n supersedes?: string[];\n }>()({\n data: {\n type: \"object\",\n required: [\"title\", \"template\", \"template_version\"],\n properties: {\n title: { type: \"string\", minLength: 1, maxLength: 200, pattern: SINGLE_LINE },\n template: { type: \"string\", pattern: \"^[a-z][a-z0-9-]*$\" },\n template_version: { type: \"integer\", minimum: 1 },\n supersedes: { type: \"array\", items: ref, uniqueItems: true, maxItems: 20 },\n },\n },\n allowedIn: [],\n to: \"proposed\",\n }),\n accepted: eventType<{ body_sha256: string }>()({\n data: {\n type: \"object\",\n required: [\"body_sha256\"],\n properties: { body_sha256: { type: \"string\", pattern: \"^[0-9a-f]{64}$\" } },\n },\n allowedIn: [\"proposed\"],\n to: \"accepted\",\n }),\n rejected: eventType()({\n data: { type: \"object\" },\n allowedIn: [\"proposed\"],\n to: \"rejected\",\n reason: \"required\",\n }),\n withdrawn: eventType()({ data: { type: \"object\" }, allowedIn: [\"proposed\"], to: \"withdrawn\" }),\n deprecated: eventType()({\n data: { type: \"object\" },\n allowedIn: [\"accepted\"],\n to: \"deprecated\",\n reason: \"required\",\n }),\n superseded: eventType<{ by: string }>()({\n data: { type: \"object\", required: [\"by\"], properties: { by: ref } },\n allowedIn: [\"accepted\", \"deprecated\"],\n to: \"superseded\",\n }),\n noted: eventType<{ text: string }>()({\n data: {\n type: \"object\",\n required: [\"text\"],\n properties: { text: { type: \"string\", minLength: 1 } },\n },\n allowedIn: \"any\",\n to: null,\n }),\n linked: eventType<{ to: string; rel: LinkRel }>()({\n data: {\n type: \"object\",\n required: [\"to\", \"rel\"],\n properties: { to: ref, rel: { enum: [\"relates-to\", \"refines\", \"depends-on\"] } },\n },\n allowedIn: \"any\",\n to: null,\n }),\n // ledger's whole-set event (G11): the same schema as before, so decision/v1 is unchanged.\n scoped: setEventType({\n item: { type: \"string\", minLength: 1, maxLength: 500 },\n maxItems: 200,\n allowedIn: [\"proposed\", \"accepted\", \"deprecated\"],\n }),\n} as const;\n\nexport type DecisionEvents = typeof decisionEvents;\n","import { defineKind, type Kind } from \"@nikovirtala/ledger\";\nimport {\n type DecisionView,\n formatDecisionNumber,\n parseDecisionNumber,\n project,\n} from \"./kind/project.js\";\nimport { type DecisionState, reduce } from \"./kind/reduce.js\";\nimport { type AdrOptions, invariants, relate } from \"./kind/rules.js\";\nimport { type DecisionEvents, type DecisionStatus, decisionEvents } from \"./kind/schemas.js\";\n\nexport type { DecisionView } from \"./kind/project.js\";\nexport { formatDecisionNumber, parseDecisionNumber } from \"./kind/project.js\";\nexport type { DecisionState } from \"./kind/reduce.js\";\nexport type { AdrOptions } from \"./kind/rules.js\";\nexport {\n DECISION_STATUSES,\n type DecisionEvents,\n type DecisionStatus,\n type LinkRel,\n REF,\n} from \"./kind/schemas.js\";\n\n/**\n * The decision kind (01:128–194), as imported by other tools through `@nikovirtala/adr/kind`.\n *\n * Decisions are proposed, then accepted (which freezes the body and earns a number on main),\n * rejected or withdrawn; accepted ones can be deprecated or superseded. This module imports only\n * `@nikovirtala/ledger` and `./kind/*`, so importing the kind never loads CLI or MCP code.\n */\nexport const adrKind: Kind<\n DecisionStatus,\n DecisionEvents,\n DecisionState,\n DecisionView,\n AdrOptions\n> = defineKind<DecisionStatus, DecisionEvents, DecisionState, DecisionView, AdrOptions>({\n name: \"decision\",\n schema: \"decision/v1\",\n states: [\"proposed\", \"accepted\", \"rejected\", \"withdrawn\", \"deprecated\", \"superseded\"],\n events: decisionEvents,\n initial: \"proposed\",\n reduce,\n invariants,\n relate,\n project,\n body: { freezeOn: \"accepted\" },\n layout: { bodies: \"decisions\", events: \"events\" },\n defaultRoot: \"docs/adr\",\n sourceName: \"adr\",\n numbering: { on: \"accepted\", format: formatDecisionNumber, parse: parseDecisionNumber },\n templates: {\n dir: \"templates\",\n nameField: \"template\",\n versionField: \"template_version\",\n lintIn: [\"proposed\"],\n lintOn: \"accepted\",\n requireSections: [\"scope\"],\n },\n // A deprecated decision's globs no longer have to match code (design 2b §4.8).\n scope: { event: \"scoped\", activeIn: [\"proposed\", \"accepted\"] },\n options: Object.freeze({ acceptRequiresHuman: true }),\n});\n"],"mappings":";;AAwCA,MAAM,SAAS;;AAGf,SAAgB,qBAAqB,GAAmB;CACtD,OAAO,OAAO,OAAO,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;AACzC;;AAGA,SAAgB,oBAAoB,GAA0B;CAC5D,MAAM,IAAI,OAAO,KAAK,EAAE,KAAK,CAAC;CAC9B,OAAO,MAAM,OAAO,OAAO,OAAO,EAAE,EAAE;AACxC;;;;;AAMA,SAAS,QAAQ,IAAY,KAA6D;CACxF,MAAM,QAAQ,CAAC,EAAE;CACjB,IAAI,MAAM;CACV,SAAS;EACP,MAAM,OAAO,IAAI,IAAI,SAAS,IAAI,GAAG,CAAC,EAAE,OAAO,gBAAgB;EAC/D,IAAI,SAAS,MAAM,OAAO;GAAE;GAAO,WAAW;EAAI;EAClD,IAAI,MAAM,SAAS,IAAI,GAAG,OAAO;GAAE;GAAO,WAAW;EAAK;EAC1D,MAAM,KAAK,IAAI;EACf,MAAM;CACR;AACF;;AAGA,SAAgB,QAAQ,SAAkB,KAA4B;CACpE,MAAM,EAAE,OAAO;CACf,MAAM,IAAI,QAAQ;CAClB,IAAI,MAAM,QAAQ,QAAQ,WAAW,MACnC,MAAM,IAAI,MAAM,YAAY,GAAG,eAAe;CAEhD,MAAM,aAAa,CAAC,GAAG,IAAI,IAAI,SAAS,OAAO,CAAC,CAAC,CAC9C,QAAQ,MAAM,EAAE,OAAO,MAAM,EAAE,OAAO,iBAAiB,EAAE,CAAC,CAC1D,KAAK,MAAM,EAAE,EAAE,CAAC,CAChB,KAAK;CACR,MAAM,EAAE,OAAO,cAAc,QAAQ,IAAI,GAAG;CA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