adrien 0.0.0-stage → 0.1.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/LICENSE +661 -0
- package/README.md +92 -2
- package/dist/index.js +2301 -0
- package/package.json +45 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2301 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import picomatch from "picomatch";
|
|
4
|
+
import { basename, dirname, isAbsolute, join, posix, relative, resolve } from "node:path";
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import YAML, { visit } from "yaml";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { execFile, spawn } from "node:child_process";
|
|
10
|
+
import { promisify } from "node:util";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { Command, CommanderError } from "commander";
|
|
14
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
15
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
16
|
+
// ../core/src/anchors.ts
|
|
17
|
+
function parseAnchor(s) {
|
|
18
|
+
const i = s.indexOf(":");
|
|
19
|
+
if (i <= 0 || i === s.length - 1) return null;
|
|
20
|
+
return {
|
|
21
|
+
component: s.slice(0, i),
|
|
22
|
+
glob: s.slice(i + 1)
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
const matchers = /* @__PURE__ */ new Map();
|
|
26
|
+
function anchorMatches(anchor, component, relPath) {
|
|
27
|
+
if (anchor.component !== component) return false;
|
|
28
|
+
let match = matchers.get(anchor.glob);
|
|
29
|
+
if (!match) {
|
|
30
|
+
match = picomatch(anchor.glob, { dot: true });
|
|
31
|
+
matchers.set(anchor.glob, match);
|
|
32
|
+
}
|
|
33
|
+
return match(relPath);
|
|
34
|
+
}
|
|
35
|
+
function section$1(body, heading) {
|
|
36
|
+
return new RegExp(`^##\\s+${heading}\\s*$([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))`, "im").exec(body)?.[1]?.trim() || null;
|
|
37
|
+
}
|
|
38
|
+
function firstParagraph(body) {
|
|
39
|
+
return body.split(/\n\s*\n/).map((p) => p.trim()).find((p) => p && !p.startsWith("#")) ?? "";
|
|
40
|
+
}
|
|
41
|
+
/** Why an ADR exists, in a few lines: its Rationale, else its Decision (or MADR's Decision Outcome), else its first paragraph. */
|
|
42
|
+
function excerpt(adr, max = 600) {
|
|
43
|
+
const text = section$1(adr.body, "Rationale") ?? section$1(adr.body, "Decision Outcome") ?? section$1(adr.body, "Decision") ?? firstParagraph(adr.body);
|
|
44
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
45
|
+
}
|
|
46
|
+
// ../core/src/errors.ts
|
|
47
|
+
/** An expected failure: the CLI prints its message without a stack trace. */
|
|
48
|
+
var AdrienError = class extends Error {
|
|
49
|
+
code;
|
|
50
|
+
constructor(code, message) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = "AdrienError";
|
|
53
|
+
this.code = code;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
// ../core/src/ids.ts
|
|
57
|
+
/** Parses an id format such as `ADR-{n:4}`; `{n}` means no padding. */
|
|
58
|
+
function parseIdFormat(fmt) {
|
|
59
|
+
const m = /^(.*)\{n(?::(\d+))?\}(.*)$/.exec(fmt);
|
|
60
|
+
if (!m) throw new AdrienError("CONFIG_INVALID", `id_format "${fmt}" must contain {n} or {n:WIDTH}`);
|
|
61
|
+
return {
|
|
62
|
+
prefix: m[1] ?? "",
|
|
63
|
+
width: m[2] ? Number(m[2]) : 1,
|
|
64
|
+
suffix: m[3] ?? ""
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function formatId(n, fmt) {
|
|
68
|
+
const { prefix, width, suffix } = parseIdFormat(fmt);
|
|
69
|
+
return `${prefix}${String(n).padStart(width, "0")}${suffix}`;
|
|
70
|
+
}
|
|
71
|
+
function idNumber(id, fmt) {
|
|
72
|
+
const { prefix, suffix } = parseIdFormat(fmt);
|
|
73
|
+
if (!id.startsWith(prefix) || !id.endsWith(suffix)) return null;
|
|
74
|
+
const digits = id.slice(prefix.length, id.length - suffix.length);
|
|
75
|
+
return /^\d+$/.test(digits) ? Number(digits) : null;
|
|
76
|
+
}
|
|
77
|
+
function nextIdNumber(ids, fmt) {
|
|
78
|
+
let max = 0;
|
|
79
|
+
for (const id of ids) max = Math.max(max, idNumber(id, fmt) ?? 0);
|
|
80
|
+
return max + 1;
|
|
81
|
+
}
|
|
82
|
+
// ../core/src/model.ts
|
|
83
|
+
const STATUSES = [
|
|
84
|
+
"proposed",
|
|
85
|
+
"accepted",
|
|
86
|
+
"rejected",
|
|
87
|
+
"superseded",
|
|
88
|
+
"deprecated"
|
|
89
|
+
];
|
|
90
|
+
/** Body skeletons `adrien new` can start from. `standard` is Adrien's own; `madr` follows MADR 4's section names. */
|
|
91
|
+
const TEMPLATE_NAMES = [
|
|
92
|
+
"standard",
|
|
93
|
+
"minimal",
|
|
94
|
+
"madr"
|
|
95
|
+
];
|
|
96
|
+
const ORIGINS = [
|
|
97
|
+
"manual",
|
|
98
|
+
"agent",
|
|
99
|
+
"mined"
|
|
100
|
+
];
|
|
101
|
+
/** The frontmatter keys Adrien owns, in the order they are written. */
|
|
102
|
+
const META_KEYS = [
|
|
103
|
+
"id",
|
|
104
|
+
"title",
|
|
105
|
+
"status",
|
|
106
|
+
"date",
|
|
107
|
+
"review_on",
|
|
108
|
+
"tags",
|
|
109
|
+
"components",
|
|
110
|
+
"code",
|
|
111
|
+
"review_rule",
|
|
112
|
+
"sources",
|
|
113
|
+
"supersedes",
|
|
114
|
+
"superseded_by",
|
|
115
|
+
"related",
|
|
116
|
+
"deciders",
|
|
117
|
+
"origin",
|
|
118
|
+
"contested"
|
|
119
|
+
];
|
|
120
|
+
const stringList = z.array(z.string()).default([]);
|
|
121
|
+
const adrMetaSchema = z.object({
|
|
122
|
+
id: z.string().min(1),
|
|
123
|
+
title: z.string().min(1),
|
|
124
|
+
status: z.enum(STATUSES),
|
|
125
|
+
date: z.string().optional(),
|
|
126
|
+
review_on: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "must be a date like 2027-03-04").optional(),
|
|
127
|
+
tags: stringList,
|
|
128
|
+
components: stringList,
|
|
129
|
+
code: stringList,
|
|
130
|
+
review_rule: z.string().optional(),
|
|
131
|
+
sources: stringList,
|
|
132
|
+
supersedes: stringList,
|
|
133
|
+
superseded_by: z.string().optional(),
|
|
134
|
+
related: stringList,
|
|
135
|
+
deciders: stringList,
|
|
136
|
+
origin: z.enum(ORIGINS).default("manual"),
|
|
137
|
+
contested: z.boolean().default(false)
|
|
138
|
+
});
|
|
139
|
+
// ../core/src/config.ts
|
|
140
|
+
const CONFIG_FILE = "adrien.config.yaml";
|
|
141
|
+
const CODE_CONFIG_FILE = ".adrien.yaml";
|
|
142
|
+
const DEFAULT_TAGS = [
|
|
143
|
+
"frontend",
|
|
144
|
+
"backend",
|
|
145
|
+
"database",
|
|
146
|
+
"infra",
|
|
147
|
+
"security"
|
|
148
|
+
];
|
|
149
|
+
const ID = /^[a-z0-9][a-z0-9._-]*$/;
|
|
150
|
+
const idMessage = "must be lowercase letters, digits, \".\", \"_\" or \"-\" (no \":\")";
|
|
151
|
+
const componentDef = z.preprocess((v) => v ?? {}, z.strictObject({
|
|
152
|
+
repo: z.string().min(1).optional(),
|
|
153
|
+
root: z.string().optional()
|
|
154
|
+
}));
|
|
155
|
+
const logConfigSchema = z.strictObject({
|
|
156
|
+
product: z.string().min(1),
|
|
157
|
+
adr_dir: z.string().min(1).default("docs/adr"),
|
|
158
|
+
id_format: z.string().default("ADR-{n:4}"),
|
|
159
|
+
template: z.enum(TEMPLATE_NAMES).default("standard"),
|
|
160
|
+
tags: z.array(z.string().regex(ID, idMessage)).default([]),
|
|
161
|
+
components: z.record(z.string(), componentDef).default({}),
|
|
162
|
+
lint: z.strictObject({ markdownlint: z.record(z.string(), z.unknown()).default({}) }).optional()
|
|
163
|
+
});
|
|
164
|
+
const codeRepoSchema = z.strictObject({
|
|
165
|
+
log: z.string().min(1),
|
|
166
|
+
components: z.array(z.string().regex(ID, idMessage)).optional()
|
|
167
|
+
});
|
|
168
|
+
function readYamlFile(file) {
|
|
169
|
+
try {
|
|
170
|
+
return YAML.parse(readFileSync(file, "utf8")) ?? {};
|
|
171
|
+
} catch (e) {
|
|
172
|
+
throw new AdrienError("CONFIG_INVALID", `${file}: invalid YAML (${e.message.split("\n")[0]})`);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
function validate(schema, data, file) {
|
|
176
|
+
const parsed = schema.safeParse(data);
|
|
177
|
+
if (parsed.success) return parsed.data;
|
|
178
|
+
const issue = parsed.error.issues[0];
|
|
179
|
+
throw new AdrienError("CONFIG_INVALID", `${file}: ${issue?.path.join(".") || "config"}: ${issue?.message}`);
|
|
180
|
+
}
|
|
181
|
+
/** Parses and validates the text of an `adrien.config.yaml`; `label` names it in error messages. */
|
|
182
|
+
function parseLogConfigText(text, label) {
|
|
183
|
+
let data;
|
|
184
|
+
try {
|
|
185
|
+
data = YAML.parse(text) ?? {};
|
|
186
|
+
} catch (e) {
|
|
187
|
+
throw new AdrienError("CONFIG_INVALID", `${label}: invalid YAML (${e.message.split("\n")[0]})`);
|
|
188
|
+
}
|
|
189
|
+
const config = validate(logConfigSchema, data, label);
|
|
190
|
+
for (const id of Object.keys(config.components)) if (!ID.test(id)) throw new AdrienError("CONFIG_INVALID", `${label}: component "${id}" ${idMessage}`);
|
|
191
|
+
parseIdFormat(config.id_format);
|
|
192
|
+
return config;
|
|
193
|
+
}
|
|
194
|
+
function loadLogConfig(logRoot) {
|
|
195
|
+
const file = join(logRoot, CONFIG_FILE);
|
|
196
|
+
if (!existsSync(file)) throw new AdrienError("CONFIG_NOT_FOUND", `No ${CONFIG_FILE} in ${logRoot}`);
|
|
197
|
+
return parseLogConfigText(readFileSync(file, "utf8"), file);
|
|
198
|
+
}
|
|
199
|
+
function writeNew(file, data) {
|
|
200
|
+
if (existsSync(file)) throw new AdrienError("CONFIG_EXISTS", `${file} already exists`);
|
|
201
|
+
writeFileSync(file, YAML.stringify(data));
|
|
202
|
+
}
|
|
203
|
+
function writeLogConfig(logRoot, config) {
|
|
204
|
+
writeNew(join(logRoot, CONFIG_FILE), config);
|
|
205
|
+
}
|
|
206
|
+
function loadCodeRepoConfig(dir) {
|
|
207
|
+
const file = join(dir, CODE_CONFIG_FILE);
|
|
208
|
+
return existsSync(file) ? validate(codeRepoSchema, readYamlFile(file), file) : null;
|
|
209
|
+
}
|
|
210
|
+
function writeCodeRepoConfig(dir, config) {
|
|
211
|
+
writeNew(join(dir, CODE_CONFIG_FILE), config);
|
|
212
|
+
}
|
|
213
|
+
/** The closest directory at or above `startDir` that contains `fileName`. */
|
|
214
|
+
function findUp(startDir, fileName) {
|
|
215
|
+
let dir = resolve(startDir);
|
|
216
|
+
for (;;) {
|
|
217
|
+
if (existsSync(join(dir, fileName))) return dir;
|
|
218
|
+
const parent = dirname(dir);
|
|
219
|
+
if (parent === dir) return null;
|
|
220
|
+
dir = parent;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// ../core/src/frontmatter.ts
|
|
224
|
+
const TEMPLATES = {
|
|
225
|
+
standard: [
|
|
226
|
+
["## Context"],
|
|
227
|
+
["## Considered options"],
|
|
228
|
+
["## Decision"],
|
|
229
|
+
["## Rationale"],
|
|
230
|
+
["## Consequences"]
|
|
231
|
+
],
|
|
232
|
+
minimal: [
|
|
233
|
+
["## Context"],
|
|
234
|
+
["## Decision"],
|
|
235
|
+
["## Consequences"]
|
|
236
|
+
],
|
|
237
|
+
madr: [
|
|
238
|
+
["## Context and Problem Statement"],
|
|
239
|
+
["## Decision Drivers"],
|
|
240
|
+
["## Considered Options"],
|
|
241
|
+
[
|
|
242
|
+
"## Decision Outcome",
|
|
243
|
+
"### Consequences",
|
|
244
|
+
"### Confirmation"
|
|
245
|
+
],
|
|
246
|
+
["## Pros and Cons of the Options"],
|
|
247
|
+
["## More Information"]
|
|
248
|
+
]
|
|
249
|
+
};
|
|
250
|
+
/** An empty skeleton: the headings only, each followed by a blank line, so it lints clean until it is filled in. */
|
|
251
|
+
function bodyTemplate(name = "standard") {
|
|
252
|
+
return `\n${TEMPLATES[name].map((headings) => headings.join("\n\n")).join("\n\n")}\n`;
|
|
253
|
+
}
|
|
254
|
+
bodyTemplate("standard");
|
|
255
|
+
const FRONTMATTER = /^---\n([\s\S]*?\n)?---[ \t]*(?:\n|$)/;
|
|
256
|
+
const FILE_NUMBER = /^(?:ADR-)?(\d+)-/i;
|
|
257
|
+
const metaKeys = new Set(META_KEYS);
|
|
258
|
+
function splitFrontmatter(text) {
|
|
259
|
+
const m = FRONTMATTER.exec(text);
|
|
260
|
+
if (!m) return {
|
|
261
|
+
yaml: null,
|
|
262
|
+
body: text
|
|
263
|
+
};
|
|
264
|
+
return {
|
|
265
|
+
yaml: m[1] ?? "",
|
|
266
|
+
body: text.slice(m[0].length)
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/** `Superseded by [3. …](…)` → superseded; `Accepted` → accepted; anything else → null. */
|
|
270
|
+
function normalizeStatus(raw) {
|
|
271
|
+
const s = raw.trim().toLowerCase();
|
|
272
|
+
if (s.startsWith("superseded")) return "superseded";
|
|
273
|
+
const word = /^[a-z]+/.exec(s)?.[0];
|
|
274
|
+
return word && STATUSES.includes(word) ? word : null;
|
|
275
|
+
}
|
|
276
|
+
function statusFromBody(body) {
|
|
277
|
+
const section = /^##\s+Status\s*\n+\s*(\S[^\n]*)/im.exec(body)?.[1];
|
|
278
|
+
if (section) return normalizeStatus(section);
|
|
279
|
+
const bullet = /^[*-]\s+Status:\s*(\S[^\n]*)/im.exec(body)?.[1];
|
|
280
|
+
return bullet ? normalizeStatus(bullet) : null;
|
|
281
|
+
}
|
|
282
|
+
function titleFromBody(body) {
|
|
283
|
+
return (/^#\s+(.+)$/m.exec(body)?.[1])?.replace(/^\d+\.\s*/, "").trim();
|
|
284
|
+
}
|
|
285
|
+
function parseError(path, message) {
|
|
286
|
+
return new AdrienError("PARSE_ERROR", `${path}: ${message}`);
|
|
287
|
+
}
|
|
288
|
+
function readYaml(yaml, path) {
|
|
289
|
+
let data;
|
|
290
|
+
try {
|
|
291
|
+
data = YAML.parse(yaml);
|
|
292
|
+
} catch (e) {
|
|
293
|
+
throw parseError(path, `invalid YAML frontmatter (${e.message.split("\n")[0]})`);
|
|
294
|
+
}
|
|
295
|
+
if (data == null) return {};
|
|
296
|
+
if (typeof data !== "object" || Array.isArray(data)) throw parseError(path, "frontmatter must be a mapping");
|
|
297
|
+
return data;
|
|
298
|
+
}
|
|
299
|
+
function parseAdr(text, path, opts) {
|
|
300
|
+
const { yaml, body } = splitFrontmatter(text.replace(/\r\n/g, "\n"));
|
|
301
|
+
const data = yaml === null ? {} : readYaml(yaml, path);
|
|
302
|
+
const fileNumber = FILE_NUMBER.exec(basename(path))?.[1];
|
|
303
|
+
const id = data.id ?? (fileNumber ? formatId(Number(fileNumber), opts.idFormat) : void 0);
|
|
304
|
+
if (id === void 0) throw parseError(path, "no `id` in frontmatter and no number in the file name");
|
|
305
|
+
let status = statusFromBody(body) ?? "proposed";
|
|
306
|
+
if (data.status !== void 0) {
|
|
307
|
+
status = normalizeStatus(String(data.status));
|
|
308
|
+
if (!status) throw parseError(path, `status "${String(data.status)}" must be one of ${STATUSES.join(", ")}`);
|
|
309
|
+
}
|
|
310
|
+
const known = {};
|
|
311
|
+
const extra = {};
|
|
312
|
+
for (const [k, v] of Object.entries(data)) (metaKeys.has(k) ? known : extra)[k] = v;
|
|
313
|
+
const parsed = adrMetaSchema.safeParse({
|
|
314
|
+
...known,
|
|
315
|
+
id: String(id),
|
|
316
|
+
title: data.title ?? titleFromBody(body),
|
|
317
|
+
status
|
|
318
|
+
});
|
|
319
|
+
if (!parsed.success) {
|
|
320
|
+
const issue = parsed.error.issues[0];
|
|
321
|
+
throw parseError(path, `${issue?.path.join(".") || "frontmatter"}: ${issue?.message}`);
|
|
322
|
+
}
|
|
323
|
+
return {
|
|
324
|
+
meta: {
|
|
325
|
+
...parsed.data,
|
|
326
|
+
extra
|
|
327
|
+
},
|
|
328
|
+
body,
|
|
329
|
+
path
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function isAdrFile(text, fileName) {
|
|
333
|
+
if (FILE_NUMBER.test(fileName)) return true;
|
|
334
|
+
const { yaml } = splitFrontmatter(text.replace(/\r\n/g, "\n"));
|
|
335
|
+
return yaml !== null && /^id:\s*\S/m.test(yaml);
|
|
336
|
+
}
|
|
337
|
+
function serializeAdr(adr) {
|
|
338
|
+
const { meta } = adr;
|
|
339
|
+
const out = {};
|
|
340
|
+
for (const key of META_KEYS) {
|
|
341
|
+
const value = meta[key];
|
|
342
|
+
if (value === void 0 || Array.isArray(value) && value.length === 0) continue;
|
|
343
|
+
if (key === "origin" && value === "manual") continue;
|
|
344
|
+
if (key === "contested" && value === false) continue;
|
|
345
|
+
out[key] = value;
|
|
346
|
+
}
|
|
347
|
+
for (const [k, v] of Object.entries(meta.extra)) if (!(k in out)) out[k] = v;
|
|
348
|
+
const doc = new YAML.Document(out);
|
|
349
|
+
visit(doc, { Seq(_, node) {
|
|
350
|
+
node.flow = true;
|
|
351
|
+
} });
|
|
352
|
+
return `---\n${doc.toString({
|
|
353
|
+
lineWidth: 0,
|
|
354
|
+
flowCollectionPadding: false
|
|
355
|
+
})}---\n${adr.body}`;
|
|
356
|
+
}
|
|
357
|
+
// ../core/src/paths.ts
|
|
358
|
+
/**
|
|
359
|
+
* The physical path: symlinks, Windows 8.3 short names (`RUNNER~1`) and drive-letter case resolved. Git reports paths
|
|
360
|
+
* this way, so every path node compares with one of git's goes through here first.
|
|
361
|
+
*/
|
|
362
|
+
function canonicalPath(path) {
|
|
363
|
+
try {
|
|
364
|
+
return realpathSync.native(path);
|
|
365
|
+
} catch {
|
|
366
|
+
return path;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** True when `child` is `parent` or lies below it. */
|
|
370
|
+
function isInside(child, parent) {
|
|
371
|
+
const rel = relative(parent, child);
|
|
372
|
+
return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
|
|
373
|
+
}
|
|
374
|
+
// ../core/src/slug.ts
|
|
375
|
+
const MAX_SLUG = 60;
|
|
376
|
+
function normalizeTitle(s) {
|
|
377
|
+
return s.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
|
378
|
+
}
|
|
379
|
+
function slugify(s) {
|
|
380
|
+
return normalizeTitle(s).replace(/ /g, "-").slice(0, MAX_SLUG).replace(/-+$/, "");
|
|
381
|
+
}
|
|
382
|
+
// ../core/src/log.ts
|
|
383
|
+
const toPosix = (p) => p.replace(/\\/g, "/");
|
|
384
|
+
/** Parses candidate files; a broken file becomes a problem instead of hiding the rest of the log. */
|
|
385
|
+
function parseLogFiles(files, config) {
|
|
386
|
+
const adrs = [];
|
|
387
|
+
const problems = [];
|
|
388
|
+
for (const { path, text } of files) {
|
|
389
|
+
if (!isAdrFile(text, posix.basename(path))) continue;
|
|
390
|
+
try {
|
|
391
|
+
adrs.push(parseAdr(text, path, { idFormat: config.id_format }));
|
|
392
|
+
} catch (e) {
|
|
393
|
+
if (!(e instanceof AdrienError) || e.code !== "PARSE_ERROR") throw e;
|
|
394
|
+
problems.push({
|
|
395
|
+
path,
|
|
396
|
+
message: e.message
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
401
|
+
adrs,
|
|
402
|
+
problems
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
function readWorkingLog(logRoot, config) {
|
|
406
|
+
const adrDir = join(logRoot, config.adr_dir);
|
|
407
|
+
if (!existsSync(adrDir)) return {
|
|
408
|
+
adrs: [],
|
|
409
|
+
problems: []
|
|
410
|
+
};
|
|
411
|
+
return parseLogFiles(readdirSync(adrDir, {
|
|
412
|
+
recursive: true,
|
|
413
|
+
encoding: "utf8"
|
|
414
|
+
}).map(toPosix).filter((rel) => rel.endsWith(".md")).sort().map((rel) => ({
|
|
415
|
+
path: posix.join(toPosix(config.adr_dir), rel),
|
|
416
|
+
text: readFileSync(join(adrDir, rel), "utf8")
|
|
417
|
+
})), config);
|
|
418
|
+
}
|
|
419
|
+
function adrFilePath(config, id, title, subdir) {
|
|
420
|
+
const adrDir = posix.join(toPosix(config.adr_dir));
|
|
421
|
+
const dir = posix.join(adrDir, toPosix(subdir ?? ""));
|
|
422
|
+
const inside = posix.relative(adrDir, dir);
|
|
423
|
+
if (inside === ".." || inside.startsWith("../")) throw new AdrienError("INVALID_INPUT", `--subdir "${subdir}" leaves the ADR directory (${config.adr_dir}).`);
|
|
424
|
+
const file = posix.join(dir, `${id}-${slugify(title)}.md`);
|
|
425
|
+
const filePart = posix.relative(adrDir, file);
|
|
426
|
+
if (filePart === ".." || filePart.startsWith("../")) throw new AdrienError("INVALID_INPUT", `The id "${id}" would place ${file} outside the ADR directory (${config.adr_dir}).`);
|
|
427
|
+
return file;
|
|
428
|
+
}
|
|
429
|
+
/** Refuses a destination that leaves the log, lexically or through a symlink (whether the file or a folder above it). */
|
|
430
|
+
function assertInsideLog(logRoot, file, adrPath) {
|
|
431
|
+
const root = canonicalPath(logRoot);
|
|
432
|
+
const outside = (where) => new AdrienError("INVALID_INPUT", `${adrPath} resolves outside the log (${where}); refusing to write it.`);
|
|
433
|
+
if (!isInside(file, logRoot)) throw outside(file);
|
|
434
|
+
if (lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) {
|
|
435
|
+
const real = canonicalPath(file);
|
|
436
|
+
if (real === file || !isInside(real, root)) throw outside(real);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
let probe = file;
|
|
440
|
+
while (!existsSync(probe) && dirname(probe) !== probe) probe = dirname(probe);
|
|
441
|
+
const real = canonicalPath(probe);
|
|
442
|
+
if (!isInside(real, root)) throw outside(real);
|
|
443
|
+
}
|
|
444
|
+
/** `exclusive` refuses to replace an existing file, so creating an ADR can never overwrite another one. */
|
|
445
|
+
function writeAdr(logRoot, adr, opts = {}) {
|
|
446
|
+
const file = join(logRoot, ...adr.path.split("/"));
|
|
447
|
+
assertInsideLog(logRoot, file, adr.path);
|
|
448
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
449
|
+
try {
|
|
450
|
+
writeFileSync(file, serializeAdr(adr), { flag: opts.exclusive ? "wx" : "w" });
|
|
451
|
+
} catch (e) {
|
|
452
|
+
if (e.code === "EEXIST") throw new AdrienError("INVALID_INPUT", `${adr.path} already exists; refusing to overwrite it.`);
|
|
453
|
+
throw e;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
// ../core/src/git.ts
|
|
457
|
+
const execFileAsync = promisify(execFile);
|
|
458
|
+
const MAX_BUFFER = 268435456;
|
|
459
|
+
/** Runs git; resolves stdout, or null when git fails (not a repo, unknown ref, offline…). */
|
|
460
|
+
async function git(cwd, args) {
|
|
461
|
+
try {
|
|
462
|
+
const { stdout } = await execFileAsync("git", args, {
|
|
463
|
+
cwd,
|
|
464
|
+
maxBuffer: MAX_BUFFER,
|
|
465
|
+
encoding: "utf8"
|
|
466
|
+
});
|
|
467
|
+
return stdout;
|
|
468
|
+
} catch {
|
|
469
|
+
return null;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
async function gitToplevel(dir) {
|
|
473
|
+
if (!existsSync(dir)) return null;
|
|
474
|
+
const out = await git(dir, ["rev-parse", "--show-toplevel"]);
|
|
475
|
+
return out ? canonicalPath(resolve(out.trim())) : null;
|
|
476
|
+
}
|
|
477
|
+
async function isCommit(repoDir, ref) {
|
|
478
|
+
return await git(repoDir, [
|
|
479
|
+
"rev-parse",
|
|
480
|
+
"--verify",
|
|
481
|
+
"-q",
|
|
482
|
+
"--end-of-options",
|
|
483
|
+
`${ref}^{commit}`
|
|
484
|
+
]) !== null;
|
|
485
|
+
}
|
|
486
|
+
/** The ref that holds the binding version of the log: origin's default branch, else a local main/master. */
|
|
487
|
+
async function resolveBaseRef(repoDir) {
|
|
488
|
+
const candidates = [
|
|
489
|
+
(await git(repoDir, [
|
|
490
|
+
"symbolic-ref",
|
|
491
|
+
"-q",
|
|
492
|
+
"--short",
|
|
493
|
+
"refs/remotes/origin/HEAD"
|
|
494
|
+
]))?.trim(),
|
|
495
|
+
"origin/main",
|
|
496
|
+
"origin/master",
|
|
497
|
+
"main",
|
|
498
|
+
"master"
|
|
499
|
+
];
|
|
500
|
+
for (const ref of candidates) if (ref && await isCommit(repoDir, ref)) return ref;
|
|
501
|
+
return null;
|
|
502
|
+
}
|
|
503
|
+
/** Splits `git cat-file --batch` output, whose object sizes are in bytes. */
|
|
504
|
+
function parseBatch(out, paths) {
|
|
505
|
+
const files = [];
|
|
506
|
+
let pos = 0;
|
|
507
|
+
for (const path of paths) {
|
|
508
|
+
const eol = out.indexOf(10, pos);
|
|
509
|
+
const header = out.subarray(pos, eol).toString("utf8");
|
|
510
|
+
pos = eol + 1;
|
|
511
|
+
const size = /^\S+ blob (\d+)$/.exec(header)?.[1];
|
|
512
|
+
if (size === void 0) continue;
|
|
513
|
+
files.push({
|
|
514
|
+
path,
|
|
515
|
+
text: out.subarray(pos, pos + Number(size)).toString("utf8")
|
|
516
|
+
});
|
|
517
|
+
pos += Number(size) + 1;
|
|
518
|
+
}
|
|
519
|
+
return files;
|
|
520
|
+
}
|
|
521
|
+
function catFileBatch(repoDir, specs) {
|
|
522
|
+
return new Promise((done, fail) => {
|
|
523
|
+
const child = spawn("git", ["cat-file", "--batch"], { cwd: repoDir });
|
|
524
|
+
const chunks = [];
|
|
525
|
+
child.stdout.on("data", (c) => chunks.push(c));
|
|
526
|
+
child.on("error", fail);
|
|
527
|
+
child.on("close", (code) => code === 0 ? done(Buffer.concat(chunks)) : fail(/* @__PURE__ */ new Error(`git cat-file exited ${code}`)));
|
|
528
|
+
child.stdin.end(specs.map((s) => `${s}\n`).join(""));
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
/** All files under `subdir` at `ref`, with paths relative to `repoDir` (the repo's top level). */
|
|
532
|
+
async function readTreeAtRef(repoDir, ref, subdir) {
|
|
533
|
+
const listing = await git(repoDir, [
|
|
534
|
+
"ls-tree",
|
|
535
|
+
"-r",
|
|
536
|
+
"-z",
|
|
537
|
+
"--name-only",
|
|
538
|
+
ref,
|
|
539
|
+
"--",
|
|
540
|
+
subdir || "."
|
|
541
|
+
]);
|
|
542
|
+
if (!listing) return [];
|
|
543
|
+
const paths = listing.split("\0").filter(Boolean);
|
|
544
|
+
if (paths.length === 0) return [];
|
|
545
|
+
return parseBatch(await catFileBatch(repoDir, paths.map((p) => `${ref}:${p}`)), paths);
|
|
546
|
+
}
|
|
547
|
+
/** The text of one file at `ref`, or null when the ref or the file does not exist. */
|
|
548
|
+
async function readFileAtRef(repoDir, ref, path) {
|
|
549
|
+
return git(repoDir, ["show", `${ref}:${path}`]);
|
|
550
|
+
}
|
|
551
|
+
async function remoteUrl(repoDir, remote = "origin") {
|
|
552
|
+
return (await git(repoDir, [
|
|
553
|
+
"remote",
|
|
554
|
+
"get-url",
|
|
555
|
+
remote
|
|
556
|
+
]))?.trim() || null;
|
|
557
|
+
}
|
|
558
|
+
async function fetchOrigin(repoDir) {
|
|
559
|
+
return await git(repoDir, [
|
|
560
|
+
"fetch",
|
|
561
|
+
"--quiet",
|
|
562
|
+
"origin"
|
|
563
|
+
]) !== null;
|
|
564
|
+
}
|
|
565
|
+
function walk(dir, rel = "") {
|
|
566
|
+
const out = [];
|
|
567
|
+
for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
568
|
+
if (entry.name === ".git" || entry.name === "node_modules") continue;
|
|
569
|
+
const child = rel ? `${rel}/${entry.name}` : entry.name;
|
|
570
|
+
if (entry.isDirectory()) out.push(...walk(dir, child));
|
|
571
|
+
else out.push(child);
|
|
572
|
+
}
|
|
573
|
+
return out;
|
|
574
|
+
}
|
|
575
|
+
/** Tracked and untracked (non-ignored) files under `subdir`, relative to `subdir`. */
|
|
576
|
+
async function listFiles(repoDir, subdir = "") {
|
|
577
|
+
const root = join(repoDir, subdir);
|
|
578
|
+
if (!existsSync(root)) return [];
|
|
579
|
+
const out = await git(root, [
|
|
580
|
+
"ls-files",
|
|
581
|
+
"-z",
|
|
582
|
+
"-co",
|
|
583
|
+
"--exclude-standard",
|
|
584
|
+
"--",
|
|
585
|
+
"."
|
|
586
|
+
]);
|
|
587
|
+
if (out !== null) return out.split("\0").filter(Boolean).map(toPosix);
|
|
588
|
+
return walk(root);
|
|
589
|
+
}
|
|
590
|
+
// ../core/src/repo-url.ts
|
|
591
|
+
const SCP_LIKE = /^(?:[\w.-]+@)?([\w.-]+):(?!\/\/)(.+)$/;
|
|
592
|
+
const WINDOWS_DRIVE = /^[A-Za-z]:[\\/]/;
|
|
593
|
+
function isGitUrl(s) {
|
|
594
|
+
return /^(https?:\/\/|git@|ssh:\/\/|file:\/\/)/.test(s);
|
|
595
|
+
}
|
|
596
|
+
const trimRepoPath = (p) => p.replace(/^\/+/, "").replace(/\/+$/, "").replace(/\.git$/, "");
|
|
597
|
+
/**
|
|
598
|
+
* Comparable identity of a repo: `host/group/name` for remotes (no credentials, port or `.git`), an absolute posix
|
|
599
|
+
* path for local repos and `file://` URLs.
|
|
600
|
+
*/
|
|
601
|
+
function normalizeRepoUrl(url) {
|
|
602
|
+
const s = url.trim();
|
|
603
|
+
if (s.startsWith("file://")) return trimRepoLocal(fileURLToPath(s));
|
|
604
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) {
|
|
605
|
+
const u = new URL(s);
|
|
606
|
+
return `${u.hostname.toLowerCase()}/${trimRepoPath(u.pathname)}`;
|
|
607
|
+
}
|
|
608
|
+
const scp = WINDOWS_DRIVE.test(s) ? null : SCP_LIKE.exec(s);
|
|
609
|
+
if (scp) return `${(scp[1] ?? "").toLowerCase()}/${trimRepoPath(scp[2] ?? "")}`;
|
|
610
|
+
return trimRepoLocal(s);
|
|
611
|
+
}
|
|
612
|
+
function trimRepoLocal(p) {
|
|
613
|
+
return toPosix(resolve(p)).replace(/\/+$/, "").replace(/\.git$/, "");
|
|
614
|
+
}
|
|
615
|
+
// ../core/src/context.ts
|
|
616
|
+
const NOT_FOUND = "No Adrien log found. Run `adrien init` in your ADR log repo, or `adrien init --code-repo --log <path|url>` in a code repo.";
|
|
617
|
+
function adrienHome(env = process.env) {
|
|
618
|
+
return env.ADRIEN_HOME || join(homedir(), ".adrien");
|
|
619
|
+
}
|
|
620
|
+
async function ensureCachedClone(url, home) {
|
|
621
|
+
const dir = join(home, "cache", normalizeRepoUrl(url).replace(/[\\/:]+/g, "__"));
|
|
622
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
623
|
+
mkdirSync(dirname(dir), { recursive: true });
|
|
624
|
+
if (await git(home, [
|
|
625
|
+
"clone",
|
|
626
|
+
"--quiet",
|
|
627
|
+
url,
|
|
628
|
+
dir
|
|
629
|
+
]) === null) throw new AdrienError("CONFIG_INVALID", `Could not clone the ADR log from ${url}`);
|
|
630
|
+
return dir;
|
|
631
|
+
}
|
|
632
|
+
async function syncCachedClone(dir) {
|
|
633
|
+
await git(dir, [
|
|
634
|
+
"fetch",
|
|
635
|
+
"--quiet",
|
|
636
|
+
"origin"
|
|
637
|
+
]);
|
|
638
|
+
await git(dir, [
|
|
639
|
+
"checkout",
|
|
640
|
+
"--quiet",
|
|
641
|
+
"--detach",
|
|
642
|
+
await resolveBaseRef(dir) ?? "origin/HEAD"
|
|
643
|
+
]);
|
|
644
|
+
}
|
|
645
|
+
async function locate(log, baseDir, env) {
|
|
646
|
+
if (isGitUrl(log)) return {
|
|
647
|
+
logRoot: await ensureCachedClone(log, adrienHome(env)),
|
|
648
|
+
readOnly: true,
|
|
649
|
+
logSource: log
|
|
650
|
+
};
|
|
651
|
+
const logRoot = resolve(baseDir, log);
|
|
652
|
+
return {
|
|
653
|
+
logRoot,
|
|
654
|
+
readOnly: false,
|
|
655
|
+
logSource: logRoot
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
async function detectCodeRepo(cwd, logRoot, config) {
|
|
659
|
+
const codeConfigDir = findUp(cwd, CODE_CONFIG_FILE);
|
|
660
|
+
const root = codeConfigDir ?? await gitToplevel(cwd) ?? (isInside(cwd, logRoot) ? logRoot : null);
|
|
661
|
+
if (!root) return null;
|
|
662
|
+
const override = codeConfigDir ? loadCodeRepoConfig(codeConfigDir)?.components : void 0;
|
|
663
|
+
if (override) return {
|
|
664
|
+
root,
|
|
665
|
+
components: override
|
|
666
|
+
};
|
|
667
|
+
const remote = await remoteUrl(root);
|
|
668
|
+
const identity = remote ? normalizeRepoUrl(remote) : null;
|
|
669
|
+
const logTop = await gitToplevel(logRoot) ?? logRoot;
|
|
670
|
+
const components = Object.entries(config.components).filter(([, def]) => def.repo === "." ? root === logTop : def.repo !== void 0 && normalizeRepoUrl(def.repo) === identity).map(([id]) => id);
|
|
671
|
+
return components.length ? {
|
|
672
|
+
root,
|
|
673
|
+
components
|
|
674
|
+
} : null;
|
|
675
|
+
}
|
|
676
|
+
async function resolveContext(opts) {
|
|
677
|
+
const env = opts.env ?? process.env;
|
|
678
|
+
const cwd = canonicalPath(resolve(opts.cwd));
|
|
679
|
+
let located;
|
|
680
|
+
if (opts.log) located = await locate(opts.log, cwd, env);
|
|
681
|
+
else {
|
|
682
|
+
const logDir = findUp(cwd, CONFIG_FILE);
|
|
683
|
+
const codeConfigDir = logDir ? null : findUp(cwd, CODE_CONFIG_FILE);
|
|
684
|
+
const codeConfig = codeConfigDir ? loadCodeRepoConfig(codeConfigDir) : null;
|
|
685
|
+
if (logDir) located = {
|
|
686
|
+
logRoot: logDir,
|
|
687
|
+
readOnly: false,
|
|
688
|
+
logSource: logDir
|
|
689
|
+
};
|
|
690
|
+
else if (codeConfig && codeConfigDir) located = await locate(codeConfig.log, codeConfigDir, env);
|
|
691
|
+
else throw new AdrienError("CONFIG_NOT_FOUND", NOT_FOUND);
|
|
692
|
+
}
|
|
693
|
+
located = {
|
|
694
|
+
...located,
|
|
695
|
+
logRoot: canonicalPath(located.logRoot)
|
|
696
|
+
};
|
|
697
|
+
const config = loadLogConfig(located.logRoot);
|
|
698
|
+
return {
|
|
699
|
+
cwd,
|
|
700
|
+
...located,
|
|
701
|
+
config,
|
|
702
|
+
codeRepo: await detectCodeRepo(cwd, located.logRoot, config),
|
|
703
|
+
env
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
const componentRoot = (config, id) => toPosix(config.components[id]?.root ?? "").replace(/^(\.\/)+/, "").replace(/^\.$/, "").replace(/\/+$/, "");
|
|
707
|
+
/** Maps a file (relative to `ctx.cwd`, `\` or `/`) to the component whose root is its longest prefix. */
|
|
708
|
+
function componentForPath(ctx, path) {
|
|
709
|
+
if (!ctx.codeRepo) return null;
|
|
710
|
+
const abs = resolve(ctx.cwd, path.replace(/\\/g, "/"));
|
|
711
|
+
if (!isInside(abs, ctx.codeRepo.root)) return null;
|
|
712
|
+
const rel = toPosix(relative(ctx.codeRepo.root, abs));
|
|
713
|
+
let best = null;
|
|
714
|
+
for (const component of ctx.codeRepo.components) {
|
|
715
|
+
const root = componentRoot(ctx.config, component);
|
|
716
|
+
if ((root === "" || rel === root || rel.startsWith(`${root}/`)) && (!best || root.length > best.root.length)) best = {
|
|
717
|
+
component,
|
|
718
|
+
root
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
if (!best) return null;
|
|
722
|
+
return {
|
|
723
|
+
component: best.component,
|
|
724
|
+
relPath: best.root ? rel.slice(best.root.length + 1) : rel
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
/** Local checkouts of components: `<ADRIEN_HOME>/workspace.yaml`, overridden by `ADRIEN_REPOS="a=/x;b=C:\\y"`. */
|
|
728
|
+
function workspacePaths(env) {
|
|
729
|
+
const paths = {};
|
|
730
|
+
const file = join(adrienHome(env), "workspace.yaml");
|
|
731
|
+
if (existsSync(file)) {
|
|
732
|
+
const data = YAML.parse(readFileSync(file, "utf8"));
|
|
733
|
+
Object.assign(paths, data?.components ?? {});
|
|
734
|
+
}
|
|
735
|
+
for (const entry of (env.ADRIEN_REPOS ?? "").split(";")) {
|
|
736
|
+
const eq = entry.indexOf("=");
|
|
737
|
+
if (eq > 0) paths[entry.slice(0, eq).trim()] = entry.slice(eq + 1).trim();
|
|
738
|
+
}
|
|
739
|
+
return paths;
|
|
740
|
+
}
|
|
741
|
+
// ../core/src/view.ts
|
|
742
|
+
const fingerprint = (adr) => JSON.stringify([adr.meta, adr.body]);
|
|
743
|
+
/** Pairs working and base ADRs by path first (handles duplicate ids), then by id (handles moved files). */
|
|
744
|
+
function diff(base, working) {
|
|
745
|
+
const baseByPath = new Map(base.map((a) => [a.path, a]));
|
|
746
|
+
const unmatchedBase = new Map(base.map((a) => [a, true]));
|
|
747
|
+
const pending = [];
|
|
748
|
+
const unmatchedWorking = [];
|
|
749
|
+
for (const current of working) {
|
|
750
|
+
const same = baseByPath.get(current.path);
|
|
751
|
+
if (same && same.meta.id === current.meta.id) {
|
|
752
|
+
unmatchedBase.delete(same);
|
|
753
|
+
if (fingerprint(same) !== fingerprint(current)) pending.push({
|
|
754
|
+
id: current.meta.id,
|
|
755
|
+
kind: "modified",
|
|
756
|
+
current,
|
|
757
|
+
base: same
|
|
758
|
+
});
|
|
759
|
+
} else unmatchedWorking.push(current);
|
|
760
|
+
}
|
|
761
|
+
for (const current of unmatchedWorking) {
|
|
762
|
+
const moved = [...unmatchedBase.keys()].find((b) => b.meta.id === current.meta.id);
|
|
763
|
+
if (moved) {
|
|
764
|
+
unmatchedBase.delete(moved);
|
|
765
|
+
pending.push({
|
|
766
|
+
id: current.meta.id,
|
|
767
|
+
kind: "modified",
|
|
768
|
+
current,
|
|
769
|
+
base: moved
|
|
770
|
+
});
|
|
771
|
+
} else pending.push({
|
|
772
|
+
id: current.meta.id,
|
|
773
|
+
kind: "added",
|
|
774
|
+
current
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
for (const gone of unmatchedBase.keys()) pending.push({
|
|
778
|
+
id: gone.meta.id,
|
|
779
|
+
kind: "deleted",
|
|
780
|
+
base: gone
|
|
781
|
+
});
|
|
782
|
+
return pending;
|
|
783
|
+
}
|
|
784
|
+
async function loadLogView(logRoot, config) {
|
|
785
|
+
const working = readWorkingLog(logRoot, config);
|
|
786
|
+
const top = await gitToplevel(logRoot);
|
|
787
|
+
const baseRef = top ? await resolveBaseRef(top) : null;
|
|
788
|
+
const adrDirFromTop = top ? toPosix(relative(top, join(logRoot, config.adr_dir))) : "";
|
|
789
|
+
const ignored = top ? await git(top, [
|
|
790
|
+
"check-ignore",
|
|
791
|
+
"-q",
|
|
792
|
+
"--",
|
|
793
|
+
adrDirFromTop || "."
|
|
794
|
+
]) !== null : false;
|
|
795
|
+
if (!top || !baseRef || ignored) {
|
|
796
|
+
const hasCommits = top ? await git(top, [
|
|
797
|
+
"rev-parse",
|
|
798
|
+
"--verify",
|
|
799
|
+
"--quiet",
|
|
800
|
+
"HEAD"
|
|
801
|
+
]) !== null : false;
|
|
802
|
+
return {
|
|
803
|
+
mode: "files",
|
|
804
|
+
baseRef: null,
|
|
805
|
+
base: working.adrs,
|
|
806
|
+
pending: [],
|
|
807
|
+
working: working.adrs,
|
|
808
|
+
problems: working.problems,
|
|
809
|
+
...top && !baseRef && !ignored && hasCommits ? { baseUnresolved: true } : {}
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
const logFromTop = toPosix(relative(top, logRoot));
|
|
813
|
+
const prefix = logFromTop ? `${logFromTop}/` : "";
|
|
814
|
+
const configAt = async (ref) => {
|
|
815
|
+
const text = await readFileAtRef(top, ref, `${prefix}${CONFIG_FILE}`);
|
|
816
|
+
if (text === null) return config;
|
|
817
|
+
try {
|
|
818
|
+
return parseLogConfigText(text, `${ref}:${prefix}${CONFIG_FILE}`);
|
|
819
|
+
} catch {
|
|
820
|
+
return config;
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
const logAt = async (ref) => {
|
|
824
|
+
const atRef = await configAt(ref);
|
|
825
|
+
const adrDir = toPosix(relative(top, join(logRoot, atRef.adr_dir)));
|
|
826
|
+
return parseLogFiles((await readTreeAtRef(top, ref, adrDir)).filter((f) => f.path.endsWith(".md")).map((f) => ({
|
|
827
|
+
path: f.path.slice(prefix.length),
|
|
828
|
+
text: f.text
|
|
829
|
+
})), atRef);
|
|
830
|
+
};
|
|
831
|
+
const atBase = await logAt(baseRef);
|
|
832
|
+
const base = atBase.adrs;
|
|
833
|
+
const inTree = /* @__PURE__ */ new Set([...working.adrs.map((a) => a.path), ...working.problems.map((p) => p.path)]);
|
|
834
|
+
const problems = [...working.problems, ...atBase.problems.filter((p) => !inTree.has(p.path))];
|
|
835
|
+
const forkPoint = (await git(top, [
|
|
836
|
+
"merge-base",
|
|
837
|
+
"HEAD",
|
|
838
|
+
baseRef
|
|
839
|
+
]))?.trim();
|
|
840
|
+
const baseSha = (await git(top, ["rev-parse", baseRef]))?.trim();
|
|
841
|
+
const fork = forkPoint && forkPoint !== baseSha ? (await logAt(forkPoint)).adrs : base;
|
|
842
|
+
return {
|
|
843
|
+
...forkPoint ? {} : { forkUnresolved: true },
|
|
844
|
+
mode: "git",
|
|
845
|
+
baseRef,
|
|
846
|
+
base,
|
|
847
|
+
pending: diff(fork, working.adrs).map((change) => ({
|
|
848
|
+
...change,
|
|
849
|
+
base: latest(change.base, base)
|
|
850
|
+
})),
|
|
851
|
+
working: working.adrs,
|
|
852
|
+
problems
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
/** The default-branch version of an ADR seen at the fork point (by path, then by id), so callers compare to base. */
|
|
856
|
+
function latest(atFork, base) {
|
|
857
|
+
if (!atFork) return void 0;
|
|
858
|
+
return base.find((a) => a.path === atFork.path && a.meta.id === atFork.meta.id) ?? base.find((a) => a.meta.id === atFork.meta.id) ?? atFork;
|
|
859
|
+
}
|
|
860
|
+
/** The ADR files in this checkout (what edits and renumbering act on). */
|
|
861
|
+
function workingAdrs(view) {
|
|
862
|
+
return view.working;
|
|
863
|
+
}
|
|
864
|
+
const sameAdr = (a, b) => a.path === b.path && a.meta.id === b.meta.id;
|
|
865
|
+
/**
|
|
866
|
+
* What the default branch would hold after merging this checkout: the latest base with every pending change applied.
|
|
867
|
+
* Unlike `workingAdrs`, it includes ADRs merged upstream since this branch forked, so id collisions show up here.
|
|
868
|
+
*/
|
|
869
|
+
function mergedAdrs(view) {
|
|
870
|
+
let merged = [...view.base];
|
|
871
|
+
for (const change of view.pending) {
|
|
872
|
+
const gone = change.base;
|
|
873
|
+
if (gone) merged = merged.filter((a) => !sameAdr(a, gone));
|
|
874
|
+
if (change.current) merged.push(change.current);
|
|
875
|
+
}
|
|
876
|
+
return merged.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
877
|
+
}
|
|
878
|
+
// ../core/src/lint.ts
|
|
879
|
+
/**
|
|
880
|
+
* markdownlint settings tuned for ADRs, overridable under `lint.markdownlint` in the config. They follow MADR's: "the
|
|
881
|
+
* linter should support the user and not annoy them".
|
|
882
|
+
*/
|
|
883
|
+
const MARKDOWNLINT_DEFAULTS = {
|
|
884
|
+
default: true,
|
|
885
|
+
MD013: false,
|
|
886
|
+
MD024: false,
|
|
887
|
+
MD025: { front_matter_title: "" },
|
|
888
|
+
MD041: false
|
|
889
|
+
};
|
|
890
|
+
const FENCE = /^(```|~~~)[\s\S]*?^\1[^\n]*$/gm;
|
|
891
|
+
const INLINE_CODE = /`[^`\n]*`/g;
|
|
892
|
+
const COMMENT = /<!--[\s\S]*?-->/g;
|
|
893
|
+
/** `{short title, representative of …}`: braces around words, without the quotes or colon of JSON or `{n:4}`. */
|
|
894
|
+
const PLACEHOLDER = /\{(?![^{}\n]*["':])[^{}\n]*\s[^{}\n]*\}/;
|
|
895
|
+
const NUMBERED_HEADING = /^#{1,6}\s+\d+[.)]\s/m;
|
|
896
|
+
const prose = (body) => body.replace(FENCE, "").replace(COMMENT, "").replace(INLINE_CODE, "");
|
|
897
|
+
/** The text under the Decision (or MADR's Decision Outcome) heading; null when the ADR has no such heading. */
|
|
898
|
+
function decisionText(body) {
|
|
899
|
+
const m = /^##\s+(?:Decision Outcome|Decision)\s*$([\s\S]*?)(?=^##\s|(?![\s\S]))/im.exec(body);
|
|
900
|
+
if (!m) return null;
|
|
901
|
+
return (m[1] ?? "").replace(COMMENT, "").replace(/^#+\s.*$/gm, "").trim();
|
|
902
|
+
}
|
|
903
|
+
function adrienRules(adr) {
|
|
904
|
+
const at = {
|
|
905
|
+
id: adr.meta.id,
|
|
906
|
+
path: adr.path
|
|
907
|
+
};
|
|
908
|
+
const out = [];
|
|
909
|
+
const text = prose(adr.body);
|
|
910
|
+
const placeholder = PLACEHOLDER.exec(text)?.[0];
|
|
911
|
+
if (placeholder) out.push({
|
|
912
|
+
severity: "warning",
|
|
913
|
+
code: "unfilled-placeholder",
|
|
914
|
+
...at,
|
|
915
|
+
message: `Template placeholder left in the body: ${placeholder}`
|
|
916
|
+
});
|
|
917
|
+
if (adr.meta.status === "accepted" && decisionText(adr.body) === "") out.push({
|
|
918
|
+
severity: "warning",
|
|
919
|
+
code: "empty-decision",
|
|
920
|
+
...at,
|
|
921
|
+
message: "An accepted ADR has an empty Decision section"
|
|
922
|
+
});
|
|
923
|
+
if (NUMBERED_HEADING.test(text)) out.push({
|
|
924
|
+
severity: "warning",
|
|
925
|
+
code: "numbered-heading",
|
|
926
|
+
...at,
|
|
927
|
+
message: "Headings are not numbered (\"## Context\", not \"## 1. Context\"), so sections can move without renumbering"
|
|
928
|
+
});
|
|
929
|
+
return out;
|
|
930
|
+
}
|
|
931
|
+
/**
|
|
932
|
+
* Style warnings for the ADRs in the working tree: markdownlint over each file, plus Adrien's own rules. They are
|
|
933
|
+
* advice about how an ADR reads, never errors: a decision with a long line is still a decision.
|
|
934
|
+
*/
|
|
935
|
+
async function lintAdrs(ctx, view) {
|
|
936
|
+
const adrs = workingAdrs(view);
|
|
937
|
+
const strings = Object.fromEntries(adrs.map((adr) => [adr.path, readFileSync(join(ctx.logRoot, ...adr.path.split("/")), "utf8")]));
|
|
938
|
+
const { lint } = await import("markdownlint/promise");
|
|
939
|
+
const results = await lint({
|
|
940
|
+
strings,
|
|
941
|
+
config: {
|
|
942
|
+
...MARKDOWNLINT_DEFAULTS,
|
|
943
|
+
...ctx.config.lint?.markdownlint
|
|
944
|
+
}
|
|
945
|
+
});
|
|
946
|
+
const out = [];
|
|
947
|
+
for (const adr of adrs) {
|
|
948
|
+
for (const e of results[adr.path] ?? []) {
|
|
949
|
+
const detail = e.errorDetail ? ` [${e.errorDetail}]` : "";
|
|
950
|
+
out.push({
|
|
951
|
+
severity: "warning",
|
|
952
|
+
code: "markdown",
|
|
953
|
+
id: adr.meta.id,
|
|
954
|
+
path: adr.path,
|
|
955
|
+
message: `${e.ruleNames[0]} ${e.ruleNames[1]}: ${e.ruleDescription}${detail} (line ${e.lineNumber})`
|
|
956
|
+
});
|
|
957
|
+
}
|
|
958
|
+
out.push(...adrienRules(adr));
|
|
959
|
+
}
|
|
960
|
+
return out;
|
|
961
|
+
}
|
|
962
|
+
// ../core/src/check.ts
|
|
963
|
+
const RETIRED$1 = /* @__PURE__ */ new Set([
|
|
964
|
+
"rejected",
|
|
965
|
+
"superseded",
|
|
966
|
+
"deprecated"
|
|
967
|
+
]);
|
|
968
|
+
const at = (adr) => ({
|
|
969
|
+
id: adr.meta.id,
|
|
970
|
+
path: adr.path
|
|
971
|
+
});
|
|
972
|
+
function checkFields(ctx, adr, out) {
|
|
973
|
+
const unknownTags = adr.meta.tags.filter((t) => !ctx.config.tags.includes(t));
|
|
974
|
+
if (unknownTags.length) out.push({
|
|
975
|
+
severity: "error",
|
|
976
|
+
code: "unknown-tag",
|
|
977
|
+
...at(adr),
|
|
978
|
+
message: `Unknown tag(s): ${unknownTags.join(", ")}. Allowed: ${ctx.config.tags.join(", ")}`
|
|
979
|
+
});
|
|
980
|
+
const known = Object.keys(ctx.config.components);
|
|
981
|
+
const unknownComponents = adr.meta.components.filter((c) => !known.includes(c));
|
|
982
|
+
if (unknownComponents.length) out.push({
|
|
983
|
+
severity: "error",
|
|
984
|
+
code: "unknown-component",
|
|
985
|
+
...at(adr),
|
|
986
|
+
message: `Unknown component(s): ${unknownComponents.join(", ")}. Allowed: ${known.join(", ")}`
|
|
987
|
+
});
|
|
988
|
+
for (const raw of adr.meta.code) {
|
|
989
|
+
const anchor = parseAnchor(raw);
|
|
990
|
+
if (!anchor || !known.includes(anchor.component)) out.push({
|
|
991
|
+
severity: "error",
|
|
992
|
+
code: "invalid-anchor",
|
|
993
|
+
...at(adr),
|
|
994
|
+
message: `Anchor "${raw}" must be <component>:<glob> with a component from the config`
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
if (adr.meta.status === "accepted" && !adr.meta.review_rule?.trim()) out.push({
|
|
998
|
+
severity: "error",
|
|
999
|
+
code: "missing-review-rule",
|
|
1000
|
+
...at(adr),
|
|
1001
|
+
message: "An accepted ADR needs a review_rule: the one checkable sentence agents and reviewers apply"
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
function checkLinks(adrs, out) {
|
|
1005
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1006
|
+
for (const adr of adrs) byId.set(adr.meta.id, [...byId.get(adr.meta.id) ?? [], adr]);
|
|
1007
|
+
for (const [id, same] of byId) if (same.length > 1) out.push({
|
|
1008
|
+
severity: "error",
|
|
1009
|
+
code: "duplicate-id",
|
|
1010
|
+
id,
|
|
1011
|
+
message: `${id} is used by ${same.map((a) => a.path).join(", ")}. Run \`adrien renumber ${id}\``
|
|
1012
|
+
});
|
|
1013
|
+
for (const adr of adrs) {
|
|
1014
|
+
const links = [
|
|
1015
|
+
...adr.meta.supersedes,
|
|
1016
|
+
...adr.meta.related,
|
|
1017
|
+
...adr.meta.superseded_by ? [adr.meta.superseded_by] : []
|
|
1018
|
+
];
|
|
1019
|
+
for (const target of links) if (!byId.has(target)) out.push({
|
|
1020
|
+
severity: "error",
|
|
1021
|
+
code: "broken-link",
|
|
1022
|
+
...at(adr),
|
|
1023
|
+
message: `Links to unknown ADR ${target}`
|
|
1024
|
+
});
|
|
1025
|
+
for (const oldId of adr.meta.supersedes) {
|
|
1026
|
+
const old = byId.get(oldId)?.[0];
|
|
1027
|
+
if (old && (old.meta.status !== "superseded" || old.meta.superseded_by !== adr.meta.id)) out.push({
|
|
1028
|
+
severity: "error",
|
|
1029
|
+
code: "supersede-asymmetry",
|
|
1030
|
+
...at(adr),
|
|
1031
|
+
message: `${adr.meta.id} supersedes ${oldId}, but ${oldId} is not "superseded" with superseded_by: ${adr.meta.id}`
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
const newId = adr.meta.superseded_by;
|
|
1035
|
+
const replacement = newId ? byId.get(newId)?.[0] : void 0;
|
|
1036
|
+
if (replacement && !replacement.meta.supersedes.includes(adr.meta.id)) out.push({
|
|
1037
|
+
severity: "error",
|
|
1038
|
+
code: "supersede-asymmetry",
|
|
1039
|
+
...at(adr),
|
|
1040
|
+
message: `${adr.meta.id} is superseded_by ${newId}, but ${newId} does not list it in supersedes`
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
/** Component → absolute checkout of its root, for every component whose code is available locally. */
|
|
1045
|
+
async function checkouts(ctx, here) {
|
|
1046
|
+
const roots = /* @__PURE__ */ new Map();
|
|
1047
|
+
const add = (component, repoRoot) => roots.set(component, join(repoRoot, componentRoot(ctx.config, component)));
|
|
1048
|
+
if (here) {
|
|
1049
|
+
for (const c of ctx.codeRepo?.components ?? []) add(c, ctx.codeRepo?.root ?? "");
|
|
1050
|
+
return roots;
|
|
1051
|
+
}
|
|
1052
|
+
const logTop = await gitToplevel(ctx.logRoot) ?? ctx.logRoot;
|
|
1053
|
+
for (const [c, def] of Object.entries(ctx.config.components)) if (def.repo === ".") add(c, logTop);
|
|
1054
|
+
for (const [c, path] of Object.entries(workspacePaths(ctx.env))) if (c in ctx.config.components) add(c, path);
|
|
1055
|
+
return roots;
|
|
1056
|
+
}
|
|
1057
|
+
async function checkAnchors(ctx, adrs, here, out) {
|
|
1058
|
+
const anchored = /* @__PURE__ */ new Map();
|
|
1059
|
+
for (const adr of adrs) {
|
|
1060
|
+
if (RETIRED$1.has(adr.meta.status)) continue;
|
|
1061
|
+
for (const raw of adr.meta.code) {
|
|
1062
|
+
const anchor = parseAnchor(raw);
|
|
1063
|
+
if (!anchor || !(anchor.component in ctx.config.components)) continue;
|
|
1064
|
+
anchored.set(anchor.component, [...anchored.get(anchor.component) ?? [], {
|
|
1065
|
+
adr,
|
|
1066
|
+
raw,
|
|
1067
|
+
glob: anchor.glob
|
|
1068
|
+
}]);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
const roots = await checkouts(ctx, here);
|
|
1072
|
+
const unverified = [];
|
|
1073
|
+
for (const [component, uses] of anchored) {
|
|
1074
|
+
const root = roots.get(component);
|
|
1075
|
+
if (!root) {
|
|
1076
|
+
unverified.push(component);
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
const files = await listFiles(root);
|
|
1080
|
+
for (const { adr, raw, glob } of uses) if (!files.some((f) => anchorMatches({
|
|
1081
|
+
component,
|
|
1082
|
+
glob
|
|
1083
|
+
}, component, f))) out.push({
|
|
1084
|
+
severity: "warning",
|
|
1085
|
+
code: "stale-anchor",
|
|
1086
|
+
...at(adr),
|
|
1087
|
+
message: `Anchor "${raw}" matches no file in ${root}`
|
|
1088
|
+
});
|
|
1089
|
+
}
|
|
1090
|
+
if (unverified.length && !here) out.push({
|
|
1091
|
+
severity: "info",
|
|
1092
|
+
code: "anchors-not-verified",
|
|
1093
|
+
message: `Anchors not verified for ${unverified.join(", ")}: no local checkout (set ADRIEN_REPOS, or run \`adrien check --here\` in each code repo's CI)`
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
async function runCheck(ctx, view, opts = {}) {
|
|
1097
|
+
const out = view.problems.map((p) => ({
|
|
1098
|
+
severity: "error",
|
|
1099
|
+
code: "parse-error",
|
|
1100
|
+
path: p.path,
|
|
1101
|
+
message: p.message
|
|
1102
|
+
}));
|
|
1103
|
+
if (opts.mr && view.baseUnresolved) out.push({
|
|
1104
|
+
severity: "error",
|
|
1105
|
+
code: "base-unresolved",
|
|
1106
|
+
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>`."
|
|
1107
|
+
});
|
|
1108
|
+
if (opts.mr && view.forkUnresolved) out.push({
|
|
1109
|
+
severity: "error",
|
|
1110
|
+
code: "fork-unresolved",
|
|
1111
|
+
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\`.`
|
|
1112
|
+
});
|
|
1113
|
+
const adrs = mergedAdrs(view);
|
|
1114
|
+
for (const adr of adrs) checkFields(ctx, adr, out);
|
|
1115
|
+
checkLinks(adrs, out);
|
|
1116
|
+
await checkAnchors(ctx, adrs, opts.here ?? false, out);
|
|
1117
|
+
if (opts.mr) {
|
|
1118
|
+
for (const change of view.pending) if (change.current && change.current.meta.status === "proposed") out.push({
|
|
1119
|
+
severity: "warning",
|
|
1120
|
+
code: "pending-proposed",
|
|
1121
|
+
...at(change.current),
|
|
1122
|
+
message: `${change.id} is still "proposed": merging it adds only a hint. Run \`adrien accept ${change.id}\` to approve it`
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
const today = opts.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1126
|
+
for (const adr of adrs) {
|
|
1127
|
+
const due = adr.meta.review_on;
|
|
1128
|
+
if (due && due <= today && !RETIRED$1.has(adr.meta.status)) out.push({
|
|
1129
|
+
severity: "warning",
|
|
1130
|
+
code: "review-due",
|
|
1131
|
+
...at(adr),
|
|
1132
|
+
message: `${adr.meta.id} was due for review on ${due}: confirm it still holds, or supersede it`
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
if (opts.lint) out.push(...await lintAdrs(ctx, view));
|
|
1136
|
+
return out;
|
|
1137
|
+
}
|
|
1138
|
+
function exitCodeFor(diags, strict = false) {
|
|
1139
|
+
return diags.some((d) => d.severity === "error" || strict && d.severity === "warning") ? 1 : 0;
|
|
1140
|
+
}
|
|
1141
|
+
// ../core/src/duplicates.ts
|
|
1142
|
+
const THRESHOLD = .6;
|
|
1143
|
+
const tokens = (title) => new Set(normalizeTitle(title).split(" ").filter((t) => t.length >= 3));
|
|
1144
|
+
/** ADRs whose title is the same after normalisation (score 1) or shares most words (token Jaccard ≥ 0.6). */
|
|
1145
|
+
function findDuplicates(title, adrs) {
|
|
1146
|
+
const wanted = normalizeTitle(title);
|
|
1147
|
+
const wantedTokens = tokens(title);
|
|
1148
|
+
const hits = [];
|
|
1149
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1150
|
+
for (const adr of adrs) {
|
|
1151
|
+
if (seen.has(adr.meta.id)) continue;
|
|
1152
|
+
let score = 0;
|
|
1153
|
+
if (normalizeTitle(adr.meta.title) === wanted) score = 1;
|
|
1154
|
+
else {
|
|
1155
|
+
const other = tokens(adr.meta.title);
|
|
1156
|
+
const common = [...wantedTokens].filter((t) => other.has(t)).length;
|
|
1157
|
+
const union = (/* @__PURE__ */ new Set([...wantedTokens, ...other])).size;
|
|
1158
|
+
score = union ? common / union : 0;
|
|
1159
|
+
}
|
|
1160
|
+
if (score >= THRESHOLD) {
|
|
1161
|
+
seen.add(adr.meta.id);
|
|
1162
|
+
hits.push({
|
|
1163
|
+
id: adr.meta.id,
|
|
1164
|
+
title: adr.meta.title,
|
|
1165
|
+
score: Math.round(score * 1e3) / 1e3
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
return hits.sort((a, b) => b.score - a.score).slice(0, 5);
|
|
1170
|
+
}
|
|
1171
|
+
// ../core/src/export.ts
|
|
1172
|
+
const EXPORT_FORMATS = ["markdown", "llms"];
|
|
1173
|
+
const byId = (a, b) => a.meta.id.localeCompare(b.meta.id, "en", { numeric: true });
|
|
1174
|
+
const cell = (text) => text.replace(/\|/g, "\\|");
|
|
1175
|
+
/**
|
|
1176
|
+
* A generated overview of the ADRs in this checkout. `markdown` is a table of all of them; `llms` follows the
|
|
1177
|
+
* llms.txt convention, so a model can read the accepted decisions and their rules from one file.
|
|
1178
|
+
* `from` is the directory of the file that will hold the export, so its links resolve from there; by default they are
|
|
1179
|
+
* relative to the log root.
|
|
1180
|
+
*/
|
|
1181
|
+
function exportLog(ctx, view, format, opts = {}) {
|
|
1182
|
+
const adrs = [...workingAdrs(view)].sort(byId);
|
|
1183
|
+
const { from } = opts;
|
|
1184
|
+
const link = (adr) => from === void 0 ? adr.path : toPosix(relative(from, join(ctx.logRoot, ...adr.path.split("/"))));
|
|
1185
|
+
const { product } = ctx.config;
|
|
1186
|
+
if (format === "markdown") {
|
|
1187
|
+
const rows = adrs.map((a) => `| [${a.meta.id}](${link(a)}) | ${cell(a.meta.title)} | ${a.meta.status} | ${a.meta.tags.join(", ")} |`);
|
|
1188
|
+
return [
|
|
1189
|
+
`# ${product}: architecture decisions`,
|
|
1190
|
+
"",
|
|
1191
|
+
"| ID | Title | Status | Tags |",
|
|
1192
|
+
"| --- | --- | --- | --- |",
|
|
1193
|
+
...rows,
|
|
1194
|
+
""
|
|
1195
|
+
].join("\n");
|
|
1196
|
+
}
|
|
1197
|
+
const base = [...view.base].sort(byId);
|
|
1198
|
+
const pending = view.pending.filter((c) => c.current !== void 0).sort((a, b) => byId(a.current, b.current));
|
|
1199
|
+
const entry = (a, kind = "") => `- [${a.meta.id}: ${a.meta.title}](${link(a)})${a.meta.review_rule ? `: ${a.meta.review_rule}` : ""}${kind}`;
|
|
1200
|
+
const group = (title, lines) => lines.length ? [
|
|
1201
|
+
"",
|
|
1202
|
+
`## ${title}`,
|
|
1203
|
+
"",
|
|
1204
|
+
...lines
|
|
1205
|
+
] : [];
|
|
1206
|
+
return [
|
|
1207
|
+
`# ${product}`,
|
|
1208
|
+
"",
|
|
1209
|
+
`> Architecture decisions for ${product}. Before changing code, follow the rule of every accepted decision that governs it.`,
|
|
1210
|
+
...group("Accepted", base.filter((a) => a.meta.status === "accepted").map((a) => entry(a))),
|
|
1211
|
+
...group("Proposed (not yet binding)", base.filter((a) => a.meta.status === "proposed").map((a) => entry(a))),
|
|
1212
|
+
...group("Pending in this checkout (not yet binding)", pending.map((c) => entry(c.current, ` (${c.kind})`))),
|
|
1213
|
+
""
|
|
1214
|
+
].join("\n");
|
|
1215
|
+
}
|
|
1216
|
+
// ../core/src/for-files.ts
|
|
1217
|
+
const RETIRED = /* @__PURE__ */ new Set([
|
|
1218
|
+
"rejected",
|
|
1219
|
+
"superseded",
|
|
1220
|
+
"deprecated"
|
|
1221
|
+
]);
|
|
1222
|
+
function matchOf(adr, component, relPath) {
|
|
1223
|
+
const anchors = adr.meta.code.map((raw) => ({
|
|
1224
|
+
raw,
|
|
1225
|
+
anchor: parseAnchor(raw)
|
|
1226
|
+
})).filter((a) => a.anchor?.component === component);
|
|
1227
|
+
const hit = anchors.find((a) => a.anchor && anchorMatches(a.anchor, component, relPath));
|
|
1228
|
+
if (hit) return {
|
|
1229
|
+
match: "anchor",
|
|
1230
|
+
anchor: hit.raw
|
|
1231
|
+
};
|
|
1232
|
+
if (anchors.length === 0 && adr.meta.components.includes(component)) return {
|
|
1233
|
+
match: "component",
|
|
1234
|
+
anchor: null
|
|
1235
|
+
};
|
|
1236
|
+
return null;
|
|
1237
|
+
}
|
|
1238
|
+
function decision(adr, layer, pendingKind, match) {
|
|
1239
|
+
return {
|
|
1240
|
+
id: adr.meta.id,
|
|
1241
|
+
title: adr.meta.title,
|
|
1242
|
+
status: adr.meta.status,
|
|
1243
|
+
binding: layer === "base" && adr.meta.status === "accepted",
|
|
1244
|
+
layer,
|
|
1245
|
+
pending_kind: pendingKind,
|
|
1246
|
+
...match,
|
|
1247
|
+
review_rule: adr.meta.review_rule ?? null,
|
|
1248
|
+
excerpt: excerpt(adr)
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
const order = (a, b) => Number(b.binding) - Number(a.binding) || Number(b.match === "anchor") - Number(a.match === "anchor") || a.id.localeCompare(b.id) || a.layer.localeCompare(b.layer);
|
|
1252
|
+
/** The decisions that govern each file: binding ones first, pending agent or developer edits labelled as such. */
|
|
1253
|
+
function adrsForFiles(ctx, view, paths) {
|
|
1254
|
+
const changeOfBase = /* @__PURE__ */ new Map();
|
|
1255
|
+
for (const change of view.pending) if (change.base) changeOfBase.set(change.base, change.kind);
|
|
1256
|
+
const pendingCurrent = view.pending.filter((c) => c.current).map((c) => ({
|
|
1257
|
+
adr: c.current,
|
|
1258
|
+
kind: c.kind
|
|
1259
|
+
}));
|
|
1260
|
+
return paths.map((path) => {
|
|
1261
|
+
const file = toPosix(path);
|
|
1262
|
+
const location = componentForPath(ctx, path);
|
|
1263
|
+
if (!location) return {
|
|
1264
|
+
file,
|
|
1265
|
+
component: null,
|
|
1266
|
+
decisions: []
|
|
1267
|
+
};
|
|
1268
|
+
const { component, relPath } = location;
|
|
1269
|
+
const decisions = [];
|
|
1270
|
+
for (const adr of view.base) {
|
|
1271
|
+
if (RETIRED.has(adr.meta.status)) continue;
|
|
1272
|
+
const match = matchOf(adr, component, relPath);
|
|
1273
|
+
if (match) decisions.push(decision(adr, "base", changeOfBase.get(adr) ?? null, match));
|
|
1274
|
+
}
|
|
1275
|
+
for (const { adr, kind } of pendingCurrent) {
|
|
1276
|
+
const match = matchOf(adr, component, relPath);
|
|
1277
|
+
if (match) decisions.push(decision(adr, "pending", kind, match));
|
|
1278
|
+
}
|
|
1279
|
+
return {
|
|
1280
|
+
file,
|
|
1281
|
+
component,
|
|
1282
|
+
decisions: decisions.sort(order)
|
|
1283
|
+
};
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
/**
|
|
1287
|
+
* A warning for callers that show decisions as binding: with no default branch to compare against, ADR statuses are
|
|
1288
|
+
* read as written, so an ADR that says `accepted` may not have been merged.
|
|
1289
|
+
*/
|
|
1290
|
+
function unverifiedBaseNote(view) {
|
|
1291
|
+
if (!view.baseUnresolved) return null;
|
|
1292
|
+
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.";
|
|
1293
|
+
}
|
|
1294
|
+
// ../core/src/sqlite.ts
|
|
1295
|
+
let loading;
|
|
1296
|
+
/**
|
|
1297
|
+
* Node prints an ExperimentalWarning the first time `node:sqlite` loads. On `adrien mcp` that stray output would
|
|
1298
|
+
* reach the user's terminal on every run, so drop that one warning and forward every other warning to stderr.
|
|
1299
|
+
*/
|
|
1300
|
+
function silenceSqliteWarning() {
|
|
1301
|
+
process.removeAllListeners("warning");
|
|
1302
|
+
process.on("warning", (warning) => {
|
|
1303
|
+
if (warning.name === "ExperimentalWarning" && /SQLite/i.test(warning.message)) return;
|
|
1304
|
+
process.stderr.write(`${warning.name}: ${warning.message}\n`);
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
function loadSqlite() {
|
|
1308
|
+
if (!loading) {
|
|
1309
|
+
silenceSqliteWarning();
|
|
1310
|
+
loading = import("node:sqlite");
|
|
1311
|
+
}
|
|
1312
|
+
return loading;
|
|
1313
|
+
}
|
|
1314
|
+
// ../core/src/index-db.ts
|
|
1315
|
+
const SCHEMA_VERSION = 1;
|
|
1316
|
+
const SCHEMA = `
|
|
1317
|
+
CREATE TABLE docs (
|
|
1318
|
+
layer TEXT NOT NULL, path TEXT NOT NULL, hash TEXT NOT NULL,
|
|
1319
|
+
id TEXT NOT NULL, title TEXT NOT NULL, status TEXT NOT NULL,
|
|
1320
|
+
tags TEXT NOT NULL, components TEXT NOT NULL, review_rule TEXT, pending_kind TEXT,
|
|
1321
|
+
PRIMARY KEY (layer, path)
|
|
1322
|
+
);
|
|
1323
|
+
CREATE VIRTUAL TABLE adr_fts USING fts5(
|
|
1324
|
+
layer UNINDEXED, path UNINDEXED, title, review_rule, body,
|
|
1325
|
+
tokenize = 'unicode61 remove_diacritics 2'
|
|
1326
|
+
);`;
|
|
1327
|
+
const ROW_COLUMNS = "docs.id, docs.title, docs.status, docs.tags, docs.components, docs.review_rule, docs.layer, docs.pending_kind, docs.path";
|
|
1328
|
+
/** Turns free text into a safe FTS5 query: every letter/digit run becomes a quoted prefix term. */
|
|
1329
|
+
function toFtsQuery(input) {
|
|
1330
|
+
const tokens = input.match(/[\p{L}\p{N}]+/gu);
|
|
1331
|
+
return tokens ? tokens.map((t) => `"${t}"*`).join(" ") : null;
|
|
1332
|
+
}
|
|
1333
|
+
function docsOf(view) {
|
|
1334
|
+
const docs = view.base.map((adr) => ({
|
|
1335
|
+
layer: "base",
|
|
1336
|
+
adr,
|
|
1337
|
+
kind: null
|
|
1338
|
+
}));
|
|
1339
|
+
for (const change of view.pending) {
|
|
1340
|
+
const adr = change.kind === "deleted" ? change.base : change.current;
|
|
1341
|
+
if (adr) docs.push({
|
|
1342
|
+
layer: "pending",
|
|
1343
|
+
adr,
|
|
1344
|
+
kind: change.kind
|
|
1345
|
+
});
|
|
1346
|
+
}
|
|
1347
|
+
return docs;
|
|
1348
|
+
}
|
|
1349
|
+
const hashOf = (doc) => createHash("sha1").update(JSON.stringify([
|
|
1350
|
+
doc.adr.meta,
|
|
1351
|
+
doc.adr.body,
|
|
1352
|
+
doc.adr.path,
|
|
1353
|
+
doc.kind
|
|
1354
|
+
])).digest("hex");
|
|
1355
|
+
function whereClause(filters) {
|
|
1356
|
+
const parts = [];
|
|
1357
|
+
const params = [];
|
|
1358
|
+
const marks = (values) => values.map(() => "?").join(", ");
|
|
1359
|
+
if (filters.layer && filters.layer !== "all") {
|
|
1360
|
+
parts.push("docs.layer = ?");
|
|
1361
|
+
params.push(filters.layer);
|
|
1362
|
+
}
|
|
1363
|
+
if (filters.status?.length) {
|
|
1364
|
+
parts.push(`docs.status IN (${marks(filters.status)})`);
|
|
1365
|
+
params.push(...filters.status);
|
|
1366
|
+
}
|
|
1367
|
+
if (filters.tags?.length) {
|
|
1368
|
+
const tags = [...new Set(filters.tags)];
|
|
1369
|
+
parts.push(`(SELECT count(DISTINCT value) FROM json_each(docs.tags) WHERE value IN (${marks(tags)})) = ?`);
|
|
1370
|
+
params.push(...tags, tags.length);
|
|
1371
|
+
}
|
|
1372
|
+
if (filters.components?.length) {
|
|
1373
|
+
parts.push(`EXISTS (SELECT 1 FROM json_each(docs.components) WHERE value IN (${marks(filters.components)}))`);
|
|
1374
|
+
params.push(...filters.components);
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
sql: parts.length ? ` AND ${parts.join(" AND ")}` : "",
|
|
1378
|
+
params
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
function toRow(r) {
|
|
1382
|
+
return {
|
|
1383
|
+
id: String(r.id),
|
|
1384
|
+
title: String(r.title),
|
|
1385
|
+
status: r.status,
|
|
1386
|
+
tags: JSON.parse(String(r.tags)),
|
|
1387
|
+
components: JSON.parse(String(r.components)),
|
|
1388
|
+
review_rule: r.review_rule == null ? null : String(r.review_rule),
|
|
1389
|
+
layer: r.layer,
|
|
1390
|
+
pending_kind: r.pending_kind ?? null,
|
|
1391
|
+
path: String(r.path)
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
/** A per-log SQLite cache of the ADRs, rebuilt incrementally from the markdown. Never committed. */
|
|
1395
|
+
var AdrIndex = class AdrIndex {
|
|
1396
|
+
db;
|
|
1397
|
+
constructor(db) {
|
|
1398
|
+
this.db = db;
|
|
1399
|
+
}
|
|
1400
|
+
static async open(logRoot) {
|
|
1401
|
+
const { DatabaseSync } = await loadSqlite();
|
|
1402
|
+
const dir = join(logRoot, ".adrien");
|
|
1403
|
+
mkdirSync(dir, { recursive: true });
|
|
1404
|
+
const gitignore = join(dir, ".gitignore");
|
|
1405
|
+
if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
|
|
1406
|
+
const db = new DatabaseSync(join(dir, "index.db"));
|
|
1407
|
+
if (db.prepare("PRAGMA user_version").get().user_version !== SCHEMA_VERSION) {
|
|
1408
|
+
db.exec("DROP TABLE IF EXISTS docs; DROP TABLE IF EXISTS adr_fts;");
|
|
1409
|
+
db.exec(SCHEMA);
|
|
1410
|
+
db.exec(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
1411
|
+
}
|
|
1412
|
+
return new AdrIndex(db);
|
|
1413
|
+
}
|
|
1414
|
+
sync(view) {
|
|
1415
|
+
const stats = {
|
|
1416
|
+
inserted: 0,
|
|
1417
|
+
updated: 0,
|
|
1418
|
+
deleted: 0,
|
|
1419
|
+
unchanged: 0
|
|
1420
|
+
};
|
|
1421
|
+
const existing = new Map(this.db.prepare("SELECT layer, path, hash FROM docs").all().map((r) => [`${r.layer}\0${r.path}`, r.hash]));
|
|
1422
|
+
const insertDoc = this.db.prepare("INSERT INTO docs (layer, path, hash, id, title, status, tags, components, review_rule, pending_kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
|
1423
|
+
const insertFts = this.db.prepare("INSERT INTO adr_fts (layer, path, title, review_rule, body) VALUES (?, ?, ?, ?, ?)");
|
|
1424
|
+
const remove = (layer, path) => {
|
|
1425
|
+
this.db.prepare("DELETE FROM docs WHERE layer = ? AND path = ?").run(layer, path);
|
|
1426
|
+
this.db.prepare("DELETE FROM adr_fts WHERE layer = ? AND path = ?").run(layer, path);
|
|
1427
|
+
};
|
|
1428
|
+
this.db.exec("BEGIN");
|
|
1429
|
+
try {
|
|
1430
|
+
for (const doc of docsOf(view)) {
|
|
1431
|
+
const key = `${doc.layer}\0${doc.adr.path}`;
|
|
1432
|
+
const hash = hashOf(doc);
|
|
1433
|
+
const previous = existing.get(key);
|
|
1434
|
+
existing.delete(key);
|
|
1435
|
+
if (previous === hash) {
|
|
1436
|
+
stats.unchanged++;
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
if (previous === void 0) stats.inserted++;
|
|
1440
|
+
else {
|
|
1441
|
+
stats.updated++;
|
|
1442
|
+
remove(doc.layer, doc.adr.path);
|
|
1443
|
+
}
|
|
1444
|
+
const { meta, body, path } = doc.adr;
|
|
1445
|
+
insertDoc.run(doc.layer, path, hash, meta.id, meta.title, meta.status, JSON.stringify(meta.tags), JSON.stringify(meta.components), meta.review_rule ?? null, doc.kind);
|
|
1446
|
+
insertFts.run(doc.layer, path, meta.title, meta.review_rule ?? "", body);
|
|
1447
|
+
}
|
|
1448
|
+
for (const key of existing.keys()) {
|
|
1449
|
+
const [layer = "", path = ""] = key.split("\0");
|
|
1450
|
+
remove(layer, path);
|
|
1451
|
+
stats.deleted++;
|
|
1452
|
+
}
|
|
1453
|
+
this.db.exec("COMMIT");
|
|
1454
|
+
} catch (e) {
|
|
1455
|
+
this.db.exec("ROLLBACK");
|
|
1456
|
+
throw e;
|
|
1457
|
+
}
|
|
1458
|
+
return stats;
|
|
1459
|
+
}
|
|
1460
|
+
list(filters = {}) {
|
|
1461
|
+
const where = whereClause(filters);
|
|
1462
|
+
return this.db.prepare(`SELECT ${ROW_COLUMNS} FROM docs WHERE 1 = 1${where.sql} ORDER BY docs.id, docs.layer, docs.path`).all(...where.params).map(toRow);
|
|
1463
|
+
}
|
|
1464
|
+
search(query, filters = {}, limit = 20) {
|
|
1465
|
+
const fts = toFtsQuery(query);
|
|
1466
|
+
if (!fts) return [];
|
|
1467
|
+
const where = whereClause(filters);
|
|
1468
|
+
return this.db.prepare(`SELECT ${ROW_COLUMNS} FROM adr_fts JOIN docs ON docs.layer = adr_fts.layer AND docs.path = adr_fts.path
|
|
1469
|
+
WHERE adr_fts MATCH ?${where.sql} ORDER BY bm25(adr_fts, 0, 0, 5.0, 3.0, 1.0) LIMIT ?`).all(fts, ...where.params, limit).map(toRow);
|
|
1470
|
+
}
|
|
1471
|
+
close() {
|
|
1472
|
+
this.db.close();
|
|
1473
|
+
}
|
|
1474
|
+
};
|
|
1475
|
+
// ../core/src/ops.ts
|
|
1476
|
+
const todayOf = (opts) => opts?.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1477
|
+
function assertWritable(ctx) {
|
|
1478
|
+
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.`);
|
|
1479
|
+
}
|
|
1480
|
+
function validateInput(ctx, input) {
|
|
1481
|
+
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`);
|
|
1482
|
+
const known = Object.keys(ctx.config.components);
|
|
1483
|
+
const badTags = (input.tags ?? []).filter((t) => !ctx.config.tags.includes(t));
|
|
1484
|
+
if (badTags.length) throw new AdrienError("INVALID_INPUT", `Unknown tag(s): ${badTags.join(", ")}. Allowed: ${ctx.config.tags.join(", ")}`);
|
|
1485
|
+
const badComponents = (input.components ?? []).filter((c) => !known.includes(c));
|
|
1486
|
+
if (badComponents.length) throw new AdrienError("INVALID_INPUT", `Unknown component(s): ${badComponents.join(", ")}. Allowed: ${known.join(", ")}`);
|
|
1487
|
+
const badAnchors = (input.code ?? []).filter((raw) => {
|
|
1488
|
+
const anchor = parseAnchor(raw);
|
|
1489
|
+
return !anchor || !known.includes(anchor.component);
|
|
1490
|
+
});
|
|
1491
|
+
if (badAnchors.length) throw new AdrienError("INVALID_INPUT", `Invalid anchor(s): ${badAnchors.join(", ")}. Use <component>:<glob> with a component from: ${known.join(", ")}`);
|
|
1492
|
+
}
|
|
1493
|
+
const allIds = (view) => [...view.base, ...workingAdrs(view)].map((a) => a.meta.id);
|
|
1494
|
+
/**
|
|
1495
|
+
* The ADR as it is on disk now. A view was loaded asynchronously and may predate another edit, and rewriting an ADR from
|
|
1496
|
+
* a stale copy would silently undo that edit.
|
|
1497
|
+
*/
|
|
1498
|
+
function findAdr(ctx, id) {
|
|
1499
|
+
const matches = readWorkingLog(ctx.logRoot, ctx.config).adrs.filter((a) => a.meta.id === id);
|
|
1500
|
+
if (matches.length === 0) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
|
|
1501
|
+
if (matches.length > 1) throw new AdrienError("INVALID_INPUT", `${id} is used by ${matches.map((a) => a.path).join(", ")}. Run \`adrien renumber ${id}\` first`);
|
|
1502
|
+
return matches[0];
|
|
1503
|
+
}
|
|
1504
|
+
function createAdr(ctx, view, input, opts) {
|
|
1505
|
+
assertWritable(ctx);
|
|
1506
|
+
validateInput(ctx, input);
|
|
1507
|
+
const live = {
|
|
1508
|
+
...view,
|
|
1509
|
+
working: readWorkingLog(ctx.logRoot, ctx.config).adrs
|
|
1510
|
+
};
|
|
1511
|
+
const duplicates = findDuplicates(input.title, [...workingAdrs(live), ...live.base]);
|
|
1512
|
+
if (duplicates.length && !opts?.force) return {
|
|
1513
|
+
written: false,
|
|
1514
|
+
duplicates
|
|
1515
|
+
};
|
|
1516
|
+
const id = formatId(nextIdNumber(allIds(live), ctx.config.id_format), ctx.config.id_format);
|
|
1517
|
+
const adr = {
|
|
1518
|
+
path: adrFilePath(ctx.config, id, input.title, input.subdir),
|
|
1519
|
+
body: input.body ?? bodyTemplate(input.template ?? ctx.config.template),
|
|
1520
|
+
meta: {
|
|
1521
|
+
id,
|
|
1522
|
+
title: input.title,
|
|
1523
|
+
status: "proposed",
|
|
1524
|
+
date: todayOf(opts),
|
|
1525
|
+
tags: input.tags ?? [],
|
|
1526
|
+
components: input.components ?? [],
|
|
1527
|
+
code: input.code ?? [],
|
|
1528
|
+
review_rule: input.review_rule,
|
|
1529
|
+
review_on: input.review_on,
|
|
1530
|
+
sources: input.sources ?? [],
|
|
1531
|
+
supersedes: [],
|
|
1532
|
+
related: input.related ?? [],
|
|
1533
|
+
deciders: [],
|
|
1534
|
+
origin: input.origin ?? "manual",
|
|
1535
|
+
contested: false,
|
|
1536
|
+
extra: {}
|
|
1537
|
+
}
|
|
1538
|
+
};
|
|
1539
|
+
if (adr.meta.review_rule === void 0) delete adr.meta.review_rule;
|
|
1540
|
+
if (adr.meta.review_on === void 0) delete adr.meta.review_on;
|
|
1541
|
+
writeAdr(ctx.logRoot, adr, { exclusive: true });
|
|
1542
|
+
return {
|
|
1543
|
+
written: true,
|
|
1544
|
+
adr
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
const PATCH_KEYS = /* @__PURE__ */ new Set([
|
|
1548
|
+
"title",
|
|
1549
|
+
"tags",
|
|
1550
|
+
"components",
|
|
1551
|
+
"code",
|
|
1552
|
+
"review_rule",
|
|
1553
|
+
"sources",
|
|
1554
|
+
"related",
|
|
1555
|
+
"body"
|
|
1556
|
+
]);
|
|
1557
|
+
/** Edits an ADR in the working copy; the merge request that carries it is the approval gate. */
|
|
1558
|
+
function updateAdr(ctx, _view, id, patch, opts) {
|
|
1559
|
+
assertWritable(ctx);
|
|
1560
|
+
const forbidden = Object.keys(patch).filter((k) => !PATCH_KEYS.has(k));
|
|
1561
|
+
if (forbidden.length) throw new AdrienError("INVALID_INPUT", `Cannot change ${forbidden.join(", ")} this way (status changes need an architect)`);
|
|
1562
|
+
validateInput(ctx, patch);
|
|
1563
|
+
const adr = findAdr(ctx, id);
|
|
1564
|
+
const { body, ...metaPatch } = patch;
|
|
1565
|
+
let nextBody = body ?? adr.body;
|
|
1566
|
+
if (opts?.note) nextBody = `${nextBody.replace(/\n*$/, "\n")}\n> Proposed change (${opts.origin ?? "agent"}, ${todayOf(opts)}): ${opts.note}\n`;
|
|
1567
|
+
const updated = {
|
|
1568
|
+
...adr,
|
|
1569
|
+
body: nextBody,
|
|
1570
|
+
meta: {
|
|
1571
|
+
...adr.meta,
|
|
1572
|
+
...metaPatch
|
|
1573
|
+
}
|
|
1574
|
+
};
|
|
1575
|
+
writeAdr(ctx.logRoot, updated);
|
|
1576
|
+
return updated;
|
|
1577
|
+
}
|
|
1578
|
+
function write(ctx, adr, meta) {
|
|
1579
|
+
const updated = {
|
|
1580
|
+
...adr,
|
|
1581
|
+
meta: {
|
|
1582
|
+
...adr.meta,
|
|
1583
|
+
...meta
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
writeAdr(ctx.logRoot, updated);
|
|
1587
|
+
return updated;
|
|
1588
|
+
}
|
|
1589
|
+
function acceptAdr(ctx, _view, id, opts) {
|
|
1590
|
+
assertWritable(ctx);
|
|
1591
|
+
const adr = findAdr(ctx, id);
|
|
1592
|
+
if (!adr.meta.review_rule?.trim()) throw new AdrienError("INVALID_INPUT", `${id} needs a review_rule before it can be accepted`);
|
|
1593
|
+
return write(ctx, adr, {
|
|
1594
|
+
status: "accepted",
|
|
1595
|
+
date: adr.meta.date ?? todayOf(opts)
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
function setStatus(ctx, _view, id, status) {
|
|
1599
|
+
assertWritable(ctx);
|
|
1600
|
+
if (![
|
|
1601
|
+
"proposed",
|
|
1602
|
+
"rejected",
|
|
1603
|
+
"deprecated"
|
|
1604
|
+
].includes(status)) throw new AdrienError("INVALID_INPUT", `Use \`adrien accept\` or \`adrien supersede\` to set "${status}"`);
|
|
1605
|
+
return write(ctx, findAdr(ctx, id), { status });
|
|
1606
|
+
}
|
|
1607
|
+
function supersede(ctx, _view, oldId, newId) {
|
|
1608
|
+
assertWritable(ctx);
|
|
1609
|
+
if (oldId === newId) throw new AdrienError("INVALID_INPUT", `${oldId} cannot supersede itself`);
|
|
1610
|
+
const oldAdr = findAdr(ctx, oldId);
|
|
1611
|
+
const newAdr = findAdr(ctx, newId);
|
|
1612
|
+
return {
|
|
1613
|
+
old: write(ctx, oldAdr, {
|
|
1614
|
+
status: "superseded",
|
|
1615
|
+
superseded_by: newId
|
|
1616
|
+
}),
|
|
1617
|
+
replacement: write(ctx, newAdr, { supersedes: [.../* @__PURE__ */ new Set([...newAdr.meta.supersedes, oldId])] })
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
/** Gives a colliding ADR the next free id; references in other pending ADRs follow it, base ADRs are never touched. */
|
|
1621
|
+
function renumber(ctx, view, id, opts) {
|
|
1622
|
+
assertWritable(ctx);
|
|
1623
|
+
const candidates = readWorkingLog(ctx.logRoot, ctx.config).adrs.filter((a) => a.meta.id === id);
|
|
1624
|
+
if (candidates.length === 0) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
|
|
1625
|
+
const basePaths = new Set(view.base.filter((a) => a.meta.id === id).map((a) => a.path));
|
|
1626
|
+
const notInBase = candidates.filter((a) => !basePaths.has(a.path));
|
|
1627
|
+
const target = opts?.path ? candidates.find((a) => a.path === opts.path) : notInBase.length === 1 ? notInBase[0] : void 0;
|
|
1628
|
+
if (!target) throw new AdrienError("INVALID_INPUT", `Say which file to renumber with --file: ${candidates.map((a) => a.path).join(", ")}`);
|
|
1629
|
+
const to = formatId(nextIdNumber(allIds(view), ctx.config.id_format), ctx.config.id_format);
|
|
1630
|
+
const path = posix.join(posix.dirname(target.path), `${to}-${slugify(target.meta.title)}.md`);
|
|
1631
|
+
const inPlace = path === target.path;
|
|
1632
|
+
writeAdr(ctx.logRoot, {
|
|
1633
|
+
...target,
|
|
1634
|
+
path,
|
|
1635
|
+
meta: {
|
|
1636
|
+
...target.meta,
|
|
1637
|
+
id: to
|
|
1638
|
+
}
|
|
1639
|
+
}, { exclusive: !inPlace });
|
|
1640
|
+
if (!inPlace) unlinkSync(join(ctx.logRoot, ...target.path.split("/")));
|
|
1641
|
+
const swap = (ids) => ids.map((x) => x === id ? to : x);
|
|
1642
|
+
for (const change of view.pending) {
|
|
1643
|
+
const adr = change.current;
|
|
1644
|
+
if (!adr || adr === target) continue;
|
|
1645
|
+
const { supersedes, related, superseded_by } = adr.meta;
|
|
1646
|
+
if (![
|
|
1647
|
+
...supersedes,
|
|
1648
|
+
...related,
|
|
1649
|
+
superseded_by
|
|
1650
|
+
].includes(id)) continue;
|
|
1651
|
+
write(ctx, adr, {
|
|
1652
|
+
supersedes: swap(supersedes),
|
|
1653
|
+
related: swap(related),
|
|
1654
|
+
superseded_by: superseded_by === id ? to : superseded_by
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
return {
|
|
1658
|
+
from: id,
|
|
1659
|
+
to,
|
|
1660
|
+
path
|
|
1661
|
+
};
|
|
1662
|
+
}
|
|
1663
|
+
// src/cli.ts
|
|
1664
|
+
const csv = (value) => (value ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
|
1665
|
+
const collect = (value, previous) => [...previous, value];
|
|
1666
|
+
const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1667
|
+
function contextOf(cli, opts) {
|
|
1668
|
+
return resolveContext({
|
|
1669
|
+
cwd: cli.cwd,
|
|
1670
|
+
log: opts.log,
|
|
1671
|
+
env: cli.env
|
|
1672
|
+
});
|
|
1673
|
+
}
|
|
1674
|
+
async function open(cli, opts) {
|
|
1675
|
+
const ctx = await contextOf(cli, opts);
|
|
1676
|
+
return {
|
|
1677
|
+
ctx,
|
|
1678
|
+
view: await loadLogView(ctx.logRoot, ctx.config)
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
async function withIndex$1(ctx, view, use) {
|
|
1682
|
+
const index = await AdrIndex.open(ctx.logRoot);
|
|
1683
|
+
try {
|
|
1684
|
+
index.sync(view);
|
|
1685
|
+
return use(index);
|
|
1686
|
+
} finally {
|
|
1687
|
+
index.close();
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
function printJson(cli, data) {
|
|
1691
|
+
cli.out(`${JSON.stringify(data, null, 2)}\n`);
|
|
1692
|
+
}
|
|
1693
|
+
// src/commands/accept.ts
|
|
1694
|
+
async function accept(cli, globals, id) {
|
|
1695
|
+
const { ctx, view } = await open(cli, globals);
|
|
1696
|
+
const adr = acceptAdr(ctx, view, id, { today: today() });
|
|
1697
|
+
if (globals.json) return printJson(cli, adr);
|
|
1698
|
+
cli.out(`${id} accepted. Commit and open/merge the MR: merging is the approval.\n`);
|
|
1699
|
+
}
|
|
1700
|
+
function registerAccept(program, cli) {
|
|
1701
|
+
program.command("accept").description("Mark an ADR accepted (the merge of its MR is the approval)").argument("<id>", "ADR id").action((id, _opts, cmd) => accept(cli, cmd.optsWithGlobals(), id));
|
|
1702
|
+
}
|
|
1703
|
+
// src/output.ts
|
|
1704
|
+
function formatRow(row) {
|
|
1705
|
+
const pending = row.layer === "pending" ? ` (pending: ${row.pending_kind})` : "";
|
|
1706
|
+
return `${row.id} ${row.status.padEnd(10)} ${row.tags.join(",")} ${row.title}${pending}\n`;
|
|
1707
|
+
}
|
|
1708
|
+
function formatFileDecisions(files) {
|
|
1709
|
+
const lines = [];
|
|
1710
|
+
for (const file of files) {
|
|
1711
|
+
lines.push(file.component ? `${file.file} [${file.component}]` : file.file);
|
|
1712
|
+
if (!file.component) lines.push(" (not inside a linked component)");
|
|
1713
|
+
for (const d of file.decisions) {
|
|
1714
|
+
const label = d.binding ? "BINDING" : d.layer === "pending" ? `pending ${d.pending_kind}` : `hint (${d.status})`;
|
|
1715
|
+
lines.push(` ${d.id} ${label} ${d.title}`);
|
|
1716
|
+
if (d.review_rule) lines.push(` rule: ${d.review_rule}`);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
return `${lines.join("\n")}\n`;
|
|
1720
|
+
}
|
|
1721
|
+
function formatDiagnostic(d) {
|
|
1722
|
+
return `${[
|
|
1723
|
+
d.severity,
|
|
1724
|
+
d.code,
|
|
1725
|
+
d.id,
|
|
1726
|
+
d.path,
|
|
1727
|
+
d.message
|
|
1728
|
+
].filter(Boolean).join(" ")}\n`;
|
|
1729
|
+
}
|
|
1730
|
+
// src/commands/check.ts
|
|
1731
|
+
function registerCheck(program, cli) {
|
|
1732
|
+
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) => {
|
|
1733
|
+
const globals = cmd.optsWithGlobals();
|
|
1734
|
+
const ctx = await contextOf(cli, globals);
|
|
1735
|
+
if (opts.mr) {
|
|
1736
|
+
const top = await gitToplevel(ctx.logRoot);
|
|
1737
|
+
if (top) await fetchOrigin(top);
|
|
1738
|
+
}
|
|
1739
|
+
const diags = await runCheck(ctx, await loadLogView(ctx.logRoot, ctx.config), {
|
|
1740
|
+
here: opts.here,
|
|
1741
|
+
mr: opts.mr,
|
|
1742
|
+
lint: opts.lint
|
|
1743
|
+
});
|
|
1744
|
+
const errors = diags.filter((d) => d.severity === "error").length;
|
|
1745
|
+
const warnings = diags.filter((d) => d.severity === "warning").length;
|
|
1746
|
+
cli.setCode(exitCodeFor(diags, opts.strict));
|
|
1747
|
+
if (globals.json) return printJson(cli, {
|
|
1748
|
+
errors,
|
|
1749
|
+
warnings,
|
|
1750
|
+
diagnostics: diags
|
|
1751
|
+
});
|
|
1752
|
+
for (const d of diags) cli.out(formatDiagnostic(d));
|
|
1753
|
+
cli.out(`${errors} errors, ${warnings} warnings\n`);
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
// src/commands/export.ts
|
|
1757
|
+
function registerExport(program, cli) {
|
|
1758
|
+
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) => {
|
|
1759
|
+
const format = opts.format;
|
|
1760
|
+
if (!EXPORT_FORMATS.includes(format)) throw new AdrienError("INVALID_INPUT", `Unknown format "${opts.format}". Use one of: ${EXPORT_FORMATS.join(", ")}`);
|
|
1761
|
+
const { ctx, view } = await open(cli, cmd.optsWithGlobals());
|
|
1762
|
+
if (!opts.out) return cli.out(exportLog(ctx, view, format));
|
|
1763
|
+
const file = resolve(cli.cwd, opts.out);
|
|
1764
|
+
const text = exportLog(ctx, view, format, { from: dirname(file) });
|
|
1765
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
1766
|
+
writeFileSync(file, text);
|
|
1767
|
+
cli.out(`Wrote ${opts.out}\n`);
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
// src/commands/for.ts
|
|
1771
|
+
function registerFor(program, cli) {
|
|
1772
|
+
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) => {
|
|
1773
|
+
const globals = cmd.optsWithGlobals();
|
|
1774
|
+
const { ctx, view } = await open(cli, globals);
|
|
1775
|
+
const files = adrsForFiles(ctx, view, paths);
|
|
1776
|
+
const note = unverifiedBaseNote(view);
|
|
1777
|
+
if (note) cli.err(`note: ${note}\n`);
|
|
1778
|
+
if (globals.json) return printJson(cli, files);
|
|
1779
|
+
cli.out(formatFileDecisions(files));
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
// src/commands/init.ts
|
|
1783
|
+
const AGENTS_SNIPPET = `<!-- adrien:start -->
|
|
1784
|
+
## Architecture decisions (Adrien)
|
|
1785
|
+
Before changing code, call the \`adr_for_files\` MCP tool with the files you will touch, and follow the \`review_rule\` of every binding ADR. If your change contradicts an accepted ADR, stop and tell the user instead of working around it. Record a new durable decision with \`adr_propose\`. Never set an ADR's status to \`accepted\` yourself.
|
|
1786
|
+
<!-- adrien:end -->`;
|
|
1787
|
+
const AGENTS_BLOCK = /<!-- adrien:start -->[\s\S]*?<!-- adrien:end -->/;
|
|
1788
|
+
function setupHint(config) {
|
|
1789
|
+
return [
|
|
1790
|
+
`Created ${CONFIG_FILE} (product: ${config.product}).`,
|
|
1791
|
+
"Next:",
|
|
1792
|
+
` 1. Add to CODEOWNERS: ${config.adr_dir}/ @your-architects-group`,
|
|
1793
|
+
" 2. GitLab Premium+: Settings > Repository > Protected branches > require Code Owner approval on the default branch.",
|
|
1794
|
+
" 3. In each code repo: adrien init --code-repo --log <path|url> && adrien init --agents",
|
|
1795
|
+
""
|
|
1796
|
+
].join("\n");
|
|
1797
|
+
}
|
|
1798
|
+
function initLog(cli, opts) {
|
|
1799
|
+
const config = {
|
|
1800
|
+
product: opts.product ?? basename(cli.cwd),
|
|
1801
|
+
adr_dir: opts.adrDir,
|
|
1802
|
+
id_format: opts.idFormat,
|
|
1803
|
+
tags: opts.tags ? csv(opts.tags) : DEFAULT_TAGS,
|
|
1804
|
+
components: Object.fromEntries(csv(opts.components).map((c) => [c, {}]))
|
|
1805
|
+
};
|
|
1806
|
+
writeLogConfig(cli.cwd, config);
|
|
1807
|
+
try {
|
|
1808
|
+
loadLogConfig(cli.cwd);
|
|
1809
|
+
} catch (e) {
|
|
1810
|
+
rmSync(join(cli.cwd, CONFIG_FILE));
|
|
1811
|
+
throw e;
|
|
1812
|
+
}
|
|
1813
|
+
const adrDir = join(cli.cwd, ...config.adr_dir.split("/"));
|
|
1814
|
+
mkdirSync(adrDir, { recursive: true });
|
|
1815
|
+
if (!existsSync(join(adrDir, ".gitkeep"))) writeFileSync(join(adrDir, ".gitkeep"), "");
|
|
1816
|
+
cli.out(setupHint(config));
|
|
1817
|
+
}
|
|
1818
|
+
function initCodeRepo(cli, opts) {
|
|
1819
|
+
if (!opts.log) throw new AdrienError("INVALID_INPUT", "--code-repo needs --log <path|url>.");
|
|
1820
|
+
if (!isGitUrl(opts.log)) loadLogConfig(resolve(cli.cwd, opts.log));
|
|
1821
|
+
const components = csv(opts.components);
|
|
1822
|
+
writeCodeRepoConfig(cli.cwd, {
|
|
1823
|
+
log: opts.log,
|
|
1824
|
+
...components.length ? { components } : {}
|
|
1825
|
+
});
|
|
1826
|
+
cli.out(`Created ${CODE_CONFIG_FILE} (log: ${opts.log}).\nNext: adrien init --agents\n`);
|
|
1827
|
+
}
|
|
1828
|
+
function initAgents(cli) {
|
|
1829
|
+
const file = join(cli.cwd, "AGENTS.md");
|
|
1830
|
+
const current = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
1831
|
+
let next;
|
|
1832
|
+
if (current === null) next = `${AGENTS_SNIPPET}\n`;
|
|
1833
|
+
else if (AGENTS_BLOCK.test(current)) next = current.replace(AGENTS_BLOCK, () => AGENTS_SNIPPET);
|
|
1834
|
+
else next = `${current}${current === "" || current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n"}${AGENTS_SNIPPET}\n`;
|
|
1835
|
+
writeFileSync(file, next);
|
|
1836
|
+
cli.out(`${current === null ? "Created" : "Updated"} AGENTS.md with the Adrien block.\n`);
|
|
1837
|
+
const claude = join(cli.cwd, "CLAUDE.md");
|
|
1838
|
+
if (existsSync(claude) && !readFileSync(claude, "utf8").includes("AGENTS.md")) cli.out("Tip: add \"@AGENTS.md\" to CLAUDE.md so Claude Code reads it.\n");
|
|
1839
|
+
}
|
|
1840
|
+
function registerInit(program, cli) {
|
|
1841
|
+
program.command("init").description("Create adrien.config.yaml for an ADR log (run it in the log repo), or set up a code repo").option("--code-repo", "in a code repo: write .adrien.yaml pointing at the log (needs --log)").option("--agents", "add the Adrien block to AGENTS.md").option("--product <name>", "product name (default: the directory name)").option("--adr-dir <dir>", "where ADR files live", "docs/adr").option("--tags <list>", "allowed tags, comma-separated (default: frontend,backend,database,infra,security)").option("--components <list>", "components, comma-separated (log: add their repo URLs to the config later; --code-repo: override detection)").option("--id-format <format>", "id format", "ADR-{n:4}").action((opts, cmd) => {
|
|
1842
|
+
const { log } = cmd.optsWithGlobals();
|
|
1843
|
+
if (opts.codeRepo) initCodeRepo(cli, {
|
|
1844
|
+
...opts,
|
|
1845
|
+
log
|
|
1846
|
+
});
|
|
1847
|
+
if (opts.agents) initAgents(cli);
|
|
1848
|
+
if (!opts.codeRepo && !opts.agents) initLog(cli, opts);
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
// src/commands/lint.ts
|
|
1852
|
+
function registerLint(program, cli) {
|
|
1853
|
+
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) => {
|
|
1854
|
+
const globals = cmd.optsWithGlobals();
|
|
1855
|
+
const ctx = await contextOf(cli, globals);
|
|
1856
|
+
const diags = await lintAdrs(ctx, await loadLogView(ctx.logRoot, ctx.config));
|
|
1857
|
+
cli.setCode(exitCodeFor(diags, opts.strict));
|
|
1858
|
+
if (globals.json) return printJson(cli, {
|
|
1859
|
+
errors: 0,
|
|
1860
|
+
warnings: diags.length,
|
|
1861
|
+
diagnostics: diags
|
|
1862
|
+
});
|
|
1863
|
+
for (const d of diags) cli.out(formatDiagnostic(d));
|
|
1864
|
+
cli.out(`0 errors, ${diags.length} warnings\n`);
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
// src/commands/list.ts
|
|
1868
|
+
function registerList(program, cli) {
|
|
1869
|
+
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) => {
|
|
1870
|
+
const globals = cmd.optsWithGlobals();
|
|
1871
|
+
const { ctx, view } = await open(cli, globals);
|
|
1872
|
+
const rows = await withIndex$1(ctx, view, (index) => index.list({
|
|
1873
|
+
tags: opts.tag,
|
|
1874
|
+
components: opts.component,
|
|
1875
|
+
status: opts.status,
|
|
1876
|
+
layer: opts.pending ? "pending" : "all"
|
|
1877
|
+
}));
|
|
1878
|
+
if (globals.json) return printJson(cli, rows);
|
|
1879
|
+
for (const row of rows) cli.out(formatRow(row));
|
|
1880
|
+
});
|
|
1881
|
+
}
|
|
1882
|
+
// ../mcp/src/tools.ts
|
|
1883
|
+
const ok = (result) => ({
|
|
1884
|
+
structuredContent: result,
|
|
1885
|
+
content: [{
|
|
1886
|
+
type: "text",
|
|
1887
|
+
text: JSON.stringify(result)
|
|
1888
|
+
}]
|
|
1889
|
+
});
|
|
1890
|
+
const fail = (text) => ({
|
|
1891
|
+
isError: true,
|
|
1892
|
+
content: [{
|
|
1893
|
+
type: "text",
|
|
1894
|
+
text
|
|
1895
|
+
}]
|
|
1896
|
+
});
|
|
1897
|
+
const strings = z.array(z.string());
|
|
1898
|
+
const status = z.array(z.enum(STATUSES));
|
|
1899
|
+
async function load(opts) {
|
|
1900
|
+
const ctx = await resolveContext({
|
|
1901
|
+
cwd: opts.cwd,
|
|
1902
|
+
log: opts.log,
|
|
1903
|
+
env: opts.env ?? process.env
|
|
1904
|
+
});
|
|
1905
|
+
return {
|
|
1906
|
+
ctx,
|
|
1907
|
+
view: await loadLogView(ctx.logRoot, ctx.config)
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
/** Every call re-reads the log, so a tool never answers from state another process has since changed. */
|
|
1911
|
+
function handler(opts, run) {
|
|
1912
|
+
return async (args) => {
|
|
1913
|
+
try {
|
|
1914
|
+
const { ctx, view } = await load(opts);
|
|
1915
|
+
return await run(args, ctx, view);
|
|
1916
|
+
} catch (e) {
|
|
1917
|
+
if (e instanceof AdrienError) return fail(`${e.code}: ${e.message}`);
|
|
1918
|
+
throw e;
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
}
|
|
1922
|
+
async function withIndex(ctx, view, use) {
|
|
1923
|
+
const index = await AdrIndex.open(ctx.logRoot);
|
|
1924
|
+
try {
|
|
1925
|
+
index.sync(view);
|
|
1926
|
+
return use(index);
|
|
1927
|
+
} finally {
|
|
1928
|
+
index.close();
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
const adrView = (adr) => ({
|
|
1932
|
+
meta: adr.meta,
|
|
1933
|
+
body: adr.body,
|
|
1934
|
+
path: adr.path
|
|
1935
|
+
});
|
|
1936
|
+
const section = (heading, text) => text?.trim() ? `## ${heading}\n\n${text.trim()}\n` : `## ${heading}\n`;
|
|
1937
|
+
function registerTools(server, opts) {
|
|
1938
|
+
server.registerTool("adr_for_files", {
|
|
1939
|
+
title: "Decisions governing files",
|
|
1940
|
+
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.",
|
|
1941
|
+
inputSchema: { paths: z.array(z.string().min(1)).min(1).max(50) }
|
|
1942
|
+
}, handler(opts, ({ paths }, ctx, view) => {
|
|
1943
|
+
const note = unverifiedBaseNote(view);
|
|
1944
|
+
return ok({
|
|
1945
|
+
files: adrsForFiles(ctx, view, paths),
|
|
1946
|
+
...note ? { notes: [note] } : {}
|
|
1947
|
+
});
|
|
1948
|
+
}));
|
|
1949
|
+
server.registerTool("adr_search", {
|
|
1950
|
+
title: "Search decisions",
|
|
1951
|
+
description: "Full-text search over ADR titles, review rules and bodies. Accent-insensitive; prefix matching.",
|
|
1952
|
+
inputSchema: {
|
|
1953
|
+
query: z.string().min(1),
|
|
1954
|
+
tags: strings.optional(),
|
|
1955
|
+
components: strings.optional(),
|
|
1956
|
+
status: status.optional(),
|
|
1957
|
+
limit: z.number().int().min(1).max(50).default(10)
|
|
1958
|
+
}
|
|
1959
|
+
}, handler(opts, async (args, ctx, view) => ok({ results: await withIndex(ctx, view, (index) => index.search(args.query, {
|
|
1960
|
+
tags: args.tags,
|
|
1961
|
+
components: args.components,
|
|
1962
|
+
status: args.status,
|
|
1963
|
+
layer: "all"
|
|
1964
|
+
}, args.limit)) })));
|
|
1965
|
+
server.registerTool("adr_list", {
|
|
1966
|
+
title: "List decisions",
|
|
1967
|
+
description: "Compact rows (id, title, status, tags, components, review_rule). Tags must all match; components any.",
|
|
1968
|
+
inputSchema: {
|
|
1969
|
+
tags: strings.optional(),
|
|
1970
|
+
components: strings.optional(),
|
|
1971
|
+
status: status.optional(),
|
|
1972
|
+
pending_only: z.boolean().optional()
|
|
1973
|
+
}
|
|
1974
|
+
}, handler(opts, async (args, ctx, view) => {
|
|
1975
|
+
const filters = {
|
|
1976
|
+
tags: args.tags,
|
|
1977
|
+
components: args.components,
|
|
1978
|
+
status: args.status,
|
|
1979
|
+
layer: args.pending_only ? "pending" : "all"
|
|
1980
|
+
};
|
|
1981
|
+
return ok({ results: await withIndex(ctx, view, (index) => index.list(filters)) });
|
|
1982
|
+
}));
|
|
1983
|
+
server.registerTool("adr_get", {
|
|
1984
|
+
title: "Read one decision",
|
|
1985
|
+
description: "The full ADR: the binding version on the default branch, and any pending change to it.",
|
|
1986
|
+
inputSchema: { id: z.string().min(1) }
|
|
1987
|
+
}, handler(opts, ({ id }, _ctx, view) => {
|
|
1988
|
+
const base = view.base.find((a) => a.meta.id === id) ?? null;
|
|
1989
|
+
const change = view.pending.find((c) => c.id === id) ?? null;
|
|
1990
|
+
if (!base && !change) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
|
|
1991
|
+
return ok({
|
|
1992
|
+
id,
|
|
1993
|
+
base: base && adrView(base),
|
|
1994
|
+
pending: change && {
|
|
1995
|
+
kind: change.kind,
|
|
1996
|
+
...change.current ? adrView(change.current) : {}
|
|
1997
|
+
}
|
|
1998
|
+
});
|
|
1999
|
+
}));
|
|
2000
|
+
server.registerTool("adr_propose", {
|
|
2001
|
+
title: "Propose a new decision",
|
|
2002
|
+
description: "Record a durable architecture decision as a PROPOSED ADR in the working copy. It is never accepted by this call: an architect accepts it by merging its merge request. Returns possible duplicates instead of writing; pass force:true only if the decision really is distinct.",
|
|
2003
|
+
inputSchema: {
|
|
2004
|
+
title: z.string().min(1),
|
|
2005
|
+
context: z.string().min(1),
|
|
2006
|
+
decision: z.string().min(1),
|
|
2007
|
+
rationale: z.string().min(1),
|
|
2008
|
+
review_rule: z.string().min(1),
|
|
2009
|
+
options: z.string().optional(),
|
|
2010
|
+
consequences: z.string().optional(),
|
|
2011
|
+
tags: strings.optional(),
|
|
2012
|
+
components: strings.optional(),
|
|
2013
|
+
code: strings.optional(),
|
|
2014
|
+
sources: strings.optional(),
|
|
2015
|
+
related: strings.optional(),
|
|
2016
|
+
force: z.boolean().optional()
|
|
2017
|
+
}
|
|
2018
|
+
}, handler(opts, (a, ctx, view) => {
|
|
2019
|
+
const body = `\n${[
|
|
2020
|
+
section("Context", a.context),
|
|
2021
|
+
section("Considered options", a.options),
|
|
2022
|
+
section("Decision", a.decision),
|
|
2023
|
+
section("Rationale", a.rationale),
|
|
2024
|
+
section("Consequences", a.consequences)
|
|
2025
|
+
].join("\n")}`;
|
|
2026
|
+
const result = createAdr(ctx, view, {
|
|
2027
|
+
title: a.title,
|
|
2028
|
+
tags: a.tags,
|
|
2029
|
+
components: a.components,
|
|
2030
|
+
code: a.code,
|
|
2031
|
+
review_rule: a.review_rule,
|
|
2032
|
+
sources: a.sources,
|
|
2033
|
+
related: a.related,
|
|
2034
|
+
body,
|
|
2035
|
+
origin: "agent"
|
|
2036
|
+
}, {
|
|
2037
|
+
today: opts.today?.(),
|
|
2038
|
+
force: a.force
|
|
2039
|
+
});
|
|
2040
|
+
return ok(result.written ? {
|
|
2041
|
+
written: true,
|
|
2042
|
+
id: result.adr.meta.id,
|
|
2043
|
+
path: result.adr.path
|
|
2044
|
+
} : {
|
|
2045
|
+
written: false,
|
|
2046
|
+
duplicates: result.duplicates
|
|
2047
|
+
});
|
|
2048
|
+
}));
|
|
2049
|
+
server.registerTool("adr_propose_change", {
|
|
2050
|
+
title: "Propose a change to a decision",
|
|
2051
|
+
description: "Edit an existing ADR in the working copy. The edit is pending until its merge request is approved; the default-branch version stays the binding one. You cannot change status.",
|
|
2052
|
+
inputSchema: {
|
|
2053
|
+
id: z.string().min(1),
|
|
2054
|
+
patch: z.strictObject({
|
|
2055
|
+
title: z.string().min(1).optional(),
|
|
2056
|
+
tags: strings.optional(),
|
|
2057
|
+
components: strings.optional(),
|
|
2058
|
+
code: strings.optional(),
|
|
2059
|
+
review_rule: z.string().min(1).optional(),
|
|
2060
|
+
sources: strings.optional(),
|
|
2061
|
+
related: strings.optional(),
|
|
2062
|
+
body: z.string().optional()
|
|
2063
|
+
}),
|
|
2064
|
+
rationale: z.string().min(1)
|
|
2065
|
+
}
|
|
2066
|
+
}, handler(opts, (a, ctx, view) => {
|
|
2067
|
+
const updated = updateAdr(ctx, view, a.id, a.patch, {
|
|
2068
|
+
note: a.rationale,
|
|
2069
|
+
origin: "agent",
|
|
2070
|
+
today: opts.today?.()
|
|
2071
|
+
});
|
|
2072
|
+
return ok({
|
|
2073
|
+
id: updated.meta.id,
|
|
2074
|
+
path: updated.path,
|
|
2075
|
+
pending: true
|
|
2076
|
+
});
|
|
2077
|
+
}));
|
|
2078
|
+
}
|
|
2079
|
+
// ../mcp/src/server.ts
|
|
2080
|
+
const INSTRUCTIONS = "Before changing code, call the `adr_for_files` tool with the files you will touch, and follow the `review_rule` of every binding ADR. If your change contradicts an accepted ADR, stop and tell the user instead of working around it. Record a new durable decision with `adr_propose`. Never set an ADR's status to `accepted` yourself.";
|
|
2081
|
+
function createAdrienServer(opts) {
|
|
2082
|
+
const server = new McpServer({
|
|
2083
|
+
name: "adrien",
|
|
2084
|
+
version: opts.version ?? "0.0.0"
|
|
2085
|
+
}, { instructions: INSTRUCTIONS });
|
|
2086
|
+
registerTools(server, opts);
|
|
2087
|
+
return server;
|
|
2088
|
+
}
|
|
2089
|
+
async function startStdio(opts) {
|
|
2090
|
+
await createAdrienServer(opts).connect(new StdioServerTransport());
|
|
2091
|
+
}
|
|
2092
|
+
// src/commands/mcp.ts
|
|
2093
|
+
function registerMcp(program, cli) {
|
|
2094
|
+
program.command("mcp").description("Run the MCP server on stdio, for AI agents (run it from the code repo or log repo)").action(async (_opts, cmd) => {
|
|
2095
|
+
const { log } = cmd.optsWithGlobals();
|
|
2096
|
+
await startStdio({
|
|
2097
|
+
cwd: cli.cwd,
|
|
2098
|
+
log,
|
|
2099
|
+
env: cli.env,
|
|
2100
|
+
version: program.version()
|
|
2101
|
+
});
|
|
2102
|
+
});
|
|
2103
|
+
}
|
|
2104
|
+
// src/commands/new.ts
|
|
2105
|
+
function registerNew(program, cli) {
|
|
2106
|
+
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) => {
|
|
2107
|
+
const globals = cmd.optsWithGlobals();
|
|
2108
|
+
if (opts.template && !TEMPLATE_NAMES.includes(opts.template)) throw new AdrienError("INVALID_INPUT", `Unknown template "${opts.template}". Use one of: ${TEMPLATE_NAMES.join(", ")}`);
|
|
2109
|
+
const { ctx, view } = await open(cli, globals);
|
|
2110
|
+
const result = createAdr(ctx, view, {
|
|
2111
|
+
title,
|
|
2112
|
+
tags: csv(opts.tags),
|
|
2113
|
+
components: csv(opts.components),
|
|
2114
|
+
code: opts.code,
|
|
2115
|
+
review_rule: opts.reviewRule,
|
|
2116
|
+
review_on: opts.reviewOn,
|
|
2117
|
+
subdir: opts.subdir,
|
|
2118
|
+
template: opts.template
|
|
2119
|
+
}, {
|
|
2120
|
+
today: today(),
|
|
2121
|
+
force: opts.force
|
|
2122
|
+
});
|
|
2123
|
+
if (!result.written) cli.setCode(1);
|
|
2124
|
+
if (globals.json) return printJson(cli, result);
|
|
2125
|
+
if (result.written) {
|
|
2126
|
+
cli.out(`Created ${result.adr.meta.id} ${result.adr.path} (proposed)\n`);
|
|
2127
|
+
return;
|
|
2128
|
+
}
|
|
2129
|
+
cli.out("Possible duplicates:\n");
|
|
2130
|
+
for (const hit of result.duplicates) cli.out(` ${hit.id} ${hit.score} ${hit.title}\n`);
|
|
2131
|
+
cli.out("Use --force to create anyway.\n");
|
|
2132
|
+
});
|
|
2133
|
+
}
|
|
2134
|
+
// src/commands/renumber.ts
|
|
2135
|
+
function registerRenumber(program, cli) {
|
|
2136
|
+
program.command("renumber").description("Give an ADR with a colliding id the next free one").argument("<id>", "the colliding id").option("--file <path>", "which file to renumber when several share the id").action(async (id, opts, cmd) => {
|
|
2137
|
+
const globals = cmd.optsWithGlobals();
|
|
2138
|
+
const { ctx, view } = await open(cli, globals);
|
|
2139
|
+
const result = renumber(ctx, view, id, { path: opts.file });
|
|
2140
|
+
if (globals.json) return printJson(cli, result);
|
|
2141
|
+
cli.out(`Renumbered ${result.from} -> ${result.to} (${result.path})\n`);
|
|
2142
|
+
});
|
|
2143
|
+
}
|
|
2144
|
+
// src/commands/search.ts
|
|
2145
|
+
function registerSearch(program, cli) {
|
|
2146
|
+
program.command("search").description("Full-text search over titles, review rules and bodies").argument("<query...>", "words to look for").action(async (query, _opts, cmd) => {
|
|
2147
|
+
const globals = cmd.optsWithGlobals();
|
|
2148
|
+
const { ctx, view } = await open(cli, globals);
|
|
2149
|
+
const rows = await withIndex$1(ctx, view, (index) => index.search(query.join(" ")));
|
|
2150
|
+
if (globals.json) return printJson(cli, rows);
|
|
2151
|
+
for (const row of rows) cli.out(formatRow(row));
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
// src/commands/show.ts
|
|
2155
|
+
function registerShow(program, cli) {
|
|
2156
|
+
program.command("show").description("Print an ADR, with its pending change if any").argument("<id>", "ADR id").action(async (id, _opts, cmd) => {
|
|
2157
|
+
const globals = cmd.optsWithGlobals();
|
|
2158
|
+
const { view } = await open(cli, globals);
|
|
2159
|
+
const base = view.base.find((a) => a.meta.id === id) ?? null;
|
|
2160
|
+
const change = view.pending.find((c) => c.id === id) ?? null;
|
|
2161
|
+
if (!base && !change) throw new AdrienError("ADR_NOT_FOUND", `No ADR ${id} in the log`);
|
|
2162
|
+
if (globals.json) return printJson(cli, {
|
|
2163
|
+
id,
|
|
2164
|
+
base,
|
|
2165
|
+
pending: change && {
|
|
2166
|
+
kind: change.kind,
|
|
2167
|
+
current: change.current ?? null
|
|
2168
|
+
}
|
|
2169
|
+
});
|
|
2170
|
+
if (base) cli.out(serializeAdr(base));
|
|
2171
|
+
if (change) {
|
|
2172
|
+
cli.out(`\n--- PENDING (${change.kind}) — not binding until merged ---\n`);
|
|
2173
|
+
cli.out(change.current ? serializeAdr(change.current) : "(deleted)\n");
|
|
2174
|
+
}
|
|
2175
|
+
});
|
|
2176
|
+
}
|
|
2177
|
+
// src/commands/status.ts
|
|
2178
|
+
const SETTABLE = [
|
|
2179
|
+
"proposed",
|
|
2180
|
+
"rejected",
|
|
2181
|
+
"deprecated"
|
|
2182
|
+
];
|
|
2183
|
+
function registerStatus(program, cli) {
|
|
2184
|
+
program.command("status").description("Set an ADR status (accepted and superseded have their own commands)").argument("<id>", "ADR id").argument("<status>", STATUSES.join(" | ")).action(async (id, status, _opts, cmd) => {
|
|
2185
|
+
const globals = cmd.optsWithGlobals();
|
|
2186
|
+
if (status === "accepted") return accept(cli, globals, id);
|
|
2187
|
+
if (status === "superseded") throw new AdrienError("INVALID_INPUT", "Use `adrien supersede <old> --by <new>`.");
|
|
2188
|
+
if (!SETTABLE.includes(status)) throw new AdrienError("INVALID_INPUT", `Unknown status "${status}". Use one of: ${STATUSES.join(", ")}`);
|
|
2189
|
+
const { ctx, view } = await open(cli, globals);
|
|
2190
|
+
const adr = setStatus(ctx, view, id, status);
|
|
2191
|
+
if (globals.json) return printJson(cli, adr);
|
|
2192
|
+
cli.out(`${id} ${status}\n`);
|
|
2193
|
+
});
|
|
2194
|
+
}
|
|
2195
|
+
// src/commands/supersede.ts
|
|
2196
|
+
function registerSupersede(program, cli) {
|
|
2197
|
+
program.command("supersede").description("Mark an ADR superseded by another and link both").argument("<old>", "the ADR being replaced").requiredOption("--by <id>", "the ADR that replaces it").action(async (oldId, opts, cmd) => {
|
|
2198
|
+
const globals = cmd.optsWithGlobals();
|
|
2199
|
+
const { ctx, view } = await open(cli, globals);
|
|
2200
|
+
const result = supersede(ctx, view, oldId, opts.by);
|
|
2201
|
+
if (globals.json) return printJson(cli, result);
|
|
2202
|
+
cli.out(`${oldId} superseded by ${opts.by}.\n`);
|
|
2203
|
+
});
|
|
2204
|
+
}
|
|
2205
|
+
// src/commands/sync.ts
|
|
2206
|
+
function registerSync(program, cli) {
|
|
2207
|
+
program.command("sync").description("Fetch the latest default branch of the ADR log").action(async (_opts, cmd) => {
|
|
2208
|
+
const globals = cmd.optsWithGlobals();
|
|
2209
|
+
const ctx = await contextOf(cli, globals);
|
|
2210
|
+
if (ctx.readOnly) await syncCachedClone(ctx.logRoot);
|
|
2211
|
+
else {
|
|
2212
|
+
const top = await gitToplevel(ctx.logRoot);
|
|
2213
|
+
if (top) await fetchOrigin(top);
|
|
2214
|
+
}
|
|
2215
|
+
const { baseRef } = await loadLogView(ctx.logRoot, ctx.config);
|
|
2216
|
+
if (globals.json) return printJson(cli, {
|
|
2217
|
+
log: ctx.logSource,
|
|
2218
|
+
baseRef
|
|
2219
|
+
});
|
|
2220
|
+
cli.out(`Log ${ctx.logSource} at ${baseRef ?? "the working tree"}\n`);
|
|
2221
|
+
});
|
|
2222
|
+
}
|
|
2223
|
+
// src/program.ts
|
|
2224
|
+
const VERSION = createRequire(import.meta.url)("../package.json").version;
|
|
2225
|
+
const CLEAN_EXITS = /* @__PURE__ */ new Set([
|
|
2226
|
+
"commander.helpDisplayed",
|
|
2227
|
+
"commander.version",
|
|
2228
|
+
"commander.help"
|
|
2229
|
+
]);
|
|
2230
|
+
function buildProgram(cli) {
|
|
2231
|
+
const program = new Command("adrien").description("Architecture Decision Records for developers and their AI agents").version(VERSION, "-v, --version").option("--log <path|url>", "ADR log to use (default: found from the current directory)").option("--json", "machine-readable output").exitOverride().configureOutput({
|
|
2232
|
+
writeOut: (s) => cli.out(s),
|
|
2233
|
+
writeErr: (s) => cli.err(s)
|
|
2234
|
+
});
|
|
2235
|
+
for (const register of [
|
|
2236
|
+
registerInit,
|
|
2237
|
+
registerNew,
|
|
2238
|
+
registerList,
|
|
2239
|
+
registerShow,
|
|
2240
|
+
registerSearch,
|
|
2241
|
+
registerFor,
|
|
2242
|
+
registerCheck,
|
|
2243
|
+
registerLint,
|
|
2244
|
+
registerAccept,
|
|
2245
|
+
registerStatus,
|
|
2246
|
+
registerSupersede,
|
|
2247
|
+
registerRenumber,
|
|
2248
|
+
registerSync,
|
|
2249
|
+
registerExport,
|
|
2250
|
+
registerMcp
|
|
2251
|
+
]) register(program, cli);
|
|
2252
|
+
return program;
|
|
2253
|
+
}
|
|
2254
|
+
/** Runs one CLI invocation and returns its exit code and output (the bin writes them; tests read them). */
|
|
2255
|
+
async function runCli(argv, io) {
|
|
2256
|
+
let stdout = "";
|
|
2257
|
+
let stderr = "";
|
|
2258
|
+
let code = 0;
|
|
2259
|
+
const env = io.env ?? process.env;
|
|
2260
|
+
const cli = {
|
|
2261
|
+
cwd: io.cwd,
|
|
2262
|
+
env,
|
|
2263
|
+
out: (s) => {
|
|
2264
|
+
stdout += s;
|
|
2265
|
+
},
|
|
2266
|
+
err: (s) => {
|
|
2267
|
+
stderr += s;
|
|
2268
|
+
},
|
|
2269
|
+
setCode: (c) => {
|
|
2270
|
+
code = c;
|
|
2271
|
+
}
|
|
2272
|
+
};
|
|
2273
|
+
try {
|
|
2274
|
+
await buildProgram(cli).parseAsync(argv, { from: "user" });
|
|
2275
|
+
} catch (e) {
|
|
2276
|
+
if (e instanceof CommanderError) code = CLEAN_EXITS.has(e.code) ? 0 : 2;
|
|
2277
|
+
else if (e instanceof AdrienError) {
|
|
2278
|
+
stderr += `adrien: ${e.message}\n`;
|
|
2279
|
+
code = 2;
|
|
2280
|
+
} else {
|
|
2281
|
+
const error = e;
|
|
2282
|
+
stderr += `adrien: unexpected error: ${error.message}\n`;
|
|
2283
|
+
if (env.ADRIEN_DEBUG === "1" && error.stack) stderr += `${error.stack}\n`;
|
|
2284
|
+
code = 3;
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
return {
|
|
2288
|
+
code,
|
|
2289
|
+
stdout,
|
|
2290
|
+
stderr
|
|
2291
|
+
};
|
|
2292
|
+
}
|
|
2293
|
+
// src/index.ts
|
|
2294
|
+
const { code, stdout, stderr } = await runCli(process.argv.slice(2), {
|
|
2295
|
+
cwd: process.cwd(),
|
|
2296
|
+
env: process.env
|
|
2297
|
+
});
|
|
2298
|
+
process.stdout.write(stdout);
|
|
2299
|
+
process.stderr.write(stderr);
|
|
2300
|
+
process.exitCode = code;
|
|
2301
|
+
export {};
|