architecture-harness 0.4.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 (109) hide show
  1. package/package.json +80 -0
  2. package/src/cli/check.mjs +535 -0
  3. package/src/cli/cli.test.mjs +120 -0
  4. package/src/cli/commit-attribution.mjs +68 -0
  5. package/src/cli/commit-attribution.test.mjs +47 -0
  6. package/src/cli/decisions.mjs +223 -0
  7. package/src/cli/doctor.mjs +135 -0
  8. package/src/cli/doctor.test.mjs +57 -0
  9. package/src/cli/init.mjs +98 -0
  10. package/src/cli/install-hooks.mjs +26 -0
  11. package/src/cli/qc.mjs +89 -0
  12. package/src/cli/scaffold.mjs +194 -0
  13. package/src/cli/sync-enforcement-map.mjs +28 -0
  14. package/src/cli/work-order-guard.mjs +0 -0
  15. package/src/cli/work-order-guard.test.mjs +79 -0
  16. package/src/cli/worktree-isolation.mjs +94 -0
  17. package/src/cli/worktree-isolation.test.mjs +82 -0
  18. package/src/config.mjs +338 -0
  19. package/src/config.test.mjs +59 -0
  20. package/src/decisions.mjs +198 -0
  21. package/src/decisions.test.mjs +183 -0
  22. package/src/descriptions.mjs +28 -0
  23. package/src/descriptions.test.mjs +27 -0
  24. package/src/enforcement-map.mjs +46 -0
  25. package/src/enforcement-map.test.mjs +60 -0
  26. package/src/eslint/index.mjs +37 -0
  27. package/src/eslint/options.mjs +53 -0
  28. package/src/eslint/preset.mjs +192 -0
  29. package/src/eslint/preset.test.mjs +96 -0
  30. package/src/eslint/rules/durable-idempotency-key.mjs +120 -0
  31. package/src/eslint/rules/external-service-only-in-adapter.mjs +52 -0
  32. package/src/eslint/rules/module-boundary.mjs +12 -0
  33. package/src/eslint/rules/name-the-pattern.mjs +111 -0
  34. package/src/eslint/rules/no-comment-paragraph.mjs +101 -0
  35. package/src/eslint/rules/no-cross-feature-internals.mjs +57 -0
  36. package/src/eslint/rules/no-number-in-comment.mjs +89 -0
  37. package/src/eslint/rules/no-offset-pagination.mjs +29 -0
  38. package/src/eslint/rules/no-orchestration-in-trigger.mjs +56 -0
  39. package/src/eslint/rules/no-promise-then.mjs +43 -0
  40. package/src/eslint/rules/no-promise-then.test.mjs +63 -0
  41. package/src/eslint/rules/no-raw-fetch.mjs +27 -0
  42. package/src/eslint/rules/no-status-literal.mjs +34 -0
  43. package/src/eslint/rules/no-supersession-trail.mjs +51 -0
  44. package/src/eslint/rules/scoped-repository.mjs +43 -0
  45. package/src/eslint/rules/signal-last-param.mjs +43 -0
  46. package/src/eslint/rules/storage-only-in-resource.mjs +52 -0
  47. package/src/eslint/rules/tenant-scoped-table.mjs +71 -0
  48. package/src/eslint/rules.test.mjs +627 -0
  49. package/src/gates/adr-format.mjs +87 -0
  50. package/src/gates/adr-format.test.mjs +54 -0
  51. package/src/gates/audit-append-only.mjs +34 -0
  52. package/src/gates/audit-append-only.test.mjs +36 -0
  53. package/src/gates/citations.mjs +93 -0
  54. package/src/gates/citations.test.mjs +115 -0
  55. package/src/gates/claimed-requirements.mjs +53 -0
  56. package/src/gates/claimed-requirements.test.mjs +60 -0
  57. package/src/gates/comment-style.mjs +76 -0
  58. package/src/gates/comment-style.test.mjs +46 -0
  59. package/src/gates/config-floor.mjs +68 -0
  60. package/src/gates/config-floor.test.mjs +52 -0
  61. package/src/gates/contract-compose.mjs +38 -0
  62. package/src/gates/contract-compose.test.mjs +40 -0
  63. package/src/gates/eight-blocks.mjs +223 -0
  64. package/src/gates/eight-blocks.test.mjs +359 -0
  65. package/src/gates/enforcement-map.mjs +62 -0
  66. package/src/gates/enforcement-map.test.mjs +41 -0
  67. package/src/gates/english-source.mjs +176 -0
  68. package/src/gates/english-source.test.mjs +122 -0
  69. package/src/gates/frontend-boundaries.mjs +154 -0
  70. package/src/gates/frontend-boundaries.test.mjs +72 -0
  71. package/src/gates/gate-tests.mjs +44 -0
  72. package/src/gates/gate-tests.test.mjs +41 -0
  73. package/src/gates/headless-sagas.mjs +54 -0
  74. package/src/gates/headless-sagas.test.mjs +71 -0
  75. package/src/gates/internal-routes.mjs +76 -0
  76. package/src/gates/internal-routes.test.mjs +53 -0
  77. package/src/gates/public-routes.mjs +67 -0
  78. package/src/gates/public-routes.test.mjs +38 -0
  79. package/src/gates/registry-agreement.mjs +37 -0
  80. package/src/gates/registry-agreement.test.mjs +36 -0
  81. package/src/gates/saga-tests.mjs +94 -0
  82. package/src/gates/saga-tests.test.mjs +92 -0
  83. package/src/gates/sql-identifiers.mjs +244 -0
  84. package/src/gates/sql-identifiers.test.mjs +197 -0
  85. package/src/gates/tenant-predicate.mjs +175 -0
  86. package/src/gates/tenant-predicate.test.mjs +161 -0
  87. package/src/gates/tenant-tables.mjs +65 -0
  88. package/src/gates/tenant-tables.test.mjs +56 -0
  89. package/src/gates/test-mirror.mjs +47 -0
  90. package/src/gates/test-mirror.test.mjs +31 -0
  91. package/src/index.mjs +9 -0
  92. package/templates/.jscpd.json +15 -0
  93. package/templates/CLAUDE.md +54 -0
  94. package/templates/decisions.examples.md +25 -0
  95. package/templates/docs/adr-template.md +58 -0
  96. package/templates/docs/architecture.md +179 -0
  97. package/templates/docs/decisions.md +72 -0
  98. package/templates/docs/enforcement.md +94 -0
  99. package/templates/docs/glossary.md +16 -0
  100. package/templates/docs/guards.md +23 -0
  101. package/templates/docs/pagination.md +113 -0
  102. package/templates/docs/performance.md +35 -0
  103. package/templates/docs/ui.md +32 -0
  104. package/templates/githooks/commit-msg +4 -0
  105. package/templates/githooks/pre-commit +18 -0
  106. package/templates/githooks/pre-push +6 -0
  107. package/templates/github/workflows/ci.yml +21 -0
  108. package/templates/qc.config.json +6 -0
  109. package/templates/quality-thresholds.json +114 -0
@@ -0,0 +1,87 @@
1
+ // An ADR records a decision so a later reader can disagree with it on the evidence. That needs the
2
+ // sections nobody writes unprompted: what it cost, and what was considered and rejected. A template
3
+ // alone does not produce them -- an empty heading under a filled-in template is the usual outcome,
4
+ // so the gate checks that each required section carries prose, not that it exists.
5
+
6
+ const DEFAULT_SECTIONS = [
7
+ "Prerequisite",
8
+ "Context",
9
+ "Decision",
10
+ "Why this, specifically",
11
+ "What this buys",
12
+ "What this costs",
13
+ "Alternatives considered and not chosen",
14
+ "Related decisions",
15
+ ];
16
+ const MIN_WORDS = 12;
17
+ const ID_PATTERN = /^([A-Z]{2,5}-\d{3,4})/;
18
+
19
+ /** @returns {{heading: string, body: string}[]} every `## ` section, in order. */
20
+ export function sections(markdown) {
21
+ const out = [];
22
+ let current = null;
23
+ for (const line of markdown.split("\n")) {
24
+ const heading = /^##\s+(.*?)\s*$/.exec(line);
25
+ if (heading && !line.startsWith("###")) {
26
+ if (current) out.push(current);
27
+ current = { heading: heading[1], body: "" };
28
+ } else if (current) {
29
+ current.body += `${line}\n`;
30
+ }
31
+ }
32
+ if (current) out.push(current);
33
+ return out;
34
+ }
35
+
36
+ /** Prose, with the template's own guidance comments and subheadings removed. */
37
+ export function wordCount(body) {
38
+ const prose = body
39
+ .replace(/<!--[\s\S]*?-->/g, " ")
40
+ .replace(/^###.*$/gm, " ")
41
+ .replace(/^\s*[|>-].*$/gm, " ");
42
+ return prose.split(/\s+/).filter(Boolean).length;
43
+ }
44
+
45
+ /**
46
+ * @param {{path: string, contents: string}[]} files the ADR documents
47
+ * @param {{sections?: string[], minWords?: number}} [options]
48
+ */
49
+ export function checkAdrFormat(files, options = {}) {
50
+ const required = options.sections ?? DEFAULT_SECTIONS;
51
+ const minWords = options.minWords ?? MIN_WORDS;
52
+ if (required.length === 0) throw new Error("adr.sections must name at least one required section");
53
+
54
+ const problems = [];
55
+ for (const { path, contents } of files) {
56
+ const title = contents.split("\n").find((line) => line.startsWith("# ")) ?? "";
57
+ const id = ID_PATTERN.exec(title.replace(/^#\s+/, ""));
58
+ if (!id) {
59
+ problems.push({ path, rule: "adr-title", detail: "the title must open with the decision id, as `# ADR-0031 — <claim>`." });
60
+ }
61
+ const present = sections(contents);
62
+ const byHeading = new Map(present.map((section) => [section.heading, section.body]));
63
+
64
+ for (const heading of required) {
65
+ if (!byHeading.has(heading)) {
66
+ problems.push({ path, rule: "adr-section-missing", detail: `no "## ${heading}" section.` });
67
+ continue;
68
+ }
69
+ const words = wordCount(byHeading.get(heading));
70
+ if (words < minWords) {
71
+ problems.push({
72
+ path,
73
+ rule: "adr-section-empty",
74
+ detail: `"${heading}" carries ${words} word(s). A heading left empty records nothing — say what it cost, or say there was no cost and why.`,
75
+ });
76
+ }
77
+ }
78
+ }
79
+ return problems;
80
+ }
81
+
82
+ /** @returns the ids an ADR relates to, for the citations gate to resolve. */
83
+ export function relatedIds(contents) {
84
+ const related = sections(contents).find((section) => section.heading === "Related decisions");
85
+ if (!related) return [];
86
+ return [...new Set(related.body.match(/\b[A-Z]{2,5}-\d{3,4}\b/g) ?? [])];
87
+ }
@@ -0,0 +1,54 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkAdrFormat, relatedIds, sections, wordCount } from "./adr-format.mjs";
4
+
5
+ const SECTIONS = ["Context", "What this costs"];
6
+ const prose = (n) => Array.from({ length: n }, (_, i) => `word${i}`).join(" ");
7
+ const doc = (body) => `# ADR-0031 — Keyset pagination everywhere\n\n${body}`;
8
+ const full = doc(`## Context\n\n${prose(20)}\n\n## What this costs\n\n${prose(20)}\n`);
9
+
10
+ test("a complete ADR passes", () => {
11
+ assert.deepEqual(checkAdrFormat([{ path: "a.md", contents: full }], { sections: SECTIONS }), []);
12
+ });
13
+
14
+ test("a missing section is named", () => {
15
+ const [problem] = checkAdrFormat([{ path: "a.md", contents: doc(`## Context\n\n${prose(20)}\n`) }], { sections: SECTIONS });
16
+ assert.equal(problem.rule, "adr-section-missing");
17
+ assert.match(problem.detail, /What this costs/);
18
+ });
19
+
20
+ test("a present but empty section fails, which is the usual way a template is defeated", () => {
21
+ const thin = doc(`## Context\n\n${prose(20)}\n\n## What this costs\n\nNone.\n`);
22
+ const [problem] = checkAdrFormat([{ path: "a.md", contents: thin }], { sections: SECTIONS });
23
+ assert.equal(problem.rule, "adr-section-empty");
24
+ assert.match(problem.detail, /say what it cost, or say there was no cost and why/);
25
+ });
26
+
27
+ test("the template's own guidance comments do not count as prose", () => {
28
+ const commented = doc(`## Context\n\n${prose(20)}\n\n## What this costs\n\n<!-- ${prose(40)} -->\n`);
29
+ assert.equal(checkAdrFormat([{ path: "a.md", contents: commented }], { sections: SECTIONS })[0].rule, "adr-section-empty");
30
+ });
31
+
32
+ test("a title without a decision id fails", () => {
33
+ const untitled = `# Keyset pagination\n\n## Context\n\n${prose(20)}\n\n## What this costs\n\n${prose(20)}\n`;
34
+ assert.equal(checkAdrFormat([{ path: "a.md", contents: untitled }], { sections: SECTIONS })[0].rule, "adr-title");
35
+ });
36
+
37
+ test("a subheading under an alternative does not open a new section", () => {
38
+ const withSub = doc(`## Context\n\n${prose(20)}\n\n## What this costs\n\n### Offset paging\n\n${prose(20)}\n`);
39
+ assert.deepEqual(sections(withSub).map((s) => s.heading), ["Context", "What this costs"]);
40
+ assert.deepEqual(checkAdrFormat([{ path: "a.md", contents: withSub }], { sections: SECTIONS }), []);
41
+ });
42
+
43
+ test("related ids are collected for the citations gate to resolve", () => {
44
+ const related = `# ADR-0031 — x\n\n## Related decisions\n\nADR-0028 owns the cursor. QC-007 names the check. ADR-0028 again.\n`;
45
+ assert.deepEqual(relatedIds(related), ["ADR-0028", "QC-007"]);
46
+ });
47
+
48
+ test("a table row is structure, not prose", () => {
49
+ assert.equal(wordCount("| Status | accepted |\n"), 0);
50
+ });
51
+
52
+ test("an empty required-section list is a named config error", () => {
53
+ assert.throws(() => checkAdrFormat([{ path: "a.md", contents: full }], { sections: [] }), /adr\.sections/);
54
+ });
@@ -0,0 +1,34 @@
1
+ // The audit log is append-only: no update or delete path exists in any repository.
2
+ // A log a writer can edit is not evidence of anything. docs/architecture.md.
3
+
4
+ function escape(text) {
5
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ }
7
+
8
+ const DEFAULT_TABLE = "audit_log";
9
+
10
+ /**
11
+ * @param {{path: string, statements: {sql: string}[]}[]} resources as sqlStatements reads them
12
+ * @param {{table?: string}} [options]
13
+ * @returns {{path: string, rule: string, detail: string}[]}
14
+ */
15
+ export function checkAuditAppendOnly(resources, options = {}) {
16
+ const table = options.table ?? DEFAULT_TABLE;
17
+ const name = escape(table);
18
+ // The table in a mutating position. An insert naming it is the whole point.
19
+ const mutation = new RegExp(`\\b(?:update\\s+${name}\\b|delete\\s+from\\s+${name}\\b|truncate\\s+(?:table\\s+)?${name}\\b)`, "i");
20
+ const problems = [];
21
+ for (const { path, statements } of resources) {
22
+ for (const { sql } of statements) {
23
+ const found = mutation.exec(sql);
24
+ if (found !== null) {
25
+ problems.push({
26
+ path,
27
+ rule: "audit-mutated",
28
+ detail: `'${found[0].trim()}' — ${table} is append-only, so no repository may hold an update or delete path for it`,
29
+ });
30
+ }
31
+ }
32
+ }
33
+ return problems;
34
+ }
@@ -0,0 +1,36 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkAuditAppendOnly } from "./audit-append-only.mjs";
4
+
5
+ const resource = (sql) => [{ path: "a/resource.ts", statements: [{ sql }] }];
6
+
7
+ test("an insert into the audit log is the point, and passes", () => {
8
+ assert.deepEqual(checkAuditAppendOnly(resource("insert into audit_log (id) values ($1)")), []);
9
+ });
10
+
11
+ test("a select from the audit log passes", () => {
12
+ assert.deepEqual(checkAuditAppendOnly(resource("select * from audit_log where tenant_id = $1")), []);
13
+ });
14
+
15
+ test("an update fails", () => {
16
+ const problems = checkAuditAppendOnly(resource("update audit_log set actor = $1"));
17
+ assert.equal(problems.length, 1);
18
+ assert.equal(problems[0].rule, "audit-mutated");
19
+ });
20
+
21
+ test("a delete fails", () => {
22
+ assert.equal(checkAuditAppendOnly(resource("delete from audit_log where id = $1")).length, 1);
23
+ });
24
+
25
+ test("a truncate fails", () => {
26
+ assert.equal(checkAuditAppendOnly(resource("truncate table audit_log")).length, 1);
27
+ });
28
+
29
+ test("another table of a similar name is not the audit log", () => {
30
+ assert.deepEqual(checkAuditAppendOnly(resource("delete from audit_log_archive where id = $1")), []);
31
+ });
32
+
33
+ test("the table name comes from options", () => {
34
+ const problems = checkAuditAppendOnly(resource("delete from trail where id = $1"), { table: "trail" });
35
+ assert.equal(problems.length, 1);
36
+ });
@@ -0,0 +1,93 @@
1
+ // A cited id is defined here, or it is a pointer to something a reader cannot open. QC-007.
2
+ const DEFAULT_PREFIXES = ["ADR", "QC"];
3
+ const DEFAULT_REQUIREMENT = "REQ-[A-Z]{3}-\\d{3}";
4
+
5
+ function escape(text) {
6
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7
+ }
8
+
9
+ function citationSource(prefixes) {
10
+ return prefixes.map((prefix) => `${escape(prefix)}-\\d{3,4}`).join("|");
11
+ }
12
+
13
+ /**
14
+ * What counts as a citation, so a tool that rewrites one matches what this gate reads.
15
+ * @param {string[]} [prefixes]
16
+ * @returns {RegExp} global, so `matchAll` and `replace` both work off it
17
+ */
18
+ export function citationPattern(prefixes) {
19
+ return new RegExp(`\\b(?:${citationSource(prefixes ?? DEFAULT_PREFIXES)})\\b`, "g");
20
+ }
21
+
22
+ /** Ids a file may cite, harvested from the decision log's table rows. */
23
+ export function definedIds(decisionsMarkdown, options = {}) {
24
+ const row = new RegExp(`^\\|\\s*(${citationSource(options.prefixes ?? DEFAULT_PREFIXES)})\\s*\\|`);
25
+ const ids = new Set();
26
+ for (const line of decisionsMarkdown.split("\n")) {
27
+ const cell = row.exec(line);
28
+ if (cell) ids.add(cell[1]);
29
+ }
30
+ return ids;
31
+ }
32
+
33
+ /**
34
+ * @param {{path: string, contents: string}[]} files
35
+ * @param {Set<string>} decisions
36
+ * @param {Set<string>} requirements
37
+ * @param {{prefixes?: string[], requirement?: string}} [options]
38
+ */
39
+ export function checkCitations(files, decisions, requirements, options = {}) {
40
+ const citation = new RegExp(`\\b(?:${citationSource(options.prefixes ?? DEFAULT_PREFIXES)})\\b`, "g");
41
+ const requirementId = new RegExp(`\\b(?:${options.requirement ?? DEFAULT_REQUIREMENT})\\b`, "g");
42
+ const problems = [];
43
+ for (const { path, contents } of files) {
44
+ for (const id of new Set(contents.match(citation) ?? [])) {
45
+ if (!decisions.has(id)) {
46
+ problems.push({ path, rule: "undefined-decision", detail: id });
47
+ }
48
+ }
49
+ for (const id of new Set(contents.match(requirementId) ?? [])) {
50
+ if (!requirements.has(id)) {
51
+ problems.push({ path, rule: "undefined-requirement", detail: id });
52
+ }
53
+ }
54
+ }
55
+ return problems;
56
+ }
57
+
58
+ /**
59
+ * A reference reaching outside this repository is a broken repository.
60
+ * @param {{path: string, contents: string}[]} files
61
+ * @param {string[]} [foreign] regular expression sources, each optionally `/pattern/flags`
62
+ */
63
+ export function checkSelfContained(files, foreign = []) {
64
+ const patterns = foreign.map((entry) => {
65
+ const delimited = /^\/(.*)\/([a-z]*)$/.exec(entry);
66
+ return delimited ? new RegExp(delimited[1], delimited[2]) : new RegExp(entry);
67
+ });
68
+ const problems = [];
69
+ for (const { path, contents } of files) {
70
+ for (const pattern of patterns) {
71
+ if (pattern.test(contents)) {
72
+ problems.push({ path, rule: "foreign-reference", detail: String(pattern) });
73
+ }
74
+ }
75
+ }
76
+ return problems;
77
+ }
78
+
79
+ const DEFAULT_DOCS_ROOT = "docs";
80
+
81
+ /** A cited doc that does not exist is a pointer a reader cannot follow. */
82
+ export function checkDocPaths(files, existingDocs, options = {}) {
83
+ const docPath = new RegExp(`\\b${escape(options.docsRoot ?? DEFAULT_DOCS_ROOT)}\\/[a-z0-9-]+\\.md\\b`, "g");
84
+ const problems = [];
85
+ for (const { path, contents } of files) {
86
+ for (const doc of new Set(contents.match(docPath) ?? [])) {
87
+ if (!existingDocs.has(doc)) {
88
+ problems.push({ path, rule: "missing-doc", detail: doc });
89
+ }
90
+ }
91
+ }
92
+ return problems;
93
+ }
@@ -0,0 +1,115 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkCitations, checkSelfContained, definedIds, citationPattern } from "./citations.mjs";
4
+
5
+ const LOG = `
6
+ | id | decision | rule |
7
+ |---|---|---|
8
+ | ADR-0047 | eight blocks | one file |
9
+ | QC-004 | canvas | instancing |
10
+ `;
11
+
12
+ test("ids are harvested from the decision table", () => {
13
+ const ids = definedIds(LOG);
14
+ assert.ok(ids.has("ADR-0047"));
15
+ assert.ok(ids.has("QC-004"));
16
+ assert.equal(ids.size, 2);
17
+ });
18
+
19
+ test("a defined citation passes", () => {
20
+ const problems = checkCitations(
21
+ [{ path: "a.ts", contents: "// ADR-0047" }],
22
+ definedIds(LOG),
23
+ new Set(),
24
+ );
25
+ assert.deepEqual(problems, []);
26
+ });
27
+
28
+ test("an undefined decision id fails and names it", () => {
29
+ const problems = checkCitations(
30
+ [{ path: "a.ts", contents: "// ADR-9999" }],
31
+ definedIds(LOG),
32
+ new Set(),
33
+ );
34
+ assert.equal(problems.length, 1);
35
+ assert.equal(problems[0].rule, "undefined-decision");
36
+ assert.equal(problems[0].detail, "ADR-9999");
37
+ });
38
+
39
+ test("an undefined requirement id fails", () => {
40
+ const problems = checkCitations(
41
+ [{ path: "a.ts", contents: "// REQ-PHO-003" }],
42
+ definedIds(LOG),
43
+ new Set(["REQ-PIN-001"]),
44
+ );
45
+ assert.equal(problems.length, 1);
46
+ assert.equal(problems[0].rule, "undefined-requirement");
47
+ });
48
+
49
+ const FOREIGN = ["PredecessorProject", "\\.\\./sibling-checkout", "/sibling spec/i"];
50
+
51
+ test("a reference to another repository fails", () => {
52
+ const problems = checkSelfContained(
53
+ [{ path: "docs/x.md", contents: "see ../PredecessorProject/docs/spec" }],
54
+ FOREIGN,
55
+ );
56
+ assert.equal(problems.length, 1);
57
+ assert.equal(problems[0].rule, "foreign-reference");
58
+ });
59
+
60
+ test("a delimited pattern keeps its flags", () => {
61
+ const problems = checkSelfContained([{ path: "a.md", contents: "the Sibling Spec says" }], FOREIGN);
62
+ assert.equal(problems.length, 1);
63
+ });
64
+
65
+ test("no foreign reference passes", () => {
66
+ assert.deepEqual(checkSelfContained([{ path: "a.ts", contents: "// docs/guards.md" }], FOREIGN), []);
67
+ });
68
+
69
+ test("a repository naming no foreign pattern has nothing to fail", () => {
70
+ assert.deepEqual(checkSelfContained([{ path: "a.ts", contents: "../PredecessorProject" }]), []);
71
+ });
72
+
73
+ test("the citation prefixes and the docs root come from options", () => {
74
+ const defined = definedIds("| RFC-001 | x | y |", { prefixes: ["RFC"] });
75
+ assert.deepEqual([...defined], ["RFC-001"]);
76
+ const problems = checkCitations(
77
+ [{ path: "a.ts", contents: "// RFC-002" }],
78
+ defined,
79
+ new Set(),
80
+ { prefixes: ["RFC"] },
81
+ );
82
+ assert.equal(problems.length, 1);
83
+ assert.equal(problems[0].rule, "undefined-decision");
84
+ });
85
+
86
+ import { checkDocPaths } from "./citations.mjs";
87
+
88
+ test("a cited doc that exists passes", () => {
89
+ const problems = checkDocPaths(
90
+ [{ path: "a.ts", contents: "// docs/guards.md" }],
91
+ new Set(["docs/guards.md"]),
92
+ );
93
+ assert.deepEqual(problems, []);
94
+ });
95
+
96
+ test("a cited doc that does not exist fails and names it", () => {
97
+ const problems = checkDocPaths(
98
+ [{ path: "a.ts", contents: "// docs/gone.md" }],
99
+ new Set(["docs/guards.md"]),
100
+ );
101
+ assert.equal(problems.length, 1);
102
+ assert.equal(problems[0].rule, "missing-doc");
103
+ assert.equal(problems[0].detail, "docs/gone.md");
104
+ });
105
+
106
+ test("the citation pattern is the one the gate reads, and a tool can rewrite by it", () => {
107
+ const pattern = citationPattern();
108
+ const found = "ADR-0054 and QC-010, not ADR-00544 or REQ-PHO-001".match(pattern);
109
+ assert.deepEqual(found, ["ADR-0054", "QC-010"]);
110
+ });
111
+
112
+ test("the citation pattern honours the prefixes a repository declares", () => {
113
+ const found = "ADR-0001 DEC-0002".match(citationPattern(["DEC"]));
114
+ assert.deepEqual(found, ["DEC-0002"]);
115
+ });
@@ -0,0 +1,53 @@
1
+ // A route names the requirements it satisfies. `docs/migration/plan.md` makes
2
+ // "every claimed id resolves, with `tests` filled" part of every unit's
3
+ // definition of done — the only item on that list a person had to check by
4
+ // reading. This checks it.
5
+ //
6
+ // It asserts a claim is backed, not that the backing is good. Whether the named
7
+ // test proves the statement is what review is for.
8
+
9
+ const DEFAULT_KEY = "req";
10
+ const DEFAULT_ID = "REQ-[A-Z]{3}-\\d{3}";
11
+
12
+ function escape(text) {
13
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+ }
15
+
16
+ /** Every requirement id a feature's routes claim. */
17
+ export function claimedIds(source, options = {}) {
18
+ const key = escape(options.key ?? DEFAULT_KEY);
19
+ const array = new RegExp(`\\b${key}:\\s*\\[([^\\]]*)\\]`, "g");
20
+ const id = new RegExp(options.id ?? DEFAULT_ID, "g");
21
+
22
+ const claimed = new Set();
23
+ let match = array.exec(source);
24
+ while (match !== null) {
25
+ for (const found of match[1].match(id) ?? []) claimed.add(found);
26
+ match = array.exec(source);
27
+ }
28
+ return claimed;
29
+ }
30
+
31
+ /**
32
+ * @param {{path: string, source: string}[]} triggers
33
+ * @param {Map<string, string[]>} tests requirement id to the tests it names
34
+ * @returns {{path: string, rule: string, detail: string}[]}
35
+ */
36
+ export function checkClaimedRequirements(triggers, tests, options = {}) {
37
+ const problems = [];
38
+ for (const { path, source } of triggers) {
39
+ for (const id of [...claimedIds(source, options)].sort()) {
40
+ const named = tests.get(id);
41
+ if (named === undefined) {
42
+ problems.push({ path, rule: "unregistered-requirement", detail: `${id} is claimed but not registered` });
43
+ } else if (named.length === 0) {
44
+ problems.push({
45
+ path,
46
+ rule: "unproven-requirement",
47
+ detail: `${id} is claimed by a route and names no test`,
48
+ });
49
+ }
50
+ }
51
+ }
52
+ return problems;
53
+ }
@@ -0,0 +1,60 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkClaimedRequirements, claimedIds } from "./claimed-requirements.mjs";
4
+
5
+ const trigger = `export const trigger = defineTrigger({
6
+ routes: [
7
+ { method: "get", path: "/v1/a", auth: "tenant", req: ["REQ-PRJ-001", "REQ-PRJ-002"], handler: a },
8
+ { method: "post", path: "/v1/b", auth: "public", req: ["REQ-PRJ-003"], handler: b },
9
+ ],
10
+ });`;
11
+
12
+ test("every id a route claims is collected", () => {
13
+ assert.deepEqual([...claimedIds(trigger)].sort(), ["REQ-PRJ-001", "REQ-PRJ-002", "REQ-PRJ-003"]);
14
+ });
15
+
16
+ test("a claim backed by a named test passes", () => {
17
+ const tests = new Map([
18
+ ["REQ-PRJ-001", ["a.test.ts"]],
19
+ ["REQ-PRJ-002", ["a.test.ts"]],
20
+ ["REQ-PRJ-003", ["b.test.ts"]],
21
+ ]);
22
+ assert.deepEqual(checkClaimedRequirements([{ path: "t.ts", source: trigger }], tests), []);
23
+ });
24
+
25
+ test("a claim that names no test is a finding", () => {
26
+ const tests = new Map([
27
+ ["REQ-PRJ-001", ["a.test.ts"]],
28
+ ["REQ-PRJ-002", []],
29
+ ["REQ-PRJ-003", ["b.test.ts"]],
30
+ ]);
31
+ const problems = checkClaimedRequirements([{ path: "t.ts", source: trigger }], tests);
32
+ assert.equal(problems.length, 1);
33
+ assert.equal(problems[0].rule, "unproven-requirement");
34
+ assert.match(problems[0].detail, /REQ-PRJ-002/);
35
+ });
36
+
37
+ test("a claim on an id nobody registered is a finding", () => {
38
+ const tests = new Map([["REQ-PRJ-001", ["a.test.ts"]], ["REQ-PRJ-002", ["a.test.ts"]]]);
39
+ const problems = checkClaimedRequirements([{ path: "t.ts", source: trigger }], tests);
40
+ assert.deepEqual(problems.map((p) => p.rule), ["unregistered-requirement"]);
41
+ });
42
+
43
+ test("a registered id no route claims is not required to be proven yet", () => {
44
+ const tests = new Map([["REQ-PRJ-001", ["a.test.ts"]], ["REQ-PRJ-002", ["a.test.ts"]], ["REQ-PRJ-003", ["b.test.ts"]], ["REQ-ADM-001", []]]);
45
+ assert.deepEqual(checkClaimedRequirements([{ path: "t.ts", source: trigger }], tests), []);
46
+ });
47
+
48
+ test("a trigger that declares no routes claims nothing", () => {
49
+ assert.deepEqual(claimedIds("export const trigger = defineTrigger({ routes: [], queues: [] });").size, 0);
50
+ });
51
+
52
+ test("the claim key and the id shape come from options", () => {
53
+ const source = 'route({ satisfies: ["STORY-12"] })';
54
+ assert.deepEqual([...claimedIds(source, { key: "satisfies", id: "STORY-\\d+" })], ["STORY-12"]);
55
+ });
56
+
57
+ test("a claim under the default key is invisible to a repository that renamed it", () => {
58
+ const source = 'route({ req: ["REQ-PHO-001"] })';
59
+ assert.deepEqual([...claimedIds(source, { key: "satisfies", id: "STORY-\\d+" })], []);
60
+ });
@@ -0,0 +1,76 @@
1
+ // `no-comment-paragraph`'s rule, for files ESLint cannot parse: Terraform, tfvars, HCL, shell.
2
+ // Same threshold (config.comments.maxLines), a raw `#`-line scan instead of an AST walk.
3
+
4
+ const BANNER = /^(?:[-=*_~#]{4,})$/;
5
+ const CODE_SHAPE = [
6
+ /^(?:resource|module|variable|data|output|locals?|provider|terraform)\s+["\w]/,
7
+ /^[\w.-]+\s*=\s*\S/,
8
+ /^(?:if|for|case|while)\s/,
9
+ /^[\w./-]+\(.*\)\s*$/,
10
+ ];
11
+ const STATEMENT_END = /[;{}")\]]$/;
12
+
13
+ function looksLikeCode(line) {
14
+ return CODE_SHAPE.some((shape) => shape.test(line)) && STATEMENT_END.test(line);
15
+ }
16
+
17
+ function runsOf(lines) {
18
+ const runs = [];
19
+ let current = null;
20
+ lines.forEach((line, index) => {
21
+ const trimmed = line.trim();
22
+ const isComment = trimmed.startsWith("#") && !trimmed.startsWith("#!");
23
+ if (!isComment) {
24
+ current = null;
25
+ return;
26
+ }
27
+ if (current && index === current.lastLine + 1) {
28
+ current.lines.push(index);
29
+ current.lastLine = index;
30
+ } else {
31
+ current = { startLine: index, lastLine: index, lines: [index] };
32
+ runs.push(current);
33
+ }
34
+ });
35
+ return runs;
36
+ }
37
+
38
+ function proseOf(run, lines) {
39
+ return run.lines
40
+ .map((i) => lines[i].trim().replace(/^#\s?/, "").trim())
41
+ .filter((line) => line !== "");
42
+ }
43
+
44
+ /**
45
+ * @param {{path: string, contents: string}[]} files
46
+ * @param {{maxLines?: number}} [options]
47
+ * @returns {{path: string, rule: string, detail: string}[]}
48
+ */
49
+ export function checkCommentStyle(files, options = {}) {
50
+ const maxLines = options.maxLines ?? 2;
51
+ const problems = [];
52
+ for (const { path, contents } of files) {
53
+ const lines = contents.split("\n");
54
+ for (const run of runsOf(lines)) {
55
+ const prose = proseOf(run, lines);
56
+ if (prose.length === 0) continue;
57
+ const range = `${run.startLine + 1}-${run.lastLine + 1}`;
58
+ if (prose.some((line) => BANNER.test(line))) {
59
+ problems.push({ path, rule: "banner-comment", detail: `${range}: banner comment` });
60
+ continue;
61
+ }
62
+ if (prose.some(looksLikeCode)) {
63
+ problems.push({ path, rule: "commented-code", detail: `${range}: commented-out code` });
64
+ continue;
65
+ }
66
+ if (prose.length > maxLines) {
67
+ problems.push({
68
+ path,
69
+ rule: "comment-paragraph",
70
+ detail: `${range}: ${prose.length} lines, max ${maxLines}`,
71
+ });
72
+ }
73
+ }
74
+ }
75
+ return problems;
76
+ }
@@ -0,0 +1,46 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkCommentStyle } from "./comment-style.mjs";
4
+
5
+ test("a one-line comment passes", () => {
6
+ const problems = checkCommentStyle([{ path: "a.tf", contents: "# why this exists\nresource {}" }]);
7
+ assert.deepEqual(problems, []);
8
+ });
9
+
10
+ test("a comment run over maxLines fails and names the range", () => {
11
+ const contents = "# line one\n# line two\n# line three\nresource {}";
12
+ const problems = checkCommentStyle([{ path: "a.tf", contents }]);
13
+ assert.equal(problems.length, 1);
14
+ assert.equal(problems[0].rule, "comment-paragraph");
15
+ assert.equal(problems[0].detail, "1-3: 3 lines, max 2");
16
+ });
17
+
18
+ test("maxLines is configurable", () => {
19
+ const contents = "# line one\n# line two\n# line three\nresource {}";
20
+ const problems = checkCommentStyle([{ path: "a.tf", contents }], { maxLines: 3 });
21
+ assert.deepEqual(problems, []);
22
+ });
23
+
24
+ test("a banner comment fails regardless of length", () => {
25
+ const problems = checkCommentStyle([{ path: "a.sh", contents: "# ----------\necho hi" }]);
26
+ assert.equal(problems.length, 1);
27
+ assert.equal(problems[0].rule, "banner-comment");
28
+ });
29
+
30
+ test("commented-out code fails regardless of length", () => {
31
+ const problems = checkCommentStyle([{ path: "a.tf", contents: '# name = "value"\nresource {}' }]);
32
+ assert.equal(problems.length, 1);
33
+ assert.equal(problems[0].rule, "commented-code");
34
+ });
35
+
36
+ test("a shebang line breaks the run rather than joining it", () => {
37
+ const contents = "#!/usr/bin/env bash\n# one\n# two\necho hi";
38
+ const problems = checkCommentStyle([{ path: "a.sh", contents }]);
39
+ assert.deepEqual(problems, []);
40
+ });
41
+
42
+ test("two runs separated by code are measured independently", () => {
43
+ const contents = "# first run\nresource {}\n# second run\nmodule {}";
44
+ const problems = checkCommentStyle([{ path: "a.tf", contents }]);
45
+ assert.deepEqual(problems, []);
46
+ });