adrien 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire } from "node:module";
3
3
  import picomatch from "picomatch";
4
4
  import { basename, dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
5
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { homedir } from "node:os";
7
7
  import YAML, { visit } from "yaml";
8
8
  import { z } from "zod";
@@ -10,9 +10,13 @@ import { execFile, spawn } from "node:child_process";
10
10
  import { promisify } from "node:util";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { createHash } from "node:crypto";
13
- import { Command, CommanderError } from "commander";
13
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
14
14
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
15
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
16
+ import { Hono } from "hono";
17
+ import { readFile, realpath, stat } from "node:fs/promises";
18
+ import { getMimeType } from "hono/utils/mime";
19
+ import { serve } from "@hono/node-server";
16
20
  // ../core/src/anchors.ts
17
21
  function parseAnchor(s) {
18
22
  const i = s.indexOf(":");
@@ -38,9 +42,9 @@ function section$1(body, heading) {
38
42
  function firstParagraph(body) {
39
43
  return body.split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !p.startsWith("#")) ?? "";
40
44
  }
41
- /** Why an ADR exists, in a few lines: its Rationale, else its Decision, else its first paragraph. */
45
+ /** Why an ADR exists, in a few lines: its Rationale, else its Decision (or MADR's Decision Outcome), else its first paragraph. */
42
46
  function excerpt(adr, max = 600) {
43
- const text = section$1(adr.body, "Rationale") ?? section$1(adr.body, "Decision") ?? firstParagraph(adr.body);
47
+ const text = section$1(adr.body, "Rationale") ?? section$1(adr.body, "Decision Outcome") ?? section$1(adr.body, "Decision") ?? firstParagraph(adr.body);
44
48
  return text.length > max ? `${text.slice(0, max - 1)}…` : text;
45
49
  }
46
50
  // ../core/src/errors.ts
@@ -59,9 +63,9 @@ function parseIdFormat(fmt) {
59
63
  const m = /^(.*)\{n(?::(\d+))?\}(.*)$/.exec(fmt);
60
64
  if (!m) throw new AdrienError("CONFIG_INVALID", `id_format "${fmt}" must contain {n} or {n:WIDTH}`);
61
65
  return {
62
- prefix: m[1] ?? "",
66
+ prefix: m[1],
63
67
  width: m[2] ? Number(m[2]) : 1,
64
- suffix: m[3] ?? ""
68
+ suffix: m[3]
65
69
  };
66
70
  }
67
71
  function formatId(n, fmt) {
@@ -79,6 +83,63 @@ function nextIdNumber(ids, fmt) {
79
83
  for (const id of ids) max = Math.max(max, idNumber(id, fmt) ?? 0);
80
84
  return max + 1;
81
85
  }
86
+ // ../core/src/model.ts
87
+ const STATUSES = [
88
+ "proposed",
89
+ "accepted",
90
+ "rejected",
91
+ "superseded",
92
+ "deprecated"
93
+ ];
94
+ /** Body skeletons `adrien new` can start from. `standard` is Adrien's own; `madr` follows MADR 4's section names. */
95
+ const TEMPLATE_NAMES = [
96
+ "standard",
97
+ "minimal",
98
+ "madr"
99
+ ];
100
+ const ORIGINS = [
101
+ "manual",
102
+ "agent",
103
+ "mined"
104
+ ];
105
+ /** The frontmatter keys Adrien owns, in the order they are written. */
106
+ const META_KEYS = [
107
+ "id",
108
+ "title",
109
+ "status",
110
+ "date",
111
+ "review_on",
112
+ "tags",
113
+ "components",
114
+ "code",
115
+ "review_rule",
116
+ "sources",
117
+ "supersedes",
118
+ "superseded_by",
119
+ "related",
120
+ "deciders",
121
+ "origin",
122
+ "contested"
123
+ ];
124
+ const stringList = z.array(z.string()).default([]);
125
+ const adrMetaSchema = z.object({
126
+ id: z.string().min(1),
127
+ title: z.string().min(1),
128
+ status: z.enum(STATUSES),
129
+ date: z.string().optional(),
130
+ review_on: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "must be a date like 2027-03-04").optional(),
131
+ tags: stringList,
132
+ components: stringList,
133
+ code: stringList,
134
+ review_rule: z.string().optional(),
135
+ sources: stringList,
136
+ supersedes: stringList,
137
+ superseded_by: z.string().optional(),
138
+ related: stringList,
139
+ deciders: stringList,
140
+ origin: z.enum(ORIGINS).default("manual"),
141
+ contested: z.boolean().default(false)
142
+ });
82
143
  // ../core/src/config.ts
83
144
  const CONFIG_FILE = "adrien.config.yaml";
84
145
  const CODE_CONFIG_FILE = ".adrien.yaml";
@@ -99,8 +160,10 @@ const logConfigSchema = z.strictObject({
99
160
  product: z.string().min(1),
100
161
  adr_dir: z.string().min(1).default("docs/adr"),
101
162
  id_format: z.string().default("ADR-{n:4}"),
163
+ template: z.enum(TEMPLATE_NAMES).default("standard"),
102
164
  tags: z.array(z.string().regex(ID, idMessage)).default([]),
103
- components: z.record(z.string(), componentDef).default({})
165
+ components: z.record(z.string(), componentDef).default({}),
166
+ lint: z.strictObject({ markdownlint: z.record(z.string(), z.unknown()).default({}) }).optional()
104
167
  });
105
168
  const codeRepoSchema = z.strictObject({
106
169
  log: z.string().min(1),
@@ -119,13 +182,23 @@ function validate(schema, data, file) {
119
182
  const issue = parsed.error.issues[0];
120
183
  throw new AdrienError("CONFIG_INVALID", `${file}: ${issue?.path.join(".") || "config"}: ${issue?.message}`);
121
184
  }
185
+ /** Parses and validates the text of an `adrien.config.yaml`; `label` names it in error messages. */
186
+ function parseLogConfigText(text, label) {
187
+ let data;
188
+ try {
189
+ data = YAML.parse(text) ?? {};
190
+ } catch (e) {
191
+ throw new AdrienError("CONFIG_INVALID", `${label}: invalid YAML (${e.message.split("\n")[0]})`);
192
+ }
193
+ const config = validate(logConfigSchema, data, label);
194
+ for (const id of Object.keys(config.components)) if (!ID.test(id)) throw new AdrienError("CONFIG_INVALID", `${label}: component "${id}" ${idMessage}`);
195
+ parseIdFormat(config.id_format);
196
+ return config;
197
+ }
122
198
  function loadLogConfig(logRoot) {
123
199
  const file = join(logRoot, CONFIG_FILE);
124
200
  if (!existsSync(file)) throw new AdrienError("CONFIG_NOT_FOUND", `No ${CONFIG_FILE} in ${logRoot}`);
125
- const config = validate(logConfigSchema, readYamlFile(file), file);
126
- for (const id of Object.keys(config.components)) if (!ID.test(id)) throw new AdrienError("CONFIG_INVALID", `${file}: component "${id}" ${idMessage}`);
127
- parseIdFormat(config.id_format);
128
- return config;
201
+ return parseLogConfigText(readFileSync(file, "utf8"), file);
129
202
  }
130
203
  function writeNew(file, data) {
131
204
  if (existsSync(file)) throw new AdrienError("CONFIG_EXISTS", `${file} already exists`);
@@ -151,55 +224,38 @@ function findUp(startDir, fileName) {
151
224
  dir = parent;
152
225
  }
153
226
  }
154
- // ../core/src/model.ts
155
- const STATUSES = [
156
- "proposed",
157
- "accepted",
158
- "rejected",
159
- "superseded",
160
- "deprecated"
161
- ];
162
- const ORIGINS = [
163
- "manual",
164
- "agent",
165
- "mined"
166
- ];
167
- /** The frontmatter keys Adrien owns, in the order they are written. */
168
- const META_KEYS = [
169
- "id",
170
- "title",
171
- "status",
172
- "date",
173
- "tags",
174
- "components",
175
- "code",
176
- "review_rule",
177
- "sources",
178
- "supersedes",
179
- "superseded_by",
180
- "related",
181
- "deciders",
182
- "origin",
183
- "contested"
184
- ];
185
- const stringList = z.array(z.string()).default([]);
186
- const adrMetaSchema = z.object({
187
- id: z.string().min(1),
188
- title: z.string().min(1),
189
- status: z.enum(STATUSES),
190
- date: z.string().optional(),
191
- tags: stringList,
192
- components: stringList,
193
- code: stringList,
194
- review_rule: z.string().optional(),
195
- sources: stringList,
196
- supersedes: stringList,
197
- superseded_by: z.string().optional(),
198
- related: stringList,
199
- deciders: stringList,
200
- origin: z.enum(ORIGINS).default("manual"),
201
- contested: z.boolean().default(false)
202
- });
227
+ // ../core/src/frontmatter.ts
228
+ const TEMPLATES = {
229
+ standard: [
230
+ ["## Context"],
231
+ ["## Considered options"],
232
+ ["## Decision"],
233
+ ["## Rationale"],
234
+ ["## Consequences"]
235
+ ],
236
+ minimal: [
237
+ ["## Context"],
238
+ ["## Decision"],
239
+ ["## Consequences"]
240
+ ],
241
+ madr: [
242
+ ["## Context and Problem Statement"],
243
+ ["## Decision Drivers"],
244
+ ["## Considered Options"],
245
+ [
246
+ "## Decision Outcome",
247
+ "### Consequences",
248
+ "### Confirmation"
249
+ ],
250
+ ["## Pros and Cons of the Options"],
251
+ ["## More Information"]
252
+ ]
253
+ };
254
+ /** An empty skeleton: the headings only, each followed by a blank line, so it lints clean until it is filled in. */
255
+ function bodyTemplate(name = "standard") {
256
+ return `\n${TEMPLATES[name].map((headings) => headings.join("\n\n")).join("\n\n")}\n`;
257
+ }
258
+ bodyTemplate("standard");
203
259
  const FRONTMATTER = /^---\n([\s\S]*?\n)?---[ \t]*(?:\n|$)/;
204
260
  const FILE_NUMBER = /^(?:ADR-)?(\d+)-/i;
205
261
  const metaKeys = new Set(META_KEYS);
@@ -266,7 +322,7 @@ function parseAdr(text, path, opts) {
266
322
  });
267
323
  if (!parsed.success) {
268
324
  const issue = parsed.error.issues[0];
269
- throw parseError(path, `${issue?.path.join(".") || "frontmatter"}: ${issue?.message}`);
325
+ throw parseError(path, `${issue?.path.join(".")}: ${issue?.message}`);
270
326
  }
271
327
  return {
272
328
  meta: {
@@ -302,6 +358,23 @@ function serializeAdr(adr) {
302
358
  flowCollectionPadding: false
303
359
  })}---\n${adr.body}`;
304
360
  }
361
+ // ../core/src/paths.ts
362
+ /**
363
+ * The physical path: symlinks, Windows 8.3 short names (`RUNNER~1`) and drive-letter case resolved. Git reports paths
364
+ * this way, so every path node compares with one of git's goes through here first.
365
+ */
366
+ function canonicalPath(path) {
367
+ try {
368
+ return realpathSync.native(path);
369
+ } catch {
370
+ return path;
371
+ }
372
+ }
373
+ /** True when `child` is `parent` or lies below it. */
374
+ function isInside(child, parent) {
375
+ const rel = relative(parent, child);
376
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
377
+ }
305
378
  // ../core/src/slug.ts
306
379
  const MAX_SLUG = 60;
307
380
  function normalizeTitle(s) {
@@ -352,11 +425,30 @@ function adrFilePath(config, id, title, subdir) {
352
425
  const dir = posix.join(adrDir, toPosix(subdir ?? ""));
353
426
  const inside = posix.relative(adrDir, dir);
354
427
  if (inside === ".." || inside.startsWith("../")) throw new AdrienError("INVALID_INPUT", `--subdir "${subdir}" leaves the ADR directory (${config.adr_dir}).`);
355
- return posix.join(dir, `${id}-${slugify(title)}.md`);
428
+ const file = posix.join(dir, `${id}-${slugify(title)}.md`);
429
+ const filePart = posix.relative(adrDir, file);
430
+ if (filePart === ".." || filePart.startsWith("../")) throw new AdrienError("INVALID_INPUT", `The id "${id}" would place ${file} outside the ADR directory (${config.adr_dir}).`);
431
+ return file;
432
+ }
433
+ /** Refuses a destination that leaves the log, lexically or through a symlink (whether the file or a folder above it). */
434
+ function assertInsideLog(logRoot, file, adrPath) {
435
+ const root = canonicalPath(logRoot);
436
+ const outside = (where) => new AdrienError("INVALID_INPUT", `${adrPath} resolves outside the log (${where}); refusing to write it.`);
437
+ if (!isInside(file, logRoot)) throw outside(file);
438
+ if (lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) {
439
+ const real = canonicalPath(file);
440
+ if (real === file || !isInside(real, root)) throw outside(real);
441
+ return;
442
+ }
443
+ let probe = file;
444
+ while (!existsSync(probe) && dirname(probe) !== probe) probe = dirname(probe);
445
+ const real = canonicalPath(probe);
446
+ if (!isInside(real, root)) throw outside(real);
356
447
  }
357
448
  /** `exclusive` refuses to replace an existing file, so creating an ADR can never overwrite another one. */
358
449
  function writeAdr(logRoot, adr, opts = {}) {
359
450
  const file = join(logRoot, ...adr.path.split("/"));
451
+ assertInsideLog(logRoot, file, adr.path);
360
452
  mkdirSync(dirname(file), { recursive: true });
361
453
  try {
362
454
  writeFileSync(file, serializeAdr(adr), { flag: opts.exclusive ? "wx" : "w" });
@@ -384,7 +476,7 @@ async function git(cwd, args) {
384
476
  async function gitToplevel(dir) {
385
477
  if (!existsSync(dir)) return null;
386
478
  const out = await git(dir, ["rev-parse", "--show-toplevel"]);
387
- return out ? resolve(out.trim()) : null;
479
+ return out ? canonicalPath(resolve(out.trim())) : null;
388
480
  }
389
481
  async function isCommit(repoDir, ref) {
390
482
  return await git(repoDir, [
@@ -453,9 +545,12 @@ async function readTreeAtRef(repoDir, ref, subdir) {
453
545
  ]);
454
546
  if (!listing) return [];
455
547
  const paths = listing.split("\0").filter(Boolean);
456
- if (paths.length === 0) return [];
457
548
  return parseBatch(await catFileBatch(repoDir, paths.map((p) => `${ref}:${p}`)), paths);
458
549
  }
550
+ /** The text of one file at `ref`, or null when the ref or the file does not exist. */
551
+ async function readFileAtRef(repoDir, ref, path) {
552
+ return git(repoDir, ["show", `${ref}:${path}`]);
553
+ }
459
554
  async function remoteUrl(repoDir, remote = "origin") {
460
555
  return (await git(repoDir, [
461
556
  "remote",
@@ -514,7 +609,7 @@ function normalizeRepoUrl(url) {
514
609
  return `${u.hostname.toLowerCase()}/${trimRepoPath(u.pathname)}`;
515
610
  }
516
611
  const scp = WINDOWS_DRIVE.test(s) ? null : SCP_LIKE.exec(s);
517
- if (scp) return `${(scp[1] ?? "").toLowerCase()}/${trimRepoPath(scp[2] ?? "")}`;
612
+ if (scp) return `${scp[1].toLowerCase()}/${trimRepoPath(scp[2])}`;
518
613
  return trimRepoLocal(s);
519
614
  }
520
615
  function trimRepoLocal(p) {
@@ -563,10 +658,6 @@ async function locate(log, baseDir, env) {
563
658
  logSource: logRoot
564
659
  };
565
660
  }
566
- const isInside = (child, parent) => {
567
- const rel = relative(parent, child);
568
- return !rel.startsWith("..") && !isAbsolute(rel);
569
- };
570
661
  async function detectCodeRepo(cwd, logRoot, config) {
571
662
  const codeConfigDir = findUp(cwd, CODE_CONFIG_FILE);
572
663
  const root = codeConfigDir ?? await gitToplevel(cwd) ?? (isInside(cwd, logRoot) ? logRoot : null);
@@ -587,7 +678,7 @@ async function detectCodeRepo(cwd, logRoot, config) {
587
678
  }
588
679
  async function resolveContext(opts) {
589
680
  const env = opts.env ?? process.env;
590
- const cwd = resolve(opts.cwd);
681
+ const cwd = canonicalPath(resolve(opts.cwd));
591
682
  let located;
592
683
  if (opts.log) located = await locate(opts.log, cwd, env);
593
684
  else {
@@ -602,6 +693,10 @@ async function resolveContext(opts) {
602
693
  else if (codeConfig && codeConfigDir) located = await locate(codeConfig.log, codeConfigDir, env);
603
694
  else throw new AdrienError("CONFIG_NOT_FOUND", NOT_FOUND);
604
695
  }
696
+ located = {
697
+ ...located,
698
+ logRoot: canonicalPath(located.logRoot)
699
+ };
605
700
  const config = loadLogConfig(located.logRoot);
606
701
  return {
607
702
  cwd,
@@ -719,12 +814,22 @@ async function loadLogView(logRoot, config) {
719
814
  }
720
815
  const logFromTop = toPosix(relative(top, logRoot));
721
816
  const prefix = logFromTop ? `${logFromTop}/` : "";
722
- const adrDir = toPosix(relative(top, join(logRoot, config.adr_dir)));
817
+ const configAt = async (ref) => {
818
+ const text = await readFileAtRef(top, ref, `${prefix}${CONFIG_FILE}`);
819
+ if (text === null) return config;
820
+ try {
821
+ return parseLogConfigText(text, `${ref}:${prefix}${CONFIG_FILE}`);
822
+ } catch {
823
+ return config;
824
+ }
825
+ };
723
826
  const logAt = async (ref) => {
827
+ const atRef = await configAt(ref);
828
+ const adrDir = toPosix(relative(top, join(logRoot, atRef.adr_dir)));
724
829
  return parseLogFiles((await readTreeAtRef(top, ref, adrDir)).filter((f) => f.path.endsWith(".md")).map((f) => ({
725
830
  path: f.path.slice(prefix.length),
726
831
  text: f.text
727
- })), config);
832
+ })), atRef);
728
833
  };
729
834
  const atBase = await logAt(baseRef);
730
835
  const base = atBase.adrs;
@@ -736,11 +841,13 @@ async function loadLogView(logRoot, config) {
736
841
  baseRef
737
842
  ]))?.trim();
738
843
  const baseSha = (await git(top, ["rev-parse", baseRef]))?.trim();
844
+ const fork = forkPoint && forkPoint !== baseSha ? (await logAt(forkPoint)).adrs : base;
739
845
  return {
846
+ ...forkPoint ? {} : { forkUnresolved: true },
740
847
  mode: "git",
741
848
  baseRef,
742
849
  base,
743
- pending: diff(forkPoint && forkPoint !== baseSha ? (await logAt(forkPoint)).adrs : base, working.adrs).map((change) => ({
850
+ pending: diff(fork, working.adrs).map((change) => ({
744
851
  ...change,
745
852
  base: latest(change.base, base)
746
853
  })),
@@ -771,6 +878,90 @@ function mergedAdrs(view) {
771
878
  }
772
879
  return merged.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
773
880
  }
881
+ // ../core/src/lint.ts
882
+ /**
883
+ * markdownlint settings tuned for ADRs, overridable under `lint.markdownlint` in the config. They follow MADR's: "the
884
+ * linter should support the user and not annoy them".
885
+ */
886
+ const MARKDOWNLINT_DEFAULTS = {
887
+ default: true,
888
+ MD013: false,
889
+ MD024: false,
890
+ MD025: { front_matter_title: "" },
891
+ MD041: false
892
+ };
893
+ const FENCE = /^(```|~~~)[\s\S]*?^\1[^\n]*$/gm;
894
+ const INLINE_CODE = /`[^`\n]*`/g;
895
+ const COMMENT = /<!--[\s\S]*?-->/g;
896
+ /** `{short title, representative of …}`: braces around words, without the quotes or colon of JSON or `{n:4}`. */
897
+ const PLACEHOLDER = /\{(?![^{}\n]*["':])[^{}\n]*\s[^{}\n]*\}/;
898
+ const NUMBERED_HEADING = /^#{1,6}\s+\d+[.)]\s/m;
899
+ const prose = (body) => body.replace(FENCE, "").replace(COMMENT, "").replace(INLINE_CODE, "");
900
+ /** The text under the Decision (or MADR's Decision Outcome) heading; null when the ADR has no such heading. */
901
+ function decisionText(body) {
902
+ const m = /^##\s+(?:Decision Outcome|Decision)\s*$([\s\S]*?)(?=^##\s|(?![\s\S]))/im.exec(body);
903
+ if (!m) return null;
904
+ return m[1].replace(COMMENT, "").replace(/^#+\s.*$/gm, "").trim();
905
+ }
906
+ function adrienRules(adr) {
907
+ const at = {
908
+ id: adr.meta.id,
909
+ path: adr.path
910
+ };
911
+ const out = [];
912
+ const text = prose(adr.body);
913
+ const placeholder = PLACEHOLDER.exec(text)?.[0];
914
+ if (placeholder) out.push({
915
+ severity: "warning",
916
+ code: "unfilled-placeholder",
917
+ ...at,
918
+ message: `Template placeholder left in the body: ${placeholder}`
919
+ });
920
+ if (adr.meta.status === "accepted" && decisionText(adr.body) === "") out.push({
921
+ severity: "warning",
922
+ code: "empty-decision",
923
+ ...at,
924
+ message: "An accepted ADR has an empty Decision section"
925
+ });
926
+ if (NUMBERED_HEADING.test(text)) out.push({
927
+ severity: "warning",
928
+ code: "numbered-heading",
929
+ ...at,
930
+ message: "Headings are not numbered (\"## Context\", not \"## 1. Context\"), so sections can move without renumbering"
931
+ });
932
+ return out;
933
+ }
934
+ /**
935
+ * Style warnings for the ADRs in the working tree: markdownlint over each file, plus Adrien's own rules. They are
936
+ * advice about how an ADR reads, never errors: a decision with a long line is still a decision.
937
+ */
938
+ async function lintAdrs(ctx, view) {
939
+ const adrs = workingAdrs(view);
940
+ const strings = Object.fromEntries(adrs.map((adr) => [adr.path, readFileSync(join(ctx.logRoot, ...adr.path.split("/")), "utf8")]));
941
+ const { lint } = await import("markdownlint/promise");
942
+ const results = await lint({
943
+ strings,
944
+ config: {
945
+ ...MARKDOWNLINT_DEFAULTS,
946
+ ...ctx.config.lint?.markdownlint
947
+ }
948
+ });
949
+ const out = [];
950
+ for (const adr of adrs) {
951
+ for (const e of results[adr.path] ?? []) {
952
+ const detail = e.errorDetail ? ` [${e.errorDetail}]` : "";
953
+ out.push({
954
+ severity: "warning",
955
+ code: "markdown",
956
+ id: adr.meta.id,
957
+ path: adr.path,
958
+ message: `${e.ruleNames[0]} ${e.ruleNames[1]}: ${e.ruleDescription}${detail} (line ${e.lineNumber})`
959
+ });
960
+ }
961
+ out.push(...adrienRules(adr));
962
+ }
963
+ return out;
964
+ }
774
965
  // ../core/src/check.ts
775
966
  const RETIRED$1 = /* @__PURE__ */ new Set([
776
967
  "rejected",
@@ -858,7 +1049,7 @@ async function checkouts(ctx, here) {
858
1049
  const roots = /* @__PURE__ */ new Map();
859
1050
  const add = (component, repoRoot) => roots.set(component, join(repoRoot, componentRoot(ctx.config, component)));
860
1051
  if (here) {
861
- for (const c of ctx.codeRepo?.components ?? []) add(c, ctx.codeRepo?.root ?? "");
1052
+ if (ctx.codeRepo) for (const c of ctx.codeRepo.components) add(c, ctx.codeRepo.root);
862
1053
  return roots;
863
1054
  }
864
1055
  const logTop = await gitToplevel(ctx.logRoot) ?? ctx.logRoot;
@@ -917,6 +1108,11 @@ async function runCheck(ctx, view, opts = {}) {
917
1108
  code: "base-unresolved",
918
1109
  message: "No default branch found (looked for origin/HEAD, origin/main, origin/master, main, master), so pending ADRs cannot be told from merged ones. Fetch it first, e.g. `git fetch origin <default-branch>`."
919
1110
  });
1111
+ if (opts.mr && view.forkUnresolved) out.push({
1112
+ severity: "error",
1113
+ code: "fork-unresolved",
1114
+ message: `This checkout shares no history with ${view.baseRef} (a shallow clone?), so what the merge request changed cannot be told from what landed upstream. Fetch more history first, e.g. \`git fetch --unshallow\`.`
1115
+ });
920
1116
  const adrs = mergedAdrs(view);
921
1117
  for (const adr of adrs) checkFields(ctx, adr, out);
922
1118
  checkLinks(adrs, out);
@@ -929,6 +1125,17 @@ async function runCheck(ctx, view, opts = {}) {
929
1125
  message: `${change.id} is still "proposed": merging it adds only a hint. Run \`adrien accept ${change.id}\` to approve it`
930
1126
  });
931
1127
  }
1128
+ const today = opts.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1129
+ for (const adr of adrs) {
1130
+ const due = adr.meta.review_on;
1131
+ if (due && due <= today && !RETIRED$1.has(adr.meta.status)) out.push({
1132
+ severity: "warning",
1133
+ code: "review-due",
1134
+ ...at(adr),
1135
+ message: `${adr.meta.id} was due for review on ${due}: confirm it still holds, or supersede it`
1136
+ });
1137
+ }
1138
+ if (opts.lint) out.push(...await lintAdrs(ctx, view));
932
1139
  return out;
933
1140
  }
934
1141
  function exitCodeFor(diags, strict = false) {
@@ -964,6 +1171,51 @@ function findDuplicates(title, adrs) {
964
1171
  }
965
1172
  return hits.sort((a, b) => b.score - a.score).slice(0, 5);
966
1173
  }
1174
+ // ../core/src/export.ts
1175
+ const EXPORT_FORMATS = ["markdown", "llms"];
1176
+ const byId = (a, b) => a.meta.id.localeCompare(b.meta.id, "en", { numeric: true });
1177
+ const cell = (text) => text.replace(/\|/g, "\\|");
1178
+ /**
1179
+ * A generated overview of the ADRs in this checkout. `markdown` is a table of all of them; `llms` follows the
1180
+ * llms.txt convention, so a model can read the accepted decisions and their rules from one file.
1181
+ * `from` is the directory of the file that will hold the export, so its links resolve from there; by default they are
1182
+ * relative to the log root.
1183
+ */
1184
+ function exportLog(ctx, view, format, opts = {}) {
1185
+ const adrs = [...workingAdrs(view)].sort(byId);
1186
+ const { from } = opts;
1187
+ const link = (adr) => from === void 0 ? adr.path : toPosix(relative(from, join(ctx.logRoot, ...adr.path.split("/"))));
1188
+ const { product } = ctx.config;
1189
+ if (format === "markdown") {
1190
+ const rows = adrs.map((a) => `| [${a.meta.id}](${link(a)}) | ${cell(a.meta.title)} | ${a.meta.status} | ${a.meta.tags.join(", ")} |`);
1191
+ return [
1192
+ `# ${product}: architecture decisions`,
1193
+ "",
1194
+ "| ID | Title | Status | Tags |",
1195
+ "| --- | --- | --- | --- |",
1196
+ ...rows,
1197
+ ""
1198
+ ].join("\n");
1199
+ }
1200
+ const base = [...view.base].sort(byId);
1201
+ const pending = view.pending.filter((c) => c.current !== void 0).sort((a, b) => byId(a.current, b.current));
1202
+ const entry = (a, kind = "") => `- [${a.meta.id}: ${a.meta.title}](${link(a)})${a.meta.review_rule ? `: ${a.meta.review_rule}` : ""}${kind}`;
1203
+ const group = (title, lines) => lines.length ? [
1204
+ "",
1205
+ `## ${title}`,
1206
+ "",
1207
+ ...lines
1208
+ ] : [];
1209
+ return [
1210
+ `# ${product}`,
1211
+ "",
1212
+ `> Architecture decisions for ${product}. Before changing code, follow the rule of every accepted decision that governs it.`,
1213
+ ...group("Accepted", base.filter((a) => a.meta.status === "accepted").map((a) => entry(a))),
1214
+ ...group("Proposed (not yet binding)", base.filter((a) => a.meta.status === "proposed").map((a) => entry(a))),
1215
+ ...group("Pending in this checkout (not yet binding)", pending.map((c) => entry(c.current, ` (${c.kind})`))),
1216
+ ""
1217
+ ].join("\n");
1218
+ }
967
1219
  // ../core/src/for-files.ts
968
1220
  const RETIRED = /* @__PURE__ */ new Set([
969
1221
  "rejected",
@@ -1034,6 +1286,14 @@ function adrsForFiles(ctx, view, paths) {
1034
1286
  };
1035
1287
  });
1036
1288
  }
1289
+ /**
1290
+ * A warning for callers that show decisions as binding: with no default branch to compare against, ADR statuses are
1291
+ * read as written, so an ADR that says `accepted` may not have been merged.
1292
+ */
1293
+ function unverifiedBaseNote(view) {
1294
+ if (!view.baseUnresolved) return null;
1295
+ return "No default branch was found (looked for origin/HEAD, origin/main, origin/master, main, master), so ADR statuses are read as written and nothing is verified as merged. Fetch the default branch to be sure which decisions are binding.";
1296
+ }
1037
1297
  // ../core/src/sqlite.ts
1038
1298
  let loading;
1039
1299
  /**
@@ -1189,7 +1449,7 @@ var AdrIndex = class AdrIndex {
1189
1449
  insertFts.run(doc.layer, path, meta.title, meta.review_rule ?? "", body);
1190
1450
  }
1191
1451
  for (const key of existing.keys()) {
1192
- const [layer = "", path = ""] = key.split("\0");
1452
+ const [layer, path] = key.split("\0");
1193
1453
  remove(layer, path);
1194
1454
  stats.deleted++;
1195
1455
  }
@@ -1221,6 +1481,7 @@ function assertWritable(ctx) {
1221
1481
  if (ctx.readOnly) throw new AdrienError("READ_ONLY_LOG", `The ADR log is a read-only cached clone (${ctx.logSource}). Check out the log repo and point \`log:\` in .adrien.yaml to its local path to propose changes.`);
1222
1482
  }
1223
1483
  function validateInput(ctx, input) {
1484
+ if (input.review_on !== void 0 && !/^\d{4}-\d{2}-\d{2}$/.test(input.review_on)) throw new AdrienError("INVALID_INPUT", `review_on "${input.review_on}" must be a date like 2027-03-04`);
1224
1485
  const known = Object.keys(ctx.config.components);
1225
1486
  const badTags = (input.tags ?? []).filter((t) => !ctx.config.tags.includes(t));
1226
1487
  if (badTags.length) throw new AdrienError("INVALID_INPUT", `Unknown tag(s): ${badTags.join(", ")}. Allowed: ${ctx.config.tags.join(", ")}`);
@@ -1233,8 +1494,12 @@ function validateInput(ctx, input) {
1233
1494
  if (badAnchors.length) throw new AdrienError("INVALID_INPUT", `Invalid anchor(s): ${badAnchors.join(", ")}. Use <component>:<glob> with a component from: ${known.join(", ")}`);
1234
1495
  }
1235
1496
  const allIds = (view) => [...view.base, ...workingAdrs(view)].map((a) => a.meta.id);
1236
- function findAdr(view, id) {
1237
- const matches = workingAdrs(view).filter((a) => a.meta.id === id);
1497
+ /**
1498
+ * The ADR as it is on disk now. A view was loaded asynchronously and may predate another edit, and rewriting an ADR from
1499
+ * a stale copy would silently undo that edit.
1500
+ */
1501
+ function findAdr(ctx, id) {
1502
+ const matches = readWorkingLog(ctx.logRoot, ctx.config).adrs.filter((a) => a.meta.id === id);
1238
1503
  if (matches.length === 0) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
1239
1504
  if (matches.length > 1) throw new AdrienError("INVALID_INPUT", `${id} is used by ${matches.map((a) => a.path).join(", ")}. Run \`adrien renumber ${id}\` first`);
1240
1505
  return matches[0];
@@ -1254,7 +1519,7 @@ function createAdr(ctx, view, input, opts) {
1254
1519
  const id = formatId(nextIdNumber(allIds(live), ctx.config.id_format), ctx.config.id_format);
1255
1520
  const adr = {
1256
1521
  path: adrFilePath(ctx.config, id, input.title, input.subdir),
1257
- body: input.body ?? "\n## Context\n\n## Considered options\n\n## Decision\n\n## Rationale\n\n## Consequences\n",
1522
+ body: input.body ?? bodyTemplate(input.template ?? ctx.config.template),
1258
1523
  meta: {
1259
1524
  id,
1260
1525
  title: input.title,
@@ -1264,6 +1529,7 @@ function createAdr(ctx, view, input, opts) {
1264
1529
  components: input.components ?? [],
1265
1530
  code: input.code ?? [],
1266
1531
  review_rule: input.review_rule,
1532
+ review_on: input.review_on,
1267
1533
  sources: input.sources ?? [],
1268
1534
  supersedes: [],
1269
1535
  related: input.related ?? [],
@@ -1274,6 +1540,7 @@ function createAdr(ctx, view, input, opts) {
1274
1540
  }
1275
1541
  };
1276
1542
  if (adr.meta.review_rule === void 0) delete adr.meta.review_rule;
1543
+ if (adr.meta.review_on === void 0) delete adr.meta.review_on;
1277
1544
  writeAdr(ctx.logRoot, adr, { exclusive: true });
1278
1545
  return {
1279
1546
  written: true,
@@ -1291,12 +1558,12 @@ const PATCH_KEYS = /* @__PURE__ */ new Set([
1291
1558
  "body"
1292
1559
  ]);
1293
1560
  /** Edits an ADR in the working copy; the merge request that carries it is the approval gate. */
1294
- function updateAdr(ctx, view, id, patch, opts) {
1561
+ function updateAdr(ctx, _view, id, patch, opts) {
1295
1562
  assertWritable(ctx);
1296
1563
  const forbidden = Object.keys(patch).filter((k) => !PATCH_KEYS.has(k));
1297
1564
  if (forbidden.length) throw new AdrienError("INVALID_INPUT", `Cannot change ${forbidden.join(", ")} this way (status changes need an architect)`);
1298
1565
  validateInput(ctx, patch);
1299
- const adr = findAdr(view, id);
1566
+ const adr = findAdr(ctx, id);
1300
1567
  const { body, ...metaPatch } = patch;
1301
1568
  let nextBody = body ?? adr.body;
1302
1569
  if (opts?.note) nextBody = `${nextBody.replace(/\n*$/, "\n")}\n> Proposed change (${opts.origin ?? "agent"}, ${todayOf(opts)}): ${opts.note}\n`;
@@ -1322,28 +1589,29 @@ function write(ctx, adr, meta) {
1322
1589
  writeAdr(ctx.logRoot, updated);
1323
1590
  return updated;
1324
1591
  }
1325
- function acceptAdr(ctx, view, id, opts) {
1592
+ function acceptAdr(ctx, _view, id, opts) {
1326
1593
  assertWritable(ctx);
1327
- const adr = findAdr(view, id);
1594
+ const adr = findAdr(ctx, id);
1328
1595
  if (!adr.meta.review_rule?.trim()) throw new AdrienError("INVALID_INPUT", `${id} needs a review_rule before it can be accepted`);
1329
1596
  return write(ctx, adr, {
1330
1597
  status: "accepted",
1331
1598
  date: adr.meta.date ?? todayOf(opts)
1332
1599
  });
1333
1600
  }
1334
- function setStatus(ctx, view, id, status) {
1601
+ function setStatus(ctx, _view, id, status) {
1335
1602
  assertWritable(ctx);
1336
1603
  if (![
1337
1604
  "proposed",
1338
1605
  "rejected",
1339
1606
  "deprecated"
1340
1607
  ].includes(status)) throw new AdrienError("INVALID_INPUT", `Use \`adrien accept\` or \`adrien supersede\` to set "${status}"`);
1341
- return write(ctx, findAdr(view, id), { status });
1608
+ return write(ctx, findAdr(ctx, id), { status });
1342
1609
  }
1343
- function supersede(ctx, view, oldId, newId) {
1610
+ function supersede(ctx, _view, oldId, newId) {
1344
1611
  assertWritable(ctx);
1345
- const oldAdr = findAdr(view, oldId);
1346
- const newAdr = findAdr(view, newId);
1612
+ if (oldId === newId) throw new AdrienError("INVALID_INPUT", `${oldId} cannot supersede itself`);
1613
+ const oldAdr = findAdr(ctx, oldId);
1614
+ const newAdr = findAdr(ctx, newId);
1347
1615
  return {
1348
1616
  old: write(ctx, oldAdr, {
1349
1617
  status: "superseded",
@@ -1355,7 +1623,7 @@ function supersede(ctx, view, oldId, newId) {
1355
1623
  /** Gives a colliding ADR the next free id; references in other pending ADRs follow it, base ADRs are never touched. */
1356
1624
  function renumber(ctx, view, id, opts) {
1357
1625
  assertWritable(ctx);
1358
- const candidates = workingAdrs(view).filter((a) => a.meta.id === id);
1626
+ const candidates = readWorkingLog(ctx.logRoot, ctx.config).adrs.filter((a) => a.meta.id === id);
1359
1627
  if (candidates.length === 0) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
1360
1628
  const basePaths = new Set(view.base.filter((a) => a.meta.id === id).map((a) => a.path));
1361
1629
  const notInBase = candidates.filter((a) => !basePaths.has(a.path));
@@ -1363,6 +1631,7 @@ function renumber(ctx, view, id, opts) {
1363
1631
  if (!target) throw new AdrienError("INVALID_INPUT", `Say which file to renumber with --file: ${candidates.map((a) => a.path).join(", ")}`);
1364
1632
  const to = formatId(nextIdNumber(allIds(view), ctx.config.id_format), ctx.config.id_format);
1365
1633
  const path = posix.join(posix.dirname(target.path), `${to}-${slugify(target.meta.title)}.md`);
1634
+ const inPlace = path === target.path;
1366
1635
  writeAdr(ctx.logRoot, {
1367
1636
  ...target,
1368
1637
  path,
@@ -1370,8 +1639,8 @@ function renumber(ctx, view, id, opts) {
1370
1639
  ...target.meta,
1371
1640
  id: to
1372
1641
  }
1373
- });
1374
- unlinkSync(join(ctx.logRoot, ...target.path.split("/")));
1642
+ }, { exclusive: !inPlace });
1643
+ if (!inPlace) unlinkSync(join(ctx.logRoot, ...target.path.split("/")));
1375
1644
  const swap = (ids) => ids.map((x) => x === id ? to : x);
1376
1645
  for (const change of view.pending) {
1377
1646
  const adr = change.current;
@@ -1412,7 +1681,7 @@ async function open(cli, opts) {
1412
1681
  view: await loadLogView(ctx.logRoot, ctx.config)
1413
1682
  };
1414
1683
  }
1415
- async function withIndex$1(ctx, view, use) {
1684
+ async function withIndex$2(ctx, view, use) {
1416
1685
  const index = await AdrIndex.open(ctx.logRoot);
1417
1686
  try {
1418
1687
  index.sync(view);
@@ -1463,7 +1732,7 @@ function formatDiagnostic(d) {
1463
1732
  }
1464
1733
  // src/commands/check.ts
1465
1734
  function registerCheck(program, cli) {
1466
- program.command("check").description("Validate the ADR log (CI-ready exit code)").option("--here", "verify anchors against the code repo this runs in (use in code-repo CI)").option("--mr", "merge-request mode: fetch the default branch, warn about ADRs left \"proposed\"").option("--strict", "fail on warnings too").action(async (opts, cmd) => {
1735
+ program.command("check").description("Validate the ADR log (CI-ready exit code)").option("--here", "verify anchors against the code repo this runs in (use in code-repo CI)").option("--mr", "merge-request mode: fetch the default branch, warn about ADRs left \"proposed\"").option("--lint", "also report style warnings (see `adrien lint`)").option("--strict", "fail on warnings too").action(async (opts, cmd) => {
1467
1736
  const globals = cmd.optsWithGlobals();
1468
1737
  const ctx = await contextOf(cli, globals);
1469
1738
  if (opts.mr) {
@@ -1472,7 +1741,8 @@ function registerCheck(program, cli) {
1472
1741
  }
1473
1742
  const diags = await runCheck(ctx, await loadLogView(ctx.logRoot, ctx.config), {
1474
1743
  here: opts.here,
1475
- mr: opts.mr
1744
+ mr: opts.mr,
1745
+ lint: opts.lint
1476
1746
  });
1477
1747
  const errors = diags.filter((d) => d.severity === "error").length;
1478
1748
  const warnings = diags.filter((d) => d.severity === "warning").length;
@@ -1486,12 +1756,28 @@ function registerCheck(program, cli) {
1486
1756
  cli.out(`${errors} errors, ${warnings} warnings\n`);
1487
1757
  });
1488
1758
  }
1759
+ // src/commands/export.ts
1760
+ function registerExport(program, cli) {
1761
+ program.command("export").description("Print or write an overview of the ADRs: a markdown table, or an llms.txt").option("--format <format>", `${EXPORT_FORMATS.join(" | ")}`, "markdown").option("--out <file>", "write to this file instead of printing (links are relative to it)").action(async (opts, cmd) => {
1762
+ const format = opts.format;
1763
+ if (!EXPORT_FORMATS.includes(format)) throw new AdrienError("INVALID_INPUT", `Unknown format "${opts.format}". Use one of: ${EXPORT_FORMATS.join(", ")}`);
1764
+ const { ctx, view } = await open(cli, cmd.optsWithGlobals());
1765
+ if (!opts.out) return cli.out(exportLog(ctx, view, format));
1766
+ const file = resolve(cli.cwd, opts.out);
1767
+ const text = exportLog(ctx, view, format, { from: dirname(file) });
1768
+ mkdirSync(dirname(file), { recursive: true });
1769
+ writeFileSync(file, text);
1770
+ cli.out(`Wrote ${opts.out}\n`);
1771
+ });
1772
+ }
1489
1773
  // src/commands/for.ts
1490
1774
  function registerFor(program, cli) {
1491
1775
  program.command("for").description("Show the decisions that govern these files, and why").argument("<paths...>", "files, relative to the current directory").action(async (paths, _opts, cmd) => {
1492
1776
  const globals = cmd.optsWithGlobals();
1493
1777
  const { ctx, view } = await open(cli, globals);
1494
1778
  const files = adrsForFiles(ctx, view, paths);
1779
+ const note = unverifiedBaseNote(view);
1780
+ if (note) cli.err(`note: ${note}\n`);
1495
1781
  if (globals.json) return printJson(cli, files);
1496
1782
  cli.out(formatFileDecisions(files));
1497
1783
  });
@@ -1565,12 +1851,28 @@ function registerInit(program, cli) {
1565
1851
  if (!opts.codeRepo && !opts.agents) initLog(cli, opts);
1566
1852
  });
1567
1853
  }
1854
+ // src/commands/lint.ts
1855
+ function registerLint(program, cli) {
1856
+ program.command("lint").description("Style warnings for the ADRs: markdownlint plus Adrien rules (placeholders, empty decisions)").option("--strict", "exit 1 on warnings").action(async (opts, cmd) => {
1857
+ const globals = cmd.optsWithGlobals();
1858
+ const ctx = await contextOf(cli, globals);
1859
+ const diags = await lintAdrs(ctx, await loadLogView(ctx.logRoot, ctx.config));
1860
+ cli.setCode(exitCodeFor(diags, opts.strict));
1861
+ if (globals.json) return printJson(cli, {
1862
+ errors: 0,
1863
+ warnings: diags.length,
1864
+ diagnostics: diags
1865
+ });
1866
+ for (const d of diags) cli.out(formatDiagnostic(d));
1867
+ cli.out(`0 errors, ${diags.length} warnings\n`);
1868
+ });
1869
+ }
1568
1870
  // src/commands/list.ts
1569
1871
  function registerList(program, cli) {
1570
1872
  program.command("list").description("List ADRs (base and pending)").option("--tag <tag>", "only ADRs with this tag (repeatable: all must match)", collect, []).option("--component <id>", "only ADRs for this component (repeatable: any matches)", collect, []).option("--status <status>", "only this status (repeatable)", collect, []).option("--pending", "only pending (unmerged) changes").action(async (opts, cmd) => {
1571
1873
  const globals = cmd.optsWithGlobals();
1572
1874
  const { ctx, view } = await open(cli, globals);
1573
- const rows = await withIndex$1(ctx, view, (index) => index.list({
1875
+ const rows = await withIndex$2(ctx, view, (index) => index.list({
1574
1876
  tags: opts.tag,
1575
1877
  components: opts.component,
1576
1878
  status: opts.status,
@@ -1588,7 +1890,7 @@ const ok = (result) => ({
1588
1890
  text: JSON.stringify(result)
1589
1891
  }]
1590
1892
  });
1591
- const fail = (text) => ({
1893
+ const fail$1 = (text) => ({
1592
1894
  isError: true,
1593
1895
  content: [{
1594
1896
  type: "text",
@@ -1615,12 +1917,12 @@ function handler(opts, run) {
1615
1917
  const { ctx, view } = await load(opts);
1616
1918
  return await run(args, ctx, view);
1617
1919
  } catch (e) {
1618
- if (e instanceof AdrienError) return fail(`${e.code}: ${e.message}`);
1920
+ if (e instanceof AdrienError) return fail$1(`${e.code}: ${e.message}`);
1619
1921
  throw e;
1620
1922
  }
1621
1923
  };
1622
1924
  }
1623
- async function withIndex(ctx, view, use) {
1925
+ async function withIndex$1(ctx, view, use) {
1624
1926
  const index = await AdrIndex.open(ctx.logRoot);
1625
1927
  try {
1626
1928
  index.sync(view);
@@ -1638,9 +1940,15 @@ const section = (heading, text) => text?.trim() ? `## ${heading}\n\n${text.trim(
1638
1940
  function registerTools(server, opts) {
1639
1941
  server.registerTool("adr_for_files", {
1640
1942
  title: "Decisions governing files",
1641
- description: "Call this BEFORE editing code. For each file, returns the architecture decisions that govern it, with the review_rule to follow. binding:true means an accepted decision on the default branch; binding:false is a pending proposal or a hint.",
1943
+ description: "Call this BEFORE editing code. For each file, returns the architecture decisions that govern it, with the review_rule to follow. binding:true means an accepted decision on the default branch; binding:false is a pending proposal or a hint. If `notes` is present, read it: it says the default branch could not be found, so bindingness is unverified.",
1642
1944
  inputSchema: { paths: z.array(z.string().min(1)).min(1).max(50) }
1643
- }, handler(opts, ({ paths }, ctx, view) => ok({ files: adrsForFiles(ctx, view, paths) })));
1945
+ }, handler(opts, ({ paths }, ctx, view) => {
1946
+ const note = unverifiedBaseNote(view);
1947
+ return ok({
1948
+ files: adrsForFiles(ctx, view, paths),
1949
+ ...note ? { notes: [note] } : {}
1950
+ });
1951
+ }));
1644
1952
  server.registerTool("adr_search", {
1645
1953
  title: "Search decisions",
1646
1954
  description: "Full-text search over ADR titles, review rules and bodies. Accent-insensitive; prefix matching.",
@@ -1651,7 +1959,7 @@ function registerTools(server, opts) {
1651
1959
  status: status.optional(),
1652
1960
  limit: z.number().int().min(1).max(50).default(10)
1653
1961
  }
1654
- }, handler(opts, async (args, ctx, view) => ok({ results: await withIndex(ctx, view, (index) => index.search(args.query, {
1962
+ }, handler(opts, async (args, ctx, view) => ok({ results: await withIndex$1(ctx, view, (index) => index.search(args.query, {
1655
1963
  tags: args.tags,
1656
1964
  components: args.components,
1657
1965
  status: args.status,
@@ -1673,7 +1981,7 @@ function registerTools(server, opts) {
1673
1981
  status: args.status,
1674
1982
  layer: args.pending_only ? "pending" : "all"
1675
1983
  };
1676
- return ok({ results: await withIndex(ctx, view, (index) => index.list(filters)) });
1984
+ return ok({ results: await withIndex$1(ctx, view, (index) => index.list(filters)) });
1677
1985
  }));
1678
1986
  server.registerTool("adr_get", {
1679
1987
  title: "Read one decision",
@@ -1798,8 +2106,9 @@ function registerMcp(program, cli) {
1798
2106
  }
1799
2107
  // src/commands/new.ts
1800
2108
  function registerNew(program, cli) {
1801
- program.command("new").description("Create a proposed ADR").argument("<title>", "decision title").option("--tags <list>", "tags, comma-separated").option("--components <list>", "components, comma-separated").option("--code <component:glob>", "code it governs (repeatable)", collect, []).option("--review-rule <text>", "one checkable sentence for reviewers and agents").option("--subdir <path>", "folder inside the ADR dir").option("--force", "create even if a similar title exists").action(async (title, opts, cmd) => {
2109
+ program.command("new").description("Create a proposed ADR").argument("<title>", "decision title").option("--tags <list>", "tags, comma-separated").option("--components <list>", "components, comma-separated").option("--code <component:glob>", "code it governs (repeatable)", collect, []).option("--review-rule <text>", "one checkable sentence for reviewers and agents").option("--review-on <date>", "when to look at this decision again, as YYYY-MM-DD").option("--subdir <path>", "folder inside the ADR dir").option("--template <name>", `body skeleton: ${TEMPLATE_NAMES.join(", ")} (default: the config's template)`).option("--force", "create even if a similar title exists").action(async (title, opts, cmd) => {
1802
2110
  const globals = cmd.optsWithGlobals();
2111
+ if (opts.template && !TEMPLATE_NAMES.includes(opts.template)) throw new AdrienError("INVALID_INPUT", `Unknown template "${opts.template}". Use one of: ${TEMPLATE_NAMES.join(", ")}`);
1803
2112
  const { ctx, view } = await open(cli, globals);
1804
2113
  const result = createAdr(ctx, view, {
1805
2114
  title,
@@ -1807,7 +2116,9 @@ function registerNew(program, cli) {
1807
2116
  components: csv(opts.components),
1808
2117
  code: opts.code,
1809
2118
  review_rule: opts.reviewRule,
1810
- subdir: opts.subdir
2119
+ review_on: opts.reviewOn,
2120
+ subdir: opts.subdir,
2121
+ template: opts.template
1811
2122
  }, {
1812
2123
  today: today(),
1813
2124
  force: opts.force
@@ -1838,11 +2149,361 @@ function registerSearch(program, cli) {
1838
2149
  program.command("search").description("Full-text search over titles, review rules and bodies").argument("<query...>", "words to look for").action(async (query, _opts, cmd) => {
1839
2150
  const globals = cmd.optsWithGlobals();
1840
2151
  const { ctx, view } = await open(cli, globals);
1841
- const rows = await withIndex$1(ctx, view, (index) => index.search(query.join(" ")));
2152
+ const rows = await withIndex$2(ctx, view, (index) => index.search(query.join(" ")));
1842
2153
  if (globals.json) return printJson(cli, rows);
1843
2154
  for (const row of rows) cli.out(formatRow(row));
1844
2155
  });
1845
2156
  }
2157
+ // ../api/src/host.ts
2158
+ const LOOPBACK = /* @__PURE__ */ new Set([
2159
+ "localhost",
2160
+ "127.0.0.1",
2161
+ "::1"
2162
+ ]);
2163
+ /** The host name in a `Host` header or a bind address: lowercased, without its port or IPv6 brackets. */
2164
+ function hostnameOf(host) {
2165
+ const name = host.trim().toLowerCase();
2166
+ if (name.startsWith("[")) {
2167
+ const end = name.indexOf("]");
2168
+ return end === -1 ? name : name.slice(1, end);
2169
+ }
2170
+ const parts = name.split(":");
2171
+ return parts.length === 2 ? parts[0] : name;
2172
+ }
2173
+ /**
2174
+ * True when a request's `Host` names this machine: a loopback name, or the host the server was bound to. A web page
2175
+ * that rebinds its own domain to 127.0.0.1 still sends that domain, so it is refused.
2176
+ */
2177
+ function isAllowedHost(host, bound) {
2178
+ const name = hostnameOf(host);
2179
+ return LOOPBACK.has(name) || bound !== void 0 && bound !== "" && name === hostnameOf(bound);
2180
+ }
2181
+ // ../api/src/views.ts
2182
+ /**
2183
+ * What the default branch would hold once this checkout is merged, one ADR per id: when ids collide (which `check`
2184
+ * reports), the first by path stands for the id, so the graph never has two nodes with one id.
2185
+ */
2186
+ function mergedById(view) {
2187
+ const seen = /* @__PURE__ */ new Set();
2188
+ const adrs = [];
2189
+ for (const adr of mergedAdrs(view)) {
2190
+ if (seen.has(adr.meta.id)) continue;
2191
+ seen.add(adr.meta.id);
2192
+ adrs.push(adr);
2193
+ }
2194
+ return adrs;
2195
+ }
2196
+ function metaOf(ctx, view, version) {
2197
+ const adrs = mergedById(view);
2198
+ const byStatus = Object.fromEntries(STATUSES.map((status) => [status, 0]));
2199
+ for (const adr of adrs) byStatus[adr.meta.status]++;
2200
+ return {
2201
+ version,
2202
+ product: ctx.config.product,
2203
+ adrDir: ctx.config.adr_dir,
2204
+ mode: view.mode,
2205
+ baseRef: view.baseRef,
2206
+ baseUnresolved: view.baseUnresolved === true,
2207
+ forkUnresolved: view.forkUnresolved === true,
2208
+ tags: ctx.config.tags,
2209
+ components: ctx.config.components,
2210
+ counts: {
2211
+ total: adrs.length,
2212
+ pending: view.pending.length,
2213
+ byStatus
2214
+ }
2215
+ };
2216
+ }
2217
+ const fileOf = (adr) => ({
2218
+ meta: adr.meta,
2219
+ body: adr.body,
2220
+ path: adr.path
2221
+ });
2222
+ function adrOf(view, id) {
2223
+ const base = view.base.find((a) => a.meta.id === id);
2224
+ const change = view.pending.find((c) => c.id === id);
2225
+ if (!base && !change) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
2226
+ return {
2227
+ id,
2228
+ base: base ? fileOf(base) : null,
2229
+ pending: change ? {
2230
+ kind: change.kind,
2231
+ ...change.current ? fileOf(change.current) : {}
2232
+ } : null
2233
+ };
2234
+ }
2235
+ function graphOf(view) {
2236
+ const adrs = mergedById(view);
2237
+ const pending = new Set(view.pending.filter((c) => c.kind !== "deleted").map((c) => c.id));
2238
+ const nodes = adrs.map(({ meta }) => ({
2239
+ id: meta.id,
2240
+ title: meta.title,
2241
+ status: meta.status,
2242
+ tags: meta.tags,
2243
+ pending: pending.has(meta.id)
2244
+ }));
2245
+ const ids = new Set(nodes.map((n) => n.id));
2246
+ const seen = /* @__PURE__ */ new Set();
2247
+ const edges = [];
2248
+ const add = (from, to, type) => {
2249
+ const key = [type, ...type === "related" ? [from, to].sort() : [from, to]].join("\0");
2250
+ if (from === to || !ids.has(from) || !ids.has(to) || seen.has(key)) return;
2251
+ seen.add(key);
2252
+ edges.push({
2253
+ from,
2254
+ to,
2255
+ type
2256
+ });
2257
+ };
2258
+ for (const { meta } of adrs) {
2259
+ for (const older of meta.supersedes) add(meta.id, older, "supersedes");
2260
+ if (meta.superseded_by) add(meta.superseded_by, meta.id, "supersedes");
2261
+ for (const other of meta.related) add(meta.id, other, "related");
2262
+ }
2263
+ return {
2264
+ nodes,
2265
+ edges
2266
+ };
2267
+ }
2268
+ // ../api/src/web.ts
2269
+ const NOT_BUILT = "The Adrien web visualizer is not part of this build. The API is served at /api/meta (see docs/api.md).\n";
2270
+ /** A built web app: its real root and its index.html, which must be a file inside that root. */
2271
+ async function builtApp(webDir) {
2272
+ let root;
2273
+ try {
2274
+ root = await realpath(webDir);
2275
+ } catch {
2276
+ return null;
2277
+ }
2278
+ const index = await fileIn(root, ["index.html"]);
2279
+ return index ? {
2280
+ root,
2281
+ index
2282
+ } : null;
2283
+ }
2284
+ /**
2285
+ * The URL path as path segments, or null when one is not valid percent-encoding or could leave the web root: an
2286
+ * encoded `/` or `\`, a NUL, or a dot segment (URL parsing resolves plain `..` before it gets here).
2287
+ */
2288
+ function segmentsOf(pathname) {
2289
+ const segments = [];
2290
+ for (const raw of pathname.split("/")) {
2291
+ if (!raw) continue;
2292
+ let segment;
2293
+ try {
2294
+ segment = decodeURIComponent(raw);
2295
+ } catch {
2296
+ return null;
2297
+ }
2298
+ if (segment === "." || segment === ".." || /[/\\\0]/.test(segment)) return null;
2299
+ segments.push(segment);
2300
+ }
2301
+ return segments;
2302
+ }
2303
+ /** The file a path names, once symlinks are resolved, only if it is a regular file inside the web root. */
2304
+ async function fileIn(root, segments) {
2305
+ try {
2306
+ const real = await realpath(join(root, ...segments));
2307
+ return isInside(real, root) && (await stat(real)).isFile() ? real : null;
2308
+ } catch {
2309
+ return null;
2310
+ }
2311
+ }
2312
+ async function send(c, file) {
2313
+ const body = new Uint8Array(await readFile(file));
2314
+ return c.body(body, 200, {
2315
+ "Content-Type": getMimeType(file) ?? "application/octet-stream",
2316
+ "X-Content-Type-Options": "nosniff",
2317
+ "Cache-Control": "no-cache"
2318
+ });
2319
+ }
2320
+ /** Serves the built web visualizer, with `index.html` for client-side routes (paths without an extension). */
2321
+ function serveWeb(webDir) {
2322
+ return async (c) => {
2323
+ const app = webDir === void 0 ? null : await builtApp(webDir);
2324
+ if (!app) return c.text(NOT_BUILT, 404);
2325
+ const segments = segmentsOf(new URL(c.req.url).pathname);
2326
+ if (!segments) return c.text("Bad request path.\n", 400);
2327
+ const file = await fileIn(app.root, segments);
2328
+ if (file) return send(c, file);
2329
+ if (!(segments.at(-1) ?? "").includes(".")) return send(c, app.index);
2330
+ return c.text("Not found.\n", 404);
2331
+ };
2332
+ }
2333
+ // ../api/src/app.ts
2334
+ const HTTP_STATUS = {
2335
+ ADR_NOT_FOUND: 404,
2336
+ INVALID_INPUT: 400
2337
+ };
2338
+ const fail = (c, status, code, message) => c.json({ error: {
2339
+ code,
2340
+ message
2341
+ } }, status);
2342
+ const isApi = (path) => path === "/api" || path.startsWith("/api/");
2343
+ const flag = (value) => value === "1" || value === "true";
2344
+ /** A repeatable query parameter, without empty values. */
2345
+ const all = (c, name) => (c.req.queries(name) ?? []).filter(Boolean);
2346
+ async function withIndex(ctx, view, use) {
2347
+ const index = await AdrIndex.open(ctx.logRoot);
2348
+ try {
2349
+ index.sync(view);
2350
+ return use(index);
2351
+ } finally {
2352
+ index.close();
2353
+ }
2354
+ }
2355
+ /** The read-only HTTP API of docs/api.md, and the web visualizer's files. Every request re-reads the log. */
2356
+ function createApp(opts) {
2357
+ const app = new Hono();
2358
+ const load = async () => {
2359
+ const ctx = await resolveContext({
2360
+ cwd: opts.cwd,
2361
+ log: opts.log,
2362
+ env: opts.env ?? process.env
2363
+ });
2364
+ return {
2365
+ ctx,
2366
+ view: await loadLogView(ctx.logRoot, ctx.config)
2367
+ };
2368
+ };
2369
+ app.use(async (c, next) => {
2370
+ await next();
2371
+ if (isApi(c.req.path)) c.header("Cache-Control", "no-store");
2372
+ });
2373
+ app.use(async (c, next) => {
2374
+ const host = c.req.header("host") ?? new URL(c.req.url).host;
2375
+ if (!isAllowedHost(host, opts.host)) return fail(c, 403, "FORBIDDEN_HOST", `Requests for host "${host}" are refused: open the URL adrien serve printed.`);
2376
+ if (c.req.method !== "GET" && c.req.method !== "HEAD") {
2377
+ c.header("Allow", "GET, HEAD");
2378
+ return fail(c, 405, "METHOD_NOT_ALLOWED", "This API is read-only: only GET and HEAD are served.");
2379
+ }
2380
+ await next();
2381
+ });
2382
+ app.get("/api/meta", async (c) => {
2383
+ const { ctx, view } = await load();
2384
+ return c.json(metaOf(ctx, view, opts.version ?? "0.0.0"));
2385
+ });
2386
+ app.get("/api/adrs", async (c) => {
2387
+ const status = all(c, "status");
2388
+ const unknown = status.filter((s) => !STATUSES.includes(s));
2389
+ if (unknown.length) throw new AdrienError("INVALID_INPUT", `Unknown status ${unknown.join(", ")}. Use: ${STATUSES.join(", ")}`);
2390
+ const filters = {
2391
+ tags: all(c, "tag"),
2392
+ components: all(c, "component"),
2393
+ status,
2394
+ layer: flag(c.req.query("pending")) ? "pending" : "all"
2395
+ };
2396
+ const q = c.req.query("q")?.trim();
2397
+ const { ctx, view } = await load();
2398
+ const limit = view.base.length + view.pending.length;
2399
+ const results = await withIndex(ctx, view, (index) => q ? index.search(q, filters, limit) : index.list(filters));
2400
+ return c.json({ results });
2401
+ });
2402
+ app.get("/api/adrs/:id", async (c) => {
2403
+ const { view } = await load();
2404
+ return c.json(adrOf(view, c.req.param("id")));
2405
+ });
2406
+ app.get("/api/graph", async (c) => {
2407
+ const { view } = await load();
2408
+ return c.json(graphOf(view));
2409
+ });
2410
+ app.get("/api/for", async (c) => {
2411
+ const paths = all(c, "path");
2412
+ if (!paths.length) throw new AdrienError("INVALID_INPUT", "Give at least one file: /api/for?path=src/a.ts");
2413
+ const { ctx, view } = await load();
2414
+ const note = unverifiedBaseNote(view);
2415
+ return c.json({
2416
+ files: adrsForFiles(ctx, view, paths),
2417
+ ...note ? { notes: [note] } : {}
2418
+ });
2419
+ });
2420
+ app.get("/api/check", async (c) => {
2421
+ const { ctx, view } = await load();
2422
+ const diagnostics = await runCheck(ctx, view, { lint: flag(c.req.query("lint")) });
2423
+ return c.json({
2424
+ errors: diagnostics.filter((d) => d.severity === "error").length,
2425
+ warnings: diagnostics.filter((d) => d.severity === "warning").length,
2426
+ diagnostics
2427
+ });
2428
+ });
2429
+ app.get("/api/export", async (c) => {
2430
+ const format = c.req.query("format") ?? "markdown";
2431
+ if (!EXPORT_FORMATS.includes(format)) throw new AdrienError("INVALID_INPUT", `Unknown format "${format}". Use one of: ${EXPORT_FORMATS.join(", ")}`);
2432
+ const { ctx, view } = await load();
2433
+ return c.text(exportLog(ctx, view, format));
2434
+ });
2435
+ const web = serveWeb(opts.webDir);
2436
+ app.get("*", (c) => isApi(c.req.path) ? c.notFound() : web(c));
2437
+ app.notFound((c) => fail(c, 404, "NOT_FOUND", `No endpoint at ${c.req.path} (see docs/api.md).`));
2438
+ app.onError((e, c) => {
2439
+ if (e instanceof AdrienError) return fail(c, HTTP_STATUS[e.code] ?? 500, e.code, e.message);
2440
+ return fail(c, 500, "INTERNAL_ERROR", e.message);
2441
+ });
2442
+ return app;
2443
+ }
2444
+ // ../api/src/server.ts
2445
+ const DEFAULT_HOST = "127.0.0.1";
2446
+ const DEFAULT_PORT = 4310;
2447
+ function closeServer(server) {
2448
+ return new Promise((resolve) => {
2449
+ server.close(() => resolve());
2450
+ server.closeAllConnections();
2451
+ });
2452
+ }
2453
+ /** Listens on `host:port` (default 127.0.0.1:4310) and resolves once the socket is bound. */
2454
+ function startServer(opts) {
2455
+ const host = hostnameOf(opts.host ?? "127.0.0.1");
2456
+ const app = createApp({
2457
+ ...opts,
2458
+ host
2459
+ });
2460
+ return new Promise((resolve, reject) => {
2461
+ const server = serve({
2462
+ fetch: app.fetch,
2463
+ hostname: host,
2464
+ port: opts.port ?? 4310
2465
+ }, (info) => {
2466
+ server.off("error", reject);
2467
+ resolve({
2468
+ url: `http://${host.includes(":") ? `[${host}]` : host}:${info.port}`,
2469
+ address: info.address,
2470
+ port: info.port,
2471
+ close: () => closeServer(server)
2472
+ });
2473
+ });
2474
+ server.once("error", reject);
2475
+ });
2476
+ }
2477
+ // src/commands/serve.ts
2478
+ const LISTEN_ERRORS = /* @__PURE__ */ new Set([
2479
+ "EADDRINUSE",
2480
+ "EADDRNOTAVAIL",
2481
+ "EACCES",
2482
+ "ENOTFOUND"
2483
+ ]);
2484
+ function port(value) {
2485
+ if (!/^\d+$/.test(value) || Number(value) > 65535) throw new InvalidArgumentError("Use a port from 0 to 65535 (0 picks a free one).");
2486
+ return Number(value);
2487
+ }
2488
+ function registerServe(program, cli) {
2489
+ program.command("serve").description("Serve the read-only HTTP API and the web visualizer on this machine").option("--port <n>", "port to listen on (0 picks a free one)", port, DEFAULT_PORT).option("--host <host>", "address to bind; requests must name it or a loopback name", DEFAULT_HOST).action(async (opts, cmd) => {
2490
+ const { log } = cmd.optsWithGlobals();
2491
+ const ctx = await contextOf(cli, { log });
2492
+ const server = await startServer({
2493
+ cwd: cli.cwd,
2494
+ log,
2495
+ env: cli.env,
2496
+ version: program.version(),
2497
+ host: opts.host,
2498
+ port: opts.port,
2499
+ webDir: fileURLToPath(new URL("./web", import.meta.url))
2500
+ }).catch((e) => {
2501
+ if (!LISTEN_ERRORS.has(e.code ?? "")) throw e;
2502
+ throw new AdrienError("INVALID_INPUT", `Cannot listen on ${opts.host}:${opts.port}: ${e.message}`);
2503
+ });
2504
+ cli.out(`Adrien serving ${ctx.config.product} at ${server.url}\n`);
2505
+ });
2506
+ }
1846
2507
  // src/commands/show.ts
1847
2508
  function registerShow(program, cli) {
1848
2509
  program.command("show").description("Print an ADR, with its pending change if any").argument("<id>", "ADR id").action(async (id, _opts, cmd) => {
@@ -1932,12 +2593,15 @@ function buildProgram(cli) {
1932
2593
  registerSearch,
1933
2594
  registerFor,
1934
2595
  registerCheck,
2596
+ registerLint,
1935
2597
  registerAccept,
1936
2598
  registerStatus,
1937
2599
  registerSupersede,
1938
2600
  registerRenumber,
1939
2601
  registerSync,
1940
- registerMcp
2602
+ registerExport,
2603
+ registerMcp,
2604
+ registerServe
1941
2605
  ]) register(program, cli);
1942
2606
  return program;
1943
2607
  }