@nikovirtala/adr 0.5.2 → 0.5.3

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/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { F as resolveDecision, M as openDecisionLog, N as readDecisions, O as runDecisionIndex, _ as withdrawDecision, b as readDecisionSources, c as followScopeRenames, d as proposeDecision, f as rejectDecision, h as supersedeDecision, i as showDecision, j as numberingNote, k as changedSince, l as linkDecision, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions, y as decisionSourceConfigs } from "./search-DDDuzVfg.js";
2
+ import { F as resolveDecision, M as openDecisionLog, N as readDecisions, O as runDecisionIndex, _ as withdrawDecision, b as readDecisionSources, c as followScopeRenames, d as proposeDecision, f as rejectDecision, h as supersedeDecision, i as showDecision, j as numberingNote, k as changedSince, l as linkDecision, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions, y as decisionSourceConfigs } from "./search-DLUlAP11.js";
3
3
  import { n as DECISION_STATUSES, t as adrKind } from "./kind-C3DiBuUp.js";
4
- import { a as installDecisionHooks, c as uninstallDecisionHooks, l as adrChecks, o as printDecisionHooks, r as addHookTrailers, s as runPreCommitHook, t as initDecisionLog, u as decisionVerifyInputs } from "./init-Bw0PZLnR.js";
4
+ import { a as installDecisionHooks, c as uninstallDecisionHooks, l as adrChecks, o as printDecisionHooks, r as addHookTrailers, s as runPreCommitHook, t as initDecisionLog, u as decisionVerifyInputs } from "./init-Cjx-E8x1.js";
5
5
  import { createRequire } from "node:module";
6
6
  import { UsageError, exitCode, findingsReport, formatText, renderStateHeader, resolveAttribution, stagedRenames, templateHistoryRef } from "@nikovirtala/ledger";
7
7
  import { realpath } from "node:fs/promises";
@@ -813,7 +813,7 @@ function mcpCommand(version) {
813
813
  async run({ io, flags }) {
814
814
  if (flags.json) throw new UsageError("adr mcp speaks JSON-RPC on stdout; it takes no --json");
815
815
  if (io.interactive) io.stderr.write("adr: adr mcp speaks MCP on stdin and stdout; start it from an MCP client\n");
816
- const { serveAdrMcp } = await import("./server-CRmWjWqD.js");
816
+ const { serveAdrMcp } = await import("./server-WidFQzlx.js");
817
817
  await serveAdrMcp({
818
818
  cwd: io.cwd,
819
819
  root: flags.root,
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { D as renderDecisionIndex, F as resolveDecision, I as sourcesNote, L as DEFAULT_ADR_CONFIG, M as openDecisionLog, N as readDecisions, P as readDecisionsFrom, R as parseAdrConfig, T as indexDecisionLog, _ as withdrawDecision, a as stateHeader, b as readDecisionSources, c as followScopeRenames, d as proposeDecision, f as rejectDecision, g as updateDraft, h as supersedeDecision, i as showDecision, k as changedSince, l as linkDecision, m as scopeToCopy, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions, y as decisionSourceConfigs } from "./search-DDDuzVfg.js";
1
+ import { D as renderDecisionIndex, F as resolveDecision, I as sourcesNote, L as DEFAULT_ADR_CONFIG, M as openDecisionLog, N as readDecisions, P as readDecisionsFrom, R as parseAdrConfig, T as indexDecisionLog, _ as withdrawDecision, a as stateHeader, b as readDecisionSources, c as followScopeRenames, d as proposeDecision, f as rejectDecision, g as updateDraft, h as supersedeDecision, i as showDecision, k as changedSince, l as linkDecision, m as scopeToCopy, n as decisionsFor, o as acceptDecision, p as scopeDecision, r as listDecisions, s as deprecateDecision, t as searchDecisions, u as noteDecision, x as readSourceDecisions, y as decisionSourceConfigs } from "./search-DLUlAP11.js";
2
2
  import { a as parseDecisionNumber, i as formatDecisionNumber, n as DECISION_STATUSES, r as REF, t as adrKind } from "./kind-C3DiBuUp.js";
3
- import { a as installDecisionHooks, c as uninstallDecisionHooks, d as verifyDecisions, i as decisionHookCommands, l as adrChecks, n as SKILL_MD, o as printDecisionHooks, r as addHookTrailers, s as runPreCommitHook, t as initDecisionLog, u as decisionVerifyInputs } from "./init-Bw0PZLnR.js";
4
- import { t as listTemplates } from "./list-CnMSw8eA.js";
3
+ import { a as installDecisionHooks, c as uninstallDecisionHooks, d as verifyDecisions, i as decisionHookCommands, l as adrChecks, n as SKILL_MD, o as printDecisionHooks, r as addHookTrailers, s as runPreCommitHook, t as initDecisionLog, u as decisionVerifyInputs } from "./init-Cjx-E8x1.js";
4
+ import { t as listTemplates } from "./list-qsuw1oAL.js";
5
5
  export { DECISION_STATUSES, DEFAULT_ADR_CONFIG, REF, SKILL_MD, acceptDecision, addHookTrailers, adrChecks, adrKind, changedSince, decisionHookCommands, decisionSourceConfigs, decisionVerifyInputs, decisionsFor, deprecateDecision, followScopeRenames, formatDecisionNumber, indexDecisionLog, initDecisionLog, installDecisionHooks, linkDecision, listDecisions, listTemplates, noteDecision, openDecisionLog, parseAdrConfig, parseDecisionNumber, printDecisionHooks, proposeDecision, readDecisionSources, readDecisions, readDecisionsFrom, readSourceDecisions, rejectDecision, renderDecisionIndex, resolveDecision, runPreCommitHook, scopeDecision, scopeToCopy, searchDecisions, showDecision, sourcesNote, stateHeader, supersedeDecision, uninstallDecisionHooks, updateDraft, verifyDecisions, withdrawDecision };
@@ -1,6 +1,6 @@
1
- import { A as numberDecisions, C as INDEX_AFTER, D as renderDecisionIndex, E as indexPath, b as readDecisionSources, c as followScopeRenames, v as BUILTIN_TEMPLATES, w as decisionIndexCheck } from "./search-DDDuzVfg.js";
1
+ import { A as numberDecisions, C as INDEX_AFTER, D as renderDecisionIndex, E as indexPath, b as readDecisionSources, c as followScopeRenames, v as BUILTIN_TEMPLATES, w as decisionIndexCheck } from "./search-DLUlAP11.js";
2
2
  import { t as adrKind } from "./kind-C3DiBuUp.js";
3
- import { ConfigError, InvalidArgumentError, UsageError, anchorCheck, assertNoHookConflicts, classifyPath, commitWithRecovery, eventTrailers, exitCode, finding, firstLine, foldChecks, gitTemplates, governedChanges, headTree, holdsText, hookSnippet, installHooks, narrowedScopes, overlayTree, parseEventFileName, projectLog, readToolConfig, renderCommitMessage, replaceFile, resolveAttribution, scopeGlobCheck, sourceFindings, stagedRenames, templateHistoryRef, uninstallHooks, verifyLog, worktreeReader, writeIndexCopy, writeIndexFile, writeNewFile } from "@nikovirtala/ledger";
3
+ import { ConfigError, InvalidArgumentError, UsageError, anchorCheck, assertNoHookConflicts, classifyPath, commitWithRecovery, eventTrailers, exitCode, finding, firstLine, foldChecks, gitTemplates, governedChanges, headTree, holdsText, hookSnippet, installHooks, narrowedScopes, overlayTree, parseEventFileName, projectLog, readToolConfig, renderCommitMessage, replaceFile, resolveAttribution, scopeGlobCheck, sourceFindings, stagedRenames, templateHistoryRef, uninstallHooks, verifyLog, withGitOperation, worktreeReader, writeIndexCopy, writeIndexFile, writeNewFile } from "@nikovirtala/ledger";
4
4
  import { access, constants, rm } from "node:fs/promises";
5
5
  import { join, relative, resolve, sep } from "node:path";
6
6
  // src/verify.ts
@@ -149,13 +149,15 @@ function decisionVerifyInputs(log) {
149
149
  * sources from the local cache only.
150
150
  */
151
151
  async function verifyDecisions(log, mode) {
152
- return verifyLog({
153
- git: log.git,
154
- kind: adrKind,
155
- layout: log.layout,
156
- mode,
157
- checks: adrChecks(log, await templateHistoryRef(log.git, mode), await readDecisionSources(log, { fetch: "cache" })),
158
- widenOn: decisionVerifyInputs(log)
152
+ return withGitOperation(async () => {
153
+ return verifyLog({
154
+ git: log.git,
155
+ kind: adrKind,
156
+ layout: log.layout,
157
+ mode,
158
+ checks: adrChecks(log, await templateHistoryRef(log.git, mode), await readDecisionSources(log, { fetch: "cache" })),
159
+ widenOn: decisionVerifyInputs(log)
160
+ });
159
161
  });
160
162
  }
161
163
  // src/hooks.ts
@@ -320,53 +322,55 @@ const displays = (views) => views.map((v) => v.display).join(", ");
320
322
  * into a temporary index (`stagingSafe`). A step that can't run throws (exit 2).
321
323
  */
322
324
  async function runPreCommitHook(o) {
323
- const { worktree, index, env } = o;
324
- const config = index.adr;
325
- const failOn = config.failOn;
326
- const notes = [...index.notes];
327
- const done = (exit, findings) => ({
328
- exit,
329
- findings,
330
- notes: [...new Set(notes)],
331
- failOn
332
- });
333
- const safe = stagingSafe(index.git, env);
334
- if (config.scopeFollowRenames !== "off" && (await stagedRenames(worktree.git)).length > 0) {
335
- const { actor, notes: attribution } = await resolveAttribution(worktree.git, { env });
336
- if (config.scopeFollowRenames === "warn") {
337
- const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });
338
- for (const v of dry.affected) notes.push(`${v.display}'s globs don't follow the renames in this commit (scope_follow_renames = "warn"); run adr scope --follow-renames`);
339
- } else if (safe) {
340
- const doc = await followScopeRenames(worktree, { actor }, {
341
- index: "skip",
342
- notes: attribution
343
- });
344
- notes.push(...doc.notes);
345
- if (!doc.ok) return done(1, doc.findings);
346
- } else {
347
- const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });
348
- if (dry.affected.length > 0) {
349
- notes.push(`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"`);
350
- return done(1, []);
325
+ return withGitOperation(async () => {
326
+ const { worktree, index, env } = o;
327
+ const config = index.adr;
328
+ const failOn = config.failOn;
329
+ const notes = [...index.notes];
330
+ const done = (exit, findings) => ({
331
+ exit,
332
+ findings,
333
+ notes: [...new Set(notes)],
334
+ failOn
335
+ });
336
+ const safe = stagingSafe(index.git, env);
337
+ if (config.scopeFollowRenames !== "off" && (await stagedRenames(worktree.git)).length > 0) {
338
+ const { actor, notes: attribution } = await resolveAttribution(worktree.git, { env });
339
+ if (config.scopeFollowRenames === "warn") {
340
+ const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });
341
+ for (const v of dry.affected) notes.push(`${v.display}'s globs don't follow the renames in this commit (scope_follow_renames = "warn"); run adr scope --follow-renames`);
342
+ } else if (safe) {
343
+ const doc = await followScopeRenames(worktree, { actor }, {
344
+ index: "skip",
345
+ notes: attribution
346
+ });
347
+ notes.push(...doc.notes);
348
+ if (!doc.ok) return done(1, doc.findings);
349
+ } else {
350
+ const dry = await followScopeRenames(worktree, { actor }, { dryRun: true });
351
+ if (dry.affected.length > 0) {
352
+ notes.push(`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"`);
353
+ return done(1, []);
354
+ }
351
355
  }
352
356
  }
353
- }
354
- if (config.index === "committed" && config.hookIndex === "stage" && safe) {
355
- const path = indexPath(index.layout);
356
- const text = await renderDecisionIndex(index.git, {
357
- layout: index.layout,
358
- adr: config,
359
- tree: index.tree,
360
- history: await index.git.resolveCommit("HEAD")
361
- });
362
- if (text !== null && !holdsText(await index.tree.read(path), text)) {
363
- await writeIndexFile(index.git, path, text);
364
- await index.git.add([path]);
365
- notes.push(`regenerated and staged ${path}`);
357
+ if (config.index === "committed" && config.hookIndex === "stage" && safe) {
358
+ const path = indexPath(index.layout);
359
+ const text = await renderDecisionIndex(index.git, {
360
+ layout: index.layout,
361
+ adr: config,
362
+ tree: index.tree,
363
+ history: await index.git.resolveCommit("HEAD")
364
+ });
365
+ if (text !== null && !holdsText(await index.tree.read(path), text)) {
366
+ await writeIndexFile(index.git, path, text);
367
+ await index.git.add([path]);
368
+ notes.push(`regenerated and staged ${path}`);
369
+ }
366
370
  }
367
- }
368
- const findings = await verifyDecisions(index, { type: "staged" });
369
- return done(exitCode(findings, { failOn }), findings);
371
+ const findings = await verifyDecisions(index, { type: "staged" });
372
+ return done(exitCode(findings, { failOn }), findings);
373
+ });
370
374
  }
371
375
  // src/skill.ts
372
376
  /**
@@ -485,167 +489,169 @@ function configText(o) {
485
489
  * with a commit and left unstaged without one.
486
490
  */
487
491
  async function initDecisionLog(log, o = {}) {
488
- if (log.ref !== null || log.tree.label !== "worktree") throw new InvalidArgumentError("init writes the work tree; open the log without a ref");
489
- const known = Object.keys(BUILTIN_TEMPLATES);
490
- const templates = [...new Set(o.templates === void 0 ? ["nygard"] : o.templates)];
491
- for (const name of templates) if (!known.includes(name)) throw new UsageError(`unknown built-in template ${name}; use nygard, madr or y-statement`);
492
- const root = log.layout.root;
493
- const notes = [...log.notes];
494
- const files = [];
495
- const kept = [];
496
- let config = log.configPath;
497
- if (config !== null) kept.push(config);
498
- else {
499
- const template = templates[0] ?? "nygard";
500
- const repo = await readToolConfig(log.tree, CONFIG);
501
- if (root === DEFAULT_ROOT) {
502
- config = `${root}/${CONFIG}`;
503
- files.push([config, configText({
504
- root: null,
505
- template
506
- })]);
507
- } else if (repo === null) {
508
- config = CONFIG;
509
- files.push([config, configText({
510
- root,
511
- template
512
- })]);
513
- } else {
514
- const section = repo.raw.log;
515
- const other = typeof section?.root === "string" ? section.root : DEFAULT_ROOT;
516
- config = `${root}/${CONFIG}`;
517
- files.push([config, configText({
518
- root: null,
519
- template
520
- })]);
521
- notes.push(`${CONFIG} names ${other}; pass --root ${root} to use this log`);
522
- }
523
- }
524
- for (const name of templates) {
525
- const path = `${root}/templates/${name}.md`;
526
- if (await log.tree.read(path) !== null) kept.push(path);
527
- else files.push([path, BUILTIN_TEMPLATES[name] ?? ""]);
528
- }
529
- const commitRequested = o.commit ?? log.adr.autoCommit;
530
- const logFiles = files.length;
531
- const skill = o.skill === void 0 ? null : o.skill.dir === "" ? "SKILL.md" : `${o.skill.dir}/SKILL.md`;
532
- let agents = null;
533
- if (skill !== null) {
534
- const current = await log.tree.read(skill);
535
- if (current === null) files.push([skill, SKILL_MD]);
492
+ return withGitOperation(async () => {
493
+ if (log.ref !== null || log.tree.label !== "worktree") throw new InvalidArgumentError("init writes the work tree; open the log without a ref");
494
+ const known = Object.keys(BUILTIN_TEMPLATES);
495
+ const templates = [...new Set(o.templates === void 0 ? ["nygard"] : o.templates)];
496
+ for (const name of templates) if (!known.includes(name)) throw new UsageError(`unknown built-in template ${name}; use nygard, madr or y-statement`);
497
+ const root = log.layout.root;
498
+ const notes = [...log.notes];
499
+ const files = [];
500
+ const kept = [];
501
+ let config = log.configPath;
502
+ if (config !== null) kept.push(config);
536
503
  else {
537
- kept.push(skill);
538
- if (decoder.decode(current) !== "---\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") notes.push(`${skill} differs from adr ${o.skill?.version ?? ""}'s skill; delete it and run adr init --skill again to replace it`);
504
+ const template = templates[0] ?? "nygard";
505
+ const repo = await readToolConfig(log.tree, CONFIG);
506
+ if (root === DEFAULT_ROOT) {
507
+ config = `${root}/${CONFIG}`;
508
+ files.push([config, configText({
509
+ root: null,
510
+ template
511
+ })]);
512
+ } else if (repo === null) {
513
+ config = CONFIG;
514
+ files.push([config, configText({
515
+ root,
516
+ template
517
+ })]);
518
+ } else {
519
+ const section = repo.raw.log;
520
+ const other = typeof section?.root === "string" ? section.root : DEFAULT_ROOT;
521
+ config = `${root}/${CONFIG}`;
522
+ files.push([config, configText({
523
+ root: null,
524
+ template
525
+ })]);
526
+ notes.push(`${CONFIG} names ${other}; pass --root ${root} to use this log`);
527
+ }
539
528
  }
540
- const old = await log.tree.read(AGENTS);
541
- const text = old === null ? null : decoder.decode(old);
542
- if ((text ?? "").split("\n").some((l) => l.includes(skill))) kept.push(AGENTS);
543
- else {
544
- let stage = true;
545
- if (old !== null) {
546
- const unstaged = (await log.git.unstagedPaths([AGENTS])).length > 0;
547
- const untracked = (await log.git.untrackedPaths([AGENTS])).length > 0;
548
- if (commitRequested && unstaged) throw new UsageError(`${AGENTS} has unstaged changes; stage or discard them, or run without --commit`);
549
- if (commitRequested && untracked) throw new UsageError(`${AGENTS} is not tracked; git add it, or run without --commit`);
550
- if (unstaged || untracked) {
551
- stage = false;
552
- notes.push(untracked ? `${AGENTS} is not tracked, so the pointer is added but not staged; review it and git add it` : `${AGENTS} had unstaged changes, so the pointer is added but not staged; review it and git add it`);
529
+ for (const name of templates) {
530
+ const path = `${root}/templates/${name}.md`;
531
+ if (await log.tree.read(path) !== null) kept.push(path);
532
+ else files.push([path, BUILTIN_TEMPLATES[name] ?? ""]);
533
+ }
534
+ const commitRequested = o.commit ?? log.adr.autoCommit;
535
+ const logFiles = files.length;
536
+ const skill = o.skill === void 0 ? null : o.skill.dir === "" ? "SKILL.md" : `${o.skill.dir}/SKILL.md`;
537
+ let agents = null;
538
+ if (skill !== null) {
539
+ const current = await log.tree.read(skill);
540
+ if (current === null) files.push([skill, SKILL_MD]);
541
+ else {
542
+ kept.push(skill);
543
+ if (decoder.decode(current) !== "---\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") notes.push(`${skill} differs from adr ${o.skill?.version ?? ""}'s skill; delete it and run adr init --skill again to replace it`);
544
+ }
545
+ const old = await log.tree.read(AGENTS);
546
+ const text = old === null ? null : decoder.decode(old);
547
+ if ((text ?? "").split("\n").some((l) => l.includes(skill))) kept.push(AGENTS);
548
+ else {
549
+ let stage = true;
550
+ if (old !== null) {
551
+ const unstaged = (await log.git.unstagedPaths([AGENTS])).length > 0;
552
+ const untracked = (await log.git.untrackedPaths([AGENTS])).length > 0;
553
+ if (commitRequested && unstaged) throw new UsageError(`${AGENTS} has unstaged changes; stage or discard them, or run without --commit`);
554
+ if (commitRequested && untracked) throw new UsageError(`${AGENTS} is not tracked; git add it, or run without --commit`);
555
+ if (unstaged || untracked) {
556
+ stage = false;
557
+ notes.push(untracked ? `${AGENTS} is not tracked, so the pointer is added but not staged; review it and git add it` : `${AGENTS} had unstaged changes, so the pointer is added but not staged; review it and git add it`);
558
+ }
553
559
  }
560
+ agents = {
561
+ bytes: encoder.encode(appendLine(text ?? "", agentsPointer(skill))),
562
+ expected: old,
563
+ stage
564
+ };
554
565
  }
555
- agents = {
556
- bytes: encoder.encode(appendLine(text ?? "", agentsPointer(skill))),
557
- expected: old,
558
- stage
559
- };
560
566
  }
561
- }
562
- const at = indexPath(log.layout);
563
- let indexed = false;
564
- if (log.adr.index === "committed") {
565
- if (await log.tree.read(at) !== null) kept.push(at);
566
- else {
567
- const head = await log.git.resolveCommit("HEAD");
568
- const added = Object.fromEntries(files.map(([p, t]) => [p, encoder.encode(t)]));
569
- const base = commitRequested ? await headTree(log.git, head) : log.tree;
570
- const text = await renderDecisionIndex(log.git, {
571
- layout: log.layout,
572
- adr: log.adr,
573
- tree: overlayTree(base, added),
574
- history: head
575
- });
576
- if (text === null) notes.push(`${at} not updated: numbers need history in this shallow clone; run git fetch --unshallow, then adr index`);
567
+ const at = indexPath(log.layout);
568
+ let indexed = false;
569
+ if (log.adr.index === "committed") {
570
+ if (await log.tree.read(at) !== null) kept.push(at);
577
571
  else {
578
- files.push([at, text]);
579
- indexed = true;
572
+ const head = await log.git.resolveCommit("HEAD");
573
+ const added = Object.fromEntries(files.map(([p, t]) => [p, encoder.encode(t)]));
574
+ const base = commitRequested ? await headTree(log.git, head) : log.tree;
575
+ const text = await renderDecisionIndex(log.git, {
576
+ layout: log.layout,
577
+ adr: log.adr,
578
+ tree: overlayTree(base, added),
579
+ history: head
580
+ });
581
+ if (text === null) notes.push(`${at} not updated: numbers need history in this shallow clone; run git fetch --unshallow, then adr index`);
582
+ else {
583
+ files.push([at, text]);
584
+ indexed = true;
585
+ }
580
586
  }
581
587
  }
582
- }
583
- const commit = (files.length > 0 || agents !== null) && commitRequested;
584
- if (commit && (await log.git.identity() === null || await log.git.committerIdentity() === null)) throw new ConfigError("--commit needs a git identity; set git user.name and user.email");
585
- const written = [];
586
- let replaced = false;
587
- try {
588
- for (const [path, text] of files) {
589
- await writeNewFile(log.git, path, encoder.encode(text));
590
- written.push(path);
591
- }
592
- if (agents !== null) {
593
- if (agents.expected === null) await writeNewFile(log.git, AGENTS, agents.bytes);
594
- else await replaceFile(log.git, AGENTS, agents.bytes, { expected: agents.expected });
595
- replaced = agents.expected !== null;
596
- written.push(AGENTS);
597
- }
598
- } catch (err) {
599
- const top = log.git.root ?? "";
600
- const restore = replaced ? agents?.expected ?? null : null;
601
- for (const path of written) if (path === AGENTS && restore !== null && agents !== null) await replaceFile(log.git, AGENTS, restore, { expected: agents.bytes }).catch(() => {});
602
- else await rm(join(top, path), { force: true });
603
- throw err;
604
- }
605
- const staged = written.filter((p) => p !== AGENTS || agents?.stage === true);
606
- if (staged.length > 0) await log.git.add(staged);
607
- let sha = null;
608
- if (commit) {
609
- const message = o.message ?? renderCommitMessage(log.adr.commitSubject, {
610
- title: logFiles > 0 ? "the decision log" : "the adr agent skill",
611
- vars: {
612
- action: "set up",
613
- id: "",
614
- display: "",
615
- command: "init"
588
+ const commit = (files.length > 0 || agents !== null) && commitRequested;
589
+ if (commit && (await log.git.identity() === null || await log.git.committerIdentity() === null)) throw new ConfigError("--commit needs a git identity; set git user.name and user.email");
590
+ const written = [];
591
+ let replaced = false;
592
+ try {
593
+ for (const [path, text] of files) {
594
+ await writeNewFile(log.git, path, encoder.encode(text));
595
+ written.push(path);
616
596
  }
617
- }).message;
618
- sha = await commitWithRecovery(log.git, {
619
- message,
620
- only: staged,
621
- rerun: INIT_RERUN,
622
- after: indexed ? INDEX_AFTER(root) : null
623
- });
624
- if (indexed) try {
625
- const again = await renderDecisionIndex(log.git, {
626
- layout: log.layout,
627
- adr: log.adr,
628
- tree: worktreeReader(log.git),
629
- history: sha
630
- });
631
- if (again !== null) {
632
- if ((await writeIndexCopy(log.git, at, again)).stage) await log.git.add([at]);
597
+ if (agents !== null) {
598
+ if (agents.expected === null) await writeNewFile(log.git, AGENTS, agents.bytes);
599
+ else await replaceFile(log.git, AGENTS, agents.bytes, { expected: agents.expected });
600
+ replaced = agents.expected !== null;
601
+ written.push(AGENTS);
633
602
  }
634
603
  } catch (err) {
635
- notes.push(`${at} may be stale: ${firstLine(err)}; run adr index`);
604
+ const top = log.git.root ?? "";
605
+ const restore = replaced ? agents?.expected ?? null : null;
606
+ for (const path of written) if (path === AGENTS && restore !== null && agents !== null) await replaceFile(log.git, AGENTS, restore, { expected: agents.bytes }).catch(() => {});
607
+ else await rm(join(top, path), { force: true });
608
+ throw err;
636
609
  }
637
- }
638
- return {
639
- format: "adr-init/v1",
640
- root,
641
- config,
642
- written,
643
- kept,
644
- skill,
645
- commit: sha,
646
- notes
647
- };
610
+ const staged = written.filter((p) => p !== AGENTS || agents?.stage === true);
611
+ if (staged.length > 0) await log.git.add(staged);
612
+ let sha = null;
613
+ if (commit) {
614
+ const message = o.message ?? renderCommitMessage(log.adr.commitSubject, {
615
+ title: logFiles > 0 ? "the decision log" : "the adr agent skill",
616
+ vars: {
617
+ action: "set up",
618
+ id: "",
619
+ display: "",
620
+ command: "init"
621
+ }
622
+ }).message;
623
+ sha = await commitWithRecovery(log.git, {
624
+ message,
625
+ only: staged,
626
+ rerun: INIT_RERUN,
627
+ after: indexed ? INDEX_AFTER(root) : null
628
+ });
629
+ if (indexed) try {
630
+ const again = await renderDecisionIndex(log.git, {
631
+ layout: log.layout,
632
+ adr: log.adr,
633
+ tree: worktreeReader(log.git),
634
+ history: sha
635
+ });
636
+ if (again !== null) {
637
+ if ((await writeIndexCopy(log.git, at, again)).stage) await log.git.add([at]);
638
+ }
639
+ } catch (err) {
640
+ notes.push(`${at} may be stale: ${firstLine(err)}; run adr index`);
641
+ }
642
+ }
643
+ return {
644
+ format: "adr-init/v1",
645
+ root,
646
+ config,
647
+ written,
648
+ kept,
649
+ skill,
650
+ commit: sha,
651
+ notes
652
+ };
653
+ });
648
654
  }
649
655
  export { installDecisionHooks as a, uninstallDecisionHooks as c, verifyDecisions as d, decisionHookCommands as i, adrChecks as l, SKILL_MD as n, printDecisionHooks as o, addHookTrailers as r, runPreCommitHook as s, initDecisionLog as t, decisionVerifyInputs as u };
650
656
 
651
- //# sourceMappingURL=init-Bw0PZLnR.js.map
657
+ //# sourceMappingURL=init-Cjx-E8x1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"init-Cjx-E8x1.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 type SourceStatus,\n scopeGlobCheck,\n sourceFindings,\n templateHistoryRef,\n type VerifyMode,\n verifyLog,\n withGitOperation,\n} from \"@nikovirtala/ledger\";\nimport { adrKind, type DecisionView } from \"./kind.js\";\nimport { type DecisionLog, numberDecisions } from \"./log.js\";\nimport { decisionIndexCheck } from \"./log-index.js\";\nimport { type DecisionSources, readDecisionSources } from \"./sources.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`. With `sources` (`readDecisionSources`), qualified\n * references are checked against the cached source logs, and each referenced source that isn't\n * cached gets one `sources/not-fetched` warning.\n */\nexport function adrChecks(\n log: DecisionLog,\n historyRef: string | null,\n sources?: DecisionSources,\n): readonly Check[] {\n return [\n ...foldChecks(adrKind, {\n options: {\n acceptRequiresHuman: log.adr.acceptRequiresHuman,\n sources: sources?.logs ?? null,\n },\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 ...(sources === undefined ? [] : [sourcesCheck(log, sources.statuses)]),\n ];\n}\n\n/** The source names that qualified references in a folded decision log name. */\nexport function referencedSources(head: FoldedLogOf<typeof adrKind>): Set<string> {\n const out = new Set<string>();\n const add = (ref: string) => {\n const at = ref.indexOf(\":\");\n if (at > 0) out.add(ref.slice(0, at));\n };\n for (const s of head.subjects.values()) {\n for (const { event } of s.applied) {\n if (event.type === \"proposed\") for (const ref of event.data.supersedes ?? []) add(ref);\n else if (event.type === \"superseded\") add(event.data.by);\n else if (event.type === \"linked\") add(event.data.to);\n }\n }\n return out;\n}\n\n/**\n * `sources/not-fetched` (warning) once per uncached source that a qualified reference in the head\n * names. It runs in every scope, because it is about the log, not about one decision.\n */\nfunction sourcesCheck(log: DecisionLog, statuses: readonly SourceStatus[]): Check {\n return {\n id: \"decision-sources\",\n async run(ctx) {\n const head = ctx.folded?.head;\n if (head === undefined) return [];\n return sourceFindings(statuses, {\n tool: \"adr\",\n file: log.configPath,\n referenced: referencedSources(head as FoldedLogOf<typeof adrKind>),\n });\n },\n };\n}\n\n/**\n * The inputs outside the decision events that adr's checks read: both candidate config paths (so\n * adding a config counts) and the log's templates. A staged change to one widens `verify --staged`\n * to every decision, because a policy, scope, severity, index or template change can make an\n * unchanged decision fail.\n */\nexport function decisionVerifyInputs(log: DecisionLog): string[] {\n const root = log.layout.root;\n return [\"adr.toml\", `${root}/adr.toml`, `${root}/templates/`];\n}\n\n/**\n * Verifies the decision log in `mode` (staged, range or full) with `adrChecks`, reading the\n * sources from the local cache only.\n */\nexport async function verifyDecisions(log: DecisionLog, mode: VerifyMode): Promise<Finding[]> {\n return withGitOperation(async () => {\n return verifyLog({\n git: log.git,\n kind: adrKind,\n layout: log.layout,\n mode,\n checks: adrChecks(\n log,\n await templateHistoryRef(log.git, mode),\n await readDecisionSources(log, { fetch: \"cache\" }),\n ),\n widenOn: decisionVerifyInputs(log),\n });\n });\n}\n","import { access, constants } from \"node:fs/promises\";\nimport { relative, resolve, sep } from \"node:path\";\nimport {\n assertNoHookConflicts,\n classifyPath,\n type EventRef,\n eventTrailers,\n exitCode,\n type Finding,\n type Git,\n type HookInstallResult,\n type HookManager,\n type HookName,\n holdsText,\n hookSnippet,\n installHooks,\n parseEventFileName,\n resolveAttribution,\n type Severity,\n stagedRenames,\n UsageError,\n uninstallHooks,\n withGitOperation,\n writeIndexFile,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\nimport { 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\", \"--fetch-sources\"],\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 decision and event type\n * among the staged added event files of the log (`eventTrailers`, ?6), in path order, keeping\n * pairs another tool already added (`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 refs = added.flatMap((p): EventRef[] => {\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 ? [{ subject: c.subject, type: name.type }]\n : [];\n });\n const trailers = eventTrailers(refs, { subject: \"ADR\", event: \"ADR-Event\" });\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 return withGitOperation(async () => {\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","/**\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 firstLine,\n headTree,\n InvalidArgumentError,\n overlayTree,\n readToolConfig,\n renderCommitMessage,\n replaceFile,\n UsageError,\n withGitOperation,\n worktreeReader,\n writeIndexCopy,\n writeNewFile,\n} from \"@nikovirtala/ledger\";\nimport { adrKind } from \"./kind.js\";\nimport type { DecisionLog } from \"./log.js\";\nimport { INDEX_AFTER, indexPath, renderDecisionIndex } 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 return withGitOperation(async () => {\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}\n"],"mappings":";;;;;;;AA2BA,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;IACN,UAAU,IAAI,IAAI;IAClB,MAAM;IACN,SAAS,QAAQ,CAAC;IAClB,MAAM,EAAE;IACR,SAAS,EAAE;GACb,CAAC,C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  import { t as adrKind } from "./kind-C3DiBuUp.js";
3
3
  import { lintTemplate, loadTemplates, parseTemplate } from "@nikovirtala/ledger";
4
4
  // src/templates/list.ts
@@ -55,4 +55,4 @@ async function listTemplates(read) {
55
55
  }
56
56
  export { listTemplates as t };
57
57
 
58
- //# sourceMappingURL=list-CnMSw8eA.js.map
58
+ //# sourceMappingURL=list-qsuw1oAL.js.map