architecture-harness 0.16.0 → 0.18.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.
Files changed (124) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/budget-counter.mjs +25 -4
  7. package/src/cli/budget-guard.mjs +73 -4
  8. package/src/cli/budget-guard.test.mjs +111 -0
  9. package/src/cli/budget.mjs +3 -2
  10. package/src/cli/check-registries.test.mjs +181 -0
  11. package/src/cli/check.mjs +130 -9
  12. package/src/cli/cli.test.mjs +215 -2
  13. package/src/cli/context-signal.mjs +92 -0
  14. package/src/cli/context-signal.test.mjs +99 -0
  15. package/src/cli/contract-history.mjs +46 -0
  16. package/src/cli/contract-history.test.mjs +118 -0
  17. package/src/cli/controller-guard.mjs +73 -0
  18. package/src/cli/controller-guard.test.mjs +119 -0
  19. package/src/cli/dispatch-guard.mjs +14 -4
  20. package/src/cli/dispatch-guard.test.mjs +5 -6
  21. package/src/cli/dispatch-reminder.mjs +19 -11
  22. package/src/cli/dispatch-reminder.test.mjs +32 -0
  23. package/src/cli/dispatch.mjs +23 -2
  24. package/src/cli/dispatch.test.mjs +39 -1
  25. package/src/cli/doctor.mjs +2 -1
  26. package/src/cli/explore-guard.mjs +2 -2
  27. package/src/cli/explore-hint.mjs +67 -7
  28. package/src/cli/explore-hint.test.mjs +104 -4
  29. package/src/cli/gh-merge-command.mjs +228 -0
  30. package/src/cli/gh-merge-command.test.mjs +273 -0
  31. package/src/cli/gh-run.mjs +30 -0
  32. package/src/cli/gh-run.test.mjs +22 -0
  33. package/src/cli/git-hooks.test.mjs +28 -0
  34. package/src/cli/git-read.mjs +42 -0
  35. package/src/cli/git-read.test.mjs +94 -0
  36. package/src/cli/handoff-note.mjs +69 -0
  37. package/src/cli/handoff-note.test.mjs +71 -0
  38. package/src/cli/init.mjs +7 -3
  39. package/src/cli/issue-gate.mjs +169 -0
  40. package/src/cli/issue-gate.test.mjs +234 -0
  41. package/src/cli/ledger.mjs +138 -0
  42. package/src/cli/ledger.test.mjs +127 -0
  43. package/src/cli/merge-guard.mjs +193 -0
  44. package/src/cli/merge-guard.test.mjs +328 -0
  45. package/src/cli/plan-check.mjs +151 -0
  46. package/src/cli/plan-check.test.mjs +143 -0
  47. package/src/cli/plan-stop.mjs +101 -0
  48. package/src/cli/plan-stop.test.mjs +136 -0
  49. package/src/cli/plugin-agents.test.mjs +105 -8
  50. package/src/cli/pr-check.mjs +17 -5
  51. package/src/cli/pr-check.test.mjs +85 -4
  52. package/src/cli/prose.mjs +192 -0
  53. package/src/cli/prose.test.mjs +248 -0
  54. package/src/cli/qc.mjs +22 -0
  55. package/src/cli/registry-history.mjs +1 -1
  56. package/src/cli/report-stash.mjs +69 -0
  57. package/src/cli/report-stash.test.mjs +71 -0
  58. package/src/cli/report-stop.mjs +266 -0
  59. package/src/cli/report-stop.test.mjs +471 -0
  60. package/src/cli/shell-command.mjs +81 -6
  61. package/src/cli/shell-command.test.mjs +101 -1
  62. package/src/cli/task-gate.mjs +179 -0
  63. package/src/cli/task-gate.test.mjs +507 -0
  64. package/src/cli/tokens.mjs +239 -0
  65. package/src/cli/tokens.test.mjs +286 -0
  66. package/src/cli/transcript-usage.mjs +135 -0
  67. package/src/cli/transcript-usage.test.mjs +129 -0
  68. package/src/cli/workflow-hooks.test.mjs +72 -0
  69. package/src/cli/workflow-place.mjs +143 -0
  70. package/src/cli/workflow-place.test.mjs +146 -0
  71. package/src/cli/workflow-settings.mjs +77 -0
  72. package/src/cli/workflow-settings.test.mjs +79 -0
  73. package/src/cli/worktree.mjs +1 -1
  74. package/src/cli/worktree.test.mjs +19 -2
  75. package/src/config.mjs +99 -4
  76. package/src/config.test.mjs +38 -3
  77. package/src/descriptions.mjs +5 -1
  78. package/src/eslint/index.mjs +2 -0
  79. package/src/eslint/jsx.mjs +57 -0
  80. package/src/eslint/preset.mjs +32 -6
  81. package/src/eslint/preset.test.mjs +60 -0
  82. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  83. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  84. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  85. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  86. package/src/eslint/rules/registry-literal.mjs +36 -2
  87. package/src/eslint/rules.test.mjs +153 -0
  88. package/src/gates/call-args.mjs +90 -0
  89. package/src/gates/call-args.test.mjs +21 -0
  90. package/src/gates/config-floor.mjs +41 -20
  91. package/src/gates/config-floor.test.mjs +71 -1
  92. package/src/gates/contract-idempotency.mjs +103 -0
  93. package/src/gates/contract-idempotency.test.mjs +276 -0
  94. package/src/gates/contract-operations.mjs +120 -0
  95. package/src/gates/contract-operations.test.mjs +275 -0
  96. package/src/gates/contract-routes.mjs +82 -0
  97. package/src/gates/contract-routes.test.mjs +210 -0
  98. package/src/gates/registry-literal.mjs +79 -15
  99. package/src/gates/registry-literal.test.mjs +89 -0
  100. package/src/gates/saga-key.mjs +253 -0
  101. package/src/gates/saga-key.test.mjs +322 -0
  102. package/src/gates/scrub.mjs +108 -0
  103. package/src/gates/scrub.test.mjs +29 -0
  104. package/src/gates/tenant-isolation-test.mjs +80 -0
  105. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  106. package/src/gates/tenant-predicate.mjs +644 -91
  107. package/src/gates/tenant-predicate.test.mjs +662 -1
  108. package/src/prose-lines.mjs +49 -0
  109. package/src/prose-lines.test.mjs +63 -0
  110. package/src/registries.mjs +89 -0
  111. package/src/registries.test.mjs +44 -0
  112. package/src/vale-style.test.mjs +158 -0
  113. package/templates/docs/enforcement.md +26 -2
  114. package/templates/github/workflows/ci.yml +18 -1
  115. package/templates/quality-thresholds.json +1 -1
  116. package/templates/vale/.vale.ini +7 -0
  117. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  118. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  119. package/templates/vale/styles/Qc/Latin.yml +9 -0
  120. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  121. package/templates/vale/styles/Qc/Please.yml +6 -0
  122. package/templates/vale/styles/Qc/Progress.yml +9 -0
  123. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  124. package/templates/vale/styles/Qc/Utilize.yml +10 -0
@@ -0,0 +1,210 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { defaults, load } from "../config.mjs";
8
+ import { runCheck } from "../cli/check.mjs";
9
+ import { checkContractRoutes, declaredTriggerRoutes } from "./contract-routes.mjs";
10
+
11
+ const trigger = {
12
+ path: "server/features/photos/trigger.ts",
13
+ source: `routes: [
14
+ { method: "post", path: "/v1/photos/:photoId/derivatives", auth: "tenant", req: [], handler: h },
15
+ { method: "get", path: "/v1/photos", auth: "tenant", req: [], handler: g },
16
+ ]`,
17
+ };
18
+
19
+ const operations = [
20
+ { method: "post", path: "/v1/photos/{photoId}/derivatives" },
21
+ { method: "get", path: "/v1/photos" },
22
+ ];
23
+
24
+ const check = (routes, ops, options = {}) => checkContractRoutes(routes, ops, { contract: "contracts/openapi.yaml", exempt: [], ...options });
25
+
26
+ test("a route is read with its method, its path and its file", () => {
27
+ assert.deepEqual(declaredTriggerRoutes([trigger]), [
28
+ { method: "post", path: "/v1/photos/:photoId/derivatives", file: trigger.path },
29
+ { method: "get", path: "/v1/photos", file: trigger.path },
30
+ ]);
31
+ });
32
+
33
+ test("a route and an operation that agree pass, and :id against {id} is one segment", () => {
34
+ assert.deepEqual(check(declaredTriggerRoutes([trigger]), operations), []);
35
+ const renamed = [{ method: "get", path: "/v1/photos/{id}" }];
36
+ const routes = declaredTriggerRoutes([{ path: "t.ts", source: 'x({ method: "GET", path: "/v1/photos/:photoId" })' }]);
37
+ assert.deepEqual(check(routes, renamed), []);
38
+ });
39
+
40
+ test("a route that differs from the contract by one segment fails both ways", () => {
41
+ const routes = declaredTriggerRoutes([trigger]);
42
+ const drifted = [operations[0], { method: "get", path: "/v1/pictures" }];
43
+ const problems = check(routes, drifted);
44
+ assert.deepEqual(problems.map(({ rule }) => rule).sort(), ["operation-not-served", "route-not-in-contract"]);
45
+ const unserved = problems.find(({ rule }) => rule === "route-not-in-contract");
46
+ assert.equal(unserved.path, trigger.path);
47
+ assert.match(unserved.detail, /get \/v1\/photos/);
48
+ const missing = problems.find(({ rule }) => rule === "operation-not-served");
49
+ assert.equal(missing.path, "contracts/openapi.yaml");
50
+ assert.match(missing.detail, /get \/v1\/pictures/);
51
+ });
52
+
53
+ test("the method is compared as well as the path", () => {
54
+ const routes = declaredTriggerRoutes([trigger]);
55
+ const swapped = [{ method: "put", path: "/v1/photos/{photoId}/derivatives" }, operations[1]];
56
+ assert.deepEqual(check(routes, swapped).map(({ rule }) => rule).sort(), ["operation-not-served", "route-not-in-contract"]);
57
+ });
58
+
59
+ test("an exempt internal route passes", () => {
60
+ const routes = declaredTriggerRoutes([
61
+ trigger,
62
+ { path: "server/features/media/trigger.ts", source: '{ method: "post", path: "/v1/internal/media/:id/done", auth: "internal" }' },
63
+ ]);
64
+ const exempt = [{ method: "POST", path: "/v1/internal/media/{mediaId}/done", why: "a worker callback, not a public operation" }];
65
+ assert.deepEqual(check(routes, operations, { exempt }), []);
66
+ assert.equal(check(routes, operations).length, 1);
67
+ });
68
+
69
+ test("an exempt operation the api does not serve passes", () => {
70
+ const exempt = [{ method: "get", path: "/v1/health", why: "served by the edge" }];
71
+ const ops = [...operations, { method: "get", path: "/v1/health" }];
72
+ assert.deepEqual(check(declaredTriggerRoutes([trigger]), ops, { exempt }), []);
73
+ });
74
+
75
+ test("a stale exemption fails", () => {
76
+ const routes = declaredTriggerRoutes([trigger]);
77
+ const gone = [{ method: "post", path: "/v1/internal/gone", why: "removed long ago" }];
78
+ const problems = check(routes, operations, { exempt: gone });
79
+ assert.equal(problems.length, 1);
80
+ assert.equal(problems[0].rule, "stale-route-exemption");
81
+ assert.match(problems[0].detail, /post \/v1\/internal\/gone/);
82
+ });
83
+
84
+ test("an exemption for a route the contract now lists is stale too", () => {
85
+ const exempt = [{ method: "get", path: "/v1/photos", why: "not yet in the contract" }];
86
+ const problems = check(declaredTriggerRoutes([trigger]), operations, { exempt });
87
+ assert.deepEqual(problems.map(({ rule }) => rule), ["stale-route-exemption"]);
88
+ });
89
+
90
+ test("a trigger with no routes and a contract with no operations agree", () => {
91
+ assert.deepEqual(check(declaredTriggerRoutes([{ path: "t.ts", source: "export {};" }]), []), []);
92
+ });
93
+
94
+ // The runner reads each feature trigger and the contract from disk.
95
+ const GATE_RULES = new Set(["route-not-in-contract", "operation-not-served", "stale-route-exemption", "exemption-without-reason", "malformed-exemption", "unreadable-contract", "contract-reader-unavailable"]);
96
+
97
+ async function checked({ contract, triggerSource = trigger.source, gates = { "contract-routes": true }, overrides = {} }) {
98
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-routes-"));
99
+ try {
100
+ execFileSync("git", ["init", "-q"], { cwd: dir });
101
+ const base = load(dir);
102
+ mkdirSync(path.join(dir, base.paths.serverFeatures, "photos"), { recursive: true });
103
+ writeFileSync(path.join(dir, base.paths.serverFeatures, "photos", base.paths.triggerFile), triggerSource);
104
+ const file = overrides.contract ?? "contracts/openapi.yaml";
105
+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
106
+ if (contract !== undefined) writeFileSync(path.join(dir, file), contract);
107
+ const config = { ...base, ...overrides, gates: { ...base.gates, ...gates } };
108
+ const { problems, lines } = await runCheck(config);
109
+ return { problems: problems.filter((problem) => GATE_RULES.has(problem.rule)), lines };
110
+ } finally {
111
+ rmSync(dir, { recursive: true, force: true });
112
+ }
113
+ }
114
+
115
+ const CONTRACT = ["paths:", " /v1/photos/{photoId}/derivatives:", " post: {}", " /v1/photos:", " get: {}", ""].join(String.fromCharCode(10));
116
+
117
+ test("qc check compares the triggers with the contract", async () => {
118
+ const agreed = await checked({ contract: CONTRACT });
119
+ assert.deepEqual(agreed.problems, []);
120
+ assert.ok(agreed.lines.some((line) => line.includes("contract")));
121
+ const drifted = await checked({ contract: CONTRACT.replace("/v1/photos:", "/v1/pictures:") });
122
+ assert.deepEqual(drifted.problems.map((problem) => problem.rule).sort(), ["operation-not-served", "route-not-in-contract"]);
123
+ assert.ok(drifted.problems.some((problem) => problem.path.endsWith("trigger.ts")));
124
+ });
125
+
126
+ test("the gate ships off, and an absent contract is ordinary", async () => {
127
+ assert.equal(defaults.gates["contract-routes"], false);
128
+ assert.deepEqual((await checked({ contract: "paths: {}", gates: {} })).problems, []);
129
+ assert.deepEqual((await checked({})).problems, []);
130
+ });
131
+
132
+ test("config.contractRoutes.exempt excuses a route, and a stale one fails", async () => {
133
+ const extra = { ...trigger, source: `${trigger.source}\n { method: "post", path: "/v1/internal/x" },` };
134
+ const exempt = [{ method: "post", path: "/v1/internal/x", why: "a worker callback" }];
135
+ const overrides = { contractRoutes: { exempt } };
136
+ assert.deepEqual((await checked({ contract: CONTRACT, triggerSource: extra.source, overrides })).problems, []);
137
+ const stale = await checked({ contract: CONTRACT, overrides });
138
+ assert.deepEqual(stale.problems.map((problem) => problem.rule), ["stale-route-exemption"]);
139
+ });
140
+
141
+ test("the contract path is the top-level `contract`, and an unreadable contract is a problem", async () => {
142
+ const moved = await checked({ contract: CONTRACT, overrides: { contract: "api/spec.yaml" } });
143
+ assert.deepEqual(moved.problems, []);
144
+ const broken = await checked({ contract: "paths: [unclosed" });
145
+ assert.deepEqual(broken.problems.map((problem) => problem.rule), ["unreadable-contract"]);
146
+ });
147
+
148
+ const rulesOf = (problems) => problems.map((problem) => problem.rule);
149
+ const exemptCheck = (exempt) => checkContractRoutes(declaredTriggerRoutes([trigger]), operations, { contract: "c.yaml", exempt });
150
+
151
+ test("an exemption with no why, or an empty one, fails as exemption-without-reason", () => {
152
+ assert.deepEqual(rulesOf(exemptCheck([{ method: "post", path: "/v1/internal/x" }])), ["exemption-without-reason"]);
153
+ assert.deepEqual(rulesOf(exemptCheck([{ method: "post", path: "/v1/internal/x", why: " " }])), ["exemption-without-reason"]);
154
+ const [problem] = exemptCheck([{ method: "post", path: "/v1/internal/x" }]);
155
+ assert.equal(problem.path, "qc.config.json");
156
+ });
157
+
158
+ test("a malformed exemption is a problem, not a TypeError, and excuses nothing", () => {
159
+ for (const bad of [{ method: "get" }, { path: "/v1/x", why: "w" }, { method: 5, path: "/v1/x", why: "w" }, null, "get /v1/x", 7]) {
160
+ assert.deepEqual(rulesOf(exemptCheck([bad])), ["malformed-exemption"], JSON.stringify(bad));
161
+ }
162
+ const routes = declaredTriggerRoutes([{ path: "t.ts", source: '{ method: "post", path: "/v1/internal/x" }' }]);
163
+ const problems = checkContractRoutes(routes, [], { contract: "c.yaml", exempt: [{ method: "post", why: "w" }] });
164
+ assert.deepEqual(rulesOf(problems).sort(), ["malformed-exemption", "route-not-in-contract"]);
165
+ });
166
+
167
+ test("a valid exemption beside a bad one still applies", () => {
168
+ const routes = declaredTriggerRoutes([{ path: "t.ts", source: '{ method: "post", path: "/v1/internal/x" }' }]);
169
+ const exempt = [{ method: "get" }, { method: "post", path: "/v1/internal/x", why: "a worker callback" }];
170
+ assert.deepEqual(rulesOf(checkContractRoutes(routes, [], { contract: "c.yaml", exempt })), ["malformed-exemption"]);
171
+ });
172
+
173
+ test("a route in a line comment or a block comment is not served", () => {
174
+ const source = [
175
+ ' // { method: "get", path: "/v1/photos" },',
176
+ ' /* { method: "post", path: "/v1/photos/:photoId/derivatives" } */',
177
+ ' { method: "get", path: "/v1/live", note: "see http://example.test/a" }, // trailing { method: "get", path: "/v1/gone" }',
178
+ ].join("\n");
179
+ assert.deepEqual(declaredTriggerRoutes([{ path: "t.ts", source }]).map(({ path: route }) => route), ["/v1/live"]);
180
+ });
181
+
182
+ test("a commented route next to its contract operation fails as operation-not-served", () => {
183
+ const source = '// { method: "get", path: "/v1/photos" },\n { method: "post", path: "/v1/photos/:photoId/derivatives" },';
184
+ const problems = check(declaredTriggerRoutes([{ path: "t.ts", source }]), operations);
185
+ assert.deepEqual(rulesOf(problems), ["operation-not-served"]);
186
+ assert.match(problems[0].detail, /get \/v1\/photos/);
187
+ });
188
+
189
+ test("qc check reports a non-array exempt and a bad entry instead of throwing", async () => {
190
+ const notList = await checked({ contract: CONTRACT, overrides: { contractRoutes: { exempt: "post /v1/x" } } });
191
+ assert.deepEqual(rulesOf(notList.problems), ["malformed-exemption"]);
192
+ const missing = await checked({ contract: CONTRACT, overrides: { contractRoutes: { exempt: [{ method: "get" }] } } });
193
+ assert.deepEqual(rulesOf(missing.problems), ["malformed-exemption"]);
194
+ const noReason = await checked({ contract: CONTRACT, overrides: { contractRoutes: { exempt: [{ method: "get", path: "/x" }] } } });
195
+ assert.deepEqual(rulesOf(noReason.problems), ["exemption-without-reason"]);
196
+ });
197
+
198
+ // Known limit: the comment stripper pairs quotes and does not read regex literals, so a quote inside
199
+ // one flips the pairing and a commented route after it is still read. This pins today's behaviour.
200
+ test("known limit: a quote inside a regex literal lets a later commented route count", () => {
201
+ const source = 'const re = /"/;\n// { method: "get", path: "/v1/photos" },';
202
+ assert.deepEqual(declaredTriggerRoutes([{ path: "t.ts", source }]).map(({ path: route }) => route), ["/v1/photos"]);
203
+ });
204
+
205
+ test("the agreement line is printed only when the gate finds no problem", async () => {
206
+ const agreed = await checked({ contract: CONTRACT });
207
+ assert.ok(agreed.lines.some((line) => line.startsWith("OK contract ")));
208
+ const drifted = await checked({ contract: CONTRACT.replace("/v1/photos:", "/v1/pictures:") });
209
+ assert.equal(drifted.lines.some((line) => line.startsWith("OK contract ")), false);
210
+ });
@@ -4,7 +4,11 @@
4
4
  import { escape } from "../eslint/options.mjs";
5
5
  import { globMatcher } from "../glob.mjs";
6
6
 
7
- const TOKEN = /\{\{(?:q|ver|v):[^}]*\}\}/g;
7
+ // The token prefixes of the two registries a repository has without a configured list.
8
+ const BUILT_IN = [
9
+ { prefixes: ["q"], from: "thresholds" },
10
+ { prefixes: ["ver", "v"], from: "libraries", valueKey: "version" },
11
+ ];
8
12
  // Words between a phrase and a number, at most. Past that the number belongs to another sentence.
9
13
  const WINDOW = 6;
10
14
  const NUMBER = /^(\d{1,3}(?:,\d{3})+|\d+(?:\.\d+)?)(%|[a-z]+)?$/;
@@ -25,14 +29,15 @@ const spellings = (unit) => UNIT_SPELLINGS[unit] ?? (unit ? [unit, unit.replace(
25
29
  const normal = (word) => word.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}%]+$/gu, "");
26
30
 
27
31
  /** 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)
32
+ function thresholdEntries({ entries, prefixes, valueKey = "value", unitKey = "unit" }) {
33
+ return Object.entries(entries)
34
+ .filter(([, entry]) => typeof entry[valueKey] === "number" && entry.match?.length > 0)
31
35
  .map(([key, entry]) => ({
32
36
  key,
33
- value: entry.value,
34
- unit: entry.unit,
35
- own: new Set(spellings(entry.unit)),
37
+ prefix: prefixes[0],
38
+ value: entry[valueKey],
39
+ unit: entry[unitKey],
40
+ own: new Set(spellings(entry[unitKey])),
36
41
  phrases: entry.match.map((phrase) => phrase.split(/\s+/).map(normal).filter(Boolean)),
37
42
  }));
38
43
  }
@@ -59,7 +64,7 @@ const near = (index, [start, end]) => (index > end ? index - end - 1 : start - i
59
64
 
60
65
  function thresholdProblems(file, words, entries, known) {
61
66
  const problems = [];
62
- const spansOf = new Map(entries.map((entry) => [entry.key, phraseSpans(words, entry.phrases)]));
67
+ const spansOf = new Map(entries.map((entry) => [entry, phraseSpans(words, entry.phrases)]));
63
68
  words.forEach((word, index) => {
64
69
  const found = NUMBER.exec(word.norm);
65
70
  if (found === null) return;
@@ -69,11 +74,11 @@ function thresholdProblems(file, words, entries, known) {
69
74
  if (entry.value !== value) continue;
70
75
  // An attached suffix that is no unit at all, as in `70th`, is not the entry's number either.
71
76
  if (unit && !entry.own.has(unit)) continue;
72
- if (!spansOf.get(entry.key).some((span) => near(index, span))) continue;
77
+ if (!spansOf.get(entry).some((span) => near(index, span))) continue;
73
78
  problems.push({
74
79
  path: `${file}:${word.line}`,
75
80
  rule: "threshold-literal",
76
- detail: `'${word.norm}' restates the '${entry.key}' threshold (${entry.value}${entry.unit ? ` ${entry.unit}` : ""}); write {{q:${entry.key}}}`,
81
+ detail: `'${word.norm}' restates the '${entry.key}' threshold (${entry.value}${entry.unit ? ` ${entry.unit}` : ""}); write {{${entry.prefix}:${entry.key}}}`,
77
82
  });
78
83
  }
79
84
  });
@@ -99,6 +104,58 @@ function paragraphs(text) {
99
104
  return out;
100
105
  }
101
106
 
107
+ /** The registries a check reads: the configured list, else the thresholds and the libraries. */
108
+ function registryList({ registries, thresholds, libraries }) {
109
+ if (registries) return registries.map((registry) => ({ ...registry, prefixes: [registry.prefixes].flat() }));
110
+ const source = { thresholds, libraries };
111
+ return BUILT_IN.map(({ from, ...rest }) => ({ ...rest, entries: source[from] }));
112
+ }
113
+
114
+ const alternatives = (prefixes) => prefixes.map(escape).join("|");
115
+ const tokenPattern = (prefixes) => new RegExp(String.raw`\{\{(?:${alternatives(prefixes)}):[^}]*\}\}`, "g");
116
+ const annotationPattern = (prefixes) =>
117
+ new RegExp(String.raw`(\S+)[ \t]*<!--\s*(${alternatives(prefixes)}):([\w.-]+)\s*-->`, "g");
118
+
119
+ /** What a word states, to compare with a figure: a number when the figure is one, else the word whole. */
120
+ function stated(word, value) {
121
+ const found = NUMBER.exec(normal(word));
122
+ if (typeof value !== "number") return normal(word);
123
+ return found === null ? null : Number(found[1].replaceAll(",", ""));
124
+ }
125
+
126
+ /**
127
+ * A number that carries its token, as in `70 <!-- q:coverage -->`, must equal the entry's figure.
128
+ * The annotation and its number become one placeholder word, so no other scan sees them.
129
+ */
130
+ function annotatedProblems(file, text, list, prefixes) {
131
+ const owner = new Map(list.flatMap((registry) => registry.prefixes.map((prefix) => [prefix, registry])));
132
+ const problems = [];
133
+ const masked = text.replace(annotationPattern(prefixes), (whole, word, prefix, id, offset) => {
134
+ const registry = owner.get(prefix);
135
+ const at = `${file}:${text.slice(0, offset).split("\n").length}`;
136
+ if (!Object.hasOwn(registry.entries, id)) {
137
+ problems.push({ path: at, rule: "unknown-token", detail: `'${prefix}:${id}' names no entry of its registry` });
138
+ return "TOKEN";
139
+ }
140
+ const valueKey = registry.valueKey ?? "value";
141
+ const value = registry.entries[id]?.[valueKey];
142
+ const figure = stated(word, value);
143
+ if (value === undefined || value === null) {
144
+ problems.push({ path: at, rule: "entry-without-value", detail: `the '${prefix}:${id}' entry has no '${valueKey}'` });
145
+ } else if (figure === null) {
146
+ problems.push({ path: at, rule: "annotation-without-number", detail: `'${prefix}:${id}' follows '${word}', which is no number` });
147
+ } else if (figure !== value) {
148
+ problems.push({
149
+ path: at,
150
+ rule: "stale-annotated-number",
151
+ detail: `'${normal(word)}' is stale: the '${id}' entry is now ${value}; write ${value} <!-- ${prefix}:${id} --> or {{${prefix}:${id}}}`,
152
+ });
153
+ }
154
+ return "TOKEN";
155
+ });
156
+ return { masked, problems };
157
+ }
158
+
102
159
  function versionProblems(file, text, libraries) {
103
160
  const problems = [];
104
161
  for (const [id, library] of Object.entries(libraries)) {
@@ -118,18 +175,25 @@ function versionProblems(file, text, libraries) {
118
175
 
119
176
  /**
120
177
  * @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
178
+ * @param {{thresholds?: object, libraries?: object, exempt?: string[], registries?: object[]}} sources
179
+ * `thresholds` and `libraries` are the `gates` and the `libraries` of the two registries; `exempt` is the
180
+ * globs of files that may hold a figure. `registries` is a list of `{prefixes, entries, valueKey?, unitKey?}`
181
+ * that replaces the two as the source of tokens, annotations and phrases. `libraries` still feeds the label scan.
123
182
  */
124
- export function checkRegistryLiteral(docs, { thresholds = {}, libraries = {}, exempt = [] }) {
125
- const entries = thresholdEntries(thresholds);
183
+ export function checkRegistryLiteral(docs, { thresholds = {}, libraries = {}, exempt = [], registries }) {
184
+ const list = registryList({ registries, thresholds, libraries });
185
+ const prefixes = [...new Set(list.flatMap((registry) => registry.prefixes))];
186
+ const token = tokenPattern(prefixes);
187
+ const entries = list.flatMap(thresholdEntries);
126
188
  const known = new Set([...Object.values(UNIT_SPELLINGS).flat(), ...entries.flatMap((entry) => [...entry.own])]);
127
189
  const isExempt = globMatcher(exempt);
128
190
  const problems = [];
129
191
  for (const { path: file, contents } of docs) {
130
192
  if (isExempt(file)) continue;
193
+ const annotated = annotatedProblems(file, contents.replace(/\r\n?/g, "\n"), list, prefixes);
194
+ problems.push(...annotated.problems);
131
195
  // 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");
196
+ const text = annotated.masked.replace(token, "TOKEN");
133
197
  for (const words of paragraphs(text)) problems.push(...thresholdProblems(file, words, entries, known));
134
198
  problems.push(...versionProblems(file, text, libraries));
135
199
  }
@@ -6,6 +6,7 @@ const thresholds = {
6
6
  coverage: { value: 70, unit: "percent", comparator: "min", match: ["coverage threshold", "coverage on new code"] },
7
7
  filelength: { value: 500, unit: "lines", comparator: "max", match: ["max-lines", "file length"] },
8
8
  holdpress: { value: 500, unit: "ms", comparator: "max" },
9
+ maxwarnings: { value: 0, unit: "count", comparator: "max", match: ["max warnings"] },
9
10
  };
10
11
  const libraries = { node: { label: "Node.js", version: "24" }, drizzle: { label: "Drizzle ORM", version: "0.44" } };
11
12
  const registries = { thresholds, libraries, exempt: ["docs/decisions/**"] };
@@ -66,3 +67,91 @@ test("a library label beside a version number fails, and its token passes", () =
66
67
  test("an exempt file passes", () => {
67
68
  assert.deepEqual(check("The coverage threshold of 70% on Node.js 24.", "docs/decisions/0001-coverage.md"), []);
68
69
  });
70
+
71
+ test("an annotated number that matches the registry passes", () => {
72
+ assert.deepEqual(check("Lint runs with 0 <!-- q:maxwarnings --> warnings allowed."), []);
73
+ assert.deepEqual(check("The coverage threshold of 70% <!-- q:coverage --> holds."), []);
74
+ assert.deepEqual(check("The coverage threshold is 70<!--q:coverage--> here."), []);
75
+ });
76
+
77
+ test("an annotated number that is stale fails, naming the entry and the current value", () => {
78
+ const problems = check("Intro.\n\nThe coverage threshold of 60 <!-- q:coverage --> holds.");
79
+ assert.equal(problems.length, 1);
80
+ assert.equal(problems[0].rule, "stale-annotated-number");
81
+ assert.equal(problems[0].path, "docs/architecture.md:3");
82
+ assert.match(problems[0].detail, /'60'/);
83
+ assert.match(problems[0].detail, /'coverage'/);
84
+ assert.match(problems[0].detail, /\b70\b/);
85
+ });
86
+
87
+ test("a bare token still passes", () => {
88
+ assert.deepEqual(check("Lint runs with {{q:maxwarnings}} warnings allowed."), []);
89
+ });
90
+
91
+ test("a bare number near a match phrase still fails", () => {
92
+ assert.deepEqual(rules("The max warnings is 0 for every package."), ["threshold-literal"]);
93
+ });
94
+
95
+ test("an unknown id in an annotation fails", () => {
96
+ const problems = check("Lint runs with 0 <!-- q:nosuch --> warnings allowed.");
97
+ assert.deepEqual(problems.map((problem) => problem.rule), ["unknown-token"]);
98
+ assert.match(problems[0].detail, /q:nosuch/);
99
+ });
100
+
101
+ test("an annotation with no number before it fails", () => {
102
+ assert.deepEqual(rules("The coverage threshold <!-- q:coverage --> holds."), ["annotation-without-number"]);
103
+ });
104
+
105
+ test("an annotation with a prefix no registry owns is a plain comment", () => {
106
+ assert.deepEqual(check("Lint runs with 0 <!-- note:x --> warnings allowed, and 9 <!-- ttl:x --> more."), []);
107
+ });
108
+
109
+ test("a version annotation is checked against the version", () => {
110
+ assert.deepEqual(check("The api runs on Node.js 24 <!-- ver:node --> and Drizzle ORM 0.44 <!-- v:drizzle -->."), []);
111
+ const problems = check("The api runs on Node.js 25 <!-- ver:node -->.");
112
+ assert.deepEqual(problems.map((problem) => problem.rule), ["stale-annotated-number"]);
113
+ assert.match(problems[0].detail, /\b24\b/);
114
+ });
115
+
116
+ const lifetimes = {
117
+ accesstoken: { value: 15, unit: "minutes", match: ["access token lifetime", "token ttl"] },
118
+ offlinegrace: { value: 7, unit: "days", match: ["offline grace"] },
119
+ };
120
+ const lifetimeRegistry = { prefixes: ["ttl"], entries: lifetimes };
121
+ const checkLifetimes = (contents, list = [lifetimeRegistry]) =>
122
+ checkRegistryLiteral([{ path: "docs/auth.md", contents }], { registries: list, exempt: [] });
123
+
124
+ test("a lifetimes registry with prefix ttl: a bare number fails and an annotated one passes", () => {
125
+ const bare = checkLifetimes("The access token lifetime is 15 minutes.");
126
+ assert.deepEqual(bare.map((problem) => problem.rule), ["threshold-literal"]);
127
+ assert.match(bare[0].detail, /\{\{ttl:accesstoken\}\}/);
128
+ assert.deepEqual(checkLifetimes("The access token lifetime is 15 <!-- ttl:accesstoken --> minutes."), []);
129
+ assert.deepEqual(checkLifetimes("The access token lifetime is {{ttl:accesstoken}}."), []);
130
+ const stale = checkLifetimes("The access token lifetime is 20 <!-- ttl:accesstoken --> minutes.");
131
+ assert.deepEqual(stale.map((problem) => problem.rule), ["stale-annotated-number"]);
132
+ });
133
+
134
+ test("valueKey and unitKey name the fields of a registry", () => {
135
+ const renamed = { prefixes: ["ttl"], entries: { grace: { span: 7, per: "days", match: ["offline grace"] } }, valueKey: "span", unitKey: "per" };
136
+ assert.deepEqual(checkLifetimes("The offline grace is 7 days.", [renamed]).map((problem) => problem.rule), ["threshold-literal"]);
137
+ assert.deepEqual(checkLifetimes("The offline grace is 7 <!-- ttl:grace --> days.", [renamed]), []);
138
+ assert.match(checkLifetimes("The offline grace is 8 <!-- ttl:grace --> days.", [renamed])[0].detail, /\b7\b/);
139
+ });
140
+
141
+ test("every listed prefix is a token and an annotation", () => {
142
+ const list = [lifetimeRegistry, { prefixes: ["q", "t"], entries: thresholds }];
143
+ const text = "Offline grace 7 <!-- ttl:offlinegrace --> days, coverage threshold 70 <!-- q:coverage -->% and 70 <!-- t:coverage -->%.";
144
+ assert.deepEqual(checkLifetimes(text, list), []);
145
+ assert.deepEqual(checkLifetimes("Offline grace {{ttl:offlinegrace}}, coverage threshold {{t:coverage}}.", list), []);
146
+ const stale = checkLifetimes("Offline grace 8 <!-- ttl:offlinegrace --> days, coverage threshold 71 <!-- t:coverage -->%.", list);
147
+ assert.deepEqual(stale.map((problem) => problem.rule), ["stale-annotated-number", "stale-annotated-number"]);
148
+ });
149
+
150
+ test("an entry with no figure under the valueKey is its own problem", () => {
151
+ const bare = { prefixes: ["ttl"], entries: { grace: { label: "Grace" } } };
152
+ const problems = checkLifetimes("Grace is 7 <!-- ttl:grace --> days.", [bare]);
153
+ assert.deepEqual(problems.map((problem) => problem.rule), ["entry-without-value"]);
154
+ assert.match(problems[0].detail, /no 'value'/);
155
+ const renamed = { ...bare, entries: { grace: { value: 7 } }, valueKey: "span" };
156
+ assert.match(checkLifetimes("Grace is 7 <!-- ttl:grace --> days.", [renamed])[0].detail, /no 'span'/);
157
+ });