architecture-harness 0.10.0 → 0.11.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
package/src/cli/check.mjs CHANGED
@@ -30,8 +30,12 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
30
30
  import { checkConfigFloor } from "../gates/config-floor.mjs";
31
31
  import { defaults } from "../config.mjs";
32
32
  import { rules as lintRules } from "../eslint/index.mjs";
33
- import { enabled, readerEntries, thresholds } from "../config.mjs";
33
+ import { adrLog, enabled, readerEntries, thresholds } from "../config.mjs";
34
34
  import { checkRegistryReaders } from "../gates/registry-readers.mjs";
35
+ import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
36
+ import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
37
+ import { checkThresholdRatchet } from "../gates/threshold-ratchet.mjs";
38
+ import { ratchetInputs } from "./registry-history.mjs";
35
39
  import { repoFiles } from "./repo-files.mjs";
36
40
 
37
41
  // Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
@@ -179,6 +183,15 @@ function sourceFiles(config, tree, only) {
179
183
  return readEach(config.root, rels);
180
184
  }
181
185
 
186
+ function parsedJson(source) {
187
+ if (source === null) return null;
188
+ try {
189
+ return JSON.parse(source);
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+
182
195
  async function registered(file) {
183
196
  const source = await read(file);
184
197
  if (source === null) return [];
@@ -463,6 +476,26 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
463
476
  if (readers.length > 0) lines.push(`OK readers ${readers.length} registry reader(s), each present and naming its entry`);
464
477
  }
465
478
 
479
+ if (enabled(config.gates, "registry-literal")) {
480
+ const docs = await readEach(config.root, tree.under(config.docs.root).filter((file) => file.endsWith(".md")));
481
+ const libraries = parsedJson(await read(path.join(config.root, config.versions)))?.libraries ?? {};
482
+ const exempt = config.registryLiteral.exempt ?? adrLog(config);
483
+ problems.push(...checkRegistryLiteral(docs, { thresholds: thresholds(config), libraries, exempt }));
484
+ if (docs.length > 0) lines.push(`OK literals ${docs.length} doc(s) carry a token, never a figure a registry owns`);
485
+ }
486
+
487
+ if (enabled(config.gates, "threshold-ratchet")) {
488
+ const { base } = config.ratchet;
489
+ const inputs = await ratchetInputs(config.root, { base, registry: config.thresholds, adrGlobs: adrLog(config) });
490
+ if (inputs.skip) {
491
+ lines.push(`OK ratchet skipped: ${inputs.skip}`);
492
+ } else {
493
+ problems.push(...checkThresholdRatchet(inputs.before, inputs.after, inputs.adrs, { registry: config.thresholds }));
494
+ const count = Object.keys(inputs.after).length;
495
+ if (count > 0) lines.push(`OK ratchet ${count} threshold(s) against the merge base with ${base}; a loosening names its ADR`);
496
+ }
497
+ }
498
+
466
499
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
467
500
  problems.push(...(await sqlAgreement(config, tree, taken)));
468
501
  lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
@@ -470,6 +503,13 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
470
503
  for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
471
504
  }
472
505
 
506
+ if (enabled(config.gates, "migration-numbers")) {
507
+ const migrationDir = posix(config.paths.migrations);
508
+ const names = tree.namesIn(migrationDir).filter((name) => tree.isFile(join(migrationDir, name)));
509
+ problems.push(...checkMigrationNumbers(names, migrationDir));
510
+ if (names.length > 0) lines.push(`OK migrations ${names.filter((name) => name.endsWith(".sql")).length} migration(s), each number unique, with no gap`);
511
+ }
512
+
473
513
  if (enabled(config.gates, "saga-tests")) {
474
514
  const sources = await sourceFiles(config, tree);
475
515
  const sagas = declaredSagas(
@@ -0,0 +1,53 @@
1
+ // A resource: the thresholds registry at the merge base with a ref, the registry now, and the ADR
2
+ // files the change touches. Git answers each question; no answer is a reason to skip, never a failure.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import { readFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { globMatcher } from "../glob.mjs";
8
+
9
+ /** @returns {string|null} stdout, or null when git is absent or the command fails. */
10
+ function git(root, ...args) {
11
+ const result = spawnSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
12
+ return result.status === 0 ? result.stdout : null;
13
+ }
14
+
15
+ function gatesOf(text) {
16
+ if (text === null) return {};
17
+ try {
18
+ return JSON.parse(text).gates ?? {};
19
+ } catch {
20
+ return {};
21
+ }
22
+ }
23
+
24
+ const paths = (listing) => (listing ?? "").split("\0").filter(Boolean);
25
+
26
+ /**
27
+ * @param {string} root the repository root, or a folder inside one
28
+ * @param {{base: string, registry: string, adrGlobs: string[]}} options
29
+ * @returns {Promise<{skip: string} | {before: object, after: object, adrs: {path: string, text: string}[]}>}
30
+ */
31
+ export async function ratchetInputs(root, { base, registry, adrGlobs }) {
32
+ if (git(root, "rev-parse", "--verify", "--quiet", "HEAD") === null) return { skip: "no git, or no commit yet" };
33
+ if (git(root, "rev-parse", "--verify", "--quiet", `${base}^{commit}`) === null) return { skip: `no ref '${base}'` };
34
+ const mergeBase = git(root, "merge-base", base, "HEAD")?.trim();
35
+ if (!mergeBase) return { skip: `no merge base with '${base}', as in a shallow clone` };
36
+
37
+ const file = registry.split(path.sep).join("/");
38
+ const before = gatesOf(git(root, "show", `${mergeBase}:./${file}`));
39
+ const after = gatesOf(await readFile(path.join(root, registry), "utf8").catch(() => null));
40
+
41
+ // Committed, staged and unstaged changes since the merge base, and a new file not yet added.
42
+ const isAdr = globMatcher(adrGlobs);
43
+ const changed = new Set([
44
+ ...paths(git(root, "diff", "--name-only", "--relative", "-z", mergeBase)),
45
+ ...paths(git(root, "ls-files", "--others", "--exclude-standard", "-z")),
46
+ ]);
47
+ const adrs = [];
48
+ for (const rel of [...changed].filter((rel) => rel.endsWith(".md") && isAdr(rel))) {
49
+ const text = await readFile(path.join(root, rel), "utf8").catch(() => null);
50
+ if (text !== null) adrs.push({ path: rel, text });
51
+ }
52
+ return { before, after, adrs };
53
+ }
@@ -0,0 +1,88 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { load } from "../config.mjs";
8
+ import { runCheck } from "./check.mjs";
9
+
10
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" });
11
+ const REGISTRY = "quality-thresholds.json";
12
+ const registry = (gates) => `${JSON.stringify({ gates }, null, 2)}\n`;
13
+ const FILELENGTH = { filelength: { value: 500, unit: "lines", comparator: "max" } };
14
+
15
+ function write(dir, files) {
16
+ for (const [rel, contents] of Object.entries(files)) {
17
+ mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
18
+ writeFileSync(path.join(dir, rel), contents);
19
+ }
20
+ }
21
+
22
+ /** A repository whose `main` holds the registry, checked out on a branch `feat`. One per case. */
23
+ function repo({ base = "main", commit = true } = {}) {
24
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-ratchet-"));
25
+ git(dir, "init", "-q", "-b", "main");
26
+ git(dir, "config", "user.name", "qc");
27
+ git(dir, "config", "user.email", "qc@example.com");
28
+ git(dir, "config", "commit.gpgsign", "false");
29
+ write(dir, { "qc.config.json": JSON.stringify({ featureRoots: [], ratchet: { base } }), [REGISTRY]: registry(FILELENGTH) });
30
+ if (!commit) return dir;
31
+ git(dir, "add", ".");
32
+ git(dir, "commit", "-q", "-m", "init");
33
+ git(dir, "checkout", "-q", "-b", "feat");
34
+ return dir;
35
+ }
36
+
37
+ async function ratchet(dir) {
38
+ const { problems, lines } = await runCheck(load(dir));
39
+ return {
40
+ loosened: problems.filter((problem) => problem.rule === "loosened-threshold"),
41
+ line: lines.find((line) => line.includes("ratchet")),
42
+ };
43
+ }
44
+
45
+ test("a max that rises from 500 to 550 fails", async () => {
46
+ const dir = repo();
47
+ write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }) });
48
+ const { loosened } = await ratchet(dir);
49
+ assert.equal(loosened.length, 1);
50
+ assert.match(loosened[0].detail, /filelength/);
51
+ });
52
+
53
+ test("the same rise passes with a committed ADR that names the key", async () => {
54
+ const dir = repo();
55
+ write(dir, {
56
+ [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }),
57
+ "docs/decisions/0002-longer-files.md": "# Longer files\n\n`filelength` rises to 550: the parser needs one file.\n",
58
+ });
59
+ git(dir, "add", ".");
60
+ git(dir, "commit", "-q", "-m", "loosen");
61
+ assert.deepEqual((await ratchet(dir)).loosened, []);
62
+ });
63
+
64
+ test("a tightening passes", async () => {
65
+ const dir = repo();
66
+ write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 450 } }) });
67
+ assert.deepEqual((await ratchet(dir)).loosened, []);
68
+ });
69
+
70
+ test("a new entry passes", async () => {
71
+ const dir = repo();
72
+ write(dir, { [REGISTRY]: registry({ ...FILELENGTH, nesting: { value: 9, unit: "count", comparator: "max" } }) });
73
+ assert.deepEqual((await ratchet(dir)).loosened, []);
74
+ });
75
+
76
+ test("a base ref that does not exist skips with an OK line that says why", async () => {
77
+ const dir = repo({ base: "origin/main" });
78
+ write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }) });
79
+ const { loosened, line } = await ratchet(dir);
80
+ assert.deepEqual(loosened, []);
81
+ assert.match(line, /^OK .*no ref 'origin\/main'/);
82
+ });
83
+
84
+ test("a repository with no commit yet skips with an OK line", async () => {
85
+ const { loosened, line } = await ratchet(repo({ commit: false }));
86
+ assert.deepEqual(loosened, []);
87
+ assert.match(line, /^OK .*no commit/);
88
+ });
package/src/config.mjs CHANGED
@@ -36,6 +36,15 @@ export const defaults = {
36
36
  },
37
37
 
38
38
  thresholds: "quality-thresholds.json",
39
+ // Pinned library versions. Docs carry a {{ver:id}} or {{v:id}} token for each.
40
+ versions: "versions.json",
41
+
42
+ // Globs of docs that may state a registry figure. Null is the ADR log, from adrLog(): a decision
43
+ // states the number as of its date.
44
+ registryLiteral: { exempt: null },
45
+
46
+ // A threshold loosens only with an ADR. `base` is the ref whose merge base the registry is compared with.
47
+ ratchet: { base: "origin/main" },
39
48
 
40
49
  // A key that makes a retry a resume rather than a second write. docs/guards.md.
41
50
  idempotency: {
@@ -273,6 +282,9 @@ export const defaults = {
273
282
  "registry-agreement": true,
274
283
  "registry-readers": true,
275
284
  "sql-identifiers": true,
285
+ "migration-numbers": true,
286
+ "registry-literal": true,
287
+ "threshold-ratchet": true,
276
288
  "tenant-predicate": true,
277
289
  "claimed-requirements": true,
278
290
  "public-routes": true,
@@ -387,6 +399,11 @@ export function thresholds(config) {
387
399
  return createRequire(import.meta.url)(file).gates ?? {};
388
400
  }
389
401
 
402
+ /** The files that hold decision records: each ADR under `adr.root`, and the decision register. */
403
+ export function adrLog(config) {
404
+ return [`${config.adr.root.replace(/\/+$/, "")}/**`, config.docs.decisions];
405
+ }
406
+
390
407
  /**
391
408
  * Registry entries that say who may hold their number. `names` are identifier patterns, each a
392
409
  * regular expression matched against the whole identifier, case-insensitive. `readers` are paths.
@@ -6,6 +6,9 @@ export const gateDescriptions = Object.freeze({
6
6
  "registry-agreement": "A value written twice agrees with the registry that owns it",
7
7
  "registry-readers": "Every reader a registry entry names exists and names the entry",
8
8
  "sql-identifiers": "A query names a column a migration declares, and only its own feature's tables",
9
+ "migration-numbers": "Each migration number is unique, and the numbers run with no gap",
10
+ "registry-literal": "A doc states a registry threshold or library version as its token, never as the figure",
11
+ "threshold-ratchet": "A threshold never loosens against the merge base unless a changed ADR names it",
9
12
  "tenant-predicate": "Every statement on a business table filters on the tenant",
10
13
  "claimed-requirements": "A requirement a route claims names the test that proves it",
11
14
  "public-routes": "The edge lets through exactly the routes the api serves without a session",
@@ -0,0 +1,33 @@
1
+ // Migration numbers are handed out by hand, so two branches can take the same one, or a rebase can
2
+ // drop one. Each numeric prefix is unique, and the run from the lowest to the highest has no gap.
3
+
4
+ const MIGRATION = /^(\d+)_.*\.sql$/;
5
+
6
+ /**
7
+ * @param {string[]} names the names in the migrations folder
8
+ * @param {string} dir the folder, as a problem names it
9
+ */
10
+ export function checkMigrationNumbers(names, dir) {
11
+ const byNumber = new Map();
12
+ for (const name of names) {
13
+ const found = MIGRATION.exec(name);
14
+ if (found === null) continue;
15
+ const number = Number(found[1]);
16
+ byNumber.set(number, [...(byNumber.get(number) ?? []), name]);
17
+ }
18
+ const problems = [];
19
+ for (const [number, files] of byNumber) {
20
+ if (files.length > 1) {
21
+ problems.push({ path: dir, rule: "duplicate-migration-number", detail: `${files.sort().join(", ")} share number ${number}; give each migration its own` });
22
+ }
23
+ }
24
+ const numbers = [...byNumber.keys()].sort((a, b) => a - b);
25
+ const missing = [];
26
+ for (let number = numbers[0]; number < numbers.at(-1); number += 1) {
27
+ if (!byNumber.has(number)) missing.push(number);
28
+ }
29
+ if (missing.length > 0) {
30
+ problems.push({ path: dir, rule: "migration-number-gap", detail: `no migration holds number ${missing.join(", ")}; the numbers run from ${numbers[0]} to ${numbers.at(-1)} with no gap` });
31
+ }
32
+ return problems;
33
+ }
@@ -0,0 +1,35 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkMigrationNumbers } from "./migration-numbers.mjs";
4
+
5
+ const DIR = "backend/src/drizzle";
6
+
7
+ test("contiguous prefixes pass, and a name that is not a migration is ignored", () => {
8
+ const names = ["0001_identity.sql", "0002_projects.sql", "0003_sites.sql", "meta", "README.md"];
9
+ assert.deepEqual(checkMigrationNumbers(names, DIR), []);
10
+ });
11
+
12
+ test("the numbers may start above one, as after a squash", () => {
13
+ assert.deepEqual(checkMigrationNumbers(["0040_base.sql", "0041_photos.sql"], DIR), []);
14
+ });
15
+
16
+ test("a duplicate prefix fails and names both files", () => {
17
+ const problems = checkMigrationNumbers(["0001_identity.sql", "0002_projects.sql", "0002_sites.sql"], DIR);
18
+ assert.equal(problems.length, 1);
19
+ assert.equal(problems[0].rule, "duplicate-migration-number");
20
+ assert.equal(problems[0].path, DIR);
21
+ assert.match(problems[0].detail, /0002_projects\.sql/);
22
+ assert.match(problems[0].detail, /0002_sites\.sql/);
23
+ });
24
+
25
+ test("a gap fails and names the missing numbers", () => {
26
+ const problems = checkMigrationNumbers(["0001_identity.sql", "0002_projects.sql", "0005_sites.sql"], DIR);
27
+ assert.equal(problems.length, 1);
28
+ assert.equal(problems[0].rule, "migration-number-gap");
29
+ assert.match(problems[0].detail, /\b3\b.*\b4\b/);
30
+ });
31
+
32
+ test("a different width is the same number", () => {
33
+ const problems = checkMigrationNumbers(["0001_identity.sql", "01_projects.sql"], DIR);
34
+ assert.equal(problems[0].rule, "duplicate-migration-number");
35
+ });
@@ -0,0 +1,137 @@
1
+ // A number a registry owns is written in the docs as a token, never as the figure. A figure goes
2
+ // stale the day the registry moves, and nothing else would notice.
3
+
4
+ import { escape } from "../eslint/options.mjs";
5
+ import { globMatcher } from "../glob.mjs";
6
+
7
+ const TOKEN = /\{\{(?:q|ver|v):[^}]*\}\}/g;
8
+ // Words between a phrase and a number, at most. Past that the number belongs to another sentence.
9
+ const WINDOW = 6;
10
+ const NUMBER = /^(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(%|[a-z]+)?$/;
11
+ const UNIT_SPELLINGS = {
12
+ percent: ["%", "percent"],
13
+ ms: ["ms", "millisecond", "milliseconds"],
14
+ s: ["s", "second", "seconds"],
15
+ px: ["px", "pixel", "pixels"],
16
+ lines: ["line", "lines"],
17
+ days: ["day", "days"],
18
+ months: ["month", "months"],
19
+ count: [],
20
+ };
21
+
22
+ const spellings = (unit) => UNIT_SPELLINGS[unit] ?? (unit ? [unit, unit.replace(/s$/, "")] : []);
23
+
24
+ /** Lowercase, with the punctuation around a word gone. A trailing `%` stays: it is the unit. */
25
+ const normal = (word) => word.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}%]+$/gu, "");
26
+
27
+ /** Each entry that states its phrases, with the units that are its own. */
28
+ function thresholdEntries(thresholds) {
29
+ return Object.entries(thresholds)
30
+ .filter(([, entry]) => typeof entry.value === "number" && entry.match?.length > 0)
31
+ .map(([key, entry]) => ({
32
+ key,
33
+ value: entry.value,
34
+ unit: entry.unit,
35
+ own: new Set(spellings(entry.unit)),
36
+ phrases: entry.match.map((phrase) => phrase.split(/\s+/).map(normal).filter(Boolean)),
37
+ }));
38
+ }
39
+
40
+ /** The unit a number carries: attached as `70%`, or the next word as `70 percent`. */
41
+ function unitOf(words, index, attached, known) {
42
+ if (attached) return attached;
43
+ const next = words[index + 1]?.norm;
44
+ return next !== undefined && known.has(next) ? next : "";
45
+ }
46
+
47
+ /** The word ranges where a phrase stands. */
48
+ function phraseSpans(words, phrases) {
49
+ const spans = [];
50
+ for (const phrase of phrases) {
51
+ for (let start = 0; start + phrase.length <= words.length; start += 1) {
52
+ if (phrase.every((part, offset) => words[start + offset].norm === part)) spans.push([start, start + phrase.length - 1]);
53
+ }
54
+ }
55
+ return spans;
56
+ }
57
+
58
+ const near = (index, [start, end]) => (index > end ? index - end - 1 : start - index - 1) <= WINDOW;
59
+
60
+ function thresholdProblems(file, words, entries, known) {
61
+ const problems = [];
62
+ const spansOf = new Map(entries.map((entry) => [entry.key, phraseSpans(words, entry.phrases)]));
63
+ words.forEach((word, index) => {
64
+ const found = NUMBER.exec(word.norm);
65
+ if (found === null) return;
66
+ const value = Number(found[1].replaceAll(",", ""));
67
+ const unit = unitOf(words, index, found[2], known);
68
+ for (const entry of entries) {
69
+ if (entry.value !== value) continue;
70
+ // An attached suffix that is no unit at all, as in `70th`, is not the entry's number either.
71
+ if (unit && !entry.own.has(unit)) continue;
72
+ if (!spansOf.get(entry.key).some((span) => near(index, span))) continue;
73
+ problems.push({
74
+ path: `${file}:${word.line}`,
75
+ rule: "threshold-literal",
76
+ detail: `'${word.norm}' restates the '${entry.key}' threshold (${entry.value}${entry.unit ? ` ${entry.unit}` : ""}); write {{q:${entry.key}}}`,
77
+ });
78
+ }
79
+ });
80
+ return problems;
81
+ }
82
+
83
+ /** Paragraphs as word lists, each word with its line. A blank line ends a paragraph. */
84
+ function paragraphs(text) {
85
+ const out = [];
86
+ let words = [];
87
+ text.split("\n").forEach((line, index) => {
88
+ if (line.trim() === "") {
89
+ if (words.length > 0) out.push(words);
90
+ words = [];
91
+ return;
92
+ }
93
+ for (const [raw] of line.matchAll(/\S+/g)) {
94
+ const norm = normal(raw);
95
+ if (norm) words.push({ raw, norm, line: index + 1 });
96
+ }
97
+ });
98
+ if (words.length > 0) out.push(words);
99
+ return out;
100
+ }
101
+
102
+ function versionProblems(file, text, libraries) {
103
+ const problems = [];
104
+ for (const [id, library] of Object.entries(libraries)) {
105
+ if (typeof library?.label !== "string" || library.label.trim() === "") continue;
106
+ const label = escape(library.label.trim()).replace(/\s+/g, "\\s+");
107
+ for (const found of text.matchAll(new RegExp(`(?<![\\w.])${label}\\s+v?\\d+(?:\\.\\d+)*\\b`, "gi"))) {
108
+ const line = text.slice(0, found.index).split("\n").length;
109
+ problems.push({
110
+ path: `${file}:${line}`,
111
+ rule: "version-literal",
112
+ detail: `'${found[0].replace(/\s+/g, " ")}' restates the '${id}' version; write {{ver:${id}}} or {{v:${id}}}`,
113
+ });
114
+ }
115
+ }
116
+ return problems;
117
+ }
118
+
119
+ /**
120
+ * @param {{path: string, contents: string}[]} docs the markdown files, paths relative to the root
121
+ * @param {{thresholds: object, libraries: object, exempt: string[]}} registries the `gates` of the
122
+ * thresholds registry, the `libraries` of the versions registry, and the globs of files that may hold a figure
123
+ */
124
+ export function checkRegistryLiteral(docs, { thresholds = {}, libraries = {}, exempt = [] }) {
125
+ const entries = thresholdEntries(thresholds);
126
+ const known = new Set([...Object.values(UNIT_SPELLINGS).flat(), ...entries.flatMap((entry) => [...entry.own])]);
127
+ const isExempt = globMatcher(exempt);
128
+ const problems = [];
129
+ for (const { path: file, contents } of docs) {
130
+ if (isExempt(file)) continue;
131
+ // A placeholder word, so a token still counts as one word of the window.
132
+ const text = contents.replace(/\r\n?/g, "\n").replace(TOKEN, "TOKEN");
133
+ for (const words of paragraphs(text)) problems.push(...thresholdProblems(file, words, entries, known));
134
+ problems.push(...versionProblems(file, text, libraries));
135
+ }
136
+ return problems;
137
+ }
@@ -0,0 +1,68 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkRegistryLiteral } from "./registry-literal.mjs";
4
+
5
+ const thresholds = {
6
+ coverage: { value: 70, unit: "percent", comparator: "min", match: ["coverage threshold", "coverage on new code"] },
7
+ filelength: { value: 500, unit: "lines", comparator: "max", match: ["max-lines", "file length"] },
8
+ holdpress: { value: 500, unit: "ms", comparator: "max" },
9
+ };
10
+ const libraries = { node: { label: "Node.js", version: "24" }, drizzle: { label: "Drizzle ORM", version: "0.44" } };
11
+ const registries = { thresholds, libraries, exempt: ["docs/decisions/**"] };
12
+ const check = (contents, file = "docs/architecture.md") => checkRegistryLiteral([{ path: file, contents }], registries);
13
+ const rules = (contents) => check(contents).map((problem) => problem.rule);
14
+
15
+ test("a threshold stated as a number beside its phrase fails", () => {
16
+ const problems = check("Intro.\n\nThe coverage threshold of 70% holds on every package.");
17
+ assert.equal(problems.length, 1);
18
+ assert.equal(problems[0].rule, "threshold-literal");
19
+ assert.equal(problems[0].path, "docs/architecture.md:3");
20
+ assert.match(problems[0].detail, /\{\{q:coverage\}\}/);
21
+ });
22
+
23
+ test("the token passes", () => {
24
+ assert.deepEqual(check("The coverage threshold of {{q:coverage}} holds."), []);
25
+ });
26
+
27
+ test("another number near the phrase passes", () => {
28
+ assert.deepEqual(check("The coverage threshold rose twice in 2024, across 3 packages and 1700 files."), []);
29
+ });
30
+
31
+ test("the number before the phrase, in a table row, fails", () => {
32
+ assert.deepEqual(rules("| 70% | coverage on new code |"), ["threshold-literal"]);
33
+ assert.deepEqual(rules("70 percent coverage on new code"), ["threshold-literal"]);
34
+ });
35
+
36
+ test("a phrase that holds a hyphen matches as a whole word", () => {
37
+ assert.deepEqual(rules("`max-lines` stops at 500 lines."), ["threshold-literal"]);
38
+ assert.deepEqual(check("`max-lines-per-function` stops at 500."), []);
39
+ });
40
+
41
+ test("the unit of another entry keeps the number quiet, and no unit reports it", () => {
42
+ assert.deepEqual(check("The file length check runs in 500 ms."), []);
43
+ assert.deepEqual(rules("The file length is 500."), ["threshold-literal"]);
44
+ });
45
+
46
+ test("a number is whole: an id, a date or a decimal holding the digits passes", () => {
47
+ assert.deepEqual(check("The coverage threshold is in ADR-0070, dated 2026-07-70, at 0.70 weight."), []);
48
+ });
49
+
50
+ test("the window is six words, and a paragraph ends it", () => {
51
+ assert.deepEqual(rules("The coverage threshold is one that we hold at\n70% here."), ["threshold-literal"]);
52
+ assert.deepEqual(check("The coverage threshold is one that we all hold firmly at 70%."), []);
53
+ assert.deepEqual(check("The coverage threshold.\n\n70% of the files."), []);
54
+ });
55
+
56
+ test("a library label beside a version number fails, and its token passes", () => {
57
+ const problems = check("The api runs on Node.js 24 and\nDrizzle ORM 0.44.");
58
+ assert.deepEqual(problems.map((problem) => [problem.rule, problem.path]), [
59
+ ["version-literal", "docs/architecture.md:1"],
60
+ ["version-literal", "docs/architecture.md:2"],
61
+ ]);
62
+ assert.match(problems[0].detail, /\{\{ver:node\}\}/);
63
+ assert.deepEqual(check("The api runs on Node.js {{v:node}} and {{ver:drizzle}}."), []);
64
+ });
65
+
66
+ test("an exempt file passes", () => {
67
+ assert.deepEqual(check("The coverage threshold of 70% on Node.js 24.", "docs/decisions/0001-coverage.md"), []);
68
+ });
@@ -11,7 +11,11 @@
11
11
  const CONSTRAINT_OPENER = new Set(["primary", "unique", "check", "constraint", "foreign", "exclude", "like"]);
12
12
  const COLUMN_LINE = /^([a-z_][a-z0-9_]*)\s+\S/;
13
13
  const CREATE_TABLE = /create table (?:if not exists )?(\w+)\s*\(/g;
14
- const ADD_COLUMN = /alter table (\w+)\s+add column (?:if not exists )?([a-z_]+)\s+/g;
14
+ const ALTER_TABLE = /\balter table (?:if exists )?(?:only )?(\w+)\s/g;
15
+ const ADD_COLUMN = /\badd column (?:if not exists )?([a-z_][a-z0-9_]*)\s/g;
16
+ // A statement ends at a semicolon outside a quoted string. A missed one must not hand a column to
17
+ // the table before it, so the next statement's opening word ends the slice too.
18
+ const STATEMENT_END = /;|\b(?:alter|create)\s+table\b/g;
15
19
  const INDEX_NAME = /\bindex\("([a-z_]+)"\)/g;
16
20
  // Columns are matched by shape — every column in this schema is snake_case.
17
21
  const SNAKE = /\b([a-z][a-z0-9]*_[a-z0-9_]+)\b/g;
@@ -83,18 +87,33 @@ export function declaredColumns(sources) {
83
87
  tables.set(match[1], columns);
84
88
  match = CREATE_TABLE.exec(sql);
85
89
  }
86
- ADD_COLUMN.lastIndex = 0;
87
- let added = ADD_COLUMN.exec(sql);
88
- while (added !== null) {
89
- const columns = tables.get(added[1]) ?? new Set();
90
- columns.add(added[2]);
91
- tables.set(added[1], columns);
92
- added = ADD_COLUMN.exec(sql);
93
- }
90
+ addedColumns(tables, sql);
94
91
  }
95
92
  return tables;
96
93
  }
97
94
 
95
+ /**
96
+ * Quoted strings and line comments declare nothing, and a semicolon inside one ends nothing. One pass
97
+ * reads them in order, so an apostrophe inside a comment opens no string.
98
+ */
99
+ const blanked = (sql) => sql.replace(/--[^\n]*|'(?:[^']|'')*'/g, (found) => (found.startsWith("--") ? "" : "''"));
100
+
101
+ /** Every `add column` of each `alter table` statement, a comma list included. */
102
+ function addedColumns(tables, sql) {
103
+ const plain = blanked(sql);
104
+ ALTER_TABLE.lastIndex = 0;
105
+ for (let alter = ALTER_TABLE.exec(plain); alter !== null; alter = ALTER_TABLE.exec(plain)) {
106
+ const rest = plain.slice(alter.index + alter[0].length);
107
+ STATEMENT_END.lastIndex = 0;
108
+ const end = STATEMENT_END.exec(rest);
109
+ const added = [...(end === null ? rest : rest.slice(0, end.index)).matchAll(ADD_COLUMN)];
110
+ if (added.length === 0) continue;
111
+ const columns = tables.get(alter[1]) ?? new Set();
112
+ for (const [, column] of added) columns.add(column);
113
+ tables.set(alter[1], columns);
114
+ }
115
+ }
116
+
98
117
  /**
99
118
  * Quoted literals are stripped first: a rank name inside a statement is a value,
100
119
  * not a column.
@@ -24,6 +24,33 @@ test("a later expand migration adds its column to the same table", () => {
24
24
 
25
25
  const resource = (sql) => `const SQL = \`${sql}\`;`;
26
26
 
27
+ test("every column of a comma list of add column is declared, and each is checked", () => {
28
+ const expand = `alter table projects
29
+ add column archived_at timestamptz,
30
+ add column if not exists site_code2 text default 'a;b',
31
+ add column owner_id uuid;`;
32
+ const tables = declaredColumns([ddl, expand]);
33
+ assert.deepEqual(
34
+ ["archived_at", "site_code2", "owner_id"].filter((column) => !tables.get("projects").has(column)),
35
+ [],
36
+ );
37
+ const agreeing = resource("select owner_id, site_code2 from projects where tenant_id = $1");
38
+ assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source: agreeing }]), []);
39
+ const unknown = resource("select owner_id, owner_name from projects where tenant_id = $1");
40
+ const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source: unknown }]);
41
+ assert.equal(problems.length, 1);
42
+ assert.match(problems[0].detail, /'owner_name'/);
43
+ });
44
+
45
+ test("an add column belongs to its own alter table, never to the one before it", () => {
46
+ const tables = declaredColumns([
47
+ ddl,
48
+ "alter table projects enable row level security\ncreate table sites (id uuid);\n-- a site's name\nalter table sites add column site_name text;",
49
+ ]);
50
+ assert.equal(tables.get("projects").has("site_name"), false);
51
+ assert.ok(tables.get("sites").has("site_name"));
52
+ });
53
+
27
54
  test("an agreeing slice has no finding", () => {
28
55
  const tables = declaredColumns([ddl]);
29
56
  const source = resource("select id, tenant_id, code from projects where tenant_id = $1");
@@ -0,0 +1,46 @@
1
+ // A threshold only tightens, unless a decision says why it loosens. Every brief says "never lower a
2
+ // threshold", and a rule a gate checks holds under pressure where a sentence does not.
3
+
4
+ import { escape } from "../eslint/options.mjs";
5
+
6
+ function loosened(comparator, was, now) {
7
+ if (comparator === "max") return now > was;
8
+ if (comparator === "min") return now < was;
9
+ return false;
10
+ }
11
+
12
+ /**
13
+ * @param {object} before the registry's `gates` at the merge base
14
+ * @param {object} after the registry's `gates` now
15
+ * @param {{path: string, text: string}[]} adrs the ADR files the diff changes, with their text
16
+ * @param {{registry: string}} options the registry path, as a problem names it
17
+ */
18
+ export function checkThresholdRatchet(before, after, adrs, { registry }) {
19
+ const problems = [];
20
+ const citedByAdr = (key) => {
21
+ const named = new RegExp(`\\b${escape(key)}\\b`);
22
+ return adrs.some((adr) => named.test(adr.text));
23
+ };
24
+ for (const [key, entry] of Object.entries(after)) {
25
+ const was = before[key];
26
+ // The comparator in force before the change is the policy the change answers to.
27
+ if (typeof was?.value !== "number" || typeof entry?.value !== "number") continue;
28
+ if (!loosened(was.comparator, was.value, entry.value)) continue;
29
+ if (citedByAdr(key)) continue;
30
+ problems.push({
31
+ path: registry,
32
+ rule: "loosened-threshold",
33
+ detail: `'${key}' moves from ${was.value} to ${entry.value}, and a ${was.comparator} that moves this way loosens; a changed ADR must name '${key}'`,
34
+ });
35
+ }
36
+ // Dropping a limit is the widest loosening of all, so it answers to the same rule.
37
+ for (const [key, was] of Object.entries(before)) {
38
+ if (key in after || typeof was?.value !== "number" || citedByAdr(key)) continue;
39
+ problems.push({
40
+ path: registry,
41
+ rule: "removed-threshold",
42
+ detail: `'${key}' (${was.comparator} ${was.value}) is removed; a changed ADR must name '${key}'`,
43
+ });
44
+ }
45
+ return problems;
46
+ }
@@ -0,0 +1,60 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkThresholdRatchet } from "./threshold-ratchet.mjs";
4
+
5
+ const REGISTRY = "quality-thresholds.json";
6
+ const base = {
7
+ filelength: { value: 500, comparator: "max" },
8
+ coverage: { value: 70, comparator: "min" },
9
+ };
10
+ const moved = (key, value) => ({ ...base, [key]: { ...base[key], value } });
11
+ const check = (after, adrs = []) => checkThresholdRatchet(base, after, adrs, { registry: REGISTRY });
12
+
13
+ test("a max that rises fails", () => {
14
+ const problems = check(moved("filelength", 550));
15
+ assert.equal(problems.length, 1);
16
+ assert.equal(problems[0].rule, "loosened-threshold");
17
+ assert.equal(problems[0].path, REGISTRY);
18
+ assert.match(problems[0].detail, /filelength.*500.*550/);
19
+ });
20
+
21
+ test("a min that falls fails", () => {
22
+ assert.equal(check(moved("coverage", 60))[0].rule, "loosened-threshold");
23
+ });
24
+
25
+ test("a changed ADR whose text names the key lets the loosening through", () => {
26
+ const adrs = [{ path: "docs/decisions/0031-longer-files.md", text: "We raise `filelength` to 550." }];
27
+ assert.deepEqual(check(moved("filelength", 550), adrs), []);
28
+ });
29
+
30
+ test("an ADR that names another key does not", () => {
31
+ const adrs = [{ path: "docs/decisions/0031-coverage.md", text: "The coverage floor and filelengths stay." }];
32
+ assert.equal(check(moved("filelength", 550), adrs).length, 1);
33
+ });
34
+
35
+ test("a tightening passes", () => {
36
+ assert.deepEqual(check({ ...moved("filelength", 450), coverage: { value: 80, comparator: "min" } }), []);
37
+ });
38
+
39
+ test("a new entry passes", () => {
40
+ assert.deepEqual(check({ ...base, nesting: { value: 9, comparator: "max" } }), []);
41
+ });
42
+
43
+ test("a removed entry fails, because dropping a limit is the widest loosening", () => {
44
+ const { coverage, ...rest } = base;
45
+ const problems = check(rest);
46
+ assert.equal(problems.length, 1);
47
+ assert.equal(problems[0].rule, "removed-threshold");
48
+ assert.match(problems[0].detail, /coverage/);
49
+ });
50
+
51
+ test("a removed entry passes when a changed ADR names it", () => {
52
+ const { coverage, ...rest } = base;
53
+ const adrs = [{ path: "docs/decisions/0032-coverage.md", text: "We retire `coverage` in favour of mutation score." }];
54
+ assert.deepEqual(check(rest, adrs), []);
55
+ });
56
+
57
+ test("the comparator in force at the base judges the change", () => {
58
+ const after = { ...base, filelength: { value: 550, comparator: "min" } };
59
+ assert.equal(check(after).length, 1);
60
+ });
@@ -2,8 +2,8 @@
2
2
  "note": "The one home for a number a quality gate enforces. Docs carry a token, never a figure; every eslint config, the coverage config and CI import this file rather than restating it. Loosening a threshold is one edit here, visible in one diff.",
3
3
  "updated": "replace with the date you adopted this",
4
4
  "policy": {
5
- "loosening": "Raising a limit or lowering coverage needs the same review as a spec change: the diff on this file is the record. A per-file override belongs in the config that needs it, with a comment naming why, never here.",
6
- "match": "A threshold has no distinctive spelling the way a version number does, so each gate lists the phrases a page or a config would use when stating it. scripts/check.mjs reports a digit beside one of them as a literal. Add a phrase when a new wording appears; the phrases are the whole reason the literal check can exist.",
5
+ "loosening": "Raising a limit or lowering coverage needs the same review as a spec change: the diff on this file is the record. The threshold-ratchet gate of `qc check` fails a max that rises or a min that falls against the merge base, unless a changed ADR names the entry key. A per-file override belongs in the config that needs it, with a comment naming why, never here.",
6
+ "match": "A threshold has no distinctive spelling the way a version number does, so each gate lists the phrases a page or a config would use when stating it. The registry-literal gate of `qc check` reports the entry's own number within six words of one of them, in any doc outside the ADR log. Add a phrase when a new wording appears; the phrases are the whole reason the literal check can exist.",
7
7
  "readers": "An entry that code reads can carry `names`, regular expressions for the identifiers that would restate it, each matched against the whole identifier and case-insensitive, and `readers`, the paths that may hold its number. qc/registry-literal reports a matching literal anywhere else, and the registry-readers gate fails a reader that is missing or never names the entry.",
8
8
  "notThresholds": "A performance budget is not a quality gate. Latency, memory and render budgets live in docs/performance.md, because they are measured per surface rather than enforced repository-wide."
9
9
  },