repo-cortex 0.0.0-stage → 0.1.0-bootstrap.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 ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alan B Smith
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,88 @@
1
- # Temporary Holding Version
1
+ # repo-cortex
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Give a repository a **cortex**: a small `cortex/` folder of plain Markdown that holds the why behind the project. It holds decisions and their reasons, open questions, why each milestone exists, and where things stand right now. A fresh agent session (or a new teammate) reads it on demand and starts planning without being re-briefed.
4
+
5
+ The code and the tracker say what and when. They rarely say why. The cortex is where the why goes, and it's kept honest by a few rules:
6
+
7
+ - **Reasons, never statuses.** Statuses live in the tracker. The cortex reads them live and never copies them, so it can't go stale that way.
8
+ - **One home per question.** The cortex's README maps each question a planning session asks to the one place that answers it.
9
+ - **Decisions are never edited.** A change of mind is a new decision that supersedes the old one, so the history of why stays trustworthy.
10
+ - **Never invent a reason.** If nobody knows why, the decision says so.
11
+
12
+ ## What's in the package
13
+
14
+ - **The `repo-cortex` CLI** does what's the same in every repo: scaffold, check, start a decision, list summaries.
15
+ - **The `build-cortex` skill** does what's different in every repo: it surveys the repo, interviews the owner, writes the decisions and the map of where things live, wires the cortex into CLAUDE.md or AGENTS.md and CI, and tests it with a cold read.
16
+
17
+ ## Quick start
18
+
19
+ With Claude Code (or another agent that reads skills), install the skill into the repo and ask for a cortex:
20
+
21
+ ```bash
22
+ npx repo-cortex skill # into .claude/skills/; --global for ~/.claude/skills/
23
+ ```
24
+
25
+ > Build a cortex for this repo.
26
+
27
+ By hand:
28
+
29
+ ```bash
30
+ npx repo-cortex init --public --milestones # scaffold cortex/ with TODO(cortex) markers
31
+ npx repo-cortex snippet # the paragraph for CLAUDE.md or AGENTS.md
32
+ npx repo-cortex decision "Use pnpm over npm" --status accepted --decided-by owner
33
+ npx repo-cortex check # until it's clean; add it to CI
34
+ ```
35
+
36
+ ## What a cortex looks like
37
+
38
+ ```text
39
+ cortex/
40
+ README.md start here: where everything lives, live-status commands, the rules
41
+ now.md the current focus and why it's the focus
42
+ open-questions.md undecided and deferred questions, each with what would reopen it
43
+ glossary.md the project's own jargon
44
+ decisions/
45
+ 0001-keep-a-cortex.md
46
+ 0002-....md one choice each: Decision, Why, Weighed, Consequences
47
+ milestones/ optional: why each active milestone exists, and its log
48
+ related-projects.md optional: neighbors, and what's private
49
+ ```
50
+
51
+ Every file starts with front matter: a one-line `summary:` so a session can choose a file without opening it, and an `updated:` date. Decisions add `status:` (`proposed`, `accepted`, `superseded`, `rejected`), `date:`, `decided-by:` and, where they apply, `supersedes:` and `superseded-by:`.
52
+
53
+ ## Commands
54
+
55
+ | Command | Does |
56
+ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
57
+ | `init` | Scaffold a cortex from the templates. Never overwrites without `--force`. |
58
+ | `check` | Check front matter, links, paths, the index, decisions and staleness. Exits 1 on errors; `--strict` on warnings too, except the ones marked `(info)`. |
59
+ | `decision "<title>"` | Start a decision with the next number. With `--supersedes <n> --status accepted` it also marks the old one superseded. |
60
+ | `list` | Print every file's summary and each decision's status. `--decisions`, `--status <s>`, `--json`. |
61
+ | `snippet` | Print the paragraph to add to CLAUDE.md or AGENTS.md. |
62
+ | `skill` | Install the `build-cortex` skill into `.claude/skills/` (or `~/.claude/skills/` with `--global`). |
63
+
64
+ Every command takes `--dir <folder>` (default: `$CORTEX_DIR`, else `cortex`) and `-C <repo>`.
65
+
66
+ ### What `check` checks
67
+
68
+ Errors: missing `README.md`, `now.md`, `open-questions.md` or `decisions/`; missing or malformed front matter, including a date that isn't a real date; a link, anchor or backticked repo path in a living file that goes nowhere; a file the README doesn't link; a decision's bad file name, duplicate number, unknown status, or supersession that doesn't point both ways.
69
+
70
+ Warnings: a decision's text changed since `main`; a decision on `main` that was deleted or renamed; a `proposed` decision already on `main`; a new decision with no `decided-by:`; a decision without a numbered title, **Decision:** or **Why:**; an `updated:` date in the future; `now.md` more than 21 days older than the last commit; an open question with no "Reopen when"; a milestone file missing Why / Why now / Done when / Log; a leftover `TODO(cortex)`.
71
+
72
+ Some warnings are marked `(info)`, and `--strict` never fails on them, because the rules forbid the fix or the change may be fine: a stale link or path in a decision (its text never changes), a small edit to a merged decision (a typo fix is allowed), shape warnings on a merged decision, and a missing `origin/main` to compare with (in CI, check out with `fetch-depth: 0`).
73
+
74
+ Exit codes: 0 ok, 1 the check failed, 2 a usage error, 70 a bug in repo-cortex.
75
+
76
+ It checks shape and freshness, not truth. A repo with its own docs drift check should add the cortex to it for repo-specific checks such as commands and flags.
77
+
78
+ ## Contributing
79
+
80
+ [CONTRIBUTING.md](CONTRIBUTING.md) says how to set up, change and submit work, and how the project is run. [cortex/](cortex/README.md) has the reasons behind it.
81
+
82
+ ## Security
83
+
84
+ Please report a vulnerability privately, not in a public issue. [SECURITY.md](SECURITY.md) says how.
85
+
86
+ ## License
87
+
88
+ MIT
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // In a checkout (src/ exists) this runs the TypeScript sources, which Node runs by stripping types, so a
3
+ // stale dist/ is never used while developing. The published package ships dist/ and not src/, so an
4
+ // installed repo-cortex runs the compiled CLI.
5
+ import { existsSync } from "node:fs";
6
+
7
+ const sources = new URL("../src/cli.ts", import.meta.url);
8
+ const { main, UsageError } = await import(
9
+ existsSync(sources)
10
+ ? sources.href
11
+ : new URL("../dist/cli.js", import.meta.url).href
12
+ );
13
+
14
+ try {
15
+ process.exitCode = main(process.argv.slice(2));
16
+ } catch (err) {
17
+ if (err instanceof UsageError) {
18
+ // The person's mistake: the message says what to do.
19
+ console.error(`repo-cortex: ${err.message}`);
20
+ process.exitCode = 2;
21
+ } else {
22
+ // A bug: show the stack so it can be reported.
23
+ console.error("repo-cortex: unexpected error. Please report it.");
24
+ console.error(err);
25
+ process.exitCode = 70;
26
+ }
27
+ }
package/dist/check.js ADDED
@@ -0,0 +1,521 @@
1
+ /**
2
+ * The cortex check: the rules every cortex follows, whatever the repo. It checks shape and
3
+ * freshness, not truth. A repo can add its own checks beside it (its commands, its docs).
4
+ *
5
+ * Errors fail the check (exit 1). Warnings are reported and don't, unless --strict, which fails on
6
+ * every warning marked fixable. Some warnings can't be fixed without breaking the cortex's own rules
7
+ * (a decision's text never changes, so a path that moved in one stays), so they are `fixable: false`.
8
+ */
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { dirname, join, normalize } from "node:path";
11
+ import { parse } from "./frontmatter.js";
12
+ import { STATUSES, decisionNumber, decisionsDir, isDecisionPath, isStatus, normalizeNumber, } from "./decision-model.js";
13
+ import { git, headingSlug, isDate, isDir, listAtRef, markdownFiles, refExists, showAtRef, today as todayFn, } from "./repo.js";
14
+ const MILESTONE_SECTIONS = ["Why", "Why now", "Done when", "Log"];
15
+ /** How to report something stale in a file: an error in a living file, an unfixable warning in a decision. */
16
+ const staleIn = (decision) => decision ? { severity: "warning", fixable: false } : { severity: "error" };
17
+ /** Read a file as text with LF line endings, so CRLF checkouts behave the same. */
18
+ const readText = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
19
+ export function check({ root, dir, mainRef = "origin/main", staleDays = 21, today = todayFn(), }) {
20
+ const problems = [];
21
+ const add = (p) => problems.push({ line: 0, severity: "error", ...p });
22
+ const abs = join(root, dir);
23
+ if (!existsSync(join(abs, "README.md"))) {
24
+ add({
25
+ file: `${dir}/README.md`,
26
+ kind: "structure",
27
+ message: `No cortex here: ${dir}/README.md is missing. Run \`repo-cortex init\` to start one, or pass --dir.`,
28
+ });
29
+ return { problems, files: [] };
30
+ }
31
+ for (const required of ["now.md", "open-questions.md"])
32
+ if (!existsSync(join(abs, required)))
33
+ add({
34
+ file: `${dir}/${required}`,
35
+ kind: "structure",
36
+ message: `${required} is missing. Every cortex has one.`,
37
+ });
38
+ if (!isDir(join(root, decisionsDir(dir))))
39
+ add({
40
+ file: `${decisionsDir(dir)}/`,
41
+ kind: "structure",
42
+ message: "decisions/ is missing. Every cortex has one, even if it holds a single decision.",
43
+ });
44
+ const files = markdownFiles(root, abs);
45
+ const ctx = {
46
+ root,
47
+ dir,
48
+ mainRef,
49
+ hasMain: refExists(root, mainRef),
50
+ staleDays,
51
+ today,
52
+ files,
53
+ anchors: new Map(),
54
+ add,
55
+ };
56
+ const decisions = new Map(); // number -> file
57
+ const parsed = new Map();
58
+ for (const file of files) {
59
+ const text = readText(join(root, file));
60
+ const info = { text, ...parse(text) };
61
+ parsed.set(file, info);
62
+ const decision = isDecisionPath(dir, file);
63
+ checkFrontMatter(ctx, file, info, decision);
64
+ checkLinks(ctx, file, text, decision);
65
+ checkPaths(ctx, file, text, decision);
66
+ checkTodos(ctx, file, text);
67
+ if (!decision)
68
+ continue;
69
+ const number = decisionNumber(file.split("/").pop());
70
+ if (!number)
71
+ add({
72
+ file,
73
+ kind: "decision",
74
+ message: "A decision's file name is a four-digit number and a slug, like 0007-use-pnpm.md.",
75
+ });
76
+ else if (decisions.has(number))
77
+ add({
78
+ file,
79
+ kind: "decision",
80
+ message: `Decision number ${number} is also used by ${decisions.get(number)}.`,
81
+ });
82
+ else
83
+ decisions.set(number, file);
84
+ }
85
+ for (const [number, file] of decisions)
86
+ checkDecision(ctx, file, number, parsed, decisions);
87
+ checkMergedDecisions(ctx, decisions);
88
+ checkIndex(ctx, abs);
89
+ checkNow(ctx, parsed.get(`${dir}/now.md`));
90
+ checkOpenQuestions(ctx, parsed.get(`${dir}/open-questions.md`));
91
+ for (const file of files.filter((f) => f.startsWith(`${dir}/milestones/`) && !f.endsWith("/README.md")))
92
+ checkMilestone(ctx, file, parsed.get(file));
93
+ problems.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
94
+ return { problems, files };
95
+ }
96
+ /**
97
+ * Lines outside fenced code blocks, with their 1-based numbers. A fence closes only on the same character
98
+ * repeated at least as many times as it opened with, so a ```` block can show a ``` example.
99
+ */
100
+ function proseLines(text) {
101
+ const out = [];
102
+ let open = null;
103
+ text.split("\n").forEach((t, i) => {
104
+ const fence = t.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
105
+ if (!open && fence) {
106
+ open = { ch: fence[1][0], len: fence[1].length };
107
+ return;
108
+ }
109
+ if (open) {
110
+ if (fence &&
111
+ fence[1][0] === open.ch &&
112
+ fence[1].length >= open.len &&
113
+ !fence[2].trim())
114
+ open = null;
115
+ return;
116
+ }
117
+ out.push({ t, line: i + 1 });
118
+ });
119
+ return out;
120
+ }
121
+ /** `<target>` to `target`: angle brackets let a link target hold spaces and parentheses. */
122
+ const unwrap = (s) => s.replace(/^<(.*)>$/, "$1");
123
+ /** A link's target, from an inline link `[x](target)`, `[x](<target>)`, or a reference definition `[x]: target`. */
124
+ function links(text) {
125
+ const out = [];
126
+ for (const { t, line } of proseLines(text)) {
127
+ const def = t.match(/^ {0,3}\[[^\]]+\]:\s*(<[^>]*>|\S+)/);
128
+ if (def) {
129
+ out.push({ target: unwrap(def[1]), line });
130
+ continue;
131
+ }
132
+ for (const m of t
133
+ .replace(/`[^`]*`/g, "")
134
+ .matchAll(/\[[^\]]*\]\((<[^>]*>|(?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?\)/g))
135
+ out.push({ target: unwrap(m[1]), line });
136
+ }
137
+ return out;
138
+ }
139
+ function checkFrontMatter(ctx, file, info, decision) {
140
+ const data = info.data;
141
+ const fail = (message, severity = "error") => ctx.add({ file, line: 1, kind: "front-matter", severity, message });
142
+ if (!data) {
143
+ fail("No front matter. Every file starts with `summary:` and `updated:` between --- lines.");
144
+ return;
145
+ }
146
+ if (!data.summary)
147
+ fail("No `summary:`. One line, so a session can choose this file without opening it.");
148
+ const updated = data.updated;
149
+ if (!updated)
150
+ fail("No `updated:` date (YYYY-MM-DD).");
151
+ else if (!isDate(updated))
152
+ fail(`\`updated: ${updated}\` isn't a real YYYY-MM-DD date.`);
153
+ else if (updated > ctx.today)
154
+ fail(`\`updated: ${updated}\` is in the future.`, "warning");
155
+ if (!decision)
156
+ return;
157
+ const { status, date } = data;
158
+ if (!status)
159
+ fail(`No \`status:\`. One of ${STATUSES.join(", ")}.`);
160
+ else if (!isStatus(status))
161
+ fail(`\`status: ${status}\` isn't one of ${STATUSES.join(", ")}.`);
162
+ if (!date)
163
+ fail("No `date:`, the day it was decided.");
164
+ else if (!isDate(date))
165
+ fail(`\`date: ${date}\` isn't a real YYYY-MM-DD date.`);
166
+ // Only a decision that hasn't merged yet can still gain a decided-by; a merged one's front matter is settled.
167
+ if (!data["decided-by"] && !isMerged(ctx, file))
168
+ fail("No `decided-by:`. Say who chose (`owner`, `owner, on a recommendation`, a name), so a reader knows whose reason it is.", "warning");
169
+ }
170
+ const isMerged = (ctx, file) => ctx.hasMain && showAtRef(ctx.root, ctx.mainRef, file) !== null;
171
+ function checkDecision(ctx, file, number, parsed, decisions) {
172
+ const info = parsed.get(file);
173
+ const data = info.data ?? {};
174
+ const fail = (p) => ctx.add({ file, line: 1, kind: "decision", ...p });
175
+ const find = (ref) => {
176
+ const n = normalizeNumber(ref);
177
+ return n ? decisions.get(n) : undefined;
178
+ };
179
+ const supersedes = (f) => [parsed.get(f)?.data?.supersedes ?? []].flat().map(normalizeNumber);
180
+ // superseded-by points forward; the decision it names must point back with supersedes.
181
+ const by = data["superseded-by"];
182
+ if (data.status === "superseded") {
183
+ if (!by)
184
+ fail({
185
+ message: "Superseded, but no `superseded-by:` names the decision that replaced it.",
186
+ });
187
+ else if (!find(by))
188
+ fail({
189
+ message: `\`superseded-by: ${by}\` doesn't match a decision in this cortex.`,
190
+ });
191
+ else if (!supersedes(find(by)).includes(number))
192
+ fail({
193
+ file: find(by),
194
+ message: `${file} says this decision superseded it, so add \`supersedes: "${number}"\` here.`,
195
+ });
196
+ }
197
+ else if (by)
198
+ fail({
199
+ message: `Has \`superseded-by:\` but \`status: ${data.status}\`. Set \`status: superseded\`.`,
200
+ });
201
+ // supersedes points back. Once this decision is accepted, the old one must say it was replaced; while it's
202
+ // proposed the old one stands; if it was rejected, the old one must not say it was replaced by this one.
203
+ for (const ref of [data.supersedes ?? []].flat()) {
204
+ const old = find(ref);
205
+ if (!old) {
206
+ fail({
207
+ message: `\`supersedes: ${ref}\` doesn't match a decision in this cortex.`,
208
+ });
209
+ continue;
210
+ }
211
+ const oldData = parsed.get(old)?.data ?? {};
212
+ const markedByThis = oldData.status === "superseded" &&
213
+ normalizeNumber(oldData["superseded-by"]) === number;
214
+ if (data.status === "accepted" && !markedByThis)
215
+ fail({
216
+ file: old,
217
+ message: `${file} replaced this decision, so set \`status: superseded\` and \`superseded-by: "${number}"\` here.`,
218
+ });
219
+ if (data.status === "rejected" && markedByThis)
220
+ fail({
221
+ file: old,
222
+ message: `${file} was rejected, so this decision stands: set its \`status:\` back and remove \`superseded-by:\`.`,
223
+ });
224
+ }
225
+ // A merged decision's text can't change, so its shape warnings can't be acted on there.
226
+ const settled = isMerged(ctx, file) ? { fixable: false } : {};
227
+ const h1 = info.body.match(/^#\s+(.*)$/m)?.[1];
228
+ if (h1 === undefined)
229
+ fail({
230
+ line: info.bodyLine,
231
+ severity: "warning",
232
+ ...settled,
233
+ message: `No title. Start the body with \`# ${number}: <what was decided>\`.`,
234
+ });
235
+ else if (!h1.startsWith(`${number}:`))
236
+ fail({
237
+ line: info.bodyLine,
238
+ severity: "warning",
239
+ ...settled,
240
+ message: `The title should start with "${number}:", so a quoted title names its decision.`,
241
+ });
242
+ for (const label of ["Decision", "Why"])
243
+ if (!new RegExp(`\\*\\*${label}[^*]*:\\*\\*`).test(info.body))
244
+ fail({
245
+ line: info.bodyLine,
246
+ severity: "warning",
247
+ ...settled,
248
+ message: `No **${label}:** paragraph.`,
249
+ });
250
+ // Against the main branch: a merged decision is never proposed, and its text never changes.
251
+ if (!ctx.hasMain)
252
+ return;
253
+ const onMain = showAtRef(ctx.root, ctx.mainRef, file);
254
+ if (onMain === null)
255
+ return;
256
+ const mainData = parse(onMain);
257
+ if (data.status === "proposed" && mainData.data?.status === "proposed")
258
+ fail({
259
+ kind: "status",
260
+ severity: "warning",
261
+ message: `Still \`status: proposed\` on ${ctx.mainRef}. The owner accepts or rejects each decision before it merges; set the status here.`,
262
+ });
263
+ const before = words(mainData.body);
264
+ const after = words(info.body);
265
+ if (before.join(" ") === after.join(" "))
266
+ return;
267
+ const typo = looksLikeTypoFix(before, after);
268
+ fail({
269
+ line: info.bodyLine,
270
+ kind: "immutable",
271
+ severity: "warning",
272
+ ...(typo ? { fixable: false } : {}),
273
+ message: typo
274
+ ? `A small edit to the text since ${ctx.mainRef}. Fine if it fixes a typo; a change of meaning is a new decision with \`supersedes:\`.`
275
+ : `The text changed since ${ctx.mainRef}. A decision's text is never edited except to fix a typo; record a change of mind as a new decision with \`supersedes:\`.`,
276
+ });
277
+ }
278
+ /** Words, so reflowing a paragraph doesn't count as an edit. */
279
+ const words = (s) => s.split(/\s+/).filter(Boolean);
280
+ /** True when two texts differ in one short run of at most two words, by at most three characters. */
281
+ function looksLikeTypoFix(a, b) {
282
+ let start = 0;
283
+ while (start < a.length && start < b.length && a[start] === b[start])
284
+ start++;
285
+ let endA = a.length;
286
+ let endB = b.length;
287
+ while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
288
+ endA--;
289
+ endB--;
290
+ }
291
+ const midA = a.slice(start, endA);
292
+ const midB = b.slice(start, endB);
293
+ if (midA.length > 2 || midB.length > 2)
294
+ return false;
295
+ return editDistance(midA.join(" "), midB.join(" ")) <= 3;
296
+ }
297
+ function editDistance(a, b) {
298
+ let prev = Array.from({ length: b.length + 1 }, (_, j) => j);
299
+ for (let i = 1; i <= a.length; i++) {
300
+ const cur = [i];
301
+ for (let j = 1; j <= b.length; j++)
302
+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
303
+ prev = cur;
304
+ }
305
+ return prev[b.length];
306
+ }
307
+ /** Decisions on the main ref that are gone here, and a notice when there's no main ref to compare with. */
308
+ function checkMergedDecisions(ctx, decisions) {
309
+ const folder = decisionsDir(ctx.dir);
310
+ if (!ctx.hasMain) {
311
+ if (decisions.size && git(ctx.root, ["rev-parse", "--git-dir"]) !== null)
312
+ ctx.add({
313
+ file: `${folder}/`,
314
+ kind: "main-ref",
315
+ severity: "warning",
316
+ fixable: false,
317
+ message: `${ctx.mainRef} isn't in this repo, so decisions weren't compared with the merged ones (edited text, proposed on main). Pass --main-ref, or in CI check out with \`fetch-depth: 0\`.`,
318
+ });
319
+ return;
320
+ }
321
+ const here = new Set([...decisions.values()].map((f) => f.split("/").pop()));
322
+ for (const name of listAtRef(ctx.root, ctx.mainRef, folder))
323
+ if (decisionNumber(name) && !here.has(name))
324
+ ctx.add({
325
+ file: `${folder}/${name}`,
326
+ kind: "immutable",
327
+ severity: "warning",
328
+ message: `This decision is on ${ctx.mainRef} but was deleted or renamed. A decision is never removed; restore it, and record a change of mind as a new decision with \`supersedes:\`.`,
329
+ });
330
+ }
331
+ /** Where a link points, or null for a link outside the repo (http:, mailto: and the like). */
332
+ function resolveLink(root, file, path) {
333
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path))
334
+ return null;
335
+ let decoded = path;
336
+ try {
337
+ decoded = decodeURI(path);
338
+ }
339
+ catch {
340
+ // A bare % that isn't an escape: use the path as written.
341
+ }
342
+ if (!decoded)
343
+ return join(root, file);
344
+ return decoded.startsWith("/")
345
+ ? normalize(join(root, decoded))
346
+ : normalize(join(dirname(join(root, file)), decoded));
347
+ }
348
+ function checkLinks(ctx, file, text, decision) {
349
+ for (const { target, line } of links(text)) {
350
+ const [path = "", anchor] = target.split("#");
351
+ const resolved = resolveLink(ctx.root, file, path);
352
+ if (resolved === null)
353
+ continue;
354
+ if (!existsSync(resolved))
355
+ ctx.add({
356
+ file,
357
+ line,
358
+ kind: "link",
359
+ ...staleIn(decision),
360
+ message: `The link to ${target} goes nowhere.`,
361
+ });
362
+ else if (anchor &&
363
+ resolved.endsWith(".md") &&
364
+ !anchorsOf(ctx, resolved).has(anchor))
365
+ ctx.add({
366
+ file,
367
+ line,
368
+ kind: "link",
369
+ ...staleIn(decision),
370
+ message: `${path || file.split("/").pop()} has no heading for #${anchor}.`,
371
+ });
372
+ }
373
+ }
374
+ function anchorsOf(ctx, absFile) {
375
+ const cached = ctx.anchors.get(absFile);
376
+ if (cached)
377
+ return cached;
378
+ const seen = new Map();
379
+ const set = new Set();
380
+ for (const { t } of proseLines(readText(absFile))) {
381
+ const h = t.match(/^#{1,6}\s+(.*?)\s*#*\s*$/)?.[1];
382
+ if (h === undefined)
383
+ continue;
384
+ const base = headingSlug(h);
385
+ const n = seen.get(base) ?? 0;
386
+ seen.set(base, n + 1);
387
+ set.add(n ? `${base}-${n}` : base);
388
+ }
389
+ ctx.anchors.set(absFile, set);
390
+ return set;
391
+ }
392
+ /**
393
+ * Backticked repo paths, like `src/cli.ts` or `docs/guides/`. A span counts as a path only when it has
394
+ * no spaces, has a slash, and its first segment is a real top-level entry, so `owner/name` and
395
+ * `origin/main` are left alone. Globs and placeholders (`*`, `<name>`, `{a,b}`) are skipped. The cost:
396
+ * a path whose whole top-level folder was removed isn't caught.
397
+ */
398
+ function checkPaths(ctx, file, text, decision) {
399
+ for (const { t, line } of proseLines(text)) {
400
+ for (const m of t.matchAll(/`([^`\s]+)`/g)) {
401
+ const raw = m[1];
402
+ if (!raw.includes("/") ||
403
+ /[*<>{}$|]/.test(raw) ||
404
+ /^[a-z]+:\/\//i.test(raw) ||
405
+ raw.startsWith("@"))
406
+ continue;
407
+ const span = raw
408
+ .replace(/^\.?\//, "")
409
+ .replace(/(?::\d+(?:-\d+)?|#.*)$/, "");
410
+ const first = span.split("/")[0];
411
+ if (!first || first === ".." || !existsSync(join(ctx.root, first)))
412
+ continue;
413
+ if (!existsSync(join(ctx.root, span)))
414
+ ctx.add({
415
+ file,
416
+ line,
417
+ kind: "path",
418
+ ...staleIn(decision),
419
+ message: `\`${raw}\` doesn't exist.${decision ? " Leave the decision's text alone; if it matters, say what moved in a new decision." : ""}`,
420
+ });
421
+ }
422
+ }
423
+ }
424
+ /** A scaffold marker left behind. A mention in code (`TODO(cortex)`) is prose about the marker, not one. */
425
+ function checkTodos(ctx, file, text) {
426
+ for (const { t, line } of proseLines(text))
427
+ if (/TODO\(cortex\)/.test(t.replace(/`[^`]*`/g, "")))
428
+ ctx.add({
429
+ file,
430
+ line,
431
+ kind: "unfinished",
432
+ severity: "warning",
433
+ message: "A TODO(cortex) marker from the scaffold is still here.",
434
+ });
435
+ }
436
+ /** README.md links every top-level file and folder, so a session can find everything from it. */
437
+ function checkIndex(ctx, abs) {
438
+ const readme = `${ctx.dir}/README.md`;
439
+ const targets = links(readText(join(ctx.root, readme))).map(({ target }) => target.split("#")[0].replace(/^\.\//, "").replace(/\/$/, ""));
440
+ const top = new Set();
441
+ for (const f of ctx.files) {
442
+ const rel = f.slice(ctx.dir.length + 1);
443
+ if (rel === "README.md")
444
+ continue;
445
+ const [head = rel, ...rest] = rel.split("/");
446
+ top.add(rest.length ? head : rel);
447
+ }
448
+ for (const entry of top)
449
+ if (!targets.some((t) => t === entry || t.startsWith(`${entry}/`)))
450
+ ctx.add({
451
+ file: readme,
452
+ kind: "index",
453
+ message: `${entry}${isDir(join(abs, entry)) ? "/" : ""} isn't linked from the README. List every file and folder there, so a session can find it.`,
454
+ });
455
+ }
456
+ function checkNow(ctx, info) {
457
+ const updated = info?.data?.updated;
458
+ if (!isDate(updated))
459
+ return;
460
+ // Measure against the last commit, so a quiet repo doesn't nag; without git, against today.
461
+ const last = git(ctx.root, ["log", "-1", "--format=%cs"])?.trim() || ctx.today;
462
+ const days = Math.round((Date.parse(last) - Date.parse(updated)) / 86_400_000);
463
+ if (days > ctx.staleDays)
464
+ ctx.add({
465
+ file: `${ctx.dir}/now.md`,
466
+ line: 1,
467
+ kind: "stale",
468
+ severity: "warning",
469
+ message: `Updated ${updated}, ${days} days before the last commit. Check that the focus hasn't moved, then rewrite it or bump \`updated:\`.`,
470
+ });
471
+ }
472
+ function checkOpenQuestions(ctx, info) {
473
+ if (!info)
474
+ return;
475
+ let current = null;
476
+ const flush = () => {
477
+ if (current && !/reopen when/i.test(current.body))
478
+ ctx.add({
479
+ file: `${ctx.dir}/open-questions.md`,
480
+ line: current.line,
481
+ kind: "open-question",
482
+ severity: "warning",
483
+ message: `"${current.title}" doesn't say what would reopen it ("Reopen when:").`,
484
+ });
485
+ };
486
+ for (const { t, line } of proseLines(info.text)) {
487
+ const h = t.match(/^##\s+(.*)$/)?.[1];
488
+ if (h !== undefined) {
489
+ flush();
490
+ current = { title: h, line, body: "" };
491
+ }
492
+ else if (current)
493
+ current.body += `${t}\n`;
494
+ }
495
+ flush();
496
+ }
497
+ function checkMilestone(ctx, file, info) {
498
+ if (!info.data || info.data.layout === "free")
499
+ return;
500
+ const headings = new Set(proseLines(info.text).flatMap(({ t }) => t.match(/^##\s+(.*?)\s*$/)?.[1] ?? []));
501
+ const missing = MILESTONE_SECTIONS.filter((s) => !headings.has(s));
502
+ if (missing.length)
503
+ ctx.add({
504
+ file,
505
+ line: info.bodyLine,
506
+ kind: "milestone",
507
+ severity: "warning",
508
+ message: `No ${missing.map((s) => `"## ${s}"`).join(", ")} section. Add ${missing.length > 1 ? "them" : "it"}, or set \`layout: free\` for a file with its own layout.`,
509
+ });
510
+ }
511
+ /** True when the problems should fail the run: any error, or with `strict`, any fixable warning. */
512
+ export const fails = (problems, strict = false) => problems.some((p) => p.severity === "error" || (strict && p.fixable !== false));
513
+ export function format(problems) {
514
+ if (!problems.length)
515
+ return "No problems found.";
516
+ const lines = problems.map((p) => `${p.file}${p.line ? `:${p.line}` : ""} ${p.severity}${p.fixable === false ? " (info)" : ""} [${p.kind}] ${p.message}`);
517
+ const errors = problems.filter((p) => p.severity === "error").length;
518
+ const warnings = problems.length - errors;
519
+ lines.push("", `${errors} error${errors === 1 ? "" : "s"}, ${warnings} warning${warnings === 1 ? "" : "s"}.`);
520
+ return lines.join("\n");
521
+ }