drawbore 0.1.0 → 0.1.1

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/lib/checker.js CHANGED
@@ -1,399 +1,399 @@
1
- // Structural linter for a Drawbore record.
2
- //
3
- // Scope is deliberately narrow: only invariants that are mechanically decidable
4
- // from the record files themselves. Semantic questions are NOT checked here.
5
-
6
- import { readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
7
- import path from "node:path";
8
-
9
- const STATUSES = new Set(["proposed", "accepted", "deprecated", "superseded"]);
10
- const DECISION_FILE = /^(\d+)-(.+)\.md$/;
11
- const FRONT_MATTER_ID = /^id:\s*(\d+)\s*$/m;
12
- const FRONT_MATTER_STATUS = /^status:\s*([A-Za-z-]+)\s*$/m;
13
- const FRONT_MATTER_SUPERSEDED_BY = /^superseded_by:\s*(\d+)\s*$/m;
14
- const FRONT_MATTER_BLOCK = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
15
-
16
- function frontMatter(text) {
17
- const match = String(text).match(FRONT_MATTER_BLOCK);
18
- return match ? match[1] : "";
19
- }
20
-
21
- const REQUIRED_HEADINGS = {
22
- "context.md": "# Project Context",
23
- "glossary.md": "# Glossary",
24
- "principles.md": "# Principles",
25
- "system.md": "# System Behavior",
26
- "stack.md": "# Technical Choices",
27
- };
28
-
29
- function stripFences(text) {
30
- const lines = String(text).split("\n");
31
- const out = [];
32
- let fence = null;
33
- for (const line of lines) {
34
- const m = line.match(/^\s*(```+|~~~+)/);
35
- if (m) {
36
- if (fence === null) fence = m[1][0];
37
- else if (m[1][0] === fence) fence = null;
38
- out.push("");
39
- continue;
40
- }
41
- out.push(fence === null ? line : "");
42
- }
43
- return out.join("\n");
44
- }
45
-
46
- async function checkArtifacts(notebookDir, findings) {
47
- for (const [file, heading] of Object.entries(REQUIRED_HEADINGS)) {
48
- let text;
49
- try {
50
- text = await readFile(path.join(notebookDir, file), "utf8");
51
- } catch {
52
- continue;
53
- }
54
- if (!stripFences(text).split("\n").some((line) => line.trim() === heading)) {
55
- findings.push({
56
- code: "E007",
57
- file,
58
- message: `missing required heading "${heading}"`,
59
- });
60
- }
61
- }
62
-
63
- let principles;
64
- try {
65
- principles = await readFile(path.join(notebookDir, "principles.md"), "utf8");
66
- } catch {
67
- return;
68
- }
69
- const rules = stripFences(principles).split("\n").filter((line) => /^\s*\d+[.)]\s+\*\*/.test(line));
70
- for (const rule of rules) {
71
- if (!/Source:/i.test(rule)) {
72
- findings.push({
73
- code: "E008",
74
- file: "principles.md",
75
- message: `principle has no Source: ${rule.trim().slice(0, 80)}`,
76
- });
77
- }
78
- }
79
- }
80
-
81
- async function checkIndex(notebookDir, findings) {
82
- const indexPath = path.join(notebookDir, "index.md");
83
- let indexText;
84
- try {
85
- indexText = await readFile(indexPath, "utf8");
86
- } catch {
87
- return;
88
- }
89
-
90
- const linkTargets = new Set();
91
- const linkRe = /\]\(([^)]+)\)/g;
92
- let match;
93
- while ((match = linkRe.exec(indexText)) !== null) {
94
- let href = match[1].trim().replace(/#.*$/, "").replace(/^\.\//, "");
95
- if (/^[a-z]+:/i.test(href)) continue;
96
- if (href.endsWith("/")) href = href.replace(/\/+$/, "");
97
- if (href) linkTargets.add(href);
98
- }
99
-
100
- let top;
101
- try {
102
- top = await readdir(notebookDir, { withFileTypes: true });
103
- } catch {
104
- return;
105
- }
106
- const artifacts = top
107
- .filter((entry) =>
108
- (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "index.md") ||
109
- (entry.isDirectory() && (entry.name === "decisions" || entry.name === "work")),
110
- )
111
- .map((entry) => entry.name);
112
-
113
- for (const name of artifacts) {
114
- if (!linkTargets.has(name)) {
115
- const label = name === "decisions" || name === "work" ? `${name}/` : name;
116
- findings.push({
117
- code: "W003",
118
- file: "index.md",
119
- message: `top-level ${label} is not linked from the index`,
120
- });
121
- }
122
- }
123
-
124
- for (const href of linkTargets) {
125
- const resolved = path.join(notebookDir, href);
126
- let ok = false;
127
- try {
128
- await stat(resolved);
129
- ok = true;
130
- } catch {
131
- ok = false;
132
- }
133
- if (!ok) {
134
- findings.push({
135
- code: "W004",
136
- file: "index.md",
137
- message: `index link target does not exist: ${href}`,
138
- });
139
- }
140
- }
141
- }
142
-
143
- export async function checkNotebook(notebookDir) {
144
- const findings = [];
145
-
146
- let notebookEntries;
147
- try {
148
- notebookEntries = await stat(notebookDir);
149
- } catch {
150
- findings.push({ code: "E000", file: null, message: `no notebook at ${notebookDir}` });
151
- return findings;
152
- }
153
- if (!notebookEntries.isDirectory()) {
154
- findings.push({ code: "E000", file: null, message: `notebook path is not a directory: ${notebookDir}` });
155
- return findings;
156
- }
157
-
158
- await checkArtifacts(notebookDir, findings);
159
- await checkIndex(notebookDir, findings);
160
-
161
- const decisionsDir = path.join(notebookDir, "decisions");
162
- let entries;
163
- try {
164
- entries = await readdir(decisionsDir, { withFileTypes: true });
165
- entries.sort((a, b) => byName(a.name, b.name));
166
- } catch {
167
- entries = [];
168
- }
169
-
170
- const records = [];
171
- for (const entry of entries) {
172
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
173
- const fileMatch = entry.name.match(DECISION_FILE);
174
- const text = await readFile(path.join(decisionsDir, entry.name), "utf8");
175
- const matter = frontMatter(text);
176
- const idMatch = matter.match(FRONT_MATTER_ID);
177
- const statusMatch = matter.match(FRONT_MATTER_STATUS);
178
- const supersededByMatch = matter.match(FRONT_MATTER_SUPERSEDED_BY);
179
- const titleMatch = text.match(/^#\s+(.+)$/m);
180
-
181
- records.push({
182
- file: entry.name,
183
- fileId: fileMatch ? fileMatch[1] : null,
184
- id: idMatch ? idMatch[1] : null,
185
- numId: idMatch ? Number(idMatch[1]) : null,
186
- status: statusMatch ? statusMatch[1].toLowerCase() : null,
187
- supersededBy: supersededByMatch ? supersededByMatch[1] : null,
188
- numSupersededBy: supersededByMatch ? Number(supersededByMatch[1]) : null,
189
- title: titleMatch ? titleMatch[1].trim() : "",
190
- });
191
- }
192
-
193
- for (const record of records) {
194
- if (record.id === null) {
195
- findings.push({ code: "E006", file: record.file, message: "decision file has no numeric id in front matter" });
196
- }
197
- }
198
-
199
- for (const record of records) {
200
- if (record.fileId !== null && record.id !== null && Number(record.fileId) !== Number(record.id)) {
201
- findings.push({
202
- code: "E002",
203
- file: record.file,
204
- message: `front-matter id ${record.id} does not match filename prefix ${record.fileId}`,
205
- });
206
- }
207
- }
208
-
209
- const byId = new Map();
210
- for (const record of records) {
211
- if (record.numId === null) continue;
212
- if (!byId.has(record.numId)) byId.set(record.numId, []);
213
- byId.get(record.numId).push(record.file);
214
- }
215
- for (const [id, files] of byId) {
216
- if (files.length > 1) {
217
- findings.push({
218
- code: "E001",
219
- file: files.join(", "),
220
- message: `id ${id} is declared by ${files.length} decision files`,
221
- });
222
- }
223
- }
224
-
225
- for (const record of records) {
226
- if (record.status !== null && !STATUSES.has(record.status)) {
227
- findings.push({ code: "E005", file: record.file, message: `invalid status "${record.status}"` });
228
- }
229
- }
230
-
231
- const idToRecord = new Map();
232
- for (const record of records) {
233
- if (record.numId !== null && !idToRecord.has(record.numId)) idToRecord.set(record.numId, record);
234
- }
235
-
236
- for (const record of records) {
237
- if (record.status === "superseded" && record.supersededBy === null) {
238
- findings.push({
239
- code: "E004",
240
- file: record.file,
241
- message: "record is marked superseded but declares no superseded_by",
242
- });
243
- }
244
- if (record.numSupersededBy === null) continue;
245
- const target = idToRecord.get(record.numSupersededBy);
246
- if (!target) {
247
- findings.push({
248
- code: "E003",
249
- file: record.file,
250
- message: `superseded_by ${record.supersededBy} points at a decision that does not exist`,
251
- });
252
- continue;
253
- }
254
- if (record.status === "accepted") {
255
- findings.push({
256
- code: "W001",
257
- file: record.file,
258
- message: `accepted record declares superseded_by ${record.supersededBy}`,
259
- });
260
- }
261
- }
262
-
263
- const uniqueIds = [...new Set(records.map((record) => record.numId).filter((id) => id !== null))].sort((a, b) => a - b);
264
- for (let index = 1; index < uniqueIds.length; index += 1) {
265
- if (uniqueIds[index] !== uniqueIds[index - 1] + 1) {
266
- findings.push({
267
- code: "W002",
268
- file: null,
269
- message: `id sequence jumps from ${uniqueIds[index - 1]} to ${uniqueIds[index]}`,
270
- });
271
- }
272
- }
273
-
274
- findings.push(...(await staleCandidates(notebookDir, records)));
275
- return findings;
276
- }
277
-
278
- function byName(a, b) {
279
- return a < b ? -1 : a > b ? 1 : 0;
280
- }
281
-
282
- const STOPWORDS = new Set([
283
- "the", "and", "for", "with", "that", "this", "from", "into", "use", "using",
284
- "keep", "must", "should", "when", "are", "was", "were", "has", "have", "not",
285
- "but", "its", "their", "they", "them", "than", "then", "also", "only", "all",
286
- "any", "each", "per", "via", "onto", "over", "under", "after", "before",
287
- ]);
288
-
289
- function significantTerms(text) {
290
- return [...new Set(
291
- (text || "")
292
- .toLowerCase()
293
- .replace(/[^a-z0-9\s-]/g, " ")
294
- .split(/\s+/)
295
- .filter((word) => word.length >= 4 && !STOPWORDS.has(word)),
296
- )];
297
- }
298
-
299
- async function staleCandidates(notebookDir, records) {
300
- const out = [];
301
- const truthFiles = ["system.md", "stack.md"];
302
- const truthText = {};
303
- for (const file of truthFiles) {
304
- try {
305
- truthText[file] = (await readFile(path.join(notebookDir, file), "utf8")).toLowerCase();
306
- } catch {
307
- truthText[file] = "";
308
- }
309
- }
310
-
311
- for (const record of records) {
312
- if (record.status !== "superseded") continue;
313
- const terms = significantTerms(record.title || "");
314
- for (const file of truthFiles) {
315
- const hits = terms.filter((term) => truthText[file].includes(term));
316
- if (hits.length > 0) {
317
- out.push({
318
- code: "S001",
319
- file: `${file} (candidate from ${record.file})`,
320
- message: `superseded decision "${record.title}" may still be described as current; terms found: ${hits.join(", ")}. Review whether ${file} reflects the superseding decision.`,
321
- });
322
- }
323
- }
324
- }
325
- return out;
326
- }
327
-
328
- export function summarize(findings) {
329
- const errors = findings.filter((finding) => finding.code.startsWith("E"));
330
- const warnings = findings.filter((finding) => finding.code.startsWith("W"));
331
- const stale = findings.filter((finding) => finding.code.startsWith("S"));
332
- return { errors, warnings, stale, ok: errors.length === 0 };
333
- }
334
-
335
- export async function fixMechanical(notebookDir) {
336
- const decisionsDir = path.join(notebookDir, "decisions");
337
- let entries;
338
- try {
339
- entries = await readdir(decisionsDir, { withFileTypes: true });
340
- } catch {
341
- return { fixed: [], changed: false };
342
- }
343
-
344
- const files = entries
345
- .filter((entry) => entry.isFile() && DECISION_FILE.test(entry.name))
346
- .map((entry) => entry.name)
347
- .sort(byName);
348
- const used = new Set();
349
- for (const file of files) {
350
- const match = file.match(DECISION_FILE);
351
- if (match) used.add(Number(match[1]));
352
- }
353
- const nextFree = () => {
354
- let candidate = 1;
355
- while (used.has(candidate)) candidate += 1;
356
- used.add(candidate);
357
- return candidate;
358
- };
359
-
360
- const seen = new Map();
361
- const fixed = [];
362
- let changed = false;
363
-
364
- for (const file of files) {
365
- const full = path.join(decisionsDir, file);
366
- let text = await readFile(full, "utf8");
367
- const fileMatch = file.match(DECISION_FILE);
368
- const before = text;
369
-
370
- const idMatch = frontMatter(text).match(FRONT_MATTER_ID);
371
- if (idMatch && Number(idMatch[1]) !== Number(fileMatch[1])) {
372
- text = text.replace(/^id:\s*\d+\s*$/m, `id: ${fileMatch[1]}`);
373
- fixed.push({ code: "E002", file, message: `aligned id to filename prefix ${fileMatch[1]}` });
374
- }
375
-
376
- const numId = Number(frontMatter(text).match(FRONT_MATTER_ID)?.[1] ?? fileMatch[1]);
377
- let finalName = file;
378
- if (seen.has(numId) && seen.get(numId) !== file) {
379
- const newId = nextFree();
380
- const padded = String(newId).padStart(fileMatch[1].length, "0");
381
- text = text.replace(/^id:\s*\d+\s*$/m, `id: ${padded}`);
382
- finalName = `${padded}-${file.slice(fileMatch[1].length + 1)}`;
383
- fixed.push({ code: "E001", file, message: `renumbered duplicate id ${numId} to ${newId} (renamed to ${finalName})` });
384
- } else if (!seen.has(numId)) {
385
- seen.set(numId, file);
386
- }
387
-
388
- if (text !== before || finalName !== file) {
389
- if (finalName !== file) {
390
- await writeFile(path.join(decisionsDir, finalName), text);
391
- await rm(full);
392
- } else {
393
- await writeFile(full, text);
394
- }
395
- changed = true;
396
- }
397
- }
398
- return { fixed, changed };
1
+ // Structural linter for a Drawbore record.
2
+ //
3
+ // Scope is deliberately narrow: only invariants that are mechanically decidable
4
+ // from the record files themselves. Semantic questions are NOT checked here.
5
+
6
+ import { readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+
9
+ const STATUSES = new Set(["proposed", "accepted", "deprecated", "superseded"]);
10
+ const DECISION_FILE = /^(\d+)-(.+)\.md$/;
11
+ const FRONT_MATTER_ID = /^id:\s*(\d+)\s*$/m;
12
+ const FRONT_MATTER_STATUS = /^status:\s*([A-Za-z-]+)\s*$/m;
13
+ const FRONT_MATTER_SUPERSEDED_BY = /^superseded_by:\s*(\d+)\s*$/m;
14
+ const FRONT_MATTER_BLOCK = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
15
+
16
+ function frontMatter(text) {
17
+ const match = String(text).match(FRONT_MATTER_BLOCK);
18
+ return match ? match[1] : "";
19
+ }
20
+
21
+ const REQUIRED_HEADINGS = {
22
+ "context.md": "# Project Context",
23
+ "glossary.md": "# Glossary",
24
+ "principles.md": "# Principles",
25
+ "system.md": "# System Behavior",
26
+ "stack.md": "# Technical Choices",
27
+ };
28
+
29
+ function stripFences(text) {
30
+ const lines = String(text).split("\n");
31
+ const out = [];
32
+ let fence = null;
33
+ for (const line of lines) {
34
+ const m = line.match(/^\s*(```+|~~~+)/);
35
+ if (m) {
36
+ if (fence === null) fence = m[1][0];
37
+ else if (m[1][0] === fence) fence = null;
38
+ out.push("");
39
+ continue;
40
+ }
41
+ out.push(fence === null ? line : "");
42
+ }
43
+ return out.join("\n");
44
+ }
45
+
46
+ async function checkArtifacts(notebookDir, findings) {
47
+ for (const [file, heading] of Object.entries(REQUIRED_HEADINGS)) {
48
+ let text;
49
+ try {
50
+ text = await readFile(path.join(notebookDir, file), "utf8");
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (!stripFences(text).split("\n").some((line) => line.trim() === heading)) {
55
+ findings.push({
56
+ code: "E007",
57
+ file,
58
+ message: `missing required heading "${heading}"`,
59
+ });
60
+ }
61
+ }
62
+
63
+ let principles;
64
+ try {
65
+ principles = await readFile(path.join(notebookDir, "principles.md"), "utf8");
66
+ } catch {
67
+ return;
68
+ }
69
+ const rules = stripFences(principles).split("\n").filter((line) => /^\s*\d+[.)]\s+\*\*/.test(line));
70
+ for (const rule of rules) {
71
+ if (!/Source:/i.test(rule)) {
72
+ findings.push({
73
+ code: "E008",
74
+ file: "principles.md",
75
+ message: `principle has no Source: ${rule.trim().slice(0, 80)}`,
76
+ });
77
+ }
78
+ }
79
+ }
80
+
81
+ async function checkIndex(notebookDir, findings) {
82
+ const indexPath = path.join(notebookDir, "index.md");
83
+ let indexText;
84
+ try {
85
+ indexText = await readFile(indexPath, "utf8");
86
+ } catch {
87
+ return;
88
+ }
89
+
90
+ const linkTargets = new Set();
91
+ const linkRe = /\]\(([^)]+)\)/g;
92
+ let match;
93
+ while ((match = linkRe.exec(indexText)) !== null) {
94
+ let href = match[1].trim().replace(/#.*$/, "").replace(/^\.\//, "");
95
+ if (/^[a-z]+:/i.test(href)) continue;
96
+ if (href.endsWith("/")) href = href.replace(/\/+$/, "");
97
+ if (href) linkTargets.add(href);
98
+ }
99
+
100
+ let top;
101
+ try {
102
+ top = await readdir(notebookDir, { withFileTypes: true });
103
+ } catch {
104
+ return;
105
+ }
106
+ const artifacts = top
107
+ .filter((entry) =>
108
+ (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "index.md") ||
109
+ (entry.isDirectory() && (entry.name === "decisions" || entry.name === "work")),
110
+ )
111
+ .map((entry) => entry.name);
112
+
113
+ for (const name of artifacts) {
114
+ if (!linkTargets.has(name)) {
115
+ const label = name === "decisions" || name === "work" ? `${name}/` : name;
116
+ findings.push({
117
+ code: "W003",
118
+ file: "index.md",
119
+ message: `top-level ${label} is not linked from the index`,
120
+ });
121
+ }
122
+ }
123
+
124
+ for (const href of linkTargets) {
125
+ const resolved = path.join(notebookDir, href);
126
+ let ok = false;
127
+ try {
128
+ await stat(resolved);
129
+ ok = true;
130
+ } catch {
131
+ ok = false;
132
+ }
133
+ if (!ok) {
134
+ findings.push({
135
+ code: "W004",
136
+ file: "index.md",
137
+ message: `index link target does not exist: ${href}`,
138
+ });
139
+ }
140
+ }
141
+ }
142
+
143
+ export async function checkNotebook(notebookDir) {
144
+ const findings = [];
145
+
146
+ let notebookEntries;
147
+ try {
148
+ notebookEntries = await stat(notebookDir);
149
+ } catch {
150
+ findings.push({ code: "E000", file: null, message: `no notebook at ${notebookDir}` });
151
+ return findings;
152
+ }
153
+ if (!notebookEntries.isDirectory()) {
154
+ findings.push({ code: "E000", file: null, message: `notebook path is not a directory: ${notebookDir}` });
155
+ return findings;
156
+ }
157
+
158
+ await checkArtifacts(notebookDir, findings);
159
+ await checkIndex(notebookDir, findings);
160
+
161
+ const decisionsDir = path.join(notebookDir, "decisions");
162
+ let entries;
163
+ try {
164
+ entries = await readdir(decisionsDir, { withFileTypes: true });
165
+ entries.sort((a, b) => byName(a.name, b.name));
166
+ } catch {
167
+ entries = [];
168
+ }
169
+
170
+ const records = [];
171
+ for (const entry of entries) {
172
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
173
+ const fileMatch = entry.name.match(DECISION_FILE);
174
+ const text = await readFile(path.join(decisionsDir, entry.name), "utf8");
175
+ const matter = frontMatter(text);
176
+ const idMatch = matter.match(FRONT_MATTER_ID);
177
+ const statusMatch = matter.match(FRONT_MATTER_STATUS);
178
+ const supersededByMatch = matter.match(FRONT_MATTER_SUPERSEDED_BY);
179
+ const titleMatch = text.match(/^#\s+(.+)$/m);
180
+
181
+ records.push({
182
+ file: entry.name,
183
+ fileId: fileMatch ? fileMatch[1] : null,
184
+ id: idMatch ? idMatch[1] : null,
185
+ numId: idMatch ? Number(idMatch[1]) : null,
186
+ status: statusMatch ? statusMatch[1].toLowerCase() : null,
187
+ supersededBy: supersededByMatch ? supersededByMatch[1] : null,
188
+ numSupersededBy: supersededByMatch ? Number(supersededByMatch[1]) : null,
189
+ title: titleMatch ? titleMatch[1].trim() : "",
190
+ });
191
+ }
192
+
193
+ for (const record of records) {
194
+ if (record.id === null) {
195
+ findings.push({ code: "E006", file: record.file, message: "decision file has no numeric id in front matter" });
196
+ }
197
+ }
198
+
199
+ for (const record of records) {
200
+ if (record.fileId !== null && record.id !== null && Number(record.fileId) !== Number(record.id)) {
201
+ findings.push({
202
+ code: "E002",
203
+ file: record.file,
204
+ message: `front-matter id ${record.id} does not match filename prefix ${record.fileId}`,
205
+ });
206
+ }
207
+ }
208
+
209
+ const byId = new Map();
210
+ for (const record of records) {
211
+ if (record.numId === null) continue;
212
+ if (!byId.has(record.numId)) byId.set(record.numId, []);
213
+ byId.get(record.numId).push(record.file);
214
+ }
215
+ for (const [id, files] of byId) {
216
+ if (files.length > 1) {
217
+ findings.push({
218
+ code: "E001",
219
+ file: files.join(", "),
220
+ message: `id ${id} is declared by ${files.length} decision files`,
221
+ });
222
+ }
223
+ }
224
+
225
+ for (const record of records) {
226
+ if (record.status !== null && !STATUSES.has(record.status)) {
227
+ findings.push({ code: "E005", file: record.file, message: `invalid status "${record.status}"` });
228
+ }
229
+ }
230
+
231
+ const idToRecord = new Map();
232
+ for (const record of records) {
233
+ if (record.numId !== null && !idToRecord.has(record.numId)) idToRecord.set(record.numId, record);
234
+ }
235
+
236
+ for (const record of records) {
237
+ if (record.status === "superseded" && record.supersededBy === null) {
238
+ findings.push({
239
+ code: "E004",
240
+ file: record.file,
241
+ message: "record is marked superseded but declares no superseded_by",
242
+ });
243
+ }
244
+ if (record.numSupersededBy === null) continue;
245
+ const target = idToRecord.get(record.numSupersededBy);
246
+ if (!target) {
247
+ findings.push({
248
+ code: "E003",
249
+ file: record.file,
250
+ message: `superseded_by ${record.supersededBy} points at a decision that does not exist`,
251
+ });
252
+ continue;
253
+ }
254
+ if (record.status === "accepted") {
255
+ findings.push({
256
+ code: "W001",
257
+ file: record.file,
258
+ message: `accepted record declares superseded_by ${record.supersededBy}`,
259
+ });
260
+ }
261
+ }
262
+
263
+ const uniqueIds = [...new Set(records.map((record) => record.numId).filter((id) => id !== null))].sort((a, b) => a - b);
264
+ for (let index = 1; index < uniqueIds.length; index += 1) {
265
+ if (uniqueIds[index] !== uniqueIds[index - 1] + 1) {
266
+ findings.push({
267
+ code: "W002",
268
+ file: null,
269
+ message: `id sequence jumps from ${uniqueIds[index - 1]} to ${uniqueIds[index]}`,
270
+ });
271
+ }
272
+ }
273
+
274
+ findings.push(...(await staleCandidates(notebookDir, records)));
275
+ return findings;
276
+ }
277
+
278
+ function byName(a, b) {
279
+ return a < b ? -1 : a > b ? 1 : 0;
280
+ }
281
+
282
+ const STOPWORDS = new Set([
283
+ "the", "and", "for", "with", "that", "this", "from", "into", "use", "using",
284
+ "keep", "must", "should", "when", "are", "was", "were", "has", "have", "not",
285
+ "but", "its", "their", "they", "them", "than", "then", "also", "only", "all",
286
+ "any", "each", "per", "via", "onto", "over", "under", "after", "before",
287
+ ]);
288
+
289
+ function significantTerms(text) {
290
+ return [...new Set(
291
+ (text || "")
292
+ .toLowerCase()
293
+ .replace(/[^a-z0-9\s-]/g, " ")
294
+ .split(/\s+/)
295
+ .filter((word) => word.length >= 4 && !STOPWORDS.has(word)),
296
+ )];
297
+ }
298
+
299
+ async function staleCandidates(notebookDir, records) {
300
+ const out = [];
301
+ const truthFiles = ["system.md", "stack.md"];
302
+ const truthText = {};
303
+ for (const file of truthFiles) {
304
+ try {
305
+ truthText[file] = (await readFile(path.join(notebookDir, file), "utf8")).toLowerCase();
306
+ } catch {
307
+ truthText[file] = "";
308
+ }
309
+ }
310
+
311
+ for (const record of records) {
312
+ if (record.status !== "superseded") continue;
313
+ const terms = significantTerms(record.title || "");
314
+ for (const file of truthFiles) {
315
+ const hits = terms.filter((term) => truthText[file].includes(term));
316
+ if (hits.length > 0) {
317
+ out.push({
318
+ code: "S001",
319
+ file: `${file} (candidate from ${record.file})`,
320
+ message: `superseded decision "${record.title}" may still be described as current; terms found: ${hits.join(", ")}. Review whether ${file} reflects the superseding decision.`,
321
+ });
322
+ }
323
+ }
324
+ }
325
+ return out;
326
+ }
327
+
328
+ export function summarize(findings) {
329
+ const errors = findings.filter((finding) => finding.code.startsWith("E"));
330
+ const warnings = findings.filter((finding) => finding.code.startsWith("W"));
331
+ const stale = findings.filter((finding) => finding.code.startsWith("S"));
332
+ return { errors, warnings, stale, ok: errors.length === 0 };
333
+ }
334
+
335
+ export async function fixMechanical(notebookDir) {
336
+ const decisionsDir = path.join(notebookDir, "decisions");
337
+ let entries;
338
+ try {
339
+ entries = await readdir(decisionsDir, { withFileTypes: true });
340
+ } catch {
341
+ return { fixed: [], changed: false };
342
+ }
343
+
344
+ const files = entries
345
+ .filter((entry) => entry.isFile() && DECISION_FILE.test(entry.name))
346
+ .map((entry) => entry.name)
347
+ .sort(byName);
348
+ const used = new Set();
349
+ for (const file of files) {
350
+ const match = file.match(DECISION_FILE);
351
+ if (match) used.add(Number(match[1]));
352
+ }
353
+ const nextFree = () => {
354
+ let candidate = 1;
355
+ while (used.has(candidate)) candidate += 1;
356
+ used.add(candidate);
357
+ return candidate;
358
+ };
359
+
360
+ const seen = new Map();
361
+ const fixed = [];
362
+ let changed = false;
363
+
364
+ for (const file of files) {
365
+ const full = path.join(decisionsDir, file);
366
+ let text = await readFile(full, "utf8");
367
+ const fileMatch = file.match(DECISION_FILE);
368
+ const before = text;
369
+
370
+ const idMatch = frontMatter(text).match(FRONT_MATTER_ID);
371
+ if (idMatch && Number(idMatch[1]) !== Number(fileMatch[1])) {
372
+ text = text.replace(/^id:\s*\d+\s*$/m, `id: ${fileMatch[1]}`);
373
+ fixed.push({ code: "E002", file, message: `aligned id to filename prefix ${fileMatch[1]}` });
374
+ }
375
+
376
+ const numId = Number(frontMatter(text).match(FRONT_MATTER_ID)?.[1] ?? fileMatch[1]);
377
+ let finalName = file;
378
+ if (seen.has(numId) && seen.get(numId) !== file) {
379
+ const newId = nextFree();
380
+ const padded = String(newId).padStart(fileMatch[1].length, "0");
381
+ text = text.replace(/^id:\s*\d+\s*$/m, `id: ${padded}`);
382
+ finalName = `${padded}-${file.slice(fileMatch[1].length + 1)}`;
383
+ fixed.push({ code: "E001", file, message: `renumbered duplicate id ${numId} to ${newId} (renamed to ${finalName})` });
384
+ } else if (!seen.has(numId)) {
385
+ seen.set(numId, file);
386
+ }
387
+
388
+ if (text !== before || finalName !== file) {
389
+ if (finalName !== file) {
390
+ await writeFile(path.join(decisionsDir, finalName), text);
391
+ await rm(full);
392
+ } else {
393
+ await writeFile(full, text);
394
+ }
395
+ changed = true;
396
+ }
397
+ }
398
+ return { fixed, changed };
399
399
  }