architecture-harness 0.10.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 +1 -1
- package/src/cli/check.mjs +168 -6
- package/src/cli/registry-history.mjs +53 -0
- package/src/cli/registry-history.test.mjs +88 -0
- package/src/config.mjs +55 -0
- package/src/descriptions.mjs +7 -0
- package/src/gates/closed-set-writers.mjs +36 -0
- package/src/gates/closed-set-writers.test.mjs +46 -0
- package/src/gates/doc-claims.mjs +45 -0
- package/src/gates/doc-claims.test.mjs +33 -0
- package/src/gates/integration-imports.mjs +49 -0
- package/src/gates/integration-imports.test.mjs +35 -0
- package/src/gates/migration-numbers.mjs +33 -0
- package/src/gates/migration-numbers.test.mjs +35 -0
- package/src/gates/parity.mjs +163 -0
- package/src/gates/parity.test.mjs +108 -0
- package/src/gates/registry-literal.mjs +137 -0
- package/src/gates/registry-literal.test.mjs +68 -0
- package/src/gates/sql-identifiers.mjs +72 -9
- package/src/gates/sql-identifiers.test.mjs +70 -1
- package/src/gates/tenant-predicate.mjs +108 -58
- package/src/gates/tenant-predicate.test.mjs +61 -39
- package/src/gates/threshold-ratchet.mjs +46 -0
- package/src/gates/threshold-ratchet.test.mjs +60 -0
- package/templates/quality-thresholds.json +2 -2
package/package.json
CHANGED
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 {
|
|
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";
|
|
@@ -30,8 +33,16 @@ import { checkAdrFormat } from "../gates/adr-format.mjs";
|
|
|
30
33
|
import { checkConfigFloor } from "../gates/config-floor.mjs";
|
|
31
34
|
import { defaults } from "../config.mjs";
|
|
32
35
|
import { rules as lintRules } from "../eslint/index.mjs";
|
|
33
|
-
import { enabled, readerEntries, thresholds } from "../config.mjs";
|
|
36
|
+
import { adrLog, enabled, readerEntries, thresholds } from "../config.mjs";
|
|
34
37
|
import { checkRegistryReaders } from "../gates/registry-readers.mjs";
|
|
38
|
+
import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
|
|
39
|
+
import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
|
|
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";
|
|
45
|
+
import { ratchetInputs } from "./registry-history.mjs";
|
|
35
46
|
import { repoFiles } from "./repo-files.mjs";
|
|
36
47
|
|
|
37
48
|
// Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
|
|
@@ -179,6 +190,15 @@ function sourceFiles(config, tree, only) {
|
|
|
179
190
|
return readEach(config.root, rels);
|
|
180
191
|
}
|
|
181
192
|
|
|
193
|
+
function parsedJson(source) {
|
|
194
|
+
if (source === null) return null;
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse(source);
|
|
197
|
+
} catch {
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
182
202
|
async function registered(file) {
|
|
183
203
|
const source = await read(file);
|
|
184
204
|
if (source === null) return [];
|
|
@@ -244,7 +264,7 @@ async function resourceFiles(config, tree) {
|
|
|
244
264
|
}
|
|
245
265
|
|
|
246
266
|
/** Nothing runs the schema and the queries together, so this asserts their names agree. */
|
|
247
|
-
async function sqlAgreement(config, tree, taken) {
|
|
267
|
+
async function sqlAgreement(config, tree, taken, lines) {
|
|
248
268
|
const migrationDir = posix(config.paths.migrations);
|
|
249
269
|
const migrations = await readEach(
|
|
250
270
|
config.root,
|
|
@@ -274,12 +294,30 @@ async function sqlAgreement(config, tree, taken) {
|
|
|
274
294
|
if (enabled(config.gates, "sql-identifiers")) {
|
|
275
295
|
const byName = migrations.map((migration) => ({ file: path.posix.basename(migration.path), sql: migration.contents }));
|
|
276
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`);
|
|
277
308
|
}
|
|
278
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 };
|
|
279
315
|
problems.push(
|
|
280
316
|
...checkTenantPredicate(scoped, owned, tenantOptions),
|
|
281
|
-
...
|
|
317
|
+
...checkExemptHelperCalls(callers, helpers, helperOptions),
|
|
282
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`);
|
|
283
321
|
}
|
|
284
322
|
return problems;
|
|
285
323
|
}
|
|
@@ -350,6 +388,83 @@ function infraFiles(config, tree) {
|
|
|
350
388
|
return readEach(config.root, rels);
|
|
351
389
|
}
|
|
352
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
|
+
|
|
353
468
|
/**
|
|
354
469
|
* @param {object} config
|
|
355
470
|
* @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
|
|
@@ -463,13 +578,40 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
|
|
|
463
578
|
if (readers.length > 0) lines.push(`OK readers ${readers.length} registry reader(s), each present and naming its entry`);
|
|
464
579
|
}
|
|
465
580
|
|
|
581
|
+
if (enabled(config.gates, "registry-literal")) {
|
|
582
|
+
const docs = await readEach(config.root, tree.under(config.docs.root).filter((file) => file.endsWith(".md")));
|
|
583
|
+
const libraries = parsedJson(await read(path.join(config.root, config.versions)))?.libraries ?? {};
|
|
584
|
+
const exempt = config.registryLiteral.exempt ?? adrLog(config);
|
|
585
|
+
problems.push(...checkRegistryLiteral(docs, { thresholds: thresholds(config), libraries, exempt }));
|
|
586
|
+
if (docs.length > 0) lines.push(`OK literals ${docs.length} doc(s) carry a token, never a figure a registry owns`);
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
if (enabled(config.gates, "threshold-ratchet")) {
|
|
590
|
+
const { base } = config.ratchet;
|
|
591
|
+
const inputs = await ratchetInputs(config.root, { base, registry: config.thresholds, adrGlobs: adrLog(config) });
|
|
592
|
+
if (inputs.skip) {
|
|
593
|
+
lines.push(`OK ratchet skipped: ${inputs.skip}`);
|
|
594
|
+
} else {
|
|
595
|
+
problems.push(...checkThresholdRatchet(inputs.before, inputs.after, inputs.adrs, { registry: config.thresholds }));
|
|
596
|
+
const count = Object.keys(inputs.after).length;
|
|
597
|
+
if (count > 0) lines.push(`OK ratchet ${count} threshold(s) against the merge base with ${base}; a loosening names its ADR`);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
466
601
|
if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
|
|
467
|
-
|
|
468
|
-
|
|
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)));
|
|
469
604
|
// An exemption is counted and named, so it stays a decision rather than a habit.
|
|
470
605
|
for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
|
|
471
606
|
}
|
|
472
607
|
|
|
608
|
+
if (enabled(config.gates, "migration-numbers")) {
|
|
609
|
+
const migrationDir = posix(config.paths.migrations);
|
|
610
|
+
const names = tree.namesIn(migrationDir).filter((name) => tree.isFile(join(migrationDir, name)));
|
|
611
|
+
problems.push(...checkMigrationNumbers(names, migrationDir));
|
|
612
|
+
if (names.length > 0) lines.push(`OK migrations ${names.filter((name) => name.endsWith(".sql")).length} migration(s), each number unique, with no gap`);
|
|
613
|
+
}
|
|
614
|
+
|
|
473
615
|
if (enabled(config.gates, "saga-tests")) {
|
|
474
616
|
const sources = await sourceFiles(config, tree);
|
|
475
617
|
const sagas = declaredSagas(
|
|
@@ -589,5 +731,25 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
|
|
|
589
731
|
if (docs.length > 0) lines.push(`OK decisions ${docs.length} record(s), each with its cost and its rejected alternatives`);
|
|
590
732
|
}
|
|
591
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
|
+
|
|
592
754
|
return { problems, lines };
|
|
593
755
|
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// A resource: the thresholds registry at the merge base with a ref, the registry now, and the ADR
|
|
2
|
+
// files the change touches. Git answers each question; no answer is a reason to skip, never a failure.
|
|
3
|
+
|
|
4
|
+
import { spawnSync } from "node:child_process";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { globMatcher } from "../glob.mjs";
|
|
8
|
+
|
|
9
|
+
/** @returns {string|null} stdout, or null when git is absent or the command fails. */
|
|
10
|
+
function git(root, ...args) {
|
|
11
|
+
const result = spawnSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
12
|
+
return result.status === 0 ? result.stdout : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function gatesOf(text) {
|
|
16
|
+
if (text === null) return {};
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(text).gates ?? {};
|
|
19
|
+
} catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const paths = (listing) => (listing ?? "").split("\0").filter(Boolean);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* @param {string} root the repository root, or a folder inside one
|
|
28
|
+
* @param {{base: string, registry: string, adrGlobs: string[]}} options
|
|
29
|
+
* @returns {Promise<{skip: string} | {before: object, after: object, adrs: {path: string, text: string}[]}>}
|
|
30
|
+
*/
|
|
31
|
+
export async function ratchetInputs(root, { base, registry, adrGlobs }) {
|
|
32
|
+
if (git(root, "rev-parse", "--verify", "--quiet", "HEAD") === null) return { skip: "no git, or no commit yet" };
|
|
33
|
+
if (git(root, "rev-parse", "--verify", "--quiet", `${base}^{commit}`) === null) return { skip: `no ref '${base}'` };
|
|
34
|
+
const mergeBase = git(root, "merge-base", base, "HEAD")?.trim();
|
|
35
|
+
if (!mergeBase) return { skip: `no merge base with '${base}', as in a shallow clone` };
|
|
36
|
+
|
|
37
|
+
const file = registry.split(path.sep).join("/");
|
|
38
|
+
const before = gatesOf(git(root, "show", `${mergeBase}:./${file}`));
|
|
39
|
+
const after = gatesOf(await readFile(path.join(root, registry), "utf8").catch(() => null));
|
|
40
|
+
|
|
41
|
+
// Committed, staged and unstaged changes since the merge base, and a new file not yet added.
|
|
42
|
+
const isAdr = globMatcher(adrGlobs);
|
|
43
|
+
const changed = new Set([
|
|
44
|
+
...paths(git(root, "diff", "--name-only", "--relative", "-z", mergeBase)),
|
|
45
|
+
...paths(git(root, "ls-files", "--others", "--exclude-standard", "-z")),
|
|
46
|
+
]);
|
|
47
|
+
const adrs = [];
|
|
48
|
+
for (const rel of [...changed].filter((rel) => rel.endsWith(".md") && isAdr(rel))) {
|
|
49
|
+
const text = await readFile(path.join(root, rel), "utf8").catch(() => null);
|
|
50
|
+
if (text !== null) adrs.push({ path: rel, text });
|
|
51
|
+
}
|
|
52
|
+
return { before, after, adrs };
|
|
53
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { load } from "../config.mjs";
|
|
8
|
+
import { runCheck } from "./check.mjs";
|
|
9
|
+
|
|
10
|
+
const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" });
|
|
11
|
+
const REGISTRY = "quality-thresholds.json";
|
|
12
|
+
const registry = (gates) => `${JSON.stringify({ gates }, null, 2)}\n`;
|
|
13
|
+
const FILELENGTH = { filelength: { value: 500, unit: "lines", comparator: "max" } };
|
|
14
|
+
|
|
15
|
+
function write(dir, files) {
|
|
16
|
+
for (const [rel, contents] of Object.entries(files)) {
|
|
17
|
+
mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
|
18
|
+
writeFileSync(path.join(dir, rel), contents);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** A repository whose `main` holds the registry, checked out on a branch `feat`. One per case. */
|
|
23
|
+
function repo({ base = "main", commit = true } = {}) {
|
|
24
|
+
const dir = mkdtempSync(path.join(tmpdir(), "qc-ratchet-"));
|
|
25
|
+
git(dir, "init", "-q", "-b", "main");
|
|
26
|
+
git(dir, "config", "user.name", "qc");
|
|
27
|
+
git(dir, "config", "user.email", "qc@example.com");
|
|
28
|
+
git(dir, "config", "commit.gpgsign", "false");
|
|
29
|
+
write(dir, { "qc.config.json": JSON.stringify({ featureRoots: [], ratchet: { base } }), [REGISTRY]: registry(FILELENGTH) });
|
|
30
|
+
if (!commit) return dir;
|
|
31
|
+
git(dir, "add", ".");
|
|
32
|
+
git(dir, "commit", "-q", "-m", "init");
|
|
33
|
+
git(dir, "checkout", "-q", "-b", "feat");
|
|
34
|
+
return dir;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function ratchet(dir) {
|
|
38
|
+
const { problems, lines } = await runCheck(load(dir));
|
|
39
|
+
return {
|
|
40
|
+
loosened: problems.filter((problem) => problem.rule === "loosened-threshold"),
|
|
41
|
+
line: lines.find((line) => line.includes("ratchet")),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
test("a max that rises from 500 to 550 fails", async () => {
|
|
46
|
+
const dir = repo();
|
|
47
|
+
write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }) });
|
|
48
|
+
const { loosened } = await ratchet(dir);
|
|
49
|
+
assert.equal(loosened.length, 1);
|
|
50
|
+
assert.match(loosened[0].detail, /filelength/);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("the same rise passes with a committed ADR that names the key", async () => {
|
|
54
|
+
const dir = repo();
|
|
55
|
+
write(dir, {
|
|
56
|
+
[REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }),
|
|
57
|
+
"docs/decisions/0002-longer-files.md": "# Longer files\n\n`filelength` rises to 550: the parser needs one file.\n",
|
|
58
|
+
});
|
|
59
|
+
git(dir, "add", ".");
|
|
60
|
+
git(dir, "commit", "-q", "-m", "loosen");
|
|
61
|
+
assert.deepEqual((await ratchet(dir)).loosened, []);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("a tightening passes", async () => {
|
|
65
|
+
const dir = repo();
|
|
66
|
+
write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 450 } }) });
|
|
67
|
+
assert.deepEqual((await ratchet(dir)).loosened, []);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("a new entry passes", async () => {
|
|
71
|
+
const dir = repo();
|
|
72
|
+
write(dir, { [REGISTRY]: registry({ ...FILELENGTH, nesting: { value: 9, unit: "count", comparator: "max" } }) });
|
|
73
|
+
assert.deepEqual((await ratchet(dir)).loosened, []);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("a base ref that does not exist skips with an OK line that says why", async () => {
|
|
77
|
+
const dir = repo({ base: "origin/main" });
|
|
78
|
+
write(dir, { [REGISTRY]: registry({ filelength: { ...FILELENGTH.filelength, value: 550 } }) });
|
|
79
|
+
const { loosened, line } = await ratchet(dir);
|
|
80
|
+
assert.deepEqual(loosened, []);
|
|
81
|
+
assert.match(line, /^OK .*no ref 'origin\/main'/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("a repository with no commit yet skips with an OK line", async () => {
|
|
85
|
+
const { loosened, line } = await ratchet(repo({ commit: false }));
|
|
86
|
+
assert.deepEqual(loosened, []);
|
|
87
|
+
assert.match(line, /^OK .*no commit/);
|
|
88
|
+
});
|
package/src/config.mjs
CHANGED
|
@@ -36,6 +36,15 @@ export const defaults = {
|
|
|
36
36
|
},
|
|
37
37
|
|
|
38
38
|
thresholds: "quality-thresholds.json",
|
|
39
|
+
// Pinned library versions. Docs carry a {{ver:id}} or {{v:id}} token for each.
|
|
40
|
+
versions: "versions.json",
|
|
41
|
+
|
|
42
|
+
// Globs of docs that may state a registry figure. Null is the ADR log, from adrLog(): a decision
|
|
43
|
+
// states the number as of its date.
|
|
44
|
+
registryLiteral: { exempt: null },
|
|
45
|
+
|
|
46
|
+
// A threshold loosens only with an ADR. `base` is the ref whose merge base the registry is compared with.
|
|
47
|
+
ratchet: { base: "origin/main" },
|
|
39
48
|
|
|
40
49
|
// A key that makes a retry a resume rather than a second write. docs/guards.md.
|
|
41
50
|
idempotency: {
|
|
@@ -71,6 +80,8 @@ export const defaults = {
|
|
|
71
80
|
// Files inside a feature that carry SQL.
|
|
72
81
|
resourceFiles: ["resource.ts", "schema.ts"],
|
|
73
82
|
resourceDirs: ["shared", "slices"],
|
|
83
|
+
// The file in each server feature whose tables and columns every migration set must name.
|
|
84
|
+
schemaFile: "schema.ts",
|
|
74
85
|
triggerFile: "trigger.ts",
|
|
75
86
|
// Platform and frontend features paths for boundary checks.
|
|
76
87
|
platform: "frontend/src/platform",
|
|
@@ -248,6 +259,36 @@ export const defaults = {
|
|
|
248
259
|
// Files a person reviewed that may call sql.raw. Each one is a decision, so the list stays short.
|
|
249
260
|
sqlRaw: { allow: [] },
|
|
250
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
|
+
|
|
251
292
|
anatomy: {
|
|
252
293
|
// Bounded vertical slices.
|
|
253
294
|
slice: {
|
|
@@ -273,6 +314,9 @@ export const defaults = {
|
|
|
273
314
|
"registry-agreement": true,
|
|
274
315
|
"registry-readers": true,
|
|
275
316
|
"sql-identifiers": true,
|
|
317
|
+
"migration-numbers": true,
|
|
318
|
+
"registry-literal": true,
|
|
319
|
+
"threshold-ratchet": true,
|
|
276
320
|
"tenant-predicate": true,
|
|
277
321
|
"claimed-requirements": true,
|
|
278
322
|
"public-routes": true,
|
|
@@ -292,6 +336,12 @@ export const defaults = {
|
|
|
292
336
|
"english-source": false,
|
|
293
337
|
"adr-format": false,
|
|
294
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,
|
|
295
345
|
},
|
|
296
346
|
|
|
297
347
|
// Gates that produce rather than inspect: a repository's codegen imports these and
|
|
@@ -387,6 +437,11 @@ export function thresholds(config) {
|
|
|
387
437
|
return createRequire(import.meta.url)(file).gates ?? {};
|
|
388
438
|
}
|
|
389
439
|
|
|
440
|
+
/** The files that hold decision records: each ADR under `adr.root`, and the decision register. */
|
|
441
|
+
export function adrLog(config) {
|
|
442
|
+
return [`${config.adr.root.replace(/\/+$/, "")}/**`, config.docs.decisions];
|
|
443
|
+
}
|
|
444
|
+
|
|
390
445
|
/**
|
|
391
446
|
* Registry entries that say who may hold their number. `names` are identifier patterns, each a
|
|
392
447
|
* regular expression matched against the whole identifier, case-insensitive. `readers` are paths.
|
package/src/descriptions.mjs
CHANGED
|
@@ -6,6 +6,9 @@ export const gateDescriptions = Object.freeze({
|
|
|
6
6
|
"registry-agreement": "A value written twice agrees with the registry that owns it",
|
|
7
7
|
"registry-readers": "Every reader a registry entry names exists and names the entry",
|
|
8
8
|
"sql-identifiers": "A query names a column a migration declares, and only its own feature's tables",
|
|
9
|
+
"migration-numbers": "Each migration number is unique, and the numbers run with no gap",
|
|
10
|
+
"registry-literal": "A doc states a registry threshold or library version as its token, never as the figure",
|
|
11
|
+
"threshold-ratchet": "A threshold never loosens against the merge base unless a changed ADR names it",
|
|
9
12
|
"tenant-predicate": "Every statement on a business table filters on the tenant",
|
|
10
13
|
"claimed-requirements": "A requirement a route claims names the test that proves it",
|
|
11
14
|
"public-routes": "The edge lets through exactly the routes the api serves without a session",
|
|
@@ -22,6 +25,10 @@ export const gateDescriptions = Object.freeze({
|
|
|
22
25
|
"english-source": "Comments, docs and rules are English; another language is data, declared beside its English variant",
|
|
23
26
|
"adr-format": "Every decision record carries its cost and the alternatives it rejected, not just its claim",
|
|
24
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",
|
|
25
32
|
});
|
|
26
33
|
|
|
27
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
|
+
}
|