architecture-harness 0.7.0 → 0.8.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/src/cli/check.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // I/O only. Every decision is a pure function under src/gates/, each with a test
2
2
  // beside it. ADR-0032. Where this file names a path, that path came from config.
3
3
 
4
- import { readFile, readdir, stat } from "node:fs/promises";
4
+ import { readFile, stat } from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { checkFeatureAnatomy, checkNoEmptyBlock } from "../gates/eight-blocks.mjs";
7
7
  import { checkCitations, checkDocPaths, checkSelfContained, definedIds } from "../gates/citations.mjs";
@@ -25,63 +25,111 @@ import { checkEnforcementMap } from "../gates/enforcement-map.mjs";
25
25
  import { checkFrontendBoundaries } from "../gates/frontend-boundaries.mjs";
26
26
  import { checkTestMirror, mirrorFolders } from "../gates/test-mirror.mjs";
27
27
  import { checkCommentStyle } from "../gates/comment-style.mjs";
28
- import { checkEnglishSource, checkTranslationPairs } from "../gates/english-source.mjs";
28
+ import { checkEnglishFiles, checkEnglishSource, checkTranslationPairs } from "../gates/english-source.mjs";
29
29
  import { checkAdrFormat } from "../gates/adr-format.mjs";
30
30
  import { checkConfigFloor } from "../gates/config-floor.mjs";
31
31
  import { defaults } from "../config.mjs";
32
32
  import { rules as lintRules } from "../eslint/index.mjs";
33
33
  import { enabled } from "../config.mjs";
34
+ import { repoFiles } from "./repo-files.mjs";
34
35
 
36
+ // Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
35
37
  const SKIP = /node_modules|\/dist\/|\.test\.[cm]?[jt]sx?$/;
38
+ const BUILD_OUTPUT = /node_modules|\/dist\//;
36
39
  const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
37
40
  const SOURCE_EXTENSION = /\.([cm]?[jt]sx?)$/;
38
41
  const CITABLE_EXTENSION = /\.(tsx?|mjs|md)$/;
39
42
  const INFRA_EXTENSIONS = [".tf", ".sh", ".tfvars", ".tfvars.example", ".hcl", ".hcl.example"];
40
43
  const INFRA_SKIP = [".lock.hcl"];
44
+ // Windows caps a command line at 32,767 characters. A longer file list is filtered here instead.
45
+ const PATHSPEC_BUDGET = 8_000;
41
46
 
42
47
  const read = (file) => readFile(file, "utf8").catch(() => null);
43
- const list = (dir, options) => readdir(dir, options).catch(() => []);
44
48
 
45
49
  /** A problem names a path a reader can open — forward slashes always, since every gate splits on "/". */
46
50
  const relativeTo = (root) => (file) => (path.relative(root, file) || file).split(path.sep).join("/");
47
51
 
48
- async function listFeature(dir) {
49
- const files = [];
50
- async function walk(current, prefix) {
51
- for (const entry of await list(current, { withFileTypes: true })) {
52
- const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
53
- if (entry.isDirectory()) await walk(path.join(current, entry.name), rel);
54
- else files.push(rel);
52
+ /** A config path as the listing spells it: forward slashes, no `./`, no trailing slash. The root is "". */
53
+ function posix(dir) {
54
+ const normal = path.posix.normalize(String(dir).split(path.sep).join("/")).replace(/\/+$/, "");
55
+ return normal === "." ? "" : normal;
56
+ }
57
+
58
+ const join = (dir, name) => (dir ? `${dir}/${name}` : name);
59
+
60
+ /** The one listing of a run, with the names each folder holds, as `readdir` returned them. */
61
+ function treeOf(files) {
62
+ const isFile = new Set(files);
63
+ const children = new Map();
64
+ for (const file of files) {
65
+ let folder = "";
66
+ for (const part of file.split("/")) {
67
+ const names = children.get(folder) ?? new Set();
68
+ names.add(part);
69
+ children.set(folder, names);
70
+ folder = join(folder, part);
55
71
  }
56
72
  }
57
- await walk(dir, "");
58
- return files;
73
+ return {
74
+ files,
75
+ isFile: (rel) => isFile.has(rel),
76
+ /** The files at or below `dir`. */
77
+ under(dir) {
78
+ const prefix = posix(dir);
79
+ return prefix === "" ? files : files.filter((file) => file.startsWith(`${prefix}/`));
80
+ },
81
+ /** The names directly in `dir`, files and folders both. */
82
+ namesIn: (dir) => [...(children.get(posix(dir)) ?? [])],
83
+ foldersIn(dir) {
84
+ const prefix = posix(dir);
85
+ return [...(children.get(prefix) ?? [])].filter((name) => children.has(join(prefix, name)));
86
+ },
87
+ };
59
88
  }
60
89
 
61
- async function readFeature(dir) {
62
- const files = await listFeature(dir);
63
- const contents = [];
64
- for (const file of files) {
65
- const full = path.join(dir, file);
66
- const isSource = /\.tsx?$/.test(file) && (await stat(full).catch(() => null))?.isFile();
67
- if (isSource) contents.push({ path: full, contents: await readFile(full, "utf8") });
90
+ /** Read each listed file. One the listing names but the disk no longer holds is skipped. */
91
+ async function readEach(root, rels) {
92
+ const files = [];
93
+ for (const rel of rels) {
94
+ const contents = await read(path.join(root, rel));
95
+ if (contents !== null) files.push({ path: rel, contents });
96
+ }
97
+ return files;
98
+ }
68
99
 
100
+ /** The given files, and the feature folders that hold them: all the fast path reads. */
101
+ function scopeOf(config, given) {
102
+ const scope = new Set(given);
103
+ for (const file of given) {
104
+ for (const root of config.featureRoots.map(posix)) {
105
+ const inside = root === "" ? file : file.startsWith(`${root}/`) ? file.slice(root.length + 1) : null;
106
+ if (inside?.includes("/")) scope.add(join(root, inside.split("/")[0]));
107
+ }
69
108
  }
70
- return { feature: { feature: dir, files }, contents };
109
+ const specs = [...scope];
110
+ return specs.join(" ").length > PATHSPEC_BUDGET ? undefined : specs;
71
111
  }
72
112
 
73
- async function featureDirs(root) {
74
- const entries = await list(root, { withFileTypes: true });
75
- return entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(root, entry.name));
113
+ async function readFeature(config, tree, dir) {
114
+ const files = tree.under(dir).map((file) => file.slice(dir.length + 1));
115
+ const contents = [];
116
+ for (const file of files) {
117
+ if (!/\.tsx?$/.test(file)) continue;
118
+ const full = path.join(config.root, dir, file);
119
+ const source = await read(full);
120
+ if (source !== null) contents.push({ path: full, contents: source });
121
+ }
122
+ return { feature: { feature: path.join(config.root, dir), files }, contents };
76
123
  }
77
124
 
78
- async function collect(roots, only) {
125
+ async function collect(config, tree, only) {
79
126
  const features = [];
80
127
  const contents = [];
81
- for (const root of roots) {
82
- for (const dir of await featureDirs(root)) {
83
- if (only && !only.startsWith(dir)) continue;
84
- const found = await readFeature(dir);
128
+ for (const root of config.featureRoots.map(posix)) {
129
+ for (const name of tree.foldersIn(root)) {
130
+ const dir = join(root, name);
131
+ if (only && !only.some((file) => file === dir || file.startsWith(`${dir}/`))) continue;
132
+ const found = await readFeature(config, tree, dir);
85
133
  features.push(found.feature);
86
134
  contents.push(...found.contents);
87
135
  }
@@ -89,60 +137,45 @@ async function collect(roots, only) {
89
137
  return { features, contents };
90
138
  }
91
139
 
92
- async function citableFiles(roots, root) {
93
- const rel = relativeTo(root);
94
- const files = [];
95
- async function walk(dir) {
96
- for (const entry of await list(dir, { withFileTypes: true })) {
97
- const full = path.join(dir, entry.name);
98
- if (SKIP.test(full)) continue;
99
- if (entry.isDirectory()) await walk(full);
100
- else if (CITABLE_EXTENSION.test(entry.name)) {
101
- files.push({ path: rel(full), contents: await readFile(full, "utf8") });
102
- }
103
- }
104
- }
105
- for (const root of roots) await walk(root);
106
- return files;
140
+ function citableFiles(config, tree, roots) {
141
+ const rels = roots
142
+ .flatMap((root) => tree.under(root))
143
+ .filter((file) => !SKIP.test(`/${file}`) && CITABLE_EXTENSION.test(file));
144
+ return readEach(config.root, rels);
107
145
  }
108
146
 
109
- /** Every file under the citable roots whose extension matches, nothing skipped but build output. */
110
- async function filesMatching(config, pattern, language) {
111
- const rel = relativeTo(config.root);
112
- const skip = new RegExp(language.exclude.join("|"));
113
- const files = [];
114
- async function walk(dir) {
115
- for (const entry of await list(dir, { withFileTypes: true }).catch(() => [])) {
116
- const full = path.join(dir, entry.name);
117
- if (skip.test(rel(full))) continue;
118
- if (entry.isDirectory()) await walk(full);
119
- else if (pattern.test(entry.name)) files.push({ path: rel(full), contents: await readFile(full, "utf8") });
120
- }
121
- }
147
+ /** A regex tested on a file and on each folder above it, as a walk that pruned folders tested it. */
148
+ function prunedBy(pattern) {
149
+ const folders = new Map();
150
+ const parentOf = (rel) => rel.slice(0, Math.max(rel.lastIndexOf("/"), 0));
151
+ const skipped = (folder) => {
152
+ if (folder === "") return false;
153
+ if (!folders.has(folder)) folders.set(folder, skipped(parentOf(folder)) || pattern.test(folder));
154
+ return folders.get(folder);
155
+ };
156
+ return (file) => skipped(parentOf(file)) || pattern.test(file);
157
+ }
158
+
159
+ /** Every listed file under the language roots whose extension matches, minus `language.exclude`. */
160
+ function languageFiles(config, files) {
161
+ const { language } = config;
162
+ const pattern = new RegExp(`\\.(${language.extensions.join("|")})$`);
163
+ const skip = prunedBy(new RegExp(language.exclude.join("|")));
122
164
  // The whole repository, not the citable roots: those name where decisions are cited, which has
123
165
  // nothing to do with where a language rule applies. Contracts and infrastructure are not citable
124
166
  // and were invisible because of it.
125
- for (const root of language.roots) await walk(path.join(config.root, root));
126
- return files;
167
+ const roots = language.roots.map(posix);
168
+ const inRoot = (file) => roots.some((root) => root === "" || file.startsWith(`${root}/`));
169
+ return files.filter((file) => inRoot(file) && pattern.test(file) && !skip(file));
127
170
  }
128
171
 
129
172
  /** Every source file under the citable roots, tests included. */
130
- async function sourceFiles(config, only) {
131
- const rel = relativeTo(config.root);
173
+ function sourceFiles(config, tree, only) {
132
174
  const roots = only === undefined ? config.paths.citable : [only];
133
- const files = [];
134
- async function walk(dir) {
135
- for (const entry of await list(dir, { withFileTypes: true })) {
136
- const full = path.join(dir, entry.name);
137
- if (/node_modules|\/dist\//.test(full)) continue;
138
- if (entry.isDirectory()) await walk(full);
139
- else if (SOURCE_EXTENSION.test(entry.name)) {
140
- files.push({ path: rel(full), contents: await readFile(full, "utf8") });
141
- }
142
- }
143
- }
144
- for (const root of roots) await walk(path.join(config.root, root));
145
- return files;
175
+ const rels = roots
176
+ .flatMap((root) => tree.under(root))
177
+ .filter((file) => !BUILD_OUTPUT.test(`/${file}`) && SOURCE_EXTENSION.test(file));
178
+ return readEach(config.root, rels);
146
179
  }
147
180
 
148
181
  async function registered(file) {
@@ -189,23 +222,20 @@ async function agreements(config) {
189
222
  }
190
223
 
191
224
  /** Every file inside a server feature that carries SQL, with the feature that owns it. */
192
- async function resourceFiles(config) {
193
- const root = path.join(config.root, config.paths.serverFeatures);
194
- const rel = relativeTo(config.root);
225
+ async function resourceFiles(config, tree) {
226
+ const root = posix(config.paths.serverFeatures);
195
227
  const resources = [];
196
- for (const feature of await list(root)) {
197
- const dir = path.join(root, feature);
198
- for (const name of config.paths.resourceFiles) {
199
- const file = path.join(dir, name);
200
- const source = await read(file);
201
- if (source) resources.push({ path: rel(file), source, feature });
202
- }
228
+ const take = async (rel, feature) => {
229
+ const source = tree.isFile(rel) ? await read(path.join(config.root, rel)) : null;
230
+ if (source) resources.push({ path: rel, source, feature });
231
+ };
232
+ for (const feature of tree.namesIn(root)) {
233
+ const dir = join(root, feature);
234
+ for (const name of config.paths.resourceFiles) await take(`${dir}/${name}`, feature);
203
235
  for (const subdir of config.paths.resourceDirs) {
204
- for (const name of await list(path.join(dir, subdir))) {
236
+ for (const name of tree.namesIn(`${dir}/${subdir}`)) {
205
237
  if (!/\.tsx?$/.test(name) || name.includes(".test.")) continue;
206
- const file = path.join(dir, subdir, name);
207
- const source = await read(file);
208
- if (source) resources.push({ path: rel(file), source, feature });
238
+ await take(`${dir}/${subdir}/${name}`, feature);
209
239
  }
210
240
  }
211
241
  }
@@ -213,16 +243,15 @@ async function resourceFiles(config) {
213
243
  }
214
244
 
215
245
  /** Nothing runs the schema and the queries together, so this asserts their names agree. */
216
- async function sqlAgreement(config, taken) {
217
- const migrationDir = path.join(config.root, config.paths.migrations);
218
- const names = (await list(migrationDir)).filter((name) => name.endsWith(".sql"));
219
- const migrations = [];
220
- for (const file of names) {
221
- migrations.push({ file, sql: await readFile(path.join(migrationDir, file), "utf8") });
222
- }
223
- const resources = await resourceFiles(config);
224
- const features = await list(path.join(config.root, config.paths.serverFeatures));
225
- const tables = declaredColumns(migrations.map((migration) => migration.sql));
246
+ async function sqlAgreement(config, tree, taken) {
247
+ const migrationDir = posix(config.paths.migrations);
248
+ const migrations = await readEach(
249
+ config.root,
250
+ tree.namesIn(migrationDir).filter((name) => name.endsWith(".sql")).map((name) => join(migrationDir, name)),
251
+ );
252
+ const resources = await resourceFiles(config, tree);
253
+ const features = tree.namesIn(config.paths.serverFeatures);
254
+ const tables = declaredColumns(migrations.map((migration) => migration.contents));
226
255
  const owned = new Set(
227
256
  [...tables]
228
257
  .filter(([, columns]) => columns.has(config.tenant.sqlColumn))
@@ -242,7 +271,8 @@ async function sqlAgreement(config, taken) {
242
271
  problems.push(...checkAuditAppendOnly(scoped, { table: config.audit.table }));
243
272
  }
244
273
  if (enabled(config.gates, "sql-identifiers")) {
245
- problems.push(...checkSqlIdentifiers(tables, resources, tableOwners(migrations, features)));
274
+ const byName = migrations.map((migration) => ({ file: path.posix.basename(migration.path), sql: migration.contents }));
275
+ problems.push(...checkSqlIdentifiers(tables, resources, tableOwners(byName, features)));
246
276
  }
247
277
  if (enabled(config.gates, "tenant-predicate")) {
248
278
  problems.push(
@@ -254,16 +284,13 @@ async function sqlAgreement(config, taken) {
254
284
  }
255
285
 
256
286
  /** Each server feature's trigger: routes, and the requirements they claim. */
257
- async function triggers(config) {
258
- const root = path.join(config.root, config.paths.serverFeatures);
259
- const rel = relativeTo(config.root);
260
- const found = [];
261
- for (const feature of await list(root)) {
262
- const file = path.join(root, feature, config.paths.triggerFile);
263
- const source = await read(file);
264
- if (source) found.push({ path: rel(file), source });
265
- }
266
- return found;
287
+ async function triggers(config, tree) {
288
+ const root = posix(config.paths.serverFeatures);
289
+ const rels = tree
290
+ .namesIn(root)
291
+ .map((feature) => `${join(root, feature)}/${config.paths.triggerFile}`)
292
+ .filter((rel) => tree.isFile(rel));
293
+ return (await readEach(config.root, rels)).map(({ path: file, contents }) => ({ path: file, source: contents }));
267
294
  }
268
295
 
269
296
  /** Every unit's definition of done ends here: a claim a route makes must be backed. */
@@ -287,15 +314,14 @@ async function publicRouteAgreement(config, routes) {
287
314
  }
288
315
 
289
316
  /** A worker builds its path as a string; nothing type-checks it against the route table. */
290
- async function internalRouteAgreement(config, routes) {
291
- const root = path.join(config.root, config.paths.workers);
292
- const entries = [];
293
- for (const worker of await list(root, { withFileTypes: true })) {
294
- if (!worker.isDirectory() || worker.name === "node_modules") continue;
295
- const file = path.join(root, worker.name, config.paths.workerEntry);
296
- const source = await read(file);
297
- if (source) entries.push({ path: path.relative(config.root, file), source });
298
- }
317
+ async function internalRouteAgreement(config, tree, routes) {
318
+ const root = posix(config.paths.workers);
319
+ const rels = tree
320
+ .foldersIn(root)
321
+ .filter((worker) => worker !== "node_modules")
322
+ .map((worker) => `${join(root, worker)}/${config.paths.workerEntry}`)
323
+ .filter((rel) => tree.isFile(rel));
324
+ const entries = (await readEach(config.root, rels)).map(({ path: file, contents }) => ({ path: file, source: contents }));
299
325
  if (entries.length === 0) return [];
300
326
  return checkInternalRoutes(
301
327
  declaredInternalRoutes(routes.map((route) => route.source)),
@@ -303,22 +329,11 @@ async function internalRouteAgreement(config, routes) {
303
329
  );
304
330
  }
305
331
 
306
- async function platformFiles(config) {
307
- const platformDir = path.join(config.root, config.paths.platform ?? "frontend/src/platform");
308
- const rel = relativeTo(config.root);
309
- const files = [];
310
- async function walk(dir) {
311
- for (const entry of await list(dir, { withFileTypes: true })) {
312
- const full = path.join(dir, entry.name);
313
- if (/node_modules|\/dist\//.test(full)) continue;
314
- if (entry.isDirectory()) await walk(full);
315
- else if (SOURCE_EXTENSION.test(entry.name)) {
316
- files.push({ path: rel(full), contents: await readFile(full, "utf8").catch(() => "") });
317
- }
318
- }
319
- }
320
- await walk(platformDir);
321
- return files;
332
+ function platformFiles(config, tree) {
333
+ const rels = tree
334
+ .under(config.paths.platform ?? "frontend/src/platform")
335
+ .filter((file) => !BUILD_OUTPUT.test(`/${file}`) && SOURCE_EXTENSION.test(file));
336
+ return readEach(config.root, rels);
322
337
  }
323
338
 
324
339
  function isInfraFile(name) {
@@ -327,32 +342,31 @@ function isInfraFile(name) {
327
342
  }
328
343
 
329
344
  /** Terraform/shell files under the configured infra roots — absent is ordinary, not an error. */
330
- async function infraFiles(config) {
331
- const rel = relativeTo(config.root);
332
- const files = [];
333
- async function walk(dir) {
334
- for (const entry of await list(dir, { withFileTypes: true })) {
335
- const full = path.join(dir, entry.name);
336
- if (/node_modules|\.terraform/.test(full)) continue;
337
- if (entry.isDirectory()) await walk(full);
338
- else if (isInfraFile(entry.name)) {
339
- files.push({ path: rel(full), contents: await readFile(full, "utf8").catch(() => "") });
340
- }
341
- }
342
- }
343
- for (const root of config.paths.infra ?? []) await walk(path.join(config.root, root));
344
- return files;
345
+ function infraFiles(config, tree) {
346
+ const rels = (config.paths.infra ?? [])
347
+ .flatMap((root) => tree.under(root))
348
+ .filter((file) => !/node_modules|\.terraform/.test(file) && isInfraFile(file));
349
+ return readEach(config.root, rels);
345
350
  }
346
351
 
347
352
  /**
348
353
  * @param {object} config
349
- * @param {string} [only] one file — the fast path a post-edit hook takes
354
+ * @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
355
+ * @param {{lister?: typeof repoFiles}} [io] the file lister, which a test replaces to count its calls
350
356
  * @returns {Promise<{problems: object[], lines: string[]}>}
351
357
  */
352
- export async function runCheck(config, only) {
358
+ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
359
+ const requested = [only].flat().filter(Boolean);
360
+ const perFile = requested.length > 0;
361
+ // A file outside the repository is in no listing and in no feature.
362
+ const given = requested
363
+ .map((file) => relativeTo(config.root)(path.resolve(config.root, file)))
364
+ .filter((rel) => !rel.startsWith("../") && !path.isAbsolute(rel));
365
+ const pathspecs = perFile ? scopeOf(config, given) : undefined;
366
+ const tree = treeOf(await lister(config.root, { ignores: config.ignores, pathspecs }));
367
+
353
368
  const roots = config.featureRoots.map((root) => path.join(config.root, root));
354
- const relativeOnly = only ? path.resolve(config.root, only) : undefined;
355
- const { features, contents } = await collect(roots, relativeOnly);
369
+ const { features, contents } = await collect(config, tree, perFile ? given : undefined);
356
370
 
357
371
  const problems = [];
358
372
  const lines = [];
@@ -382,7 +396,7 @@ export async function runCheck(config, only) {
382
396
  if (enabled(config.gates, "headless-sagas")) {
383
397
  problems.push(...checkHeadlessPipelines(contents, { block: config.saga.headlessBlock, viewModules: config.saga.viewModules }));
384
398
  }
385
- if (enabled(config.gates, "feature-cli") && !relativeOnly) {
399
+ if (enabled(config.gates, "feature-cli") && !perFile) {
386
400
  const rel = relativeTo(config.root);
387
401
  const relativeFeatures = features.map((feature) => ({ ...feature, feature: rel(feature.feature) }));
388
402
  const relativeContents = contents.map((file) => ({ ...file, path: rel(file.path) }));
@@ -403,21 +417,30 @@ export async function runCheck(config, only) {
403
417
  }
404
418
  if (!rootless) lines.push(`OK structure ${features.length} feature folder(s)`);
405
419
 
406
- if (relativeOnly) return { problems, lines };
420
+ if (perFile) {
421
+ // The English rules that judge one file alone, on exactly the files given. The ledger-wide
422
+ // rules need every file, so only the full check runs them.
423
+ if (enabled(config.gates, "english-source")) {
424
+ const judged = languageFiles(config, tree.files.filter((file) => given.some((g) => file === g || file.startsWith(`${g}/`))));
425
+ problems.push(...checkEnglishFiles(await readEach(config.root, judged), config.language));
426
+ lines.push(`OK english ${judged.length} given file(s): comments and prose are English`);
427
+ }
428
+ return { problems, lines };
429
+ }
407
430
 
408
431
  if (enabled(config.gates, "citations")) {
409
- const cited = await citableFiles(
410
- config.paths.citable.map((root) => path.join(config.root, root)),
411
- config.root,
412
- );
432
+ const cited = await citableFiles(config, tree, config.paths.citable);
413
433
  const decisionsFile = await read(path.join(config.root, config.docs.decisions));
414
434
  const decisions = definedIds(decisionsFile ?? "", config.citations);
415
435
  const requirementIds = new Set(
416
436
  (await registered(path.join(config.root, config.paths.traceability))).map((entry) => entry.id),
417
437
  );
418
- const docsDir = path.join(config.root, config.docs.root);
438
+ const docsRoot = posix(config.docs.root);
419
439
  const docs = new Set(
420
- (await list(docsDir)).filter((name) => name.endsWith(".md")).map((name) => `${config.docs.root}/${name}`),
440
+ tree
441
+ .namesIn(docsRoot)
442
+ .filter((name) => name.endsWith(".md") && tree.isFile(join(docsRoot, name)))
443
+ .map((name) => `${config.docs.root}/${name}`),
421
444
  );
422
445
  problems.push(
423
446
  ...checkCitations(cited, decisions, requirementIds, config.citations),
@@ -432,14 +455,14 @@ export async function runCheck(config, only) {
432
455
  }
433
456
 
434
457
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
435
- problems.push(...(await sqlAgreement(config, taken)));
458
+ problems.push(...(await sqlAgreement(config, tree, taken)));
436
459
  lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
437
460
  // An exemption is counted and named, so it stays a decision rather than a habit.
438
461
  for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
439
462
  }
440
463
 
441
464
  if (enabled(config.gates, "saga-tests")) {
442
- const sources = await sourceFiles(config);
465
+ const sources = await sourceFiles(config, tree);
443
466
  const sagas = declaredSagas(
444
467
  sources.filter((file) => !TEST_FILE.test(file.path)),
445
468
  { factories: config.saga.factories },
@@ -454,7 +477,7 @@ export async function runCheck(config, only) {
454
477
  }
455
478
 
456
479
  if (enabled(config.gates, "gate-tests")) {
457
- const own = await sourceFiles(config, config.paths.checks);
480
+ const own = await sourceFiles(config, tree, config.paths.checks);
458
481
  problems.push(
459
482
  ...checkGatesAreTested(
460
483
  own.filter((file) => !TEST_FILE.test(file.path)),
@@ -478,7 +501,7 @@ export async function runCheck(config, only) {
478
501
  }
479
502
  }
480
503
 
481
- const routes = await triggers(config);
504
+ const routes = await triggers(config, tree);
482
505
  if (enabled(config.gates, "claimed-requirements")) {
483
506
  problems.push(...(await claimAgreement(config, routes)));
484
507
  lines.push("OK claims every requirement a route claims names a test that proves it");
@@ -488,38 +511,38 @@ export async function runCheck(config, only) {
488
511
  lines.push("OK public the edge lets through exactly the routes the api serves without a session");
489
512
  }
490
513
  if (enabled(config.gates, "internal-routes")) {
491
- problems.push(...(await internalRouteAgreement(config, routes)));
514
+ problems.push(...(await internalRouteAgreement(config, tree, routes)));
492
515
  lines.push("OK internal every path a worker posts to is a route the api serves");
493
516
  }
494
517
  if (enabled(config.gates, "headless-sagas")) {
495
518
  lines.push("OK headless pipelines are headless and triggers remain thin presenters");
496
519
  }
497
520
  if (enabled(config.gates, "frontend-boundaries")) {
498
- const platform = await platformFiles(config);
521
+ const platform = await platformFiles(config, tree);
499
522
  if (platform.length > 0) {
500
523
  problems.push(...checkFrontendBoundaries(platform, contents));
501
524
  lines.push("OK boundaries platform remains a thin substrate without domain leaks or junk drawers");
502
525
  }
503
526
  }
504
527
  if (enabled(config.gates, "test-mirror")) {
505
- const { roots } = config.testMirror;
528
+ const { roots: mirrorRoots } = config.testMirror;
506
529
  const walked = new Set();
507
- for (const dir of mirrorFolders(roots)) {
508
- for (const file of await sourceFiles(config, dir)) walked.add(file.path);
530
+ for (const dir of mirrorFolders(mirrorRoots)) {
531
+ for (const file of await sourceFiles(config, tree, dir)) walked.add(file.path);
509
532
  }
510
533
  const all = [...walked];
511
534
  const testPaths = all.filter((file) => TEST_FILE.test(file));
512
535
  const srcPaths = all.filter((file) => !TEST_FILE.test(file));
513
- const mirrorProblems = checkTestMirror(testPaths, srcPaths, roots);
536
+ const mirrorProblems = checkTestMirror(testPaths, srcPaths, mirrorRoots);
514
537
  problems.push(...mirrorProblems);
515
538
  if (mirrorProblems.length === 0) {
516
- const judged = roots.map((root) => root.tests).join(", ") || "no configured root";
539
+ const judged = mirrorRoots.map((root) => root.tests).join(", ") || "no configured root";
517
540
  lines.push(`OK mirror tests mirror src paths 1:1, no orphaned test, in ${judged}`);
518
541
  }
519
542
  }
520
543
 
521
544
  if (enabled(config.gates, "comment-style")) {
522
- const infra = await infraFiles(config);
545
+ const infra = await infraFiles(config, tree);
523
546
  if (infra.length > 0) {
524
547
  problems.push(...checkCommentStyle(infra, config.comments));
525
548
  lines.push("OK comments every comment under infra/ is one line of why, never a paragraph");
@@ -535,7 +558,7 @@ export async function runCheck(config, only) {
535
558
  // Its own file set. The citation and source walkers were built for other questions and each
536
559
  // skips something this one needs -- tests, documents, migrations, contracts. Language is not
537
560
  // a property of TypeScript: a Japanese column default in .sql reaches a reader just the same.
538
- const everything = await filesMatching(config, new RegExp(`\\.(${config.language.extensions.join("|")})$`), config.language);
561
+ const everything = await readEach(config.root, languageFiles(config, tree.files));
539
562
  problems.push(...checkEnglishSource(everything, config.language));
540
563
  problems.push(...checkTranslationPairs(everything.map((file) => file.path), config.language.translationPairs));
541
564
  // The ledger is printed on every run, not only when it fails: a file listed once and never
@@ -551,7 +574,7 @@ export async function runCheck(config, only) {
551
574
  }
552
575
 
553
576
  if (enabled(config.gates, "adr-format")) {
554
- const records = await citableFiles([path.join(config.root, config.adr.root)], config.root);
577
+ const records = await citableFiles(config, tree, [config.adr.root]);
555
578
  const docs = records.filter((file) => file.path.endsWith(".md"));
556
579
  problems.push(...checkAdrFormat(docs, config.adr));
557
580
  if (docs.length > 0) lines.push(`OK decisions ${docs.length} record(s), each with its cost and its rejected alternatives`);
@@ -0,0 +1,16 @@
1
+ // A fragment that finds a checkout's top level with no git process, for hooks that run on every
2
+ // call. `.git` is a folder in a primary checkout and a file in a linked worktree.
3
+
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+
7
+ /** @returns the nearest folder at or above `dir` that holds `.git`, or null when none does. */
8
+ export function checkoutRootOf(dir, exists = existsSync) {
9
+ let current = path.resolve(dir);
10
+ for (;;) {
11
+ if (exists(path.join(current, ".git"))) return current;
12
+ const parent = path.dirname(current);
13
+ if (parent === current) return null;
14
+ current = parent;
15
+ }
16
+ }