architecture-harness 0.15.0 → 0.17.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 (112) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/check-registries.test.mjs +181 -0
  7. package/src/cli/check.mjs +130 -9
  8. package/src/cli/cli.test.mjs +215 -2
  9. package/src/cli/contract-history.mjs +46 -0
  10. package/src/cli/contract-history.test.mjs +118 -0
  11. package/src/cli/controller-guard.mjs +73 -0
  12. package/src/cli/controller-guard.test.mjs +119 -0
  13. package/src/cli/dispatch-guard.mjs +14 -6
  14. package/src/cli/dispatch-guard.test.mjs +37 -0
  15. package/src/cli/dispatch-reminder.mjs +26 -12
  16. package/src/cli/dispatch-reminder.test.mjs +43 -0
  17. package/src/cli/dispatch-slot.mjs +151 -36
  18. package/src/cli/dispatch-slot.test.mjs +160 -11
  19. package/src/cli/dispatch.mjs +25 -7
  20. package/src/cli/dispatch.test.mjs +55 -1
  21. package/src/cli/doctor.mjs +2 -1
  22. package/src/cli/explore-guard.mjs +2 -2
  23. package/src/cli/gh-merge-command.mjs +228 -0
  24. package/src/cli/gh-merge-command.test.mjs +273 -0
  25. package/src/cli/gh-run.mjs +30 -0
  26. package/src/cli/gh-run.test.mjs +22 -0
  27. package/src/cli/git-hooks.test.mjs +28 -0
  28. package/src/cli/git-read.mjs +42 -0
  29. package/src/cli/git-read.test.mjs +94 -0
  30. package/src/cli/init.mjs +7 -3
  31. package/src/cli/issue-gate.mjs +169 -0
  32. package/src/cli/issue-gate.test.mjs +234 -0
  33. package/src/cli/ledger.mjs +136 -0
  34. package/src/cli/ledger.test.mjs +127 -0
  35. package/src/cli/merge-guard.mjs +193 -0
  36. package/src/cli/merge-guard.test.mjs +328 -0
  37. package/src/cli/plan-check.mjs +151 -0
  38. package/src/cli/plan-check.test.mjs +143 -0
  39. package/src/cli/plan-stop.mjs +101 -0
  40. package/src/cli/plan-stop.test.mjs +136 -0
  41. package/src/cli/plugin-agents.test.mjs +96 -8
  42. package/src/cli/pr-check.mjs +17 -5
  43. package/src/cli/pr-check.test.mjs +85 -4
  44. package/src/cli/prose.mjs +192 -0
  45. package/src/cli/prose.test.mjs +248 -0
  46. package/src/cli/qc.mjs +16 -0
  47. package/src/cli/registry-history.mjs +1 -1
  48. package/src/cli/report-stash.mjs +69 -0
  49. package/src/cli/report-stash.test.mjs +71 -0
  50. package/src/cli/report-stop.mjs +256 -0
  51. package/src/cli/report-stop.test.mjs +432 -0
  52. package/src/cli/shell-command.mjs +81 -6
  53. package/src/cli/shell-command.test.mjs +101 -1
  54. package/src/cli/task-gate.mjs +157 -0
  55. package/src/cli/task-gate.test.mjs +421 -0
  56. package/src/cli/workflow-hooks.test.mjs +72 -0
  57. package/src/cli/workflow-place.mjs +143 -0
  58. package/src/cli/workflow-place.test.mjs +146 -0
  59. package/src/cli/workflow-settings.mjs +77 -0
  60. package/src/cli/workflow-settings.test.mjs +79 -0
  61. package/src/cli/worktree.mjs +1 -1
  62. package/src/cli/worktree.test.mjs +19 -2
  63. package/src/config.mjs +87 -4
  64. package/src/config.test.mjs +38 -3
  65. package/src/descriptions.mjs +5 -1
  66. package/src/eslint/index.mjs +2 -0
  67. package/src/eslint/jsx.mjs +57 -0
  68. package/src/eslint/preset.mjs +32 -6
  69. package/src/eslint/preset.test.mjs +60 -0
  70. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  71. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  72. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  73. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  74. package/src/eslint/rules/registry-literal.mjs +36 -2
  75. package/src/eslint/rules.test.mjs +153 -0
  76. package/src/gates/call-args.mjs +90 -0
  77. package/src/gates/call-args.test.mjs +21 -0
  78. package/src/gates/config-floor.mjs +41 -20
  79. package/src/gates/config-floor.test.mjs +71 -1
  80. package/src/gates/contract-idempotency.mjs +103 -0
  81. package/src/gates/contract-idempotency.test.mjs +276 -0
  82. package/src/gates/contract-operations.mjs +120 -0
  83. package/src/gates/contract-operations.test.mjs +275 -0
  84. package/src/gates/contract-routes.mjs +82 -0
  85. package/src/gates/contract-routes.test.mjs +210 -0
  86. package/src/gates/registry-literal.mjs +79 -15
  87. package/src/gates/registry-literal.test.mjs +89 -0
  88. package/src/gates/saga-key.mjs +253 -0
  89. package/src/gates/saga-key.test.mjs +322 -0
  90. package/src/gates/scrub.mjs +108 -0
  91. package/src/gates/scrub.test.mjs +29 -0
  92. package/src/gates/tenant-isolation-test.mjs +80 -0
  93. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  94. package/src/gates/tenant-predicate.mjs +644 -91
  95. package/src/gates/tenant-predicate.test.mjs +662 -1
  96. package/src/prose-lines.mjs +49 -0
  97. package/src/prose-lines.test.mjs +63 -0
  98. package/src/registries.mjs +89 -0
  99. package/src/registries.test.mjs +44 -0
  100. package/src/vale-style.test.mjs +158 -0
  101. package/templates/docs/enforcement.md +26 -2
  102. package/templates/github/workflows/ci.yml +18 -1
  103. package/templates/quality-thresholds.json +1 -1
  104. package/templates/vale/.vale.ini +7 -0
  105. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  106. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  107. package/templates/vale/styles/Qc/Latin.yml +9 -0
  108. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  109. package/templates/vale/styles/Qc/Please.yml +6 -0
  110. package/templates/vale/styles/Qc/Progress.yml +9 -0
  111. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  112. package/templates/vale/styles/Qc/Utilize.yml +10 -0
package/src/cli/check.mjs CHANGED
@@ -15,13 +15,22 @@ import {
15
15
  sqlStatements,
16
16
  tableOwners,
17
17
  } from "../gates/sql-identifiers.mjs";
18
- import { checkExemptHelperCalls, checkTenantPredicate, exemptHelperCalls, exemptions } from "../gates/tenant-predicate.mjs";
18
+ import {
19
+ aliasMap,
20
+ checkExemptHelperCalls,
21
+ checkTenantPredicate,
22
+ exemptHelperCalls,
23
+ exemptions,
24
+ unresolvedHelperImports,
25
+ } from "../gates/tenant-predicate.mjs";
19
26
  import { checkClaimedRequirements } from "../gates/claimed-requirements.mjs";
20
27
  import { allowedPublicRoutes, checkPublicRoutes, declaredPublicRoutes } from "../gates/public-routes.mjs";
21
28
  import { calledInternalRoutes, checkInternalRoutes, declaredInternalRoutes } from "../gates/internal-routes.mjs";
22
29
  import { checkHeadlessPipelines } from "../gates/headless-sagas.mjs";
30
+ import { checkSagaKey } from "../gates/saga-key.mjs";
23
31
  import { checkFeatureCommands, governedFeatures } from "../gates/feature-cli.mjs";
24
32
  import { checkSagaTests, declaredSagas } from "../gates/saga-tests.mjs";
33
+ import { checkTenantIsolationTests, tenantFeatures } from "../gates/tenant-isolation-test.mjs";
25
34
  import { checkGatesAreTested } from "../gates/gate-tests.mjs";
26
35
  import { checkAuditAppendOnly } from "../gates/audit-append-only.mjs";
27
36
  import { checkEnforcementMap } from "../gates/enforcement-map.mjs";
@@ -33,15 +42,20 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
33
42
  import { checkConfigFloor } from "../gates/config-floor.mjs";
34
43
  import { defaults } from "../config.mjs";
35
44
  import { rules as lintRules } from "../eslint/index.mjs";
36
- import { adrLog, enabled, readerEntries, thresholds } from "../config.mjs";
45
+ import { adrLog, enabled, readerEntries, requiredHooks, thresholds } from "../config.mjs";
37
46
  import { checkRegistryReaders } from "../gates/registry-readers.mjs";
38
47
  import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
39
48
  import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
49
+ import { literalRegistries } from "../registries.mjs";
40
50
  import { checkThresholdRatchet } from "../gates/threshold-ratchet.mjs";
41
51
  import { checkParity, placeholderSlices } from "../gates/parity.mjs";
42
52
  import { checkIntegrationImports } from "../gates/integration-imports.mjs";
43
53
  import { checkClosedSetWriters, matchedKeys } from "../gates/closed-set-writers.mjs";
44
54
  import { checkDocClaims, parseDocClaims } from "../gates/doc-claims.mjs";
55
+ import { checkContractIdempotency, checkLedgerGrowth } from "../gates/contract-idempotency.mjs";
56
+ import { contractHistory } from "./contract-history.mjs";
57
+ import { contractOperations } from "../gates/contract-operations.mjs";
58
+ import { checkContractRoutes, declaredTriggerRoutes } from "../gates/contract-routes.mjs";
45
59
  import { ratchetInputs } from "./registry-history.mjs";
46
60
  import { hookDrift } from "./git-hooks.mjs";
47
61
  import { repoFiles } from "./repo-files.mjs";
@@ -50,6 +64,8 @@ import { repoFiles } from "./repo-files.mjs";
50
64
  const SKIP = /node_modules|\/dist\/|\.test\.[cm]?[jt]sx?$/;
51
65
  const BUILD_OUTPUT = /node_modules|\/dist\//;
52
66
  const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
67
+ // A file with none of these cannot import an exempt helper, alias it, or re-export it.
68
+ const MODULE_LINKS = /\bimport\b|\bexport\s*(?:\{|\*|default\b|(?:const|let|var)\b)/;
53
69
  const SOURCE_EXTENSION = /\.([cm]?[jt]sx?)$/;
54
70
  const CITABLE_EXTENSION = /\.(tsx?|mjs|md)$/;
55
71
  const INFRA_EXTENSIONS = [".tf", ".sh", ".tfvars", ".tfvars.example", ".hcl", ".hcl.example"];
@@ -308,13 +324,30 @@ async function sqlAgreement(config, tree, taken, lines) {
308
324
  if (declared.length > 0) lines.push(`OK schema ${declared.length} table(s), ${columns} column(s) in schema files, each named by a migration`);
309
325
  }
310
326
  if (enabled(config.gates, "tenant-predicate")) {
311
- const helpers = config.tenantPredicate.exemptHelpers;
312
- const callers = (await sourceFiles(config, tree)).filter(
313
- (file) => !TEST_FILE.test(file.path) && helpers.some((helper) => file.contents.includes(helper.name)),
327
+ // A default also listed in `extraExemptHelpers` is one helper, so each call is judged once.
328
+ const helpers = [...config.tenantPredicate.exemptHelpers, ...config.tenantPredicate.extraExemptHelpers].filter(
329
+ (helper, at, all) => all.findIndex((first) => first.module === helper.module && first.name === helper.name) === at,
314
330
  );
315
- const helperOptions = { column: config.tenant.sqlColumn, identifier: config.tenant.column };
331
+ // A file with no import and no export list cannot reach a helper, and cannot be a barrel: the gate
332
+ // treats it as read, so a barrel that re-exports it is not an untraceable one. A helper's own
333
+ // module is always parsed, since it may export its helper under another name, or as its default.
334
+ const scanned = await sourceFiles(config, tree);
335
+ const isCaller = (file) =>
336
+ !TEST_FILE.test(file.path) && (MODULE_LINKS.test(file.contents) || helpers.some((helper) => helper.module === file.path));
337
+ const callers = scanned.filter(isCaller);
338
+ const leaves = new Set(scanned.filter((file) => !isCaller(file)).map((file) => file.path));
339
+ const tsconfig = posix(config.tenantPredicate.tsconfig);
340
+ const tsconfigText = tsconfig && tree.isFile(tsconfig) ? await read(path.join(config.root, tsconfig)) : null;
341
+ let aliases = [];
342
+ try {
343
+ aliases = tsconfigText === null ? [] : aliasMap(tsconfigText, path.posix.dirname(tsconfig).replace(/^\.$/, ""));
344
+ } catch (error) {
345
+ problems.push({ path: tsconfig, rule: "unresolved-helper-import", detail: `${error.message}, so no alias resolves` });
346
+ }
347
+ const helperOptions = { column: config.tenant.sqlColumn, identifier: config.tenant.column, aliases, leaves };
316
348
  problems.push(
317
349
  ...checkTenantPredicate(scoped, owned, tenantOptions),
350
+ ...unresolvedHelperImports(callers, helpers, helperOptions),
318
351
  ...checkExemptHelperCalls(callers, helpers, helperOptions),
319
352
  );
320
353
  const calls = exemptHelperCalls(callers, helpers, helperOptions).length;
@@ -466,6 +499,62 @@ async function docClaims(config, lines) {
466
499
  return problems;
467
500
  }
468
501
 
502
+ /** Every write of the composed contract names its idempotency key, or sits in the ledger. */
503
+ async function contractIdempotency(config, lines) {
504
+ const { contract } = config;
505
+ const { legacy, exemptDeleteById } = config.contractIdempotency;
506
+ const text = await read(path.join(config.root, contract));
507
+ if (text === null) return [];
508
+ let operations;
509
+ try {
510
+ operations = await contractOperations(text);
511
+ } catch (error) {
512
+ const rule = error.code === "CONTRACT_PEER_MISSING" ? "contract-reader-unavailable" : "unreadable-contract";
513
+ return [{ path: contract, rule, detail: error.message }];
514
+ }
515
+ const ledgerText = await read(path.join(config.root, legacy));
516
+ const ledger = parsedJson(ledgerText);
517
+ if (ledgerText !== null && !(Array.isArray(ledger) && ledger.every((id) => typeof id === "string"))) {
518
+ return [{ path: legacy, rule: "unreadable-ledger", detail: "the ledger is not a JSON array of operation-id strings" }];
519
+ }
520
+ const fields = config.idempotency.keys;
521
+ const problems = checkContractIdempotency(operations, ledger ?? [], { fields, exemptDeleteById, contract, ledger: legacy });
522
+ lines.push(`OK idempotency ${operations.length} operation(s), each write names its key or sits in the ${(ledger ?? []).length}-entry ledger`);
523
+ const history = await contractHistory(config.root, { base: config.ratchet.base, contract, legacy, fields, exemptDeleteById });
524
+ if (history.skip) {
525
+ lines.push("NOTE idempotency ledger growth skipped: " + history.skip);
526
+ } else if (history.unreadable) {
527
+ problems.push({ path: contract, rule: "unreadable-base-contract", detail: history.unreadable });
528
+ } else {
529
+ problems.push(...checkLedgerGrowth(ledger ?? [], history, operations, { ledger: legacy }));
530
+ }
531
+ return problems;
532
+ }
533
+
534
+ /** A feature serves exactly the operations the composed contract lists. */
535
+ async function contractRouteAgreement(config, routes, lines) {
536
+ const { contract } = config;
537
+ const text = await read(path.join(config.root, contract));
538
+ if (text === null) return [];
539
+ let operations;
540
+ try {
541
+ operations = await contractOperations(text);
542
+ } catch (error) {
543
+ const rule = error.code === "CONTRACT_PEER_MISSING" ? "contract-reader-unavailable" : "unreadable-contract";
544
+ return [{ path: contract, rule, detail: error.message }];
545
+ }
546
+ const { exempt } = config.contractRoutes;
547
+ if (!Array.isArray(exempt)) {
548
+ return [{ path: "qc.config.json", rule: "malformed-exemption", detail: "contractRoutes.exempt must be an array of { method, path, why }" }];
549
+ }
550
+ const served = declaredTriggerRoutes(routes);
551
+ const problems = checkContractRoutes(served, operations, { contract, exempt });
552
+ if (problems.length === 0) {
553
+ lines.push(`OK contract ${served.length} route(s) and ${operations.length} operation(s) agree by method and path`);
554
+ }
555
+ return problems;
556
+ }
557
+
469
558
  /**
470
559
  * @param {object} config
471
560
  * @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
@@ -513,6 +602,12 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
513
602
  if (enabled(config.gates, "headless-sagas")) {
514
603
  problems.push(...checkHeadlessPipelines(contents, { block: config.saga.headlessBlock, viewModules: config.saga.viewModules }));
515
604
  }
605
+ if (enabled(config.gates, "saga-key")) {
606
+ const rel = relativeTo(config.root);
607
+ const sources = contents.filter((file) => !TEST_FILE.test(file.path)).map((file) => ({ ...file, path: rel(file.path) }));
608
+ const { volatile, ledgerKey, throwawayLedgers } = config.idempotency;
609
+ problems.push(...checkSagaKey(sources, { runners: config.sagaKey.runners, key: config.sagaKey.key, volatile, ledgerKey, throwawayLedgers }));
610
+ }
516
611
  if (enabled(config.gates, "feature-cli") && !perFile) {
517
612
  const rel = relativeTo(config.root);
518
613
  const relativeFeatures = features.map((feature) => ({ ...feature, feature: rel(feature.feature) }));
@@ -572,7 +667,7 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
572
667
  }
573
668
 
574
669
  if (enabled(config.gates, "registry-readers")) {
575
- const entries = readerEntries(thresholds(config));
670
+ const entries = literalRegistries(config).list.flatMap((registry) => readerEntries(registry.entries));
576
671
  const readers = [...new Set(entries.flatMap((entry) => entry.readers))];
577
672
  const sources = new Map(await Promise.all(readers.map(async (reader) => [reader, await read(path.join(config.root, reader))])));
578
673
  problems.push(...checkRegistryReaders(entries, sources));
@@ -583,7 +678,9 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
583
678
  const docs = await readEach(config.root, tree.under(config.docs.root).filter((file) => file.endsWith(".md")));
584
679
  const libraries = parsedJson(await read(path.join(config.root, config.versions)))?.libraries ?? {};
585
680
  const exempt = config.registryLiteral.exempt ?? adrLog(config);
586
- problems.push(...checkRegistryLiteral(docs, { thresholds: thresholds(config), libraries, exempt }));
681
+ const registries = literalRegistries(config);
682
+ problems.push(...checkRegistryLiteral(docs, { thresholds: thresholds(config), libraries, exempt, registries: registries.list }));
683
+ problems.push(...registries.problems);
587
684
  if (docs.length > 0) lines.push(`OK literals ${docs.length} doc(s) carry a token, never a figure a registry owns`);
588
685
  }
589
686
 
@@ -628,6 +725,19 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
628
725
  lines.push(`OK sagas ${sagas.length} workflow(s), each named by a test that runs without a view`);
629
726
  }
630
727
 
728
+ if (enabled(config.gates, "tenant-isolation-test")) {
729
+ const roots = config.featureRoots.map(posix);
730
+ const features = (await Promise.all(roots.map((root) => sourceFiles(config, tree, root)))).flat();
731
+ const isolation = {
732
+ helper: config.tenant.isolationHelper,
733
+ featureRoots: roots,
734
+ tableFactory: config.tenant.tableFactory,
735
+ column: config.tenant.column,
736
+ };
737
+ problems.push(...checkTenantIsolationTests(features, isolation));
738
+ lines.push(`OK tenancy ${tenantFeatures(features, isolation).length} feature(s) with tenant tables, each with a two-tenant test`);
739
+ }
740
+
631
741
  if (enabled(config.gates, "gate-tests")) {
632
742
  const own = await sourceFiles(config, tree, config.paths.checks);
633
743
  problems.push(
@@ -669,6 +779,9 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
669
779
  if (enabled(config.gates, "headless-sagas")) {
670
780
  lines.push("OK headless pipelines are headless and triggers remain thin presenters");
671
781
  }
782
+ if (enabled(config.gates, "saga-key")) {
783
+ lines.push("OK saga-key no saga runner takes a key minted at the call");
784
+ }
672
785
  if (enabled(config.gates, "frontend-boundaries")) {
673
786
  const platform = await platformFiles(config, tree);
674
787
  if (platform.length > 0) {
@@ -704,7 +817,7 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
704
817
  if (enabled(config.gates, "config-floor")) {
705
818
  problems.push(...checkConfigFloor(defaults, config, { exemptions: config.floor.exemptions }));
706
819
  lines.push("OK floor every check the kit ships on is in force, or names the decision that switched it off");
707
- const hooks = hookDrift(config.root, config.hooks.required);
820
+ const hooks = hookDrift(config.root, requiredHooks(config));
708
821
  problems.push(...hooks.problems);
709
822
  lines.push("OK hooks each git hook makes the calls hooks.required names");
710
823
  for (const note of hooks.notes) lines.push(`NOTE hooks ${note}`);
@@ -756,5 +869,13 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
756
869
  problems.push(...(await docClaims(config, lines)));
757
870
  }
758
871
 
872
+ if (enabled(config.gates, "contract-idempotency")) {
873
+ problems.push(...(await contractIdempotency(config, lines)));
874
+ }
875
+
876
+ if (enabled(config.gates, "contract-routes")) {
877
+ problems.push(...(await contractRouteAgreement(config, routes, lines)));
878
+ }
879
+
759
880
  return { problems, lines };
760
881
  }
@@ -4,7 +4,8 @@ import { execFileSync } from "node:child_process";
4
4
  import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import path from "node:path";
7
- import { load } from "../config.mjs";
7
+ import { load, requiredHooks } from "../config.mjs";
8
+ import { hookDrift } from "./git-hooks.mjs";
8
9
  import { runInit } from "./init.mjs";
9
10
  import { installHooks } from "./install-hooks.mjs";
10
11
  import { runCheck } from "./check.mjs";
@@ -29,7 +30,7 @@ const quiet = (run) => {
29
30
  test("init writes the documents the gates read", async () => {
30
31
  const dir = repo();
31
32
  await quiet(() => runInit(load(dir)));
32
- for (const file of ["qc.config.json", "docs/decisions.md", "docs/enforcement.md", "docs/pagination.md", ".githooks/pre-commit", ".githooks/pre-push"]) {
33
+ for (const file of ["qc.config.json", "docs/decisions.md", "docs/enforcement.md", "docs/pagination.md", ".githooks/pre-commit", ".githooks/commit-msg", ".githooks/pre-push"]) {
33
34
  assert.ok(existsSync(path.join(dir, file)), `${file} is missing`);
34
35
  }
35
36
  rmSync(dir, { recursive: true, force: true });
@@ -241,3 +242,215 @@ test("a clean mirror run names every root it judged", async () => {
241
242
  assert.ok(line?.includes("frontend/tests") && line.includes("backend/tests"), `mirror line: ${line}`);
242
243
  rmSync(dir, { recursive: true, force: true });
243
244
  });
245
+
246
+ test("a fresh init repository with the default config passes the hooks check", async () => {
247
+ const dir = repo();
248
+ await quiet(() => runInit(load(dir)));
249
+ const config = load(dir);
250
+ assert.deepEqual(hookDrift(dir, requiredHooks(config)).problems, []);
251
+ rmSync(dir, { recursive: true, force: true });
252
+ });
253
+
254
+ test("a config with only extraExemptHelpers checks the kit defaults and the extra helper", async () => {
255
+ const dir = repo();
256
+ await quiet(() => runInit(load(dir)));
257
+ const config = JSON.parse(readFileSync(path.join(dir, "qc.config.json"), "utf8"));
258
+ config.tenantPredicate = {
259
+ extraExemptHelpers: [{ module: "backend/src/application/sql/bulk.ts", name: "insertMany", argument: 1 }],
260
+ };
261
+ write(dir, {
262
+ "qc.config.json": JSON.stringify(config),
263
+ "backend/src/application/orders.ts": [
264
+ 'import { insertReturning } from "./sql/crud";',
265
+ 'import { insertMany } from "./sql/bulk";',
266
+ "export function place(tx, v) {",
267
+ ' insertReturning(tx, "orders", ["id"], v);',
268
+ ' insertMany(tx, ["id"]);',
269
+ "}",
270
+ "",
271
+ ].join("\n"),
272
+ });
273
+ const { problems } = await runCheck(load(dir));
274
+ const helperCalls = problems.filter((problem) => problem.rule === "unscoped-helper-call");
275
+ assert.equal(helperCalls.length, 2, "the default helper and the extra helper are each checked");
276
+ assert.match(helperCalls.map((problem) => problem.detail).join("\n"), /insertReturning/);
277
+ assert.match(helperCalls.map((problem) => problem.detail).join("\n"), /insertMany/);
278
+ assert.ok(!problems.some((problem) => problem.rule === "dropped-default-helper"), "appending drops no default");
279
+ rmSync(dir, { recursive: true, force: true });
280
+ });
281
+
282
+ test("a config whose exemptHelpers omits a default fails the check as dropped-default-helper", async () => {
283
+ const dir = repo();
284
+ await quiet(() => runInit(load(dir)));
285
+ const config = JSON.parse(readFileSync(path.join(dir, "qc.config.json"), "utf8"));
286
+ config.gates = { ...config.gates, "config-floor": true };
287
+ config.tenantPredicate = { exemptHelpers: [{ module: "backend/src/application/sql/crud.ts", name: "insertReturning", argument: 2 }] };
288
+ write(dir, { "qc.config.json": JSON.stringify(config) });
289
+ const { problems } = await runCheck(load(dir));
290
+ const dropped = problems.filter((problem) => problem.rule === "dropped-default-helper");
291
+ assert.equal(dropped.length, 1);
292
+ assert.match(dropped[0].detail, /updateVersionedRow/);
293
+ rmSync(dir, { recursive: true, force: true });
294
+ });
295
+
296
+ test("a default also listed in extraExemptHelpers gives one unscoped-helper-call per call", async () => {
297
+ const dir = repo();
298
+ await quiet(() => runInit(load(dir)));
299
+ const config = JSON.parse(readFileSync(path.join(dir, "qc.config.json"), "utf8"));
300
+ config.tenantPredicate = {
301
+ extraExemptHelpers: [{ module: "backend/src/application/sql/crud.ts", name: "insertReturning", argument: 2 }],
302
+ };
303
+ write(dir, {
304
+ "qc.config.json": JSON.stringify(config),
305
+ "backend/src/application/orders.ts": [
306
+ 'import { insertReturning } from "./sql/crud";',
307
+ "export function place(tx, v) {",
308
+ ' insertReturning(tx, "orders", ["id"], v);',
309
+ "}",
310
+ "",
311
+ ].join("\n"),
312
+ });
313
+ const { problems } = await runCheck(load(dir));
314
+ assert.equal(problems.filter((problem) => problem.rule === "unscoped-helper-call").length, 1);
315
+ rmSync(dir, { recursive: true, force: true });
316
+ });
317
+
318
+ // The tenant-predicate gate reads how a caller imports an exempt helper. These run the whole check,
319
+ // so the wiring in `check.mjs` (the tsconfig read, the alias map, the two rules) is under test too.
320
+ const HELPER_RULES = new Set(["unscoped-helper-call", "unresolved-helper-import"]);
321
+ const CRUD_SOURCE = "export function insertReturning() {}\n";
322
+ const helperProblems = (problems) => problems.filter((problem) => HELPER_RULES.has(problem.rule)).map(({ path: file, rule }) => ({ file, rule }));
323
+
324
+ async function helperRepo(files, config = {}) {
325
+ const dir = repo();
326
+ write(dir, { "qc.config.json": JSON.stringify({ featureRoots: ["backend/src/features"], ...config }), ...files });
327
+ return dir;
328
+ }
329
+
330
+ test("check resolves an alias call through the tsconfig, and an unscoped one fails", async () => {
331
+ const dir = await helperRepo({
332
+ "tsconfig.json": '{ // a comment\n "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["backend/src/*"], }, }, }',
333
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
334
+ "backend/src/features/a/bad.ts": 'import { insertReturning } from "@/application/sql/crud.js";\ninsertReturning(tx, "a", ["id"], v);\n',
335
+ "backend/src/features/a/good.ts": 'import { insertReturning } from "@/application/sql/crud.js";\ninsertReturning(tx, "a", ["id", "tenant_id"], v);\n',
336
+ });
337
+ const { problems } = await runCheck(load(dir));
338
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/bad.ts", rule: "unscoped-helper-call" }]);
339
+ rmSync(dir, { recursive: true, force: true });
340
+ });
341
+
342
+ test("check fails a barrel import it cannot read, naming the file", async () => {
343
+ const dir = await helperRepo({
344
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
345
+ "backend/src/features/a/x.ts": 'import { insertReturning } from "../../application/sql/index.js";\n',
346
+ });
347
+ const { problems } = await runCheck(load(dir));
348
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unresolved-helper-import" }]);
349
+ rmSync(dir, { recursive: true, force: true });
350
+ });
351
+
352
+ test("check follows a renamed re-export in a barrel one level", async () => {
353
+ const dir = await helperRepo({
354
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
355
+ "backend/src/application/sql/index.ts": 'export { insertReturning as insertRow } from "./crud.js";\n',
356
+ "backend/src/features/a/x.ts": 'import { insertRow } from "../../application/sql/index.js";\ninsertRow(tx, "a", ["id"], v);\n',
357
+ });
358
+ const { problems } = await runCheck(load(dir));
359
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unscoped-helper-call" }]);
360
+ rmSync(dir, { recursive: true, force: true });
361
+ });
362
+
363
+ test("check reports a tsconfig it cannot parse, at the tsconfig", async () => {
364
+ const dir = await helperRepo({
365
+ "tsconfig.json": "{ not json",
366
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
367
+ "backend/src/features/a/x.ts": 'import { insertReturning } from "@/application/sql/crud.js";\n',
368
+ });
369
+ const { problems } = await runCheck(load(dir));
370
+ assert.deepEqual(
371
+ helperProblems(problems).sort((a, b) => a.file.localeCompare(b.file)),
372
+ [
373
+ { file: "backend/src/features/a/x.ts", rule: "unresolved-helper-import" },
374
+ { file: "tsconfig.json", rule: "unresolved-helper-import" },
375
+ ],
376
+ );
377
+ rmSync(dir, { recursive: true, force: true });
378
+ });
379
+
380
+ test("tenantPredicate.tsconfig points at the file that holds the paths, and its targets resolve from its folder", async () => {
381
+ const dir = await helperRepo(
382
+ {
383
+ "backend/tsconfig.json": '{ "compilerOptions": { "paths": { "@/*": ["src/*"] } } }',
384
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
385
+ "backend/src/features/a/x.ts": 'import { insertReturning } from "@/application/sql/crud.js";\ninsertReturning(tx, "a", ["id"], v);\n',
386
+ },
387
+ { tenantPredicate: { tsconfig: "backend/tsconfig.json" } },
388
+ );
389
+ const { problems } = await runCheck(load(dir));
390
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unscoped-helper-call" }]);
391
+ rmSync(dir, { recursive: true, force: true });
392
+ });
393
+
394
+ test("with the default tsconfig absent, an alias import fails closed", async () => {
395
+ const dir = await helperRepo({
396
+ "backend/tsconfig.json": '{ "compilerOptions": { "paths": { "@/*": ["src/*"] } } }',
397
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
398
+ "backend/src/features/a/x.ts": 'import { insertReturning } from "@/application/sql/crud.js";\n',
399
+ });
400
+ const { problems } = await runCheck(load(dir));
401
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unresolved-helper-import" }]);
402
+ rmSync(dir, { recursive: true, force: true });
403
+ });
404
+
405
+ test("check follows a helper renamed through two barrels", async () => {
406
+ const dir = await helperRepo({
407
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
408
+ "backend/src/application/sql/inner.ts": 'export { insertReturning as insertRow } from "./crud.js";\n',
409
+ "backend/src/application/sql/index.ts": 'export { insertRow as put } from "./inner.js";\n',
410
+ "backend/src/features/a/x.ts": 'import { put } from "../../application/sql/index.js";\nput(tx, "a", ["id"], v);\n',
411
+ });
412
+ const { problems } = await runCheck(load(dir));
413
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unscoped-helper-call" }]);
414
+ rmSync(dir, { recursive: true, force: true });
415
+ });
416
+
417
+ test("check treats a scanned file with no import as read, and one outside the scanned roots as untraceable", async () => {
418
+ const dir = await helperRepo({
419
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
420
+ "backend/src/application/sql/plain.ts": "export const plain = 1;\n",
421
+ "backend/src/application/sql/index.ts": 'export { plain as p } from "./plain.js";\nexport { thing as t } from "../../../../vendor/lib.js";\n',
422
+ "backend/src/features/a/x.ts": 'import { p } from "../../application/sql/index.js";\n',
423
+ "backend/src/features/a/y.ts": 'import { t } from "../../application/sql/index.js";\n',
424
+ });
425
+ const { problems } = await runCheck(load(dir));
426
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/y.ts", rule: "unresolved-helper-import" }]);
427
+ rmSync(dir, { recursive: true, force: true });
428
+ });
429
+
430
+ test("check follows a default export of a helper module that has no import or re-export", async () => {
431
+ const dir = await helperRepo({
432
+ "backend/src/application/sql/crud.ts": "export function insertReturning() {}\nexport default insertReturning;\n",
433
+ "backend/src/features/a/x.ts": 'import put from "../../application/sql/crud.js";\nput(tx, "a", ["id"], v);\n',
434
+ });
435
+ const { problems } = await runCheck(load(dir));
436
+ assert.deepEqual(helperProblems(problems), [{ file: "backend/src/features/a/x.ts", rule: "unscoped-helper-call" }]);
437
+ rmSync(dir, { recursive: true, force: true });
438
+ });
439
+
440
+ test("check follows an export const alias, and fails a file that aliases the helper in its body", async () => {
441
+ const dir = await helperRepo({
442
+ "backend/src/application/sql/crud.ts": CRUD_SOURCE,
443
+ "backend/src/application/sql/index.ts": 'import { insertReturning } from "./crud.js";\nexport const insertRow = insertReturning;\n',
444
+ "backend/src/features/a/x.ts": 'import { insertRow } from "../../application/sql/index.js";\ninsertRow(tx, "a", ["id"], v);\n',
445
+ "backend/src/features/a/y.ts": 'import { insertReturning } from "../../application/sql/crud.js";\nconst f = insertReturning;\nf(tx, "a", ["id"], v);\n',
446
+ });
447
+ const { problems } = await runCheck(load(dir));
448
+ assert.deepEqual(
449
+ helperProblems(problems).sort((a, b) => a.file.localeCompare(b.file)),
450
+ [
451
+ { file: "backend/src/features/a/x.ts", rule: "unscoped-helper-call" },
452
+ { file: "backend/src/features/a/y.ts", rule: "unresolved-helper-import" },
453
+ ],
454
+ );
455
+ rmSync(dir, { recursive: true, force: true });
456
+ });
@@ -0,0 +1,46 @@
1
+ // A resource: the operations of the contract and the ledger as they stood at the merge base with a
2
+ // ref. Git answers a missing ref or clone with a skip, never a failure. A base contract that does
3
+ // not parse is reported, because the check cannot say what it could not read.
4
+
5
+ import path from "node:path";
6
+ import { owesKey } from "../gates/contract-idempotency.mjs";
7
+ import { contractOperations } from "../gates/contract-operations.mjs";
8
+ import { git } from "./registry-history.mjs";
9
+
10
+ /** The ledger's ids as `git show` returned them. A missing or unreadable file is an empty ledger. */
11
+ function ledgerOf(text) {
12
+ try {
13
+ const parsed = JSON.parse(text ?? "[]");
14
+ return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
15
+ } catch {
16
+ return [];
17
+ }
18
+ }
19
+
20
+ /**
21
+ * @param {string} root the repository root, or a folder inside one
22
+ * @param {{base: string, contract: string, legacy: string, fields: string[], exemptDeleteById: boolean}} options
23
+ * the paths are relative to `root`; `fields` and `exemptDeleteById` decide which operation `owed` its key
24
+ * @returns {Promise<{skip: string} | {unreadable: string} | {ledger: string[], operations: {id: string, method: string, path: string, owed: boolean}[]}>}
25
+ */
26
+ export async function contractHistory(root, { base, contract, legacy, fields, exemptDeleteById }) {
27
+ if (git(root, "rev-parse", "--verify", "--quiet", "HEAD") === null) return { skip: "no git, or no commit yet" };
28
+ if (git(root, "rev-parse", "--verify", "--quiet", base + "^{commit}") === null) return { skip: "no ref '" + base + "'" };
29
+ const mergeBase = git(root, "merge-base", base, "HEAD")?.trim();
30
+ if (!mergeBase) return { skip: "no merge base with '" + base + "', as in a shallow clone" };
31
+ const at = (file) => git(root, "show", mergeBase + ":./" + file.split(path.sep).join("/"));
32
+ const contractText = at(contract);
33
+ let operations = [];
34
+ try {
35
+ const found = contractText === null ? [] : await contractOperations(contractText);
36
+ operations = found.map((operation) => ({
37
+ id: operation.id,
38
+ method: operation.method,
39
+ path: operation.path,
40
+ owed: owesKey(operation, { fields, exemptDeleteById }),
41
+ }));
42
+ } catch (error) {
43
+ return { unreadable: "the contract at the merge base with '" + base + "' does not parse: " + error.message };
44
+ }
45
+ return { ledger: ledgerOf(at(legacy)), operations };
46
+ }
@@ -0,0 +1,118 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { contractHistory } from "./contract-history.mjs";
8
+
9
+ const git = (dir, ...args) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd: dir, stdio: "pipe" });
10
+ const options = {
11
+ base: "main",
12
+ contract: "contracts/openapi.yaml",
13
+ legacy: "contracts/idempotency-legacy.json",
14
+ fields: ["mutationId"],
15
+ exemptDeleteById: true,
16
+ };
17
+ const CONTRACT = "paths:\n /v1/a:\n post:\n operationId: createA\n get:\n operationId: listA\n";
18
+
19
+ /** A repository whose one commit holds `files` under `folder`. The history is asked from `folder`. */
20
+ function committed(files, folder = "") {
21
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-history-"));
22
+ git(dir, "init", "-q", "-b", "main");
23
+ for (const [name, text] of Object.entries(files)) {
24
+ const file = path.join(dir, folder, name);
25
+ mkdirSync(path.dirname(file), { recursive: true });
26
+ writeFileSync(file, text);
27
+ }
28
+ git(dir, "add", "-A");
29
+ git(dir, "commit", "-q", "-m", "base");
30
+ return { root: path.join(dir, folder), done: () => rmSync(dir, { recursive: true, force: true }) };
31
+ }
32
+
33
+ test("the operations and the ledger are read as they stood at the merge base, and owed marks a missing key", async () => {
34
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": '["createA"]' });
35
+ const found = await contractHistory(repo.root, options);
36
+ repo.done();
37
+ assert.deepEqual(found.ledger, ["createA"]);
38
+ assert.deepEqual(found.operations, [
39
+ { id: "createA", method: "post", path: "/v1/a", owed: true },
40
+ { id: "listA", method: "get", path: "/v1/a", owed: false },
41
+ ]);
42
+ });
43
+
44
+ test("a root that is a folder inside the repository reads its own files", async () => {
45
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": '["createA"]' }, "service");
46
+ const found = await contractHistory(repo.root, options);
47
+ repo.done();
48
+ assert.deepEqual(found.ledger, ["createA"]);
49
+ assert.equal(found.operations.length, 2);
50
+ });
51
+
52
+ test("a malformed base ledger reads as empty", async () => {
53
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": "{not json" });
54
+ const found = await contractHistory(repo.root, options);
55
+ repo.done();
56
+ assert.deepEqual(found.ledger, []);
57
+ assert.equal(found.operations.length, 2);
58
+ });
59
+
60
+ test("a contract absent at the base holds no operations, so every ledger id is new", async () => {
61
+ const repo = committed({ "README.md": "x\n" });
62
+ const found = await contractHistory(repo.root, options);
63
+ repo.done();
64
+ assert.deepEqual(found, { ledger: [], operations: [] });
65
+ });
66
+
67
+ test("a base contract that does not parse is reported, not skipped", async () => {
68
+ const repo = committed({ "contracts/openapi.yaml": "paths: [unclosed\n" });
69
+ const found = await contractHistory(repo.root, options);
70
+ repo.done();
71
+ assert.equal(found.skip, undefined);
72
+ assert.match(found.unreadable, /merge base/);
73
+ });
74
+
75
+ test("no ref, and no repository, skip with a reason", async () => {
76
+ const repo = committed({ "README.md": "x\n" });
77
+ assert.match((await contractHistory(repo.root, { ...options, base: "no-such-ref" })).skip, /no ref 'no-such-ref'/);
78
+ repo.done();
79
+ const bare = mkdtempSync(path.join(tmpdir(), "qc-history-"));
80
+ try {
81
+ assert.match((await contractHistory(bare, options)).skip, /no git/);
82
+ } finally {
83
+ rmSync(bare, { recursive: true, force: true });
84
+ }
85
+ });
86
+
87
+ test("a keyed POST and an exempt DELETE by id are not owed", async () => {
88
+ const contract = [
89
+ "paths:",
90
+ " /v1/a:",
91
+ " post:",
92
+ " operationId: createA",
93
+ " requestBody:",
94
+ " content:",
95
+ " application/json:",
96
+ " schema:",
97
+ " properties: { mutationId: {} }",
98
+ " /v1/a/{id}:",
99
+ " delete:",
100
+ " operationId: deleteA",
101
+ "",
102
+ ].join("\n");
103
+ const repo = committed({ "contracts/openapi.yaml": contract });
104
+ const found = await contractHistory(repo.root, options);
105
+ const judged = await contractHistory(repo.root, { ...options, exemptDeleteById: false });
106
+ repo.done();
107
+ assert.deepEqual(found.operations.map(({ id, owed }) => [id, owed]), [["createA", false], ["deleteA", false]]);
108
+ assert.deepEqual(judged.operations.map(({ id, owed }) => [id, owed]), [["createA", false], ["deleteA", true]]);
109
+ });
110
+
111
+ test("a base ref that resolves but shares no history with HEAD skips as having no merge base", async () => {
112
+ const repo = committed({ "README.md": "x\n" });
113
+ git(repo.root, "checkout", "-q", "--orphan", "other");
114
+ git(repo.root, "commit", "-q", "--allow-empty", "-m", "unrelated");
115
+ const found = await contractHistory(repo.root, options);
116
+ repo.done();
117
+ assert.match(found.skip, /no merge base with 'main'/);
118
+ });