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,53 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { calledInternalRoutes, checkInternalRoutes, declaredInternalRoutes } from "./internal-routes.mjs";
4
+
5
+ const trigger = `routes: [
6
+ { method: "post", path: "/v1/internal/photos/:photoId/derivatives", auth: "internal", req: [], handler: h },
7
+ { method: "get", path: "/v1/photos", auth: "tenant", req: [], handler: g },
8
+ ]`;
9
+
10
+ const worker = {
11
+ path: "workers/media-process/src/entry.ts",
12
+ source: 'const r = await fetch(`${config.apiBaseUrl}/v1/internal/photos/${photoId}/derivatives`, {});',
13
+ };
14
+
15
+ test("an internal route is read out of the trigger", () => {
16
+ assert.deepEqual([...declaredInternalRoutes([trigger])], ["/v1/internal/photos/:/derivatives"]);
17
+ });
18
+
19
+ test("a tenant route is not an internal one", () => {
20
+ assert.equal(declaredInternalRoutes([trigger]).has("/v1/photos"), false);
21
+ });
22
+
23
+ test("a worker's interpolated segment matches the route's parameter", () => {
24
+ assert.deepEqual(checkInternalRoutes(declaredInternalRoutes([trigger]), calledInternalRoutes([worker])), []);
25
+ });
26
+
27
+ test("a worker posting to a path no route serves is named, with the file", () => {
28
+ const stale = {
29
+ path: "workers/media-process/src/entry.ts",
30
+ source: 'fetch(`${base}/v1/internal/photos/${photoId}/thumbnails`, {});',
31
+ };
32
+ const problems = checkInternalRoutes(declaredInternalRoutes([trigger]), calledInternalRoutes([stale]));
33
+ assert.equal(problems.length, 1);
34
+ assert.equal(problems[0].rule, "unserved-internal-route");
35
+ assert.match(problems[0].path, /media-process/);
36
+ });
37
+
38
+ test("a segment count mismatch is caught, not smoothed over", () => {
39
+ const deep = { path: "w.ts", source: 'fetch(`${base}/v1/internal/photos/${id}/derivatives/extra`, {});' };
40
+ assert.equal(checkInternalRoutes(declaredInternalRoutes([trigger]), calledInternalRoutes([deep])).length, 1);
41
+ });
42
+
43
+ test("the internal prefix comes from options", () => {
44
+ const declared = declaredInternalRoutes(['path: "/api/private/report"'], { prefix: "/api/private/" });
45
+ const called = calledInternalRoutes(
46
+ [{ path: "workers/a.ts", source: "await post(`${base}/api/private/missing`)" }],
47
+ { prefix: "/api/private/" },
48
+ );
49
+ assert.deepEqual([...declared], ["/api/private/report"]);
50
+ const problems = checkInternalRoutes(declared, called);
51
+ assert.equal(problems.length, 1);
52
+ assert.equal(problems[0].rule, "unserved-internal-route");
53
+ });
@@ -0,0 +1,67 @@
1
+ // The API decides which routes need no session; the BFF must let exactly those
2
+ // through. They are separate services, so the set is written twice — QC-007:
3
+ // where a tool demands a literal, assert agreement rather than forbid it.
4
+ //
5
+ // Drift in either direction is a finding. A route the API opened that the BFF
6
+ // still guards is dead; a route the BFF opens that the API guards is a hole.
7
+
8
+ const DEFAULT_AUTH_KEY = "auth";
9
+ const DEFAULT_PUBLIC_VALUE = "public";
10
+
11
+ function publicRoutePattern(key, value) {
12
+ return new RegExp(`\\{\\s*method:\\s*"(\\w+)",\\s*path:\\s*"([^"]+)",\\s*${key}:\\s*"${value}"`, "g");
13
+ }
14
+ const BFF_ENTRY = /\{\s*method:\s*"(\w+)",\s*path:\s*"([^"]+)"\s*\}/g;
15
+
16
+ function collect(source, pattern) {
17
+ const found = new Set();
18
+ pattern.lastIndex = 0;
19
+ let match = pattern.exec(source);
20
+ while (match !== null) {
21
+ found.add(`${match[1].toUpperCase()} ${match[2]}`);
22
+ match = pattern.exec(source);
23
+ }
24
+ return found;
25
+ }
26
+
27
+ /** Every route a backend trigger declares `auth: "public"`. */
28
+ export function declaredPublicRoutes(triggerSources, options = {}) {
29
+ const PUBLIC_ROUTE = publicRoutePattern(
30
+ options.authKey ?? DEFAULT_AUTH_KEY,
31
+ options.publicValue ?? DEFAULT_PUBLIC_VALUE,
32
+ );
33
+ const found = new Set();
34
+ for (const source of triggerSources) {
35
+ for (const route of collect(source, PUBLIC_ROUTE)) found.add(route);
36
+ }
37
+ return found;
38
+ }
39
+
40
+ /** Every route the BFF forwards without a session. */
41
+ export function allowedPublicRoutes(source) {
42
+ return collect(source, BFF_ENTRY);
43
+ }
44
+
45
+ /** @returns {{path: string, rule: string, detail: string}[]} */
46
+ export function checkPublicRoutes(declared, allowed, label) {
47
+ const problems = [];
48
+ for (const route of [...declared].sort()) {
49
+ if (!allowed.has(route)) {
50
+ problems.push({
51
+ path: label,
52
+ rule: "public-route-unreachable",
53
+ detail: `the api serves '${route}' without a session, but the bff still demands one`,
54
+ });
55
+ }
56
+ }
57
+ for (const route of [...allowed].sort()) {
58
+ if (!declared.has(route)) {
59
+ problems.push({
60
+ path: label,
61
+ rule: "public-route-unguarded",
62
+ detail: `the bff forwards '${route}' with no session, but no api route declares itself public`,
63
+ });
64
+ }
65
+ }
66
+ return problems;
67
+ }
@@ -0,0 +1,38 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { allowedPublicRoutes, checkPublicRoutes, declaredPublicRoutes } from "./public-routes.mjs";
4
+
5
+ const trigger = `export const trigger = defineTrigger({
6
+ routes: [
7
+ { method: "get", path: "/v1/me", auth: "tenant", req: [], handler: a },
8
+ { method: "post", path: "/v1/shares/:shareId/resolve", auth: "public", req: [], handler: b },
9
+ ],
10
+ });`;
11
+
12
+ const bff = `export const PUBLIC_ROUTES = [
13
+ { method: "POST", path: "/v1/shares/:shareId/resolve" },
14
+ ];`;
15
+
16
+ test("a public route is read out of the trigger that declares it", () => {
17
+ assert.deepEqual([...declaredPublicRoutes([trigger])], ["POST /v1/shares/:shareId/resolve"]);
18
+ });
19
+
20
+ test("a tenant route is never read as public", () => {
21
+ assert.equal(declaredPublicRoutes([trigger]).has("GET /v1/me"), false);
22
+ });
23
+
24
+ test("two lists that agree pass", () => {
25
+ assert.deepEqual(checkPublicRoutes(declaredPublicRoutes([trigger]), allowedPublicRoutes(bff), "bff"), []);
26
+ });
27
+
28
+ test("a public api route the bff still guards is unreachable, and is named", () => {
29
+ const problems = checkPublicRoutes(declaredPublicRoutes([trigger]), new Set(), "bff");
30
+ assert.equal(problems.length, 1);
31
+ assert.equal(problems[0].rule, "public-route-unreachable");
32
+ });
33
+
34
+ test("a route the bff opens that no api route declares public is a hole, and is named", () => {
35
+ const problems = checkPublicRoutes(new Set(), allowedPublicRoutes(bff), "bff");
36
+ assert.equal(problems.length, 1);
37
+ assert.equal(problems[0].rule, "public-route-unguarded");
38
+ });
@@ -0,0 +1,37 @@
1
+ // A value may be written twice only where a tool demands a literal. Where that
2
+ // happens, the gate asserts agreement rather than forbidding the number. QC-007.
3
+
4
+ const ENTRY = /^\s*(\w+):\s*(\d+),?\s*$/;
5
+
6
+ /** Numbers declared in a source constant, by key. */
7
+ export function declaredValues(source, constantName) {
8
+ const start = source.indexOf(constantName);
9
+ if (start === -1) return {};
10
+ const open = source.indexOf("{", start);
11
+ const close = source.indexOf("};", open);
12
+ const values = {};
13
+ for (const line of source.slice(open + 1, close).split("\n")) {
14
+ const match = ENTRY.exec(line);
15
+ if (match) values[match[1]] = Number(match[2]);
16
+ }
17
+ return values;
18
+ }
19
+
20
+ /**
21
+ * @param {Record<string, number>} declared key → value in the source
22
+ * @param {Record<string, {value: number}>} registry registry entries
23
+ * @param {(key: string) => string} toRegistryKey
24
+ */
25
+ export function checkAgreement(declared, registry, toRegistryKey, label) {
26
+ const problems = [];
27
+ for (const [key, value] of Object.entries(declared)) {
28
+ const registryKey = toRegistryKey(key);
29
+ const entry = registry[registryKey];
30
+ if (!entry) {
31
+ problems.push({ path: label, rule: "unregistered-value", detail: `${key} (${registryKey})` });
32
+ } else if (entry.value !== value) {
33
+ problems.push({ path: label, rule: "registry-disagreement", detail: `${key}: source has one value, the registry another` });
34
+ }
35
+ }
36
+ return problems;
37
+ }
@@ -0,0 +1,36 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkAgreement, declaredValues } from "./registry-agreement.mjs";
4
+
5
+ const SOURCE = `
6
+ export const PRESIGN_LIFETIME_SECONDS: Readonly<Record<PresignLifetime, number>> = {
7
+ clientDefault: 600,
8
+ downloadRedirect: 60,
9
+ };
10
+ `;
11
+ const key = (k) => "presign" + k.toLowerCase();
12
+
13
+ test("values are read out of the source constant", () => {
14
+ assert.deepEqual(declaredValues(SOURCE, "PRESIGN_LIFETIME_SECONDS"), {
15
+ clientDefault: 600,
16
+ downloadRedirect: 60,
17
+ });
18
+ });
19
+
20
+ test("agreement passes", () => {
21
+ const registry = { presignclientdefault: { value: 600 }, presigndownloadredirect: { value: 60 } };
22
+ assert.deepEqual(checkAgreement(declaredValues(SOURCE, "PRESIGN_LIFETIME_SECONDS"), registry, key, "port"), []);
23
+ });
24
+
25
+ test("a disagreement fails", () => {
26
+ const registry = { presignclientdefault: { value: 900 }, presigndownloadredirect: { value: 60 } };
27
+ const problems = checkAgreement(declaredValues(SOURCE, "PRESIGN_LIFETIME_SECONDS"), registry, key, "port");
28
+ assert.equal(problems.length, 1);
29
+ assert.equal(problems[0].rule, "registry-disagreement");
30
+ });
31
+
32
+ test("a value with no registry entry fails", () => {
33
+ const problems = checkAgreement({ ghost: 1 }, {}, key, "port");
34
+ assert.equal(problems.length, 1);
35
+ assert.equal(problems[0].rule, "unregistered-value");
36
+ });
@@ -0,0 +1,94 @@
1
+ // A headless architecture is a claim until something checks it. The two lint-side
2
+ // rules keep orchestration out of the view and the view out of the pipeline; neither
3
+ // proves a workflow is ever *run* without one. This does.
4
+ //
5
+ // It asserts a saga is named by a test that imports no view module — not that the
6
+ // test is good. Whether the test proves the workflow is what review is for.
7
+
8
+ const DEFAULT_FACTORIES = ["definePipeline", "defineSaga"];
9
+ const DEFAULT_VIEW_MODULES = ["react", "react-dom"];
10
+
11
+ function escape(text) {
12
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
13
+ }
14
+
15
+ /**
16
+ * Every saga a source file exports, by the factory that declares it.
17
+ *
18
+ * @param {{path: string, contents: string}[]} files
19
+ * @param {{factories?: string[]}} [options]
20
+ * @returns {{path: string, name: string}[]}
21
+ */
22
+ export function declaredSagas(files, options = {}) {
23
+ const factories = (options.factories ?? DEFAULT_FACTORIES).map(escape).join("|");
24
+ const declaration = new RegExp(`export\\s+const\\s+(\\w+)\\s*=\\s*(?:${factories})\\s*[<(]`, "g");
25
+ const found = [];
26
+ for (const { path, contents } of files) {
27
+ declaration.lastIndex = 0;
28
+ let match = declaration.exec(contents);
29
+ while (match !== null) {
30
+ found.push({ path, name: match[1] });
31
+ match = declaration.exec(contents);
32
+ }
33
+ }
34
+ return found;
35
+ }
36
+
37
+ /**
38
+ * Every name a test could use to reach this saga: the saga itself, and any exported
39
+ * function in the same file whose body names it. A runner is one indirection and is
40
+ * followed — a check that cries wolf is a check somebody turns off.
41
+ */
42
+ export function entryPoints(source, saga) {
43
+ const names = [saga];
44
+ const named = new RegExp(`\\b${escape(saga)}\\b`);
45
+ // Top-level exports, each chunk running to the next one.
46
+ const chunks = source.split(/\nexport\s+/);
47
+ for (const chunk of chunks) {
48
+ const declared = /^(?:async\s+)?function\s+(\w+)|^const\s+(\w+)\s*=/.exec(chunk);
49
+ if (!declared) continue;
50
+ const name = declared[1] ?? declared[2];
51
+ if (name === saga) continue;
52
+ if (named.test(chunk)) names.push(name);
53
+ }
54
+ return names;
55
+ }
56
+
57
+ /** A test that reaches for the view layer is not the proof this gate is asking for. */
58
+ function isHeadless(contents, viewModules) {
59
+ const viewImport = new RegExp(`\\bfrom\\s+["'](?:${viewModules.map(escape).join("|")})["']`);
60
+ return !viewImport.test(contents);
61
+ }
62
+
63
+ /**
64
+ * @param {{path: string, name: string}[]} sagas
65
+ * @param {{path: string, contents: string}[]} tests
66
+ * @param {{viewModules?: string[]}} [options]
67
+ * @returns {{path: string, rule: string, detail: string}[]}
68
+ */
69
+ export function checkSagaTests(sagas, tests, options = {}) {
70
+ const viewModules = options.viewModules ?? DEFAULT_VIEW_MODULES;
71
+ const bySource = new Map(options.sources?.map((file) => [file.path, file.contents]) ?? []);
72
+ const problems = [];
73
+ for (const { path, name } of sagas) {
74
+ const reachable = entryPoints(bySource.get(path) ?? "", name);
75
+ const named = new RegExp(`\\b(?:${reachable.map(escape).join("|")})\\b`);
76
+ const naming = tests.filter((test) => named.test(test.contents));
77
+ if (naming.length === 0) {
78
+ problems.push({
79
+ path,
80
+ rule: "untested-saga",
81
+ detail: `'${name}' is never named by a test, nor is any runner that calls it — nothing runs it without a browser`,
82
+ });
83
+ continue;
84
+ }
85
+ if (!naming.some((test) => isHeadless(test.contents, viewModules))) {
86
+ problems.push({
87
+ path,
88
+ rule: "view-bound-saga",
89
+ detail: `every test naming '${name}' imports ${viewModules.join(" or ")} — none proves it runs headlessly`,
90
+ });
91
+ }
92
+ }
93
+ return problems;
94
+ }
@@ -0,0 +1,92 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkSagaTests, declaredSagas } from "./saga-tests.mjs";
4
+
5
+ const source = [
6
+ {
7
+ path: "backend/src/features/orders/slices/create.ts",
8
+ contents: "export const createOrderPipeline = definePipeline<CreateOrderState>({ name: 'create' });",
9
+ },
10
+ ];
11
+
12
+ test("an exported pipeline is found by the factory that declares it", () => {
13
+ assert.deepEqual(declaredSagas(source), [
14
+ { path: "backend/src/features/orders/slices/create.ts", name: "createOrderPipeline" },
15
+ ]);
16
+ });
17
+
18
+ test("a saga no test names fails", () => {
19
+ const problems = checkSagaTests(declaredSagas(source), []);
20
+ assert.equal(problems.length, 1);
21
+ assert.equal(problems[0].rule, "untested-saga");
22
+ });
23
+
24
+ test("a saga named by a headless test passes", () => {
25
+ const tests = [{ path: "a.test.ts", contents: "import { createOrderPipeline } from './create.js';" }];
26
+ assert.deepEqual(checkSagaTests(declaredSagas(source), tests), []);
27
+ });
28
+
29
+ // The gate exists for this case: the workflow is tested, but only through a component,
30
+ // so nothing shows it can run without one.
31
+ test("a saga only named by a view-bound test fails", () => {
32
+ const tests = [
33
+ {
34
+ path: "a.test.tsx",
35
+ contents: 'import { render } from "react";\nimport { createOrderPipeline } from "./create.js";',
36
+ },
37
+ ];
38
+ const problems = checkSagaTests(declaredSagas(source), tests);
39
+ assert.equal(problems.length, 1);
40
+ assert.equal(problems[0].rule, "view-bound-saga");
41
+ });
42
+
43
+ test("one headless test is enough even beside a view-bound one", () => {
44
+ const tests = [
45
+ { path: "a.test.tsx", contents: 'import { render } from "react";\nconst x = createOrderPipeline;' },
46
+ { path: "b.test.ts", contents: "const x = createOrderPipeline;" },
47
+ ];
48
+ assert.deepEqual(checkSagaTests(declaredSagas(source), tests), []);
49
+ });
50
+
51
+ test("the factory list and the view modules come from options", () => {
52
+ const vue = [{ path: "a.ts", contents: "export const flow = defineFlow({});" }];
53
+ assert.deepEqual(declaredSagas(vue, { factories: ["defineFlow"] }), [{ path: "a.ts", name: "flow" }]);
54
+ const tests = [{ path: "a.test.ts", contents: 'import { h } from "vue";\nconst x = flow;' }];
55
+ const problems = checkSagaTests(declaredSagas(vue, { factories: ["defineFlow"] }), tests, {
56
+ viewModules: ["vue"],
57
+ });
58
+ assert.equal(problems.length, 1);
59
+ assert.equal(problems[0].rule, "view-bound-saga");
60
+ });
61
+
62
+ test("a name that merely appears as a substring does not count", () => {
63
+ const tests = [{ path: "a.test.ts", contents: "const x = createOrderPipelineBuilder;" }];
64
+ const problems = checkSagaTests(declaredSagas(source), tests);
65
+ assert.equal(problems.length, 1);
66
+ assert.equal(problems[0].rule, "untested-saga");
67
+ });
68
+
69
+ // A runner is how these are actually called; demanding the pipeline's own name
70
+ // would fail every correctly-tested workflow. One indirection is followed.
71
+ test("a test naming the runner that calls the saga counts", () => {
72
+ const contents = `export const createOrderPipeline = definePipeline({});
73
+ export function runCreateOrder(state, signal) {
74
+ return runOnce(createOrderPipeline, state, signal);
75
+ }`;
76
+ const sources = [{ path: "slices/create.ts", contents }];
77
+ const sagas = declaredSagas(sources);
78
+ const tests = [{ path: "a.test.ts", contents: "import { runCreateOrder } from './create.js';" }];
79
+ assert.deepEqual(checkSagaTests(sagas, tests, { sources }), []);
80
+ });
81
+
82
+ test("an unrelated exported function in the same file does not count", () => {
83
+ const contents = `export const createOrderPipeline = definePipeline({});
84
+ export function unrelatedHelper(x) {
85
+ return x + 1;
86
+ }`;
87
+ const sources = [{ path: "slices/create.ts", contents }];
88
+ const tests = [{ path: "a.test.ts", contents: "import { unrelatedHelper } from './create.js';" }];
89
+ const problems = checkSagaTests(declaredSagas(sources), tests, { sources });
90
+ assert.equal(problems.length, 1);
91
+ assert.equal(problems[0].rule, "untested-saga");
92
+ });
@@ -0,0 +1,244 @@
1
+ // A resource slice writes hand-written SQL; a migration declares the columns it
2
+ // names. Nothing has ever run the two together, so a typo or a renamed column
3
+ // is invisible until deploy. This reads both and asserts they agree. QC-007.
4
+ //
5
+ // It proves names, not behaviour: that the policy applies, that a constraint
6
+ // fires, that a join is correct — none of that is in scope here.
7
+
8
+ // A column line is a name followed by anything; a constraint line opens with one
9
+ // of these words instead. Recognising constraints is robust where listing every
10
+ // type is not — a type this did not know once pushed a unit to pick another one.
11
+ const CONSTRAINT_OPENER = new Set(["primary", "unique", "check", "constraint", "foreign", "exclude", "like"]);
12
+ const COLUMN_LINE = /^([a-z_][a-z0-9_]*)\s+\S/;
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;
15
+ const INDEX_NAME = /\bindex\("([a-z_]+)"\)/g;
16
+ // Columns are matched by shape — every column in this schema is snake_case.
17
+ const SNAKE = /\b([a-z][a-z0-9]*_[a-z0-9_]+)\b/g;
18
+ // Tables are matched by position instead. A single-word table name is
19
+ // indistinguishable from a keyword by shape, and a stop-list of keywords is the
20
+ // same trap as a list of column types: the one it misses blocks a unit.
21
+ const TABLE_POSITION = /\b(?:from|join|into|update)\s+([a-z][a-z0-9_]*)/g;
22
+ /** The few words that legally stand where a table would: `do update set`, `join lateral (`. */
23
+ const NOT_A_TABLE = new Set(["set", "lateral", "only", "select"]);
24
+ /** Names a statement binds for itself: a common table expression, or an alias. */
25
+ const LOCAL_BINDING = /(?:\bwith\s+(?:recursive\s+)?|,\s*)([a-z][a-z0-9_]*)\s+as\s*\(|\bas\s+([a-z][a-z0-9_]*)\b/g;
26
+
27
+ /** Functions and reserved names a statement may use that no table declares. */
28
+ export const SQL_BUILTINS = Object.freeze([
29
+ "gen_random_uuid",
30
+ "current_setting",
31
+ "set_config",
32
+ "pg_advisory_lock",
33
+ "pg_advisory_unlock",
34
+ "row_number",
35
+ "string_agg",
36
+ "array_agg",
37
+ "jsonb_build_object",
38
+ "to_jsonb",
39
+ "date_trunc",
40
+ "to_char",
41
+ "to_timestamp",
42
+ "generate_series",
43
+ "array_position",
44
+ "array_length",
45
+ "char_length",
46
+ "string_to_array",
47
+ "jsonb_array_elements",
48
+ "jsonb_set",
49
+ "current_timestamp",
50
+ "current_date",
51
+ ]);
52
+
53
+ /** The text between the parenthesis at `open` and its match. */
54
+ function parens(source, open) {
55
+ let depth = 0;
56
+ for (let index = open; index < source.length; index += 1) {
57
+ if (source[index] === "(") depth += 1;
58
+ if (source[index] === ")") {
59
+ depth -= 1;
60
+ if (depth === 0) return source.slice(open + 1, index);
61
+ }
62
+ }
63
+ return source.slice(open + 1);
64
+ }
65
+
66
+ /** A constraint line declares no column, so only a name followed by a type counts. */
67
+ function addColumnLines(columns, body) {
68
+ for (const line of body.split("\n")) {
69
+ const column = COLUMN_LINE.exec(line.trim());
70
+ if (column && !CONSTRAINT_OPENER.has(column[1])) columns.add(column[1]);
71
+ }
72
+ }
73
+
74
+ /** @returns {Map<string, Set<string>>} table to its declared columns, across every migration. */
75
+ export function declaredColumns(sources) {
76
+ const tables = new Map();
77
+ for (const sql of sources) {
78
+ CREATE_TABLE.lastIndex = 0;
79
+ let match = CREATE_TABLE.exec(sql);
80
+ while (match !== null) {
81
+ const columns = tables.get(match[1]) ?? new Set();
82
+ addColumnLines(columns, parens(sql, match.index + match[0].length - 1));
83
+ tables.set(match[1], columns);
84
+ match = CREATE_TABLE.exec(sql);
85
+ }
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
+ }
94
+ }
95
+ return tables;
96
+ }
97
+
98
+ /**
99
+ * Quoted literals are stripped first: a rank name inside a statement is a value,
100
+ * not a column.
101
+ *
102
+ * A statement may be excused from the tenant predicate, but only out loud. The
103
+ * marker sits directly above the statement, carries its reason, and is counted
104
+ * and printed — an exemption is a thing a reviewer sees, not a thing a regex is
105
+ * talked around. The one honest case so far is a share resolved by its secret,
106
+ * where the tenant is what the lookup returns rather than what it filters on.
107
+ */
108
+ const EXEMPT = /\/\/\s*tenant-predicate:\s*exempt\s*—\s*(.+)/;
109
+ // A migration file is `<sequence>_<slug>.sql`; the slug names the feature that owns it.
110
+ const MIGRATION_FILE = /^\d+_(.+)\.sql$/;
111
+
112
+ function statements(source) {
113
+ const found = [];
114
+ for (const match of source.matchAll(/`([^`]*)`/g)) {
115
+ const body = match[1];
116
+ if (!/\b(select|insert into|update|delete from)\b/i.test(body)) continue;
117
+ const preamble = source.slice(Math.max(0, match.index - 400), match.index);
118
+ const lastLines = preamble.split("\n").slice(-4).join("\n");
119
+ found.push({
120
+ sql: body.replace(/'[^']*'/g, "''").replace(/"[^"]*"/g, '""'),
121
+ exemption: EXEMPT.exec(lastLines)?.[1]?.trim() ?? null,
122
+ });
123
+ }
124
+ return found;
125
+ }
126
+
127
+ /** Names a statement binds for itself, so they are not references to a table. */
128
+ function boundIn(statement) {
129
+ const bound = new Set();
130
+ LOCAL_BINDING.lastIndex = 0;
131
+ let binding = LOCAL_BINDING.exec(statement);
132
+ while (binding !== null) {
133
+ bound.add(binding[1] ?? binding[2]);
134
+ binding = LOCAL_BINDING.exec(statement);
135
+ }
136
+ return bound;
137
+ }
138
+
139
+ /** Each statement a resource issues, with the names it binds for itself. */
140
+ export function sqlStatements(source) {
141
+ return statements(source).map(({ sql, exemption }) => ({ sql, bound: boundIn(sql), exemption }));
142
+ }
143
+
144
+ /** Every name a resource's SQL leans on, split by how it was recognised. */
145
+ export function usedIdentifiers(source) {
146
+ const used = new Set();
147
+ const tables = new Set();
148
+ const bound = new Set();
149
+ for (const { sql: statement } of statements(source)) {
150
+ for (const name of boundIn(statement)) bound.add(name);
151
+ SNAKE.lastIndex = 0;
152
+ let match = SNAKE.exec(statement);
153
+ while (match !== null) {
154
+ used.add(match[1]);
155
+ match = SNAKE.exec(statement);
156
+ }
157
+ TABLE_POSITION.lastIndex = 0;
158
+ let table = TABLE_POSITION.exec(statement);
159
+ while (table !== null) {
160
+ if (!NOT_A_TABLE.has(table[1])) tables.add(table[1]);
161
+ table = TABLE_POSITION.exec(statement);
162
+ }
163
+ }
164
+ for (const name of bound) {
165
+ used.delete(name);
166
+ tables.delete(name);
167
+ }
168
+ const declaredIndexes = new Set();
169
+ INDEX_NAME.lastIndex = 0;
170
+ let index = INDEX_NAME.exec(source);
171
+ while (index !== null) {
172
+ declaredIndexes.add(index[1]);
173
+ index = INDEX_NAME.exec(source);
174
+ }
175
+ return { used, tables, declaredIndexes, bound };
176
+ }
177
+
178
+ /**
179
+ * A migration is named for the feature that owns it, so the table it declares has
180
+ * an owner. A feature reading another feature's table is the boundary rule broken
181
+ * in SQL, where `qc/no-cross-feature-internals` cannot see it: there is no import
182
+ * to flag. The answer is the other feature's published surface — ADR-0047.
183
+ *
184
+ * A feature may own more than one migration, so the slug is matched against the
185
+ * features that exist rather than required to equal one: `0006_blueprints` and
186
+ * `0006_blueprints_render_pages` both belong to `blueprints`. Requiring equality
187
+ * once forced a unit to rename its file to get past this — the gate bent the
188
+ * work instead of checking it.
189
+ *
190
+ * @param {{file: string, sql: string}[]} migrations
191
+ * @param {Iterable<string>} [features] feature directory names, longest match wins
192
+ * @returns {Map<string, string>} table to the feature whose migration declares it
193
+ */
194
+ export function tableOwners(migrations, features = []) {
195
+ const known = [...features].sort((a, b) => b.length - a.length);
196
+ const owners = new Map();
197
+ for (const { file, sql } of migrations) {
198
+ const named = MIGRATION_FILE.exec(file);
199
+ const slug = named ? named[1].replace(/_/g, "-") : file;
200
+ const owner = known.find((feature) => slug === feature || slug.startsWith(`${feature}-`)) ?? slug;
201
+ for (const table of declaredColumns([sql]).keys()) {
202
+ owners.set(table, owner);
203
+ }
204
+ }
205
+ return owners;
206
+ }
207
+
208
+ /**
209
+ * @param {Map<string, Set<string>>} tables
210
+ * @param {{path: string, source: string, feature?: string}[]} resources
211
+ * @param {Map<string, string>} [owners]
212
+ * @returns {{path: string, rule: string, detail: string}[]}
213
+ */
214
+ export function checkSqlIdentifiers(tables, resources, owners = new Map()) {
215
+ const known = new Set(SQL_BUILTINS);
216
+ for (const [table, columns] of tables) {
217
+ known.add(table);
218
+ for (const column of columns) known.add(column);
219
+ }
220
+ const problems = [];
221
+ for (const { path, source, feature } of resources) {
222
+ const { used, tables: named, declaredIndexes } = usedIdentifiers(source);
223
+ for (const identifier of [...new Set([...used, ...named])].sort()) {
224
+ if (declaredIndexes.has(identifier)) continue;
225
+ if (!known.has(identifier)) {
226
+ problems.push({
227
+ path,
228
+ rule: "undeclared-sql-identifier",
229
+ detail: `'${identifier}' is named in SQL but no migration declares it`,
230
+ });
231
+ continue;
232
+ }
233
+ const owner = owners.get(identifier);
234
+ if (feature && owner && owner !== feature) {
235
+ problems.push({
236
+ path,
237
+ rule: "cross-feature-table",
238
+ detail: `'${identifier}' belongs to feature '${owner}'. Ask for its published surface, not its table`,
239
+ });
240
+ }
241
+ }
242
+ }
243
+ return problems;
244
+ }