architecture-harness 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
package/src/cli/check.mjs CHANGED
@@ -7,12 +7,15 @@ import { checkFeatureAnatomy, checkNoEmptyBlock } from "../gates/eight-blocks.mj
7
7
  import { checkCitations, checkDocPaths, checkSelfContained, definedIds } from "../gates/citations.mjs";
8
8
  import { checkAgreement, declaredValues } from "../gates/registry-agreement.mjs";
9
9
  import {
10
+ checkSchemaInMigrations,
10
11
  checkSqlIdentifiers,
11
12
  declaredColumns,
13
+ migrationNames,
14
+ schemaTables,
12
15
  sqlStatements,
13
16
  tableOwners,
14
17
  } from "../gates/sql-identifiers.mjs";
15
- import { checkSharedInsertCallSites, checkTenantPredicate, exemptions } from "../gates/tenant-predicate.mjs";
18
+ import { checkExemptHelperCalls, checkTenantPredicate, exemptHelperCalls, exemptions } from "../gates/tenant-predicate.mjs";
16
19
  import { checkClaimedRequirements } from "../gates/claimed-requirements.mjs";
17
20
  import { allowedPublicRoutes, checkPublicRoutes, declaredPublicRoutes } from "../gates/public-routes.mjs";
18
21
  import { calledInternalRoutes, checkInternalRoutes, declaredInternalRoutes } from "../gates/internal-routes.mjs";
@@ -35,6 +38,10 @@ import { checkRegistryReaders } from "../gates/registry-readers.mjs";
35
38
  import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
36
39
  import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
37
40
  import { checkThresholdRatchet } from "../gates/threshold-ratchet.mjs";
41
+ import { checkParity, placeholderSlices } from "../gates/parity.mjs";
42
+ import { checkIntegrationImports } from "../gates/integration-imports.mjs";
43
+ import { checkClosedSetWriters, matchedKeys } from "../gates/closed-set-writers.mjs";
44
+ import { checkDocClaims, parseDocClaims } from "../gates/doc-claims.mjs";
38
45
  import { ratchetInputs } from "./registry-history.mjs";
39
46
  import { repoFiles } from "./repo-files.mjs";
40
47
 
@@ -257,7 +264,7 @@ async function resourceFiles(config, tree) {
257
264
  }
258
265
 
259
266
  /** Nothing runs the schema and the queries together, so this asserts their names agree. */
260
- async function sqlAgreement(config, tree, taken) {
267
+ async function sqlAgreement(config, tree, taken, lines) {
261
268
  const migrationDir = posix(config.paths.migrations);
262
269
  const migrations = await readEach(
263
270
  config.root,
@@ -287,12 +294,30 @@ async function sqlAgreement(config, tree, taken) {
287
294
  if (enabled(config.gates, "sql-identifiers")) {
288
295
  const byName = migrations.map((migration) => ({ file: path.posix.basename(migration.path), sql: migration.contents }));
289
296
  problems.push(...checkSqlIdentifiers(tables, resources, tableOwners(byName, features)));
297
+ const declared = [];
298
+ // With no migration yet there is no ledger to compare with, as with any path that does not exist.
299
+ for (const feature of migrations.length > 0 ? features : []) {
300
+ const rel = `${join(posix(config.paths.serverFeatures), feature)}/${config.paths.schemaFile}`;
301
+ const source = tree.isFile(rel) ? await read(path.join(config.root, rel)) : null;
302
+ if (source === null) continue;
303
+ for (const entry of schemaTables(source, { tableFactory: config.tenant.tableFactory })) declared.push({ path: rel, ...entry });
304
+ }
305
+ problems.push(...checkSchemaInMigrations(declared, migrationNames(migrations.map((migration) => migration.contents))));
306
+ const columns = declared.reduce((sum, entry) => sum + entry.columns.length, 0);
307
+ if (declared.length > 0) lines.push(`OK schema ${declared.length} table(s), ${columns} column(s) in schema files, each named by a migration`);
290
308
  }
291
309
  if (enabled(config.gates, "tenant-predicate")) {
310
+ const helpers = config.tenantPredicate.exemptHelpers;
311
+ const callers = (await sourceFiles(config, tree)).filter(
312
+ (file) => !TEST_FILE.test(file.path) && helpers.some((helper) => file.contents.includes(helper.name)),
313
+ );
314
+ const helperOptions = { column: config.tenant.sqlColumn, identifier: config.tenant.column };
292
315
  problems.push(
293
316
  ...checkTenantPredicate(scoped, owned, tenantOptions),
294
- ...checkSharedInsertCallSites(resources, tenantOptions),
317
+ ...checkExemptHelperCalls(callers, helpers, helperOptions),
295
318
  );
319
+ const calls = exemptHelperCalls(callers, helpers, helperOptions).length;
320
+ if (calls > 0) lines.push(`OK helpers ${calls} call(s) of ${helpers.length} exempt helper(s), each naming the tenant`);
296
321
  }
297
322
  return problems;
298
323
  }
@@ -363,6 +388,83 @@ function infraFiles(config, tree) {
363
388
  return readEach(config.root, rels);
364
389
  }
365
390
 
391
+ const SLICE_FILE = /\.[jt]sx?$/;
392
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
393
+
394
+ /** Both surfaces, feature by feature, and every slice file either one holds. */
395
+ async function parityAgreement(config, tree) {
396
+ const { sliceDir } = config.anatomy.slice;
397
+ const server = posix(config.paths.serverFeatures);
398
+ const client = posix(config.paths.frontendFeatures);
399
+ const sliceFiles = [];
400
+ const slicesOf = (dir) => {
401
+ const folder = `${dir}/${sliceDir}`;
402
+ const names = tree
403
+ .namesIn(folder)
404
+ .filter((name) => SLICE_FILE.test(name) && !TEST_FILE.test(name) && tree.isFile(`${folder}/${name}`));
405
+ sliceFiles.push(...names.map((name) => `${folder}/${name}`));
406
+ return [...new Set(names.map((name) => name.replace(SLICE_FILE, "")))];
407
+ };
408
+ const routeImport = new RegExp(`from\\s+["']\\./${escapeRegex(sliceDir)}/([^"']+)\\.[cm]?[jt]sx?["']`, "g");
409
+ const serverSide = [];
410
+ for (const name of tree.foldersIn(server).sort()) {
411
+ const dir = join(server, name);
412
+ const trigger = (await read(path.join(config.root, dir, config.paths.triggerFile))) ?? "";
413
+ serverSide.push({ name, slices: slicesOf(dir), routes: [...trigger.matchAll(routeImport)].map((match) => match[1]) });
414
+ }
415
+ const clientSide = tree.foldersIn(client).sort().map((name) => ({ name, slices: slicesOf(join(client, name)) }));
416
+ const registry = parsedJson(await read(path.join(config.root, config.parity.registry))) ?? {};
417
+ const roots = { server, client, registry: config.parity.registry, trigger: config.paths.triggerFile };
418
+ return {
419
+ problems: [
420
+ ...checkParity({ server: serverSide, client: clientSide, registry }, roots),
421
+ ...placeholderSlices(await readEach(config.root, sliceFiles)),
422
+ ],
423
+ paired: serverSide.filter(({ name }) => clientSide.some((feature) => feature.name === name)).length,
424
+ };
425
+ }
426
+
427
+ /** Every file under the configured roots that the integration subject pattern matches. */
428
+ function integrationSubjects(config, tree) {
429
+ const { roots, subject } = config.integrationImports;
430
+ const pattern = new RegExp(subject);
431
+ const skip = prunedBy(/(?:^|\/)(?:node_modules|dist|\.[^/]+)$/);
432
+ const rels = new Set(roots.flatMap((root) => tree.under(root)).filter((file) => pattern.test(file) && !skip(file)));
433
+ return readEach(config.root, [...rels].sort());
434
+ }
435
+
436
+ /** Each closed set against the keys its writers write. */
437
+ async function closedSets(config, tree, lines) {
438
+ const problems = [];
439
+ for (const set of config.closedSetWriters.sets) {
440
+ const declared = matchedKeys((await read(path.join(config.root, set.source))) ?? "", set.key);
441
+ const rels = (set.roots ?? []).flatMap((root) => tree.under(root)).filter((file) => SOURCE_EXTENSION.test(file) && !SKIP.test(`/${file}`));
442
+ const written = new Set();
443
+ for (const file of await readEach(config.root, rels)) {
444
+ for (const key of matchedKeys(file.contents, set.writer)) written.add(key);
445
+ }
446
+ problems.push(...checkClosedSetWriters(declared, written, set));
447
+ const waiting = Object.keys(set.declaredAhead ?? {}).length;
448
+ lines.push(`OK closed set ${set.name}: ${written.size} of ${declared.length} key(s) written, ${waiting} waiting for a mutation`);
449
+ }
450
+ return problems;
451
+ }
452
+
453
+ /** Every state-claim block in the configured documents, against the file it counts. */
454
+ async function docClaims(config, lines) {
455
+ const problems = [];
456
+ for (const doc of config.docClaims.files) {
457
+ const contents = await read(path.join(config.root, doc));
458
+ if (contents === null) continue;
459
+ const claims = parseDocClaims(contents);
460
+ const targets = new Map();
461
+ for (const claim of claims) targets.set(claim.file, await read(path.join(config.root, claim.file)));
462
+ problems.push(...checkDocClaims(doc, claims, targets));
463
+ lines.push(`OK doc claims ${claims.length} claim(s) in ${doc}, each still true`);
464
+ }
465
+ return problems;
466
+ }
467
+
366
468
  /**
367
469
  * @param {object} config
368
470
  * @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
@@ -497,8 +599,8 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
497
599
  }
498
600
 
499
601
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
500
- problems.push(...(await sqlAgreement(config, tree, taken)));
501
- lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
602
+ lines.push("OK sql every column is declared, every statement and every exempt helper's caller carries the tenant");
603
+ problems.push(...(await sqlAgreement(config, tree, taken, lines)));
502
604
  // An exemption is counted and named, so it stays a decision rather than a habit.
503
605
  for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
504
606
  }
@@ -629,5 +731,25 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
629
731
  if (docs.length > 0) lines.push(`OK decisions ${docs.length} record(s), each with its cost and its rejected alternatives`);
630
732
  }
631
733
 
734
+ if (enabled(config.gates, "parity")) {
735
+ const parity = await parityAgreement(config, tree);
736
+ problems.push(...parity.problems);
737
+ lines.push(`OK parity ${parity.paired} feature(s) on both surfaces, every divergence named, no no-op slice`);
738
+ }
739
+
740
+ if (enabled(config.gates, "integration-imports")) {
741
+ const subjects = await integrationSubjects(config, tree);
742
+ problems.push(...checkIntegrationImports(subjects, config.integrationImports));
743
+ lines.push(`OK integration ${subjects.length} integration test(s), each importing the product it integrates with`);
744
+ }
745
+
746
+ if (enabled(config.gates, "closed-set-writers")) {
747
+ problems.push(...(await closedSets(config, tree, lines)));
748
+ }
749
+
750
+ if (enabled(config.gates, "doc-claims")) {
751
+ problems.push(...(await docClaims(config, lines)));
752
+ }
753
+
632
754
  return { problems, lines };
633
755
  }
package/src/config.mjs CHANGED
@@ -80,6 +80,8 @@ export const defaults = {
80
80
  // Files inside a feature that carry SQL.
81
81
  resourceFiles: ["resource.ts", "schema.ts"],
82
82
  resourceDirs: ["shared", "slices"],
83
+ // The file in each server feature whose tables and columns every migration set must name.
84
+ schemaFile: "schema.ts",
83
85
  triggerFile: "trigger.ts",
84
86
  // Platform and frontend features paths for boundary checks.
85
87
  platform: "frontend/src/platform",
@@ -257,6 +259,36 @@ export const defaults = {
257
259
  // Files a person reviewed that may call sql.raw. Each one is a decision, so the list stays short.
258
260
  sqlRaw: { allow: [] },
259
261
 
262
+ // The registry names each divergence of the two surfaces with its reason: `backendOnlyFeatures`,
263
+ // `frontendOnlyFeatures`, and `slices` by feature. The surfaces are `paths.serverFeatures` and
264
+ // `paths.frontendFeatures`.
265
+ parity: { registry: "contracts/parity.json" },
266
+
267
+ // A test that `subject` matches imports a module under a product root or a product package.
268
+ // `productPackages` are patterns; the kernel every test may hold is not one of them.
269
+ integrationImports: {
270
+ roots: ["packages", "backend", "bff", "frontend", "workers"],
271
+ subject: "\\.(interop|live)\\.test\\.ts$",
272
+ productRoots: ["backend", "bff", "frontend", "workers"],
273
+ productPackages: [],
274
+ },
275
+
276
+ // Each set: `source` declares the keys, `key` and `writer` are patterns whose first group is a key,
277
+ // `roots` hold the writers, and `declaredAhead` maps a key with no writer yet to its reason.
278
+ closedSetWriters: { sets: [] },
279
+
280
+ // Documents that hold fenced `state-claim` blocks, each a file and its line count.
281
+ docClaims: { files: ["STATE.md"] },
282
+
283
+ // A helper exempt from the statement scan because its caller supplies the table or the columns.
284
+ // Each call names the tenant in the argument at index `argument`, so its callers are checked instead.
285
+ tenantPredicate: {
286
+ exemptHelpers: [
287
+ { module: "backend/src/application/sql/crud.ts", name: "insertReturning", argument: 2 },
288
+ { module: "backend/src/application/sql/crud.ts", name: "updateVersionedRow", argument: 3 },
289
+ ],
290
+ },
291
+
260
292
  anatomy: {
261
293
  // Bounded vertical slices.
262
294
  slice: {
@@ -304,6 +336,12 @@ export const defaults = {
304
336
  "english-source": false,
305
337
  "adr-format": false,
306
338
  "feature-cli": false,
339
+ // Each reads inputs only a repository can name: its registry, its product roots, its closed
340
+ // sets, its claims. Shipped on, each would also red a consumer's enforcement map on upgrade.
341
+ parity: false,
342
+ "integration-imports": false,
343
+ "closed-set-writers": false,
344
+ "doc-claims": false,
307
345
  },
308
346
 
309
347
  // Gates that produce rather than inspect: a repository's codegen imports these and
@@ -25,6 +25,10 @@ export const gateDescriptions = Object.freeze({
25
25
  "english-source": "Comments, docs and rules are English; another language is data, declared beside its English variant",
26
26
  "adr-format": "Every decision record carries its cost and the alternatives it rejected, not just its claim",
27
27
  "comment-style": "A comment under infra/ is one line of why, never a paragraph, a banner or code",
28
+ parity: "Every server slice has a client slice of its name and the reverse, a divergence is registered, and no slice is a no-op",
29
+ "integration-imports": "An integration test imports the product it integrates with",
30
+ "closed-set-writers": "Every key of a closed set has a writer, and every writer writes a key of the set",
31
+ "doc-claims": "A state-claim block in a document still matches the file it counts",
28
32
  });
29
33
 
30
34
  /** The gates a consumer can switch on, so a caller need not import the defaults to find out. */
@@ -0,0 +1,36 @@
1
+ // A closed set is a value, and no type asks whether a declared key is ever written. So a key
2
+ // either has a writer or names the mutation it waits for, and the waiting list can only shrink.
3
+
4
+ /** The first group of each match of `pattern` in `source`. */
5
+ export function matchedKeys(source, pattern) {
6
+ return [...source.matchAll(new RegExp(pattern, "g"))].map((match) => match[1]);
7
+ }
8
+
9
+ /**
10
+ * @param {string[]} declared the keys the set's source declares
11
+ * @param {Set<string>} written the keys some writer writes
12
+ * @param {{name: string, source: string, declaredAhead?: Record<string, string>}} set
13
+ * @returns {{path: string, rule: string, detail: string}[]}
14
+ */
15
+ export function checkClosedSetWriters(declared, written, set) {
16
+ const ahead = set.declaredAhead ?? {};
17
+ const path = set.source;
18
+ const problems = [];
19
+ const push = (rule, detail) => problems.push({ path, rule, detail });
20
+ if (declared.length === 0) {
21
+ push("empty-closed-set", `${set.name}: the source declares no key, so this set checks nothing`);
22
+ return problems;
23
+ }
24
+ for (const key of declared) {
25
+ if (written.has(key) || key in ahead) continue;
26
+ push("unwritten-key", `${key} is declared in ${set.name}, never written, and not listed as waiting for a mutation`);
27
+ }
28
+ for (const key of Object.keys(ahead)) {
29
+ if (!declared.includes(key)) push("stale-declared-ahead", `${key} is listed as waiting but is no longer in ${set.name} — delete the entry`);
30
+ if (written.has(key)) push("stale-declared-ahead", `${key} is listed as waiting but something writes it now — delete the entry`);
31
+ }
32
+ for (const key of written) {
33
+ if (!declared.includes(key)) push("undeclared-write", `${key} is written but not declared in ${set.name}`);
34
+ }
35
+ return problems;
36
+ }
@@ -0,0 +1,46 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkClosedSetWriters, matchedKeys } from "./closed-set-writers.mjs";
4
+
5
+ const set = {
6
+ name: "AUDIT_ACTIONS",
7
+ source: "audit/types.ts",
8
+ key: '\\{ key: "([a-z_.]+)", category:',
9
+ writer: 'record\\([\\s\\S]{0,400}?action: "([a-z_.]+)"',
10
+ declaredAhead: { "role.rename": "roles are fixed" },
11
+ };
12
+
13
+ const declared = matchedKeys('[{ key: "pin.create", category: "pin" }, { key: "role.rename", category: "role" }]', set.key);
14
+
15
+ test("a key and its writer are read by the configured patterns", () => {
16
+ assert.deepEqual(declared, ["pin.create", "role.rename"]);
17
+ assert.deepEqual(matchedKeys('await record(tx, {\n action: "pin.create",\n});', set.writer), ["pin.create"]);
18
+ });
19
+
20
+ test("every key written, or waiting with its reason, passes", () => {
21
+ assert.deepEqual(checkClosedSetWriters(declared, new Set(["pin.create"]), set), []);
22
+ });
23
+
24
+ test("a key with no writer and no reason fails", () => {
25
+ const problems = checkClosedSetWriters(declared, new Set(), set);
26
+ assert.deepEqual(problems.map((problem) => problem.rule), ["unwritten-key"]);
27
+ assert.equal(problems[0].path, "audit/types.ts");
28
+ assert.match(problems[0].detail, /pin\.create is declared in AUDIT_ACTIONS/);
29
+ });
30
+
31
+ test("a waiting entry that is written now, or no longer declared, fails", () => {
32
+ const written = checkClosedSetWriters(declared, new Set(["pin.create", "role.rename"]), set);
33
+ assert.deepEqual(written.map((problem) => problem.rule), ["stale-declared-ahead"]);
34
+ const gone = checkClosedSetWriters(["pin.create"], new Set(["pin.create"]), set);
35
+ assert.deepEqual(gone.map((problem) => problem.rule), ["stale-declared-ahead"]);
36
+ });
37
+
38
+ test("a writer that writes a key outside the set fails", () => {
39
+ const problems = checkClosedSetWriters(declared, new Set(["pin.create", "pin.explode"]), set);
40
+ assert.deepEqual(problems.map((problem) => problem.rule), ["undeclared-write"]);
41
+ });
42
+
43
+ test("a set whose source declares no key fails, since it checks nothing", () => {
44
+ const problems = checkClosedSetWriters([], new Set(), { ...set, declaredAhead: {} });
45
+ assert.deepEqual(problems.map((problem) => problem.rule), ["empty-closed-set"]);
46
+ });
@@ -0,0 +1,45 @@
1
+ // A true claim in a document can go stale and still read as current. A fenced state-claim
2
+ // block pairs a file with its line count, so the claim is checked instead of trusted.
3
+
4
+ const CLAIM_BLOCK = /```state-claim\r?\n([\s\S]*?)```/g;
5
+
6
+ /** @returns {{file: string, lines: number}[]} each block that names both a file and a count */
7
+ export function parseDocClaims(contents) {
8
+ const claims = [];
9
+ for (const [, block] of contents.matchAll(CLAIM_BLOCK)) {
10
+ const file = /file:\s*(\S+)/.exec(block)?.[1];
11
+ const lines = /lines:\s*(\d+)/.exec(block)?.[1];
12
+ if (file && lines) claims.push({ file, lines: Number(lines) });
13
+ }
14
+ return claims;
15
+ }
16
+
17
+ /** Newline-terminated lines, as `wc -l` counts them, with CRLF read as LF. */
18
+ export function lineCount(contents) {
19
+ const normalized = contents.replace(/\r\n/g, "\n");
20
+ const parts = normalized.split("\n");
21
+ return normalized.endsWith("\n") ? parts.length - 1 : parts.length;
22
+ }
23
+
24
+ /**
25
+ * @param {string} doc the document that makes the claims
26
+ * @param {{file: string, lines: number}[]} claims
27
+ * @param {Map<string, string | null>} targets each claimed file's contents, null when it is missing
28
+ * @returns {{path: string, rule: string, detail: string}[]}
29
+ */
30
+ export function checkDocClaims(doc, claims, targets) {
31
+ const problems = [];
32
+ for (const claim of claims) {
33
+ const contents = targets.get(claim.file) ?? null;
34
+ const actual = contents === null ? null : lineCount(contents);
35
+ if (actual === claim.lines) continue;
36
+ problems.push({
37
+ path: claim.file,
38
+ rule: "stale-doc-claim",
39
+ detail: actual === null
40
+ ? `${doc} claims ${claim.lines} lines; the file no longer exists`
41
+ : `${doc} claims ${claim.lines} lines; the file now has ${actual}`,
42
+ });
43
+ }
44
+ return problems;
45
+ }
@@ -0,0 +1,33 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkDocClaims, lineCount, parseDocClaims } from "./doc-claims.mjs";
4
+
5
+ const doc = "# State\n\n```state-claim\nfile: src/big.ts\nlines: 3\n```\n\n```state-claim\r\nfile: src/gone.ts\r\nlines: 9\r\n```\n";
6
+
7
+ test("each fenced block yields its file and line count, and a block missing one is skipped", () => {
8
+ assert.deepEqual(parseDocClaims(doc), [{ file: "src/big.ts", lines: 3 }, { file: "src/gone.ts", lines: 9 }]);
9
+ assert.deepEqual(parseDocClaims("```state-claim\nfile: a.ts\n```\n"), []);
10
+ });
11
+
12
+ test("lines are counted the way wc -l counts them, for LF and CRLF alike", () => {
13
+ assert.equal(lineCount("a\nb\nc\n"), 3);
14
+ assert.equal(lineCount("a\r\nb\r\nc\r\n"), 3);
15
+ assert.equal(lineCount("a\nb\nc"), 3);
16
+ });
17
+
18
+ test("a claim that is still true passes", () => {
19
+ const found = checkDocClaims("STATE.md", [{ file: "src/big.ts", lines: 3 }], new Map([["src/big.ts", "1\n2\n3\n"]]));
20
+ assert.deepEqual(found, []);
21
+ });
22
+
23
+ test("a claim whose count changed, or whose file is gone, fails", () => {
24
+ const found = checkDocClaims(
25
+ "STATE.md",
26
+ parseDocClaims(doc),
27
+ new Map([["src/big.ts", "1\n2\n3\n4\n"], ["src/gone.ts", null]]),
28
+ );
29
+ assert.deepEqual(found.map((problem) => problem.rule), ["stale-doc-claim", "stale-doc-claim"]);
30
+ assert.equal(found[0].path, "src/big.ts");
31
+ assert.equal(found[0].detail, "STATE.md claims 3 lines; the file now has 4");
32
+ assert.equal(found[1].detail, "STATE.md claims 9 lines; the file no longer exists");
33
+ });
@@ -0,0 +1,49 @@
1
+ // A test named for integration has to reach the thing it integrates with. One that imports
2
+ // only a test runner and the kernel builds its own subject and asserts about it, so it passes
3
+ // for every failure a user would meet.
4
+
5
+ /** Each `import ... from "<specifier>"`, so a name in a comment or a string is not one. */
6
+ const IMPORT_SPECIFIER = /^\s*import\s[\s\S]*?from\s+"([^"]+)"/gm;
7
+
8
+ /**
9
+ * A test inside a product root reaches its neighbours with `./`, so any relative import counts.
10
+ * One outside has to name the product root it climbs into, or import a product package.
11
+ * @param {string} source
12
+ * @param {string} file the repository-relative path
13
+ * @param {{productRoots: string[], productPackages: string[]}} options
14
+ * @returns {number}
15
+ */
16
+ export function productImportCount(source, file, { productRoots, productPackages }) {
17
+ const inProduct = productRoots.some((root) => file.startsWith(`${root}/`));
18
+ const productPackage = productPackages.length > 0 ? new RegExp(productPackages.join("|")) : null;
19
+ let count = 0;
20
+ for (const [, specifier] of source.matchAll(IMPORT_SPECIFIER)) {
21
+ if (productPackage?.test(specifier)) count += 1;
22
+ else if (!specifier.startsWith(".")) continue;
23
+ else if (inProduct) count += 1;
24
+ else if (productRoots.some((root) => specifier.split("/").includes(root))) count += 1;
25
+ }
26
+ return count;
27
+ }
28
+
29
+ /**
30
+ * @param {{path: string, contents: string}[]} subjects every file the subject pattern matched
31
+ * @param {{productRoots: string[], productPackages: string[]}} options
32
+ * @returns {{path: string, rule: string, detail: string}[]}
33
+ */
34
+ export function checkIntegrationImports(subjects, options) {
35
+ if (subjects.length === 0) {
36
+ return [{
37
+ path: "qc.config.json",
38
+ rule: "no-integration-tests",
39
+ detail: "no file matches integrationImports.subject, so this gate is checking nothing",
40
+ }];
41
+ }
42
+ return subjects
43
+ .filter(({ path, contents }) => productImportCount(contents, path, options) === 0)
44
+ .map(({ path }) => ({
45
+ path,
46
+ rule: "integration-without-product",
47
+ detail: "imports no product module, so it can only assert about subjects it declares itself",
48
+ }));
49
+ }
@@ -0,0 +1,35 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkIntegrationImports, productImportCount } from "./integration-imports.mjs";
4
+
5
+ const options = { productRoots: ["backend", "frontend"], productPackages: ["^@app/(?:domain|contracts)(?:/|$)"] };
6
+
7
+ test("an integration test that imports only the runner and the kernel fails", () => {
8
+ const contents = 'import { test } from "vitest";\nimport { ok } from "@app/kernel";\ntest("x", () => {});\n';
9
+ const problems = checkIntegrationImports([{ path: "packages/journeys/src/flow.interop.test.ts", contents }], options);
10
+ assert.equal(problems.length, 1);
11
+ assert.equal(problems[0].rule, "integration-without-product");
12
+ assert.equal(problems[0].path, "packages/journeys/src/flow.interop.test.ts");
13
+ });
14
+
15
+ test("a product package, a climb into a product root, or any relative import inside one counts", () => {
16
+ assert.equal(productImportCount('import { Pin } from "@app/domain/pin";', "packages/x/a.live.test.ts", options), 1);
17
+ assert.equal(productImportCount('import { app } from "../../backend/src/main.js";', "packages/x/a.live.test.ts", options), 1);
18
+ assert.equal(productImportCount('import { route } from "./route.js";', "backend/src/pins/a.live.test.ts", options), 1);
19
+ assert.equal(productImportCount('import { helper } from "./helper.js";', "packages/x/a.live.test.ts", options), 0);
20
+ });
21
+
22
+ test("a product root named in a comment or a string is not an import", () => {
23
+ const contents = '// see backend/src/main.ts\nimport { test } from "vitest";\nconst path = "@app/domain";\n';
24
+ assert.equal(checkIntegrationImports([{ path: "packages/x/a.interop.test.ts", contents }], options).length, 1);
25
+ });
26
+
27
+ test("with no integration test at all the gate says it checks nothing", () => {
28
+ const problems = checkIntegrationImports([], options);
29
+ assert.deepEqual(problems.map((problem) => problem.rule), ["no-integration-tests"]);
30
+ });
31
+
32
+ test("a test that reaches the product passes", () => {
33
+ const contents = 'import { test } from "vitest";\nimport { createPin } from "@app/domain";\n';
34
+ assert.deepEqual(checkIntegrationImports([{ path: "packages/x/a.interop.test.ts", contents }], options), []);
35
+ });
@@ -0,0 +1,163 @@
1
+ // The two surfaces carry one architecture: a feature exists on both under one name, and a
2
+ // server slice has a client slice of the same stem. A divergence is legal only when the
3
+ // registry names it with its reason, and an entry that stops being true fails like a gap.
4
+ // A slice that only exists to satisfy this pairing is refused too, or the pairing proves nothing.
5
+
6
+ /**
7
+ * @param {{
8
+ * server: {name: string, slices: string[], routes: string[]}[],
9
+ * client: {name: string, slices: string[]}[],
10
+ * registry: {backendOnlyFeatures?: {name: string}[], frontendOnlyFeatures?: {name: string}[], slices?: Record<string, {stem: string, why?: string}[]>},
11
+ * }} surfaces
12
+ * @param {{server: string, client: string, registry: string, trigger?: string}} roots
13
+ * @returns {{path: string, rule: string, detail: string}[]}
14
+ */
15
+ export function checkParity({ server, client, registry }, roots) {
16
+ const where = roots.registry;
17
+ const trigger = roots.trigger ?? "trigger.ts";
18
+ const backend = server.map((feature) => feature.name);
19
+ const frontend = client.map((feature) => feature.name);
20
+ const backendOnly = new Set((registry.backendOnlyFeatures ?? []).map((entry) => entry.name));
21
+ const frontendOnly = new Set((registry.frontendOnlyFeatures ?? []).map((entry) => entry.name));
22
+ const problems = [];
23
+ const push = (path, rule, detail) => problems.push({ path, rule, detail });
24
+
25
+ for (const name of backend) {
26
+ if (frontend.includes(name) || backendOnly.has(name)) continue;
27
+ push(`${roots.server}/${name}`, "one-sided-feature", `${name}: served by the api with no client feature, and not named in ${where}`);
28
+ }
29
+ for (const name of frontend) {
30
+ if (backend.includes(name) || frontendOnly.has(name)) continue;
31
+ push(`${roots.client}/${name}`, "one-sided-feature", `${name}: a client feature the api does not serve, and not named in ${where}`);
32
+ }
33
+ for (const name of [...backendOnly, ...frontendOnly]) {
34
+ if (backend.includes(name) && frontend.includes(name)) {
35
+ push(where, "stale-divergence", `${name}: listed as one-sided in ${where}, but both surfaces have it — delete the entry`);
36
+ }
37
+ }
38
+
39
+ const drawnBy = new Map(client.map((feature) => [feature.name, new Set(feature.slices)]));
40
+ for (const feature of server.filter(({ name }) => drawnBy.has(name))) {
41
+ const { name } = feature;
42
+ const served = new Set(feature.slices);
43
+ const drawn = drawnBy.get(name);
44
+ const routes = [...new Set(feature.routes)].sort();
45
+ const excuses = new Map((registry.slices?.[name] ?? []).map((entry) => [entry.stem, entry.why ?? ""]));
46
+ const serverPath = `${roots.server}/${name}`;
47
+ const clientPath = `${roots.client}/${name}`;
48
+
49
+ for (const stem of routes) {
50
+ if (!served.has(stem)) push(serverPath, "one-sided-slice", `${name}/${stem}: route in ${trigger} has no backend slice implementation`);
51
+ }
52
+ for (const stem of routes) {
53
+ if (!drawn.has(stem) && !excuses.has(stem)) push(clientPath, "one-sided-slice", `${name}/${stem}: backend route has no frontend slice`);
54
+ }
55
+ for (const stem of [...served].sort()) {
56
+ if (drawn.has(stem) || excuses.has(stem)) continue;
57
+ push(clientPath, "one-sided-slice", `${name}/${stem}: a backend slice with no frontend slice of that name`);
58
+ }
59
+ for (const stem of [...drawn].sort()) {
60
+ if (served.has(stem) || excuses.has(stem)) continue;
61
+ push(serverPath, "one-sided-slice", `${name}/${stem}: a frontend slice with no backend slice/route of that name`);
62
+ }
63
+ for (const [stem, why] of excuses) {
64
+ const stale = (detail) => push(where, "stale-divergence", `${name}/${stem}: ${detail}`);
65
+ if (served.has(stem) && drawn.has(stem)) stale(`excused in ${where}, but both surfaces have it — delete the entry`);
66
+ else if (!served.has(stem) && !drawn.has(stem)) stale(`excused in ${where}, but neither surface has a slice of that name — delete the entry`);
67
+ else if (why.startsWith("Client-only") && !drawn.has(stem)) stale(`excused as client-only in ${where}, but no frontend slice exists`);
68
+ else if (why.startsWith("Backend-only") && !served.has(stem)) stale(`excused as backend-only in ${where}, but no backend slice exists`);
69
+ }
70
+ }
71
+ return problems;
72
+ }
73
+
74
+ // A string can hold "//" or a brace, so a comment is removed only outside a string.
75
+ const COMMENT_OR_STRING = /("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g;
76
+ const NO_OP_STATEMENT = /^(?:void 0|return|return undefined|return void 0)$/;
77
+
78
+ /** The index just past the bracket that closes the one at `open`, skipping strings. */
79
+ function closing(source, open) {
80
+ const pair = { "(": ")", "{": "}", "<": ">" }[source[open]];
81
+ let depth = 0;
82
+ for (let i = open; i < source.length; i += 1) {
83
+ const ch = source[i];
84
+ if (ch === '"' || ch === "'" || ch === "`") {
85
+ const end = source.indexOf(ch, i + 1);
86
+ if (end === -1) return source.length;
87
+ i = end;
88
+ } else if (ch === source[open]) depth += 1;
89
+ else if (ch === pair && (depth -= 1) === 0) return i + 1;
90
+ }
91
+ return source.length;
92
+ }
93
+
94
+ function isNoOpBody(body) {
95
+ return body
96
+ .split(/[;\n]/)
97
+ .map((statement) => statement.trim())
98
+ .filter(Boolean)
99
+ .every((statement) => NO_OP_STATEMENT.test(statement));
100
+ }
101
+
102
+ /** True for a function whose parameters open at `open` and whose body does nothing. */
103
+ function noOpFunctionAt(source, open, { arrow }) {
104
+ const after = source.slice(closing(source, open));
105
+ if (arrow) {
106
+ const head = /^\s*(?::[^=]*?)?=>\s*/.exec(after);
107
+ if (head === null) return false;
108
+ const rest = after.slice(head[0].length);
109
+ if (rest.startsWith("{")) return isNoOpBody(rest.slice(1, closing(rest, 0) - 1));
110
+ return /^(?:void 0|undefined)\s*(?:;|$|\n)/.test(rest);
111
+ }
112
+ const brace = after.indexOf("{");
113
+ return brace !== -1 && isNoOpBody(after.slice(brace + 1, closing(after, brace) - 1));
114
+ }
115
+
116
+ /**
117
+ * Each value export: true when it is a function that does nothing. A type export carries no
118
+ * behavior and is skipped; anything else, a constant, a class or a re-export, is real.
119
+ */
120
+ function valueExports(source) {
121
+ const found = [];
122
+ for (const match of source.matchAll(/(?:^|[;\n])\s*export\s+/g)) {
123
+ const rest = source.slice(match.index + match[0].length);
124
+ if (/^(?:type|interface|declare)\b/.test(rest)) continue;
125
+ const declared = /^(?:default\s+)?(?:async\s+)?function\b\s*\*?\s*[\w$]*\s*(?:<[^>]*>\s*)?(?=\()/.exec(rest);
126
+ if (declared) {
127
+ found.push(noOpFunctionAt(rest, declared[0].length, { arrow: false }));
128
+ continue;
129
+ }
130
+ const bound = /^(?:const|let|var)\s+[\w$]+\s*(?::[^=]+)?=\s*(?:async\s+)?/.exec(rest);
131
+ if (bound) {
132
+ const value = rest.slice(bound[0].length);
133
+ const expression = /^function\b\s*[\w$]*\s*(?=\()/.exec(value);
134
+ if (expression) found.push(noOpFunctionAt(value, expression[0].length, { arrow: false }));
135
+ else if (value.startsWith("(")) found.push(noOpFunctionAt(value, 0, { arrow: true }));
136
+ else if (/^[\w$]+\s*=>/.test(value)) found.push(noOpFunctionAt(`(${value.replace(/^([\w$]+)/, "$1)")}`, 0, { arrow: true }));
137
+ else found.push(false);
138
+ continue;
139
+ }
140
+ found.push(false);
141
+ }
142
+ return found;
143
+ }
144
+
145
+ /**
146
+ * A slice file whose every value export is a function that does nothing: it pairs a name and
147
+ * carries no behavior. A file with no value export is left to the empty-block check.
148
+ * @param {{path: string, contents: string}[]} files
149
+ * @returns {{path: string, rule: string, detail: string}[]}
150
+ */
151
+ export function placeholderSlices(files) {
152
+ const problems = [];
153
+ for (const { path, contents } of files) {
154
+ const exports = valueExports(contents.replace(COMMENT_OR_STRING, (whole, string) => string ?? ""));
155
+ if (exports.length === 0 || !exports.every(Boolean)) continue;
156
+ problems.push({
157
+ path,
158
+ rule: "placeholder-slice",
159
+ detail: "every export is a function that does nothing, so the slice pairs a name and carries no behavior — build the slice, or name the divergence in the parity registry",
160
+ });
161
+ }
162
+ return problems;
163
+ }
@@ -0,0 +1,108 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { checkParity, placeholderSlices } from "./parity.mjs";
4
+
5
+ const roots = { server: "backend/src/features", client: "frontend/src/features", registry: "contracts/parity.json" };
6
+
7
+ function run({ server = [], client = [], registry = {} }) {
8
+ return checkParity({ server, client, registry }, roots);
9
+ }
10
+
11
+ const rules = (problems) => problems.map((problem) => problem.rule);
12
+
13
+ test("two surfaces that carry the same features and slices pass", () => {
14
+ const server = [{ name: "pins", slices: ["create-pin"], routes: ["create-pin"] }];
15
+ const client = [{ name: "pins", slices: ["create-pin"] }];
16
+ assert.deepEqual(run({ server, client }), []);
17
+ });
18
+
19
+ test("a feature on one surface only fails in both directions", () => {
20
+ const problems = run({ server: [{ name: "billing", slices: [], routes: [] }], client: [{ name: "outbox", slices: [] }] });
21
+ assert.deepEqual(rules(problems), ["one-sided-feature", "one-sided-feature"]);
22
+ assert.equal(problems[0].path, "backend/src/features/billing");
23
+ assert.equal(problems[1].path, "frontend/src/features/outbox");
24
+ });
25
+
26
+ test("a one-sided feature the registry names passes, and an entry both surfaces now have fails", () => {
27
+ const registry = {
28
+ backendOnlyFeatures: [{ name: "billing", why: "server only" }],
29
+ frontendOnlyFeatures: [{ name: "pins", why: "stale" }],
30
+ };
31
+ const server = [{ name: "billing", slices: [], routes: [] }, { name: "pins", slices: [], routes: [] }];
32
+ const problems = run({ server, client: [{ name: "pins", slices: [] }], registry });
33
+ assert.deepEqual(rules(problems), ["stale-divergence"]);
34
+ assert.equal(problems[0].path, "contracts/parity.json");
35
+ assert.match(problems[0].detail, /pins: listed as one-sided/);
36
+ });
37
+
38
+ test("a slice or a route with no counterpart fails, in both directions", () => {
39
+ const server = [{ name: "pins", slices: ["create-pin", "move-pin"], routes: ["create-pin", "drop-pin"] }];
40
+ const client = [{ name: "pins", slices: ["create-pin", "draw-pin"] }];
41
+ const details = run({ server, client }).map((problem) => problem.detail);
42
+ assert.deepEqual(details.sort(), [
43
+ "pins/draw-pin: a frontend slice with no backend slice/route of that name",
44
+ "pins/drop-pin: backend route has no frontend slice",
45
+ "pins/drop-pin: route in trigger.ts has no backend slice implementation",
46
+ "pins/move-pin: a backend slice with no frontend slice of that name",
47
+ ]);
48
+ });
49
+
50
+ test("a registry excuse covers a one-sided slice, and fails once it stops being true", () => {
51
+ const server = [{ name: "pins", slices: ["render", "both"], routes: [] }];
52
+ const client = [{ name: "pins", slices: ["both", "local"] }];
53
+ const registry = {
54
+ slices: {
55
+ pins: [
56
+ { stem: "render", why: "Backend-only: a worker route." },
57
+ { stem: "local", why: "Client-only: a draft." },
58
+ { stem: "both", why: "Backend-only: stale." },
59
+ { stem: "gone", why: "Backend-only: deleted." },
60
+ ],
61
+ },
62
+ };
63
+ const details = run({ server, client, registry }).map((problem) => problem.detail);
64
+ assert.deepEqual(details, [
65
+ "pins/both: excused in contracts/parity.json, but both surfaces have it — delete the entry",
66
+ "pins/gone: excused in contracts/parity.json, but neither surface has a slice of that name — delete the entry",
67
+ ]);
68
+ });
69
+
70
+ test("an excuse whose reason names the wrong side fails", () => {
71
+ const server = [{ name: "pins", slices: ["render"], routes: [] }];
72
+ const client = [{ name: "pins", slices: [] }];
73
+ const registry = { slices: { pins: [{ stem: "render", why: "Client-only: wrong side." }] } };
74
+ const problems = run({ server, client, registry });
75
+ assert.deepEqual(rules(problems), ["stale-divergence"]);
76
+ assert.match(problems[0].detail, /excused as client-only/);
77
+ });
78
+
79
+ const slice = (contents, path = "frontend/src/features/tasks/slices/get-task.tsx") => [{ path, contents }];
80
+
81
+ test("a slice whose only export is a no-op fails as a placeholder, whatever its name", () => {
82
+ const problems = placeholderSlices(slice("// placeholder for parity\nexport function PLACEHOLDER(): void { void 0; }"));
83
+ assert.equal(problems.length, 1);
84
+ assert.equal(problems[0].rule, "placeholder-slice");
85
+ assert.equal(problems[0].path, "frontend/src/features/tasks/slices/get-task.tsx");
86
+ });
87
+
88
+ test("an empty body, a bare return, and return undefined are no-ops too", () => {
89
+ for (const body of ["", "return;", "return undefined;", "void 0"]) {
90
+ assert.equal(placeholderSlices(slice(`export function stub() { ${body} }`)).length, 1, body);
91
+ }
92
+ assert.equal(placeholderSlices(slice("export const stub = () => {};")).length, 1);
93
+ assert.equal(placeholderSlices(slice("export const stub = (): void => void 0;")).length, 1);
94
+ assert.equal(placeholderSlices(slice("export async function stub(a: string): Promise<void> {\n return;\n}")).length, 1);
95
+ });
96
+
97
+ test("a slice with one real export passes, even beside a no-op", () => {
98
+ const real = "export function GetTask(props: Props) {\n return <Task id={props.id} />;\n}";
99
+ assert.deepEqual(placeholderSlices(slice(real)), []);
100
+ assert.deepEqual(placeholderSlices(slice(`${real}\nexport function noop(): void { void 0; }`)), []);
101
+ assert.deepEqual(placeholderSlices(slice("export const LIMIT = 20;\nexport function noop() {}")), []);
102
+ assert.deepEqual(placeholderSlices(slice("export { getTask } from './get';\nexport function noop() {}")), []);
103
+ });
104
+
105
+ test("a file with no value export is not a placeholder, and a type export does not make one real", () => {
106
+ assert.deepEqual(placeholderSlices(slice("const local = 1;\n")), []);
107
+ assert.equal(placeholderSlices(slice("export type Row = { id: string };\nexport function noop() {}")).length, 1);
108
+ });
@@ -261,3 +261,47 @@ export function checkSqlIdentifiers(tables, resources, owners = new Map()) {
261
261
  }
262
262
  return problems;
263
263
  }
264
+
265
+ // The other direction. A schema declaration with no migration behind it typechecks, passes every
266
+ // statement check, and fails at runtime. This is the text-level half: it cannot see a type or a
267
+ // default that differs, and a column a later migration dropped still matches the one that added it.
268
+ const SCHEMA_COLUMN = /\b(?:uuid|text|integer|bigint|boolean|jsonb|timestamp|numeric|real|doublePrecision|date|smallint)\(\s*"([a-z0-9_]+)"/g;
269
+
270
+ /**
271
+ * Each table a schema file declares, with the columns under it. A column belongs to the table
272
+ * whose factory call precedes it: one table, then its columns.
273
+ * @param {string} source
274
+ * @param {{tableFactory?: string}} [options]
275
+ * @returns {{table: string, columns: string[]}[]}
276
+ */
277
+ export function schemaTables(source, { tableFactory = "pgTable" } = {}) {
278
+ const factory = tableFactory.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
279
+ const starts = [...source.matchAll(new RegExp(`${factory}\\(\\s*"([a-z0-9_]+)"`, "g"))].map((match) => ({ table: match[1], at: match.index }));
280
+ return starts.map((start, index) => {
281
+ const body = source.slice(start.at, starts[index + 1]?.at ?? source.length);
282
+ return { table: start.table, columns: [...new Set([...body.matchAll(SCHEMA_COLUMN)].map((match) => match[1]))] };
283
+ });
284
+ }
285
+
286
+ /** Every name the migrations write down. A name anywhere in the SQL is enough: the question is whether it was ever written. */
287
+ export function migrationNames(sources) {
288
+ const names = new Set();
289
+ for (const sql of sources) for (const [name] of sql.matchAll(/[a-z0-9_]+/g)) names.add(name);
290
+ return names;
291
+ }
292
+
293
+ /**
294
+ * @param {{path: string, table: string, columns: string[]}[]} declared
295
+ * @param {Set<string>} names
296
+ * @returns {{path: string, rule: string, detail: string}[]}
297
+ */
298
+ export function checkSchemaInMigrations(declared, names) {
299
+ const problems = [];
300
+ for (const { path, table, columns } of declared) {
301
+ const missing = names.has(table) ? columns.filter((column) => !names.has(column)).map((column) => `${table}.${column}`) : [`table ${table}`];
302
+ for (const name of missing) {
303
+ problems.push({ path, rule: "schema-without-migration", detail: `${name} is declared here and named by no migration` });
304
+ }
305
+ }
306
+ return problems;
307
+ }
@@ -1,6 +1,14 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { checkSqlIdentifiers, declaredColumns, tableOwners, usedIdentifiers } from "./sql-identifiers.mjs";
3
+ import {
4
+ checkSchemaInMigrations,
5
+ checkSqlIdentifiers,
6
+ declaredColumns,
7
+ migrationNames,
8
+ schemaTables,
9
+ tableOwners,
10
+ usedIdentifiers,
11
+ } from "./sql-identifiers.mjs";
4
12
 
5
13
  const ddl = `
6
14
  create table if not exists projects (
@@ -222,3 +230,37 @@ test("a slug matching no feature keeps its own name, so an unowned table is stil
222
230
  const owners = tableOwners([{ file: "0010_orphan.sql", sql: ddl }], ["blueprints"]);
223
231
  assert.equal(owners.get("projects"), "orphan");
224
232
  });
233
+
234
+ const schema = `
235
+ export const projects = pgTable("projects", {
236
+ id: uuid("id").primaryKey(),
237
+ tenantId: uuid("tenant_id").notNull(),
238
+ code: text("code").notNull(),
239
+ });
240
+ export const folders = pgTable("folders", {
241
+ id: uuid("id").primaryKey(),
242
+ sortOrder: integer("sort_order"),
243
+ });`;
244
+
245
+ test("a schema file yields each table with the columns declared under it", () => {
246
+ assert.deepEqual(schemaTables(schema), [
247
+ { table: "projects", columns: ["id", "tenant_id", "code"] },
248
+ { table: "folders", columns: ["id", "sort_order"] },
249
+ ]);
250
+ assert.deepEqual(schemaTables('export const t = table("things", { id: uuid("id") });', { tableFactory: "table" }), [{ table: "things", columns: ["id"] }]);
251
+ });
252
+
253
+ test("a schema whose every table and column a migration names passes", () => {
254
+ const declared = schemaTables(schema).map((entry) => ({ path: "f/schema.ts", ...entry }));
255
+ const names = migrationNames([ddl, "create table folders (id uuid, sort_order integer);"]);
256
+ assert.deepEqual(checkSchemaInMigrations(declared, names), []);
257
+ });
258
+
259
+ test("a table or a column no migration names fails, one finding each", () => {
260
+ const declared = schemaTables(schema).map((entry) => ({ path: "f/schema.ts", ...entry }));
261
+ const problems = checkSchemaInMigrations(declared, migrationNames([ddl]));
262
+ assert.deepEqual(problems.map((problem) => problem.rule), ["schema-without-migration"]);
263
+ assert.equal(problems[0].detail, "table folders is declared here and named by no migration");
264
+ const column = checkSchemaInMigrations([{ path: "f/schema.ts", table: "projects", columns: ["id", "archived_at"] }], migrationNames([ddl]));
265
+ assert.equal(column[0].detail, "projects.archived_at is declared here and named by no migration");
266
+ });
@@ -7,8 +7,10 @@
7
7
  // It reads the predicate, not the value. That a predicate is present is
8
8
  // structural; that it is correct is what the two-tenant test is for.
9
9
 
10
+ import { posix } from "node:path";
11
+
10
12
  const DEFAULT_TENANT_COLUMN = "tenant_id";
11
- const DEFAULT_INSERT_HELPER = "insertReturning";
13
+ const DEFAULT_TENANT_IDENTIFIER = "tenantId";
12
14
 
13
15
  function escape(text) {
14
16
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -66,19 +68,39 @@ export function checkTenantPredicate(resources, owned, options = {}) {
66
68
  return problems;
67
69
  }
68
70
 
69
- // Adopting the shared `insertReturning` moved the statement text out of the file
70
- // that calls it, so the predicate check above stops seeing it. The tenant is now
71
- // carried in the caller's column list instead — which is still in the caller's
72
- // file, and still checkable. Without this, cleaning up duplication would have
73
- // quietly bought a weaker gate.
74
- // A call, not a declaration: `function insertReturning<Row>(` is where the helper
75
- // is defined, and its own parameters are not a column list.
76
- function sharedInsertPattern(helper) {
77
- return new RegExp(`(?<!function\\s)${escape(helper)}\\s*(?:<[^>]*>)?\\s*\\(`, "g");
71
+ // A helper that takes its table or its columns from the caller carries an exemption above,
72
+ // because the tenant is not readable inside it. The tenant is readable at each call, so each
73
+ // call is checked instead, or moving a statement into a shared helper buys a weaker gate.
74
+
75
+ /** A call, not the declaration: the helper's own parameters are not a tenant argument. */
76
+ function callPattern(name) {
77
+ return new RegExp(`(?<![\\w$.]|function\\s)${escape(name)}\\s*(?:<[^>]*>)?\\s*\\(`, "g");
78
78
  }
79
79
 
80
- function tenantLiteralPattern(column) {
81
- return new RegExp(`["']${escape(column)}["']`);
80
+ /** The tenant as a quoted column, as a row key, or as the tenant identifier. */
81
+ function tenantPattern(column, identifier) {
82
+ return new RegExp(`["'\`]${escape(column)}["'\`]|\\b${escape(column)}\\s*:|\\b${escape(identifier)}\\b`);
83
+ }
84
+
85
+ /** The index just past the bracket that closes the one at `open`. */
86
+ function closeOf(source, open) {
87
+ let depth = 0;
88
+ for (let i = open; i < source.length; i += 1) {
89
+ if ("([{".includes(source[i])) depth += 1;
90
+ else if (")]}".includes(source[i]) && (depth -= 1) === 0) return i + 1;
91
+ }
92
+ return source.length;
93
+ }
94
+
95
+ /** From `at` to the semicolon that ends its statement, outside any bracket. */
96
+ function statementFrom(source, at) {
97
+ let depth = 0;
98
+ for (let i = at; i < source.length; i += 1) {
99
+ if ("([{".includes(source[i])) depth += 1;
100
+ else if (")]}".includes(source[i])) depth -= 1;
101
+ if (depth < 0 || (depth === 0 && source[i] === ";")) return source.slice(at, i);
102
+ }
103
+ return source.slice(at);
82
104
  }
83
105
 
84
106
  /** The arguments of a call, split at the top level so a nested array stays whole. */
@@ -106,61 +128,89 @@ function callArguments(source, openIndex) {
106
128
  return args;
107
129
  }
108
130
 
131
+ /** The nearest declaration of `name` inside the enclosing function, else at the top level. */
132
+ function declarationOf(source, name, from, callAt) {
133
+ const id = escape(name);
134
+ const declares = `\\b(?:const|let|var)\\s+(?:\\{[^}]*\\b${id}\\b[^}]*\\}|\\[[^\\]]*\\b${id}\\b[^\\]]*\\]|${id}\\b)`;
135
+ const local = [...source.slice(from, callAt).matchAll(new RegExp(declares, "g"))].at(-1);
136
+ if (local) return statementFrom(source, from + local.index);
137
+ const top = new RegExp(`^(?:export\\s+)?${declares}`, "m").exec(source);
138
+ return top ? statementFrom(source, top.index) : "";
139
+ }
140
+
109
141
  /**
110
- * The body of the factory a call passed its columns to. Only a call — `f()` — is
111
- * followed. A bare name is left to the enclosing-function window, because a local
112
- * one is free to repeat: resolving `columns` by name would find the first `const
113
- * columns` in the file and let a correct list two functions away vouch for this one.
142
+ * The text an argument stands for. A call `f()` is followed to the body of `function f`, one
143
+ * indirection. A bare name is followed to its own declaration only, so a neighbour's local of
144
+ * the same name, or a values list beside it, cannot vouch for it.
114
145
  */
115
- function factoryBody(source, argument) {
116
- const called = /^([A-Za-z_$][\w$]*)\s*\(/.exec(argument.trim());
117
- if (called === null) return "";
118
- const declared = new RegExp(`function\\s+${called[1]}\\b`).exec(source);
119
- return declared === null ? "" : source.slice(declared.index, declared.index + 700);
146
+ function resolved(source, argument, from, callAt) {
147
+ const called = /^([A-Za-z_$][\w$]*)\s*\(/.exec(argument);
148
+ if (called) {
149
+ const declared = new RegExp(`function\\s+${escape(called[1])}\\s*(?:<[^>]*>)?\\s*\\(`).exec(source);
150
+ if (declared === null) return declarationOf(source, called[1], from, callAt);
151
+ const open = source.indexOf("{", closeOf(source, declared.index + declared[0].length - 1));
152
+ return open === -1 ? "" : source.slice(open, closeOf(source, open));
153
+ }
154
+ return /^[A-Za-z_$][\w$]*$/.test(argument) ? declarationOf(source, argument, from, callAt) : "";
155
+ }
156
+
157
+ /** The local names a file imports `helper.name` under from `helper.module`. */
158
+ function importedNames(file, source, helper) {
159
+ const stem = (spec) => spec.replace(/\.[cm]?[jt]sx?$/, "");
160
+ const folder = posix.dirname(file);
161
+ const names = [];
162
+ for (const [, list, specifier] of source.matchAll(/\bimport\s+\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
163
+ if (!specifier.startsWith(".") || stem(posix.join(folder, specifier)) !== stem(helper.module)) continue;
164
+ for (const part of list.split(",")) {
165
+ const [imported, local] = part.trim().split(/\s+as\s+/);
166
+ if (imported === helper.name) names.push(local ?? imported);
167
+ }
168
+ }
169
+ return names;
120
170
  }
121
171
 
122
172
  /**
123
- * Every call to the shared insert must name the tenant column: inline in the
124
- * argument list, in a `columns` array built just above it, or in the definition
125
- * of whatever it passed — a named factory is one indirection and is followed,
126
- * because a check that cries wolf is a check somebody turns off.
127
- *
128
- * @param {{path: string, source: string}[]} resources
129
- * @returns {{path: string, rule: string, detail: string}[]}
173
+ * Every call of an exempt helper, in a file that imports it from its module, with the argument
174
+ * that carries the tenant and whether that argument names it.
175
+ * @param {{path: string, contents: string}[]} files
176
+ * @param {{module: string, name: string, argument: number}[]} helpers
177
+ * @param {{column?: string, identifier?: string}} [options]
178
+ * @returns {{path: string, line: number, name: string, index: number, argument: string, scoped: boolean}[]}
130
179
  */
131
- export function checkSharedInsertCallSites(resources, options = {}) {
132
- const column = options.column ?? DEFAULT_TENANT_COLUMN;
133
- const sharedInsert = sharedInsertPattern(options.insertHelper ?? DEFAULT_INSERT_HELPER);
134
- const tenantLiteral = tenantLiteralPattern(column);
135
- const problems = [];
136
- for (const { path, source } of resources) {
137
- sharedInsert.lastIndex = 0;
138
- let match = sharedInsert.exec(source);
139
- while (match !== null) {
140
- // Look back only as far as the enclosing function starts, so a neighbouring
141
- // insert that does name the tenant cannot vouch for this one, and forward
142
- // across this call's own argument list.
143
- const before = source.slice(0, match.index);
144
- const boundary = Math.max(
145
- before.lastIndexOf("function "),
146
- before.lastIndexOf("=> {"),
147
- before.lastIndexOf("\n}"),
148
- );
149
- const from = boundary === -1 ? Math.max(0, match.index - 400) : boundary;
150
- const args = callArguments(source, match.index + match[0].length - 1);
151
- const followed = factoryBody(source, args[2] ?? "");
152
- const neighbourhood = source.slice(from, match.index + 700) + followed;
153
- if (!tenantLiteral.test(neighbourhood)) {
154
- problems.push({
155
- path,
156
- rule: "insert-without-tenant",
157
- detail: `line ${before.split("\n").length}: a shared insert names no ${column} column — the tenant moved into the caller's list, so the caller is what carries it`,
158
- });
180
+ export function exemptHelperCalls(files, helpers, options = {}) {
181
+ const tenant = tenantPattern(options.column ?? DEFAULT_TENANT_COLUMN, options.identifier ?? DEFAULT_TENANT_IDENTIFIER);
182
+ const calls = [];
183
+ for (const { path, contents: source } of files) {
184
+ for (const helper of helpers) {
185
+ for (const local of importedNames(path, source, helper)) {
186
+ for (const match of source.matchAll(callPattern(local))) {
187
+ // The enclosing function starts the window, so a neighbour cannot vouch for this call.
188
+ const before = source.slice(0, match.index);
189
+ const from = Math.max(0, before.lastIndexOf("function "), before.lastIndexOf("=> {"), before.lastIndexOf("\n}"));
190
+ const argument = (callArguments(source, match.index + match[0].length - 1)[helper.argument] ?? "").trim();
191
+ const scoped = tenant.test(argument) || tenant.test(resolved(source, argument, from, match.index));
192
+ calls.push({ path, line: before.split("\n").length, name: helper.name, index: helper.argument, argument, scoped });
193
+ }
159
194
  }
160
- match = sharedInsert.exec(source);
161
195
  }
162
196
  }
163
- return problems;
197
+ return calls.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
198
+ }
199
+
200
+ /**
201
+ * @param {{path: string, contents: string}[]} files
202
+ * @param {{module: string, name: string, argument: number}[]} helpers
203
+ * @param {{column?: string, identifier?: string}} [options]
204
+ * @returns {{path: string, rule: string, detail: string}[]}
205
+ */
206
+ export function checkExemptHelperCalls(files, helpers, options = {}) {
207
+ return exemptHelperCalls(files, helpers, options)
208
+ .filter((call) => !call.scoped)
209
+ .map((call) => ({
210
+ path: call.path,
211
+ rule: "unscoped-helper-call",
212
+ detail: `line ${call.line}: ${call.name} is exempt from the statement scan, and its argument ${call.index + 1} (${call.argument}) names no tenant — the caller is what carries it`,
213
+ }));
164
214
  }
165
215
 
166
216
  /** Every statement whose exemption was taken, so a reviewer can count them. */
@@ -1,6 +1,6 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { checkSharedInsertCallSites, checkTenantPredicate } from "./tenant-predicate.mjs";
3
+ import { checkExemptHelperCalls, checkTenantPredicate, exemptHelperCalls } from "./tenant-predicate.mjs";
4
4
 
5
5
  const owned = new Set(["projects", "pin_annotations"]);
6
6
  const one = (sql, bound = new Set()) => [{ path: "r.ts", statements: [{ sql, bound }] }];
@@ -39,36 +39,44 @@ test("a table whose name merely starts the same is not matched", () => {
39
39
  assert.deepEqual(checkTenantPredicate(one("select id from projects_archive where id = $1"), owned), []);
40
40
  });
41
41
 
42
- test("a shared insert naming the tenant inline passes", () => {
43
- const source = `return insertReturning(tx, "projects", ["id", "tenant_id", "code"], [a, b, c], COLS, onDup, signal);`;
44
- assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
42
+ const CRUD = "backend/src/application/sql/crud.ts";
43
+ const helpers = [
44
+ { module: CRUD, name: "insertReturning", argument: 2 },
45
+ { module: CRUD, name: "updateVersionedRow", argument: 3 },
46
+ ];
47
+ const IMPORT = 'import { insertReturning, updateVersionedRow } from "../../../application/sql/crud.js";\n';
48
+ const FILE = "backend/src/features/projects/shared/queries.ts";
49
+ const calls = (source, options = {}) => checkExemptHelperCalls([{ path: FILE, contents: IMPORT + source }], helpers, options);
50
+
51
+ test("a call that names the tenant inline passes", () => {
52
+ assert.deepEqual(calls(`return insertReturning(tx, "projects", ["id", "tenant_id", "code"], [a, b, c], COLS, onDup, signal);`), []);
45
53
  });
46
54
 
47
- test("a shared insert naming the tenant in a columns array just above passes", () => {
55
+ test("a call whose columns array just above names the tenant passes", () => {
48
56
  const source = `
49
57
  async function insertProject(tx, input, signal) {
50
58
  const columns = ["id", "tenant_id", "code", "name"];
51
59
  const values = [input.id, input.tenantId, input.code, input.name];
52
60
  return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
53
61
  }`;
54
- assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
62
+ assert.deepEqual(calls(source), []);
55
63
  });
56
64
 
57
- test("a shared insert that forgot the tenant is caught", () => {
65
+ test("a call that forgot the tenant fails, and a tenant in the values beside it does not vouch", () => {
58
66
  const source = `
59
67
  async function insertProject(tx, input, signal) {
60
68
  const columns = ["id", "code", "name"];
61
- const values = [input.id, input.code, input.name];
69
+ const values = [input.id, input.tenantId, input.code, input.name];
62
70
  return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
63
71
  }`;
64
- const problems = checkSharedInsertCallSites([{ path: "r.ts", source }]);
72
+ const problems = calls(source);
65
73
  assert.equal(problems.length, 1);
66
- assert.equal(problems[0].rule, "insert-without-tenant");
74
+ assert.equal(problems[0].rule, "unscoped-helper-call");
75
+ assert.equal(problems[0].path, FILE);
67
76
  });
68
77
 
69
78
  test("a generic call with a type argument is still matched", () => {
70
- const source = `return insertReturning<ProjectRow>(tx, "projects", ["id", "code"], [a, b], COLS, onDup);`;
71
- assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
79
+ assert.equal(calls(`return insertReturning<{ id: string }>(tx, "projects", ["id", "code"], [a, b], COLS, onDup);`).length, 1);
72
80
  });
73
81
 
74
82
  test("every call is checked, and a neighbour naming the tenant cannot vouch for one that does not", () => {
@@ -82,29 +90,19 @@ function insertB(tx, v) {
82
90
  function insertC(tx, v) {
83
91
  return insertReturning(tx, "c", ["id"], v, C, f);
84
92
  }`;
85
- assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 2);
93
+ assert.equal(calls(source).length, 2);
86
94
  });
87
95
 
88
- test("a columns factory one call away is followed, not guessed at", () => {
89
- const source = `
96
+ test("a columns factory one call away is followed, and one that forgets the tenant is caught", () => {
97
+ const factory = (columns) => `
90
98
  function newPhotoColumns() {
91
- return ["id", "tenant_id", "delivery_id"];
99
+ return [${columns}];
92
100
  }
93
101
  export async function insertPhoto(tx, input, signal) {
94
- return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
102
+ return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input.tenantId), COLS, onDup, signal);
95
103
  }`;
96
- assert.deepEqual(checkSharedInsertCallSites([{ path: "r.ts", source }]), []);
97
- });
98
-
99
- test("a columns factory that forgets the tenant is still caught through the indirection", () => {
100
- const source = `
101
- function newPhotoColumns() {
102
- return ["id", "delivery_id"];
103
- }
104
- export async function insertPhoto(tx, input, signal) {
105
- return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
106
- }`;
107
- assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
104
+ assert.deepEqual(calls(factory('"id", "tenant_id", "delivery_id"')), []);
105
+ assert.equal(calls(factory('"id", "delivery_id"')).length, 1);
108
106
  });
109
107
 
110
108
  test("a repeated local name is not resolved to the first one in the file", () => {
@@ -117,11 +115,42 @@ export async function insertTwo(tx, input, signal) {
117
115
  const columns = ["id", "name"];
118
116
  return insertReturning(tx, "b", columns, values(input), COLS, onDup, signal);
119
117
  }`;
120
- const found = checkSharedInsertCallSites([{ path: "r.ts", source }]);
118
+ const found = calls(source);
121
119
  assert.equal(found.length, 1);
122
- assert.match(found[0].detail, /line 8:/);
120
+ assert.match(found[0].detail, /line 9:/);
121
+ });
122
+
123
+ test("a row object must carry the tenant key: the must-fail and must-pass of the issue", () => {
124
+ const helper = [{ module: CRUD, name: "insertRow", argument: 2 }];
125
+ const run = (source) => checkExemptHelperCalls([{ path: FILE, contents: `import { insertRow } from "../../../application/sql/crud.js";\n${source}` }], helper);
126
+ assert.equal(run('await insertRow(tx, "items", { id, name }, "id");').length, 1);
127
+ assert.deepEqual(run('await insertRow(tx, "items", { tenant_id: tenantId, id, name }, "id");'), []);
128
+ });
129
+
130
+ test("a tenant value argument must name the tenant, so swapped arguments fail", () => {
131
+ assert.deepEqual(calls('return updateVersionedRow(tx, "pins", fields, tenantId, pinId, expectedVersion, COLS, signal);'), []);
132
+ assert.deepEqual(calls('return updateVersionedRow(tx, "pins", fields, input.tenantId, pinId, 3, COLS, signal);'), []);
133
+ assert.equal(calls('return updateVersionedRow(tx, "pins", fields, pinId, tenantId, expectedVersion, COLS, signal);').length, 1);
123
134
  });
124
135
 
136
+ test("only a file that imports the helper from its module is checked, under the name it imports", () => {
137
+ const other = 'import { insertReturning } from "./local.js";\ninsertReturning(tx, "a", ["id"], v, C, f);';
138
+ assert.deepEqual(checkExemptHelperCalls([{ path: FILE, contents: other }], helpers), []);
139
+ const renamed = 'import { insertReturning as insert } from "../../../application/sql/crud.js";\ninsert(tx, "a", ["id"], v, C, f);';
140
+ assert.equal(checkExemptHelperCalls([{ path: FILE, contents: renamed }], helpers).length, 1);
141
+ });
142
+
143
+ test("every call is listed with its verdict, so a reviewer can count them", () => {
144
+ const source = 'insertReturning(tx, "a", ["tenant_id"], v, C, f);\nupdateVersionedRow(tx, "b", f, id, id, 1, C);';
145
+ const found = exemptHelperCalls([{ path: FILE, contents: IMPORT + source }], helpers);
146
+ assert.deepEqual(found.map((call) => [call.name, call.line, call.scoped]), [["insertReturning", 2, true], ["updateVersionedRow", 3, false]]);
147
+ });
148
+
149
+ test("the tenant column and identifier come from options", () => {
150
+ const source = 'insertReturning(tx, "a", ["org_id"], v, C, f);\nupdateVersionedRow(tx, "b", f, orgId, id, 1, C);';
151
+ assert.deepEqual(calls(source, { column: "org_id", identifier: "orgId" }), []);
152
+ assert.equal(calls(source).length, 2);
153
+ });
125
154
 
126
155
  test("a statement on a table named at runtime is still checked", () => {
127
156
  const sql = "select id from ${table} where id = $1";
@@ -142,7 +171,7 @@ test("an insert into a runtime-named table must list the tenant column", () => {
142
171
  assert.deepEqual(checkTenantPredicate(one(good), owned), []);
143
172
  });
144
173
 
145
- test("the tenant column and the shared insert helper come from options", () => {
174
+ test("the tenant column comes from options", () => {
146
175
  const resources = [
147
176
  { path: "a/resource.ts", statements: [{ sql: "select * from pins where org_id = $1", bound: new Set() }] },
148
177
  ];
@@ -152,10 +181,3 @@ test("the tenant column and the shared insert helper come from options", () => {
152
181
  assert.equal(problems.length, 1);
153
182
  assert.ok(problems[0].detail.includes("tenant_id"));
154
183
  });
155
-
156
- test("a renamed shared insert helper is still followed to its call sites", () => {
157
- const resources = [{ path: "a/resource.ts", source: 'await addRow(uow, "pins", ["name"], [n]);' }];
158
- const problems = checkSharedInsertCallSites(resources, { insertHelper: "addRow", column: "org_id" });
159
- assert.equal(problems.length, 1);
160
- assert.ok(problems[0].detail.includes("org_id"));
161
- });