architecture-harness 0.11.0 → 0.13.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 (40) hide show
  1. package/package.json +14 -4
  2. package/src/cli/bash-command-guard.mjs +25 -8
  3. package/src/cli/bash-command-guard.test.mjs +44 -0
  4. package/src/cli/branch-name.test.mjs +31 -0
  5. package/src/cli/check.mjs +132 -5
  6. package/src/cli/commit-msg.mjs +94 -0
  7. package/src/cli/commit-msg.test.mjs +60 -0
  8. package/src/cli/doctor.mjs +39 -5
  9. package/src/cli/doctor.test.mjs +18 -1
  10. package/src/cli/git-hooks.mjs +67 -0
  11. package/src/cli/git-hooks.test.mjs +85 -0
  12. package/src/cli/post-edit-gate.test.mjs +10 -0
  13. package/src/cli/powershell-command.mjs +3 -0
  14. package/src/cli/pr-check.mjs +74 -0
  15. package/src/cli/pr-check.test.mjs +59 -0
  16. package/src/cli/qc.mjs +8 -6
  17. package/src/cli/stop-gate.test.mjs +113 -0
  18. package/src/cli/templates.test.mjs +9 -0
  19. package/src/cli/work-order-guard.mjs +25 -1
  20. package/src/config.mjs +48 -7
  21. package/src/descriptions.mjs +4 -0
  22. package/src/gates/closed-set-writers.mjs +36 -0
  23. package/src/gates/closed-set-writers.test.mjs +46 -0
  24. package/src/gates/config-floor.mjs +23 -8
  25. package/src/gates/config-floor.test.mjs +10 -0
  26. package/src/gates/doc-claims.mjs +45 -0
  27. package/src/gates/doc-claims.test.mjs +33 -0
  28. package/src/gates/english-source.mjs +1 -1
  29. package/src/gates/integration-imports.mjs +49 -0
  30. package/src/gates/integration-imports.test.mjs +35 -0
  31. package/src/gates/parity.mjs +163 -0
  32. package/src/gates/parity.test.mjs +108 -0
  33. package/src/gates/sql-identifiers.mjs +44 -0
  34. package/src/gates/sql-identifiers.test.mjs +43 -1
  35. package/src/gates/tenant-predicate.mjs +108 -58
  36. package/src/gates/tenant-predicate.test.mjs +61 -39
  37. package/templates/githooks/commit-msg +2 -1
  38. package/templates/github/workflows/ci.yml +7 -0
  39. package/src/cli/commit-attribution.mjs +0 -68
  40. package/src/cli/commit-attribution.test.mjs +0 -47
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.11.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -51,11 +51,13 @@
51
51
  "test": "node src/eslint/rules.test.mjs && node --test \"src/**/*.test.mjs\""
52
52
  },
53
53
  "peerDependencies": {
54
- "eslint": ">=9",
55
54
  "@typescript-eslint/eslint-plugin": ">=8",
56
55
  "@typescript-eslint/parser": ">=8",
56
+ "eslint": ">=9",
57
57
  "eslint-plugin-boundaries": ">=5",
58
- "eslint-plugin-sonarjs": ">=3"
58
+ "eslint-plugin-sonarjs": ">=3",
59
+ "@commitlint/lint": ">=19",
60
+ "@commitlint/config-conventional": ">=19"
59
61
  },
60
62
  "peerDependenciesMeta": {
61
63
  "@typescript-eslint/eslint-plugin": {
@@ -69,12 +71,20 @@
69
71
  },
70
72
  "eslint-plugin-sonarjs": {
71
73
  "optional": true
74
+ },
75
+ "@commitlint/lint": {
76
+ "optional": true
77
+ },
78
+ "@commitlint/config-conventional": {
79
+ "optional": true
72
80
  }
73
81
  },
74
82
  "devDependencies": {
75
- "eslint": "^9",
83
+ "@commitlint/config-conventional": "^21.2.3",
84
+ "@commitlint/lint": "^21.2.3",
76
85
  "@typescript-eslint/eslint-plugin": "^8",
77
86
  "@typescript-eslint/parser": "^8",
87
+ "eslint": "^9",
78
88
  "eslint-plugin-boundaries": "^5",
79
89
  "eslint-plugin-sonarjs": "^3",
80
90
  "typescript": "^5"
@@ -1,12 +1,13 @@
1
1
  #!/usr/bin/env node
2
- // The PreToolUse trigger that refuses a Bash command which skips the git hooks, or which runs a hook
3
- // script by hand. It reads the command through shell-command.mjs and never runs it.
2
+ // The PreToolUse trigger that refuses a Bash or PowerShell command which skips the git hooks, or
3
+ // which runs a hook script by hand. It reads the command through the shell parsers and never runs it.
4
4
 
5
5
  import { existsSync } from "node:fs";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { CONFIG_FILE } from "../config.mjs";
9
9
  import { checkoutRootOf } from "./checkout-root.mjs";
10
+ import { powershellSegments } from "./powershell-command.mjs";
10
11
  import { commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
11
12
 
12
13
  const HOOK_SCRIPTS = [
@@ -24,6 +25,11 @@ const VALUE_OPTIONS = new Set([
24
25
  /** The short options of commit whose value is the rest of the cluster, or the next word. */
25
26
  const COMMIT_VALUE_FLAGS = new Set(["m", "F", "C", "c", "t"]);
26
27
 
28
+ /** The parser for each guarded tool. */
29
+ const PARSERS = { Bash: segmentsOf, PowerShell: powershellSegments };
30
+ /** The shells whose `-c` or `-Command` argument is a command line of its own, and the parser that reads it. */
31
+ const NESTED = { bash: segmentsOf, sh: segmentsOf, pwsh: powershellSegments, powershell: powershellSegments };
32
+
27
33
  const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
28
34
  const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
29
35
 
@@ -69,6 +75,14 @@ function runsTests(segment) {
69
75
  return [program, ...args].some((word) => programName(word) === "vitest");
70
76
  }
71
77
 
78
+ /** @returns the command line a shell runs from `-c` or `-Command`, with its parser, or null. */
79
+ function nestedCommand(segment) {
80
+ const [program, ...args] = commandWords(segment);
81
+ const parse = NESTED[programName(program)];
82
+ const at = args.findIndex((arg) => /^-(c|command)$/i.test(arg));
83
+ return parse && at !== -1 && args[at + 1] !== undefined ? { command: args[at + 1], parse } : null;
84
+ }
85
+
72
86
  const REASONS = {
73
87
  hooks:
74
88
  "the command skips the git hooks. The pre-commit and pre-push hooks are the gates: run the command " +
@@ -81,31 +95,34 @@ const REASONS = {
81
95
  };
82
96
 
83
97
  /** @returns the reasons the command breaks a rule, in a stable order. */
84
- export function violations(command) {
85
- const segments = segmentsOf(command);
98
+ export function violations(command, parse = segmentsOf) {
99
+ const segments = parse(command);
86
100
  const found = new Set();
87
101
  for (const segment of segments) {
88
102
  const git = gitCall(segment);
89
103
  if (git && skipsHooks(git)) found.add("hooks");
90
104
  if (git && setsHooksPath(git)) found.add("hooksPath");
105
+ const nested = nestedCommand(segment);
106
+ if (nested) for (const key of violations(nested.command, nested.parse)) found.add(key);
91
107
  }
92
108
  if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
93
109
  return Object.keys(REASONS).filter((key) => found.has(key));
94
110
  }
95
111
 
96
- /** The verdict on one Bash call. @returns the hook output, or null to let the call run with no message. */
112
+ /** The verdict on one Bash or PowerShell call. @returns the hook output, or null to let the call run with no message. */
97
113
  export function decide(call) {
98
114
  const command = call.tool_input?.command;
99
- if (call.tool_name !== "Bash" || typeof command !== "string") return null;
115
+ const parse = PARSERS[call.tool_name];
116
+ if (!parse || typeof command !== "string") return null;
100
117
  const root = checkoutRootOf(call.cwd ?? process.cwd());
101
118
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
102
- const found = violations(command);
119
+ const found = violations(command, parse);
103
120
  if (found.length === 0) return null;
104
121
  return {
105
122
  hookSpecificOutput: {
106
123
  hookEventName: "PreToolUse",
107
124
  permissionDecision: "deny",
108
- permissionDecisionReason: `Bash command guard: ${found.map((key) => REASONS[key]).join(" Also, ")}`,
125
+ permissionDecisionReason: `${call.tool_name} command guard: ${found.map((key) => REASONS[key]).join(" Also, ")}`,
109
126
  },
110
127
  };
111
128
  }
@@ -94,3 +94,47 @@ test("the hook process prints the deny", (t) => {
94
94
  assert.equal(result.status, 0, result.stderr);
95
95
  assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
96
96
  });
97
+
98
+ const powershell = (cwd, command) => ({ ...bash(cwd, command), tool_name: "PowerShell" });
99
+
100
+ test("a PowerShell command is held to the same rules as a Bash one", (t) => {
101
+ const ws = workspace(t);
102
+ const denied = {
103
+ "skips the git hooks": [
104
+ "git commit --no-verify -m x",
105
+ "git commit -nm x",
106
+ "git push --no-verify",
107
+ String.raw`Set-Location C:\repo; git commit -n -m x`,
108
+ "git --% commit --no-verify",
109
+ "& git.exe commit --no-verify -m x",
110
+ 'pwsh -NoProfile -Command "git commit --no-verify -m x"',
111
+ "bash -c 'git push --no-verify'",
112
+ ],
113
+ "core\.hooksPath": ["git -c core.hooksPath= commit -m x", "git -c core.hooksPath=NUL push"],
114
+ "writes a lease": [
115
+ String.raw`& node C:\kit\packages\qc-harness\src\cli\work-order-guard.mjs`,
116
+ String.raw`Get-Content input.json | node .\budget-guard.mjs`,
117
+ "bash hooks/pre-edit-guard.sh",
118
+ ],
119
+ };
120
+ for (const [reason, commands] of Object.entries(denied)) {
121
+ for (const command of commands) {
122
+ assert.match(reasonOf(decide(powershell(ws.adopted, command))) ?? "", new RegExp(reason), command);
123
+ }
124
+ }
125
+ for (const command of [
126
+ 'git commit -m "-n is fine"',
127
+ "git log -n 5",
128
+ "git push -n",
129
+ String.raw`node --test packages\qc-harness\src\cli\work-order-guard.test.mjs`,
130
+ "Get-Content packages/qc-harness/src/cli/work-order-guard.mjs",
131
+ 'pwsh -Command "git status"',
132
+ ]) {
133
+ assert.equal(decide(powershell(ws.adopted, command)), null, command);
134
+ }
135
+ });
136
+
137
+ test("the deny names the tool it guarded", (t) => {
138
+ const ws = workspace(t);
139
+ assert.match(reasonOf(decide(powershell(ws.adopted, "git push --no-verify"))), /^PowerShell command guard:/);
140
+ });
@@ -0,0 +1,31 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { defaults } from "../config.mjs";
8
+ import { branchNameRefusal, runWorkOrderCheck } from "./work-order-guard.mjs";
9
+
10
+ test("a branch names its issue: feat/340-roles passes and feat/back-action fails", () => {
11
+ assert.equal(branchNameRefusal("feat/340-roles", defaults.branches), null);
12
+ assert.match(branchNameRefusal("feat/back-action", defaults.branches), /names no issue/);
13
+ assert.match(branchNameRefusal("Feat/340-roles", defaults.branches), /names no issue/);
14
+ });
15
+
16
+ test("main, a release branch and a detached HEAD pass, and a null pattern switches the rule off", () => {
17
+ for (const branch of ["main", "master", "release/1.2", ""]) assert.equal(branchNameRefusal(branch, defaults.branches), null, branch);
18
+ assert.equal(branchNameRefusal("feat/back-action", { ...defaults.branches, pattern: null }), null);
19
+ });
20
+
21
+ test("qc work-order-check refuses a commit on a branch that names no issue", async (t) => {
22
+ const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-branch-name-")));
23
+ t.after(() => rmSync(root, { recursive: true, force: true }));
24
+ const git = (...args) => execFileSync("git", args, { cwd: root, stdio: "pipe" });
25
+ git("init", "-q", "-b", "feat/back-action");
26
+ writeFileSync(path.join(root, "qc.config.json"), "{}");
27
+ t.mock.method(console, "error", () => {});
28
+ assert.equal(await runWorkOrderCheck(root), 1);
29
+ git("checkout", "-q", "-b", "feat/340-roles");
30
+ assert.equal(await runWorkOrderCheck(root), 0);
31
+ });
package/src/cli/check.mjs CHANGED
@@ -7,12 +7,15 @@ import { checkFeatureAnatomy, checkNoEmptyBlock } from "../gates/eight-blocks.mj
7
7
  import { checkCitations, checkDocPaths, checkSelfContained, definedIds } from "../gates/citations.mjs";
8
8
  import { checkAgreement, declaredValues } from "../gates/registry-agreement.mjs";
9
9
  import {
10
+ checkSchemaInMigrations,
10
11
  checkSqlIdentifiers,
11
12
  declaredColumns,
13
+ migrationNames,
14
+ schemaTables,
12
15
  sqlStatements,
13
16
  tableOwners,
14
17
  } from "../gates/sql-identifiers.mjs";
15
- import { checkSharedInsertCallSites, checkTenantPredicate, exemptions } from "../gates/tenant-predicate.mjs";
18
+ import { checkExemptHelperCalls, checkTenantPredicate, exemptHelperCalls, exemptions } from "../gates/tenant-predicate.mjs";
16
19
  import { checkClaimedRequirements } from "../gates/claimed-requirements.mjs";
17
20
  import { allowedPublicRoutes, checkPublicRoutes, declaredPublicRoutes } from "../gates/public-routes.mjs";
18
21
  import { calledInternalRoutes, checkInternalRoutes, declaredInternalRoutes } from "../gates/internal-routes.mjs";
@@ -35,7 +38,12 @@ import { checkRegistryReaders } from "../gates/registry-readers.mjs";
35
38
  import { checkMigrationNumbers } from "../gates/migration-numbers.mjs";
36
39
  import { checkRegistryLiteral } from "../gates/registry-literal.mjs";
37
40
  import { checkThresholdRatchet } from "../gates/threshold-ratchet.mjs";
41
+ import { checkParity, placeholderSlices } from "../gates/parity.mjs";
42
+ import { checkIntegrationImports } from "../gates/integration-imports.mjs";
43
+ import { checkClosedSetWriters, matchedKeys } from "../gates/closed-set-writers.mjs";
44
+ import { checkDocClaims, parseDocClaims } from "../gates/doc-claims.mjs";
38
45
  import { ratchetInputs } from "./registry-history.mjs";
46
+ import { hookDrift } from "./git-hooks.mjs";
39
47
  import { repoFiles } from "./repo-files.mjs";
40
48
 
41
49
  // Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
@@ -257,7 +265,7 @@ async function resourceFiles(config, tree) {
257
265
  }
258
266
 
259
267
  /** Nothing runs the schema and the queries together, so this asserts their names agree. */
260
- async function sqlAgreement(config, tree, taken) {
268
+ async function sqlAgreement(config, tree, taken, lines) {
261
269
  const migrationDir = posix(config.paths.migrations);
262
270
  const migrations = await readEach(
263
271
  config.root,
@@ -287,12 +295,30 @@ async function sqlAgreement(config, tree, taken) {
287
295
  if (enabled(config.gates, "sql-identifiers")) {
288
296
  const byName = migrations.map((migration) => ({ file: path.posix.basename(migration.path), sql: migration.contents }));
289
297
  problems.push(...checkSqlIdentifiers(tables, resources, tableOwners(byName, features)));
298
+ const declared = [];
299
+ // With no migration yet there is no ledger to compare with, as with any path that does not exist.
300
+ for (const feature of migrations.length > 0 ? features : []) {
301
+ const rel = `${join(posix(config.paths.serverFeatures), feature)}/${config.paths.schemaFile}`;
302
+ const source = tree.isFile(rel) ? await read(path.join(config.root, rel)) : null;
303
+ if (source === null) continue;
304
+ for (const entry of schemaTables(source, { tableFactory: config.tenant.tableFactory })) declared.push({ path: rel, ...entry });
305
+ }
306
+ problems.push(...checkSchemaInMigrations(declared, migrationNames(migrations.map((migration) => migration.contents))));
307
+ const columns = declared.reduce((sum, entry) => sum + entry.columns.length, 0);
308
+ if (declared.length > 0) lines.push(`OK schema ${declared.length} table(s), ${columns} column(s) in schema files, each named by a migration`);
290
309
  }
291
310
  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)),
314
+ );
315
+ const helperOptions = { column: config.tenant.sqlColumn, identifier: config.tenant.column };
292
316
  problems.push(
293
317
  ...checkTenantPredicate(scoped, owned, tenantOptions),
294
- ...checkSharedInsertCallSites(resources, tenantOptions),
318
+ ...checkExemptHelperCalls(callers, helpers, helperOptions),
295
319
  );
320
+ const calls = exemptHelperCalls(callers, helpers, helperOptions).length;
321
+ if (calls > 0) lines.push(`OK helpers ${calls} call(s) of ${helpers.length} exempt helper(s), each naming the tenant`);
296
322
  }
297
323
  return problems;
298
324
  }
@@ -363,6 +389,83 @@ function infraFiles(config, tree) {
363
389
  return readEach(config.root, rels);
364
390
  }
365
391
 
392
+ const SLICE_FILE = /\.[jt]sx?$/;
393
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
394
+
395
+ /** Both surfaces, feature by feature, and every slice file either one holds. */
396
+ async function parityAgreement(config, tree) {
397
+ const { sliceDir } = config.anatomy.slice;
398
+ const server = posix(config.paths.serverFeatures);
399
+ const client = posix(config.paths.frontendFeatures);
400
+ const sliceFiles = [];
401
+ const slicesOf = (dir) => {
402
+ const folder = `${dir}/${sliceDir}`;
403
+ const names = tree
404
+ .namesIn(folder)
405
+ .filter((name) => SLICE_FILE.test(name) && !TEST_FILE.test(name) && tree.isFile(`${folder}/${name}`));
406
+ sliceFiles.push(...names.map((name) => `${folder}/${name}`));
407
+ return [...new Set(names.map((name) => name.replace(SLICE_FILE, "")))];
408
+ };
409
+ const routeImport = new RegExp(`from\\s+["']\\./${escapeRegex(sliceDir)}/([^"']+)\\.[cm]?[jt]sx?["']`, "g");
410
+ const serverSide = [];
411
+ for (const name of tree.foldersIn(server).sort()) {
412
+ const dir = join(server, name);
413
+ const trigger = (await read(path.join(config.root, dir, config.paths.triggerFile))) ?? "";
414
+ serverSide.push({ name, slices: slicesOf(dir), routes: [...trigger.matchAll(routeImport)].map((match) => match[1]) });
415
+ }
416
+ const clientSide = tree.foldersIn(client).sort().map((name) => ({ name, slices: slicesOf(join(client, name)) }));
417
+ const registry = parsedJson(await read(path.join(config.root, config.parity.registry))) ?? {};
418
+ const roots = { server, client, registry: config.parity.registry, trigger: config.paths.triggerFile };
419
+ return {
420
+ problems: [
421
+ ...checkParity({ server: serverSide, client: clientSide, registry }, roots),
422
+ ...placeholderSlices(await readEach(config.root, sliceFiles)),
423
+ ],
424
+ paired: serverSide.filter(({ name }) => clientSide.some((feature) => feature.name === name)).length,
425
+ };
426
+ }
427
+
428
+ /** Every file under the configured roots that the integration subject pattern matches. */
429
+ function integrationSubjects(config, tree) {
430
+ const { roots, subject } = config.integrationImports;
431
+ const pattern = new RegExp(subject);
432
+ const skip = prunedBy(/(?:^|\/)(?:node_modules|dist|\.[^/]+)$/);
433
+ const rels = new Set(roots.flatMap((root) => tree.under(root)).filter((file) => pattern.test(file) && !skip(file)));
434
+ return readEach(config.root, [...rels].sort());
435
+ }
436
+
437
+ /** Each closed set against the keys its writers write. */
438
+ async function closedSets(config, tree, lines) {
439
+ const problems = [];
440
+ for (const set of config.closedSetWriters.sets) {
441
+ const declared = matchedKeys((await read(path.join(config.root, set.source))) ?? "", set.key);
442
+ const rels = (set.roots ?? []).flatMap((root) => tree.under(root)).filter((file) => SOURCE_EXTENSION.test(file) && !SKIP.test(`/${file}`));
443
+ const written = new Set();
444
+ for (const file of await readEach(config.root, rels)) {
445
+ for (const key of matchedKeys(file.contents, set.writer)) written.add(key);
446
+ }
447
+ problems.push(...checkClosedSetWriters(declared, written, set));
448
+ const waiting = Object.keys(set.declaredAhead ?? {}).length;
449
+ lines.push(`OK closed set ${set.name}: ${written.size} of ${declared.length} key(s) written, ${waiting} waiting for a mutation`);
450
+ }
451
+ return problems;
452
+ }
453
+
454
+ /** Every state-claim block in the configured documents, against the file it counts. */
455
+ async function docClaims(config, lines) {
456
+ const problems = [];
457
+ for (const doc of config.docClaims.files) {
458
+ const contents = await read(path.join(config.root, doc));
459
+ if (contents === null) continue;
460
+ const claims = parseDocClaims(contents);
461
+ const targets = new Map();
462
+ for (const claim of claims) targets.set(claim.file, await read(path.join(config.root, claim.file)));
463
+ problems.push(...checkDocClaims(doc, claims, targets));
464
+ lines.push(`OK doc claims ${claims.length} claim(s) in ${doc}, each still true`);
465
+ }
466
+ return problems;
467
+ }
468
+
366
469
  /**
367
470
  * @param {object} config
368
471
  * @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
@@ -497,8 +600,8 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
497
600
  }
498
601
 
499
602
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
500
- problems.push(...(await sqlAgreement(config, tree, taken)));
501
- lines.push("OK sql every column is declared, every statement and shared insert carries the tenant");
603
+ lines.push("OK sql every column is declared, every statement and every exempt helper's caller carries the tenant");
604
+ problems.push(...(await sqlAgreement(config, tree, taken, lines)));
502
605
  // An exemption is counted and named, so it stays a decision rather than a habit.
503
606
  for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
504
607
  }
@@ -601,6 +704,10 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
601
704
  if (enabled(config.gates, "config-floor")) {
602
705
  problems.push(...checkConfigFloor(defaults, config, { exemptions: config.floor.exemptions }));
603
706
  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);
708
+ problems.push(...hooks.problems);
709
+ lines.push("OK hooks each git hook makes the calls hooks.required names");
710
+ for (const note of hooks.notes) lines.push(`NOTE hooks ${note}`);
604
711
  }
605
712
 
606
713
  if (enabled(config.gates, "english-source")) {
@@ -629,5 +736,25 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
629
736
  if (docs.length > 0) lines.push(`OK decisions ${docs.length} record(s), each with its cost and its rejected alternatives`);
630
737
  }
631
738
 
739
+ if (enabled(config.gates, "parity")) {
740
+ const parity = await parityAgreement(config, tree);
741
+ problems.push(...parity.problems);
742
+ lines.push(`OK parity ${parity.paired} feature(s) on both surfaces, every divergence named, no no-op slice`);
743
+ }
744
+
745
+ if (enabled(config.gates, "integration-imports")) {
746
+ const subjects = await integrationSubjects(config, tree);
747
+ problems.push(...checkIntegrationImports(subjects, config.integrationImports));
748
+ lines.push(`OK integration ${subjects.length} integration test(s), each importing the product it integrates with`);
749
+ }
750
+
751
+ if (enabled(config.gates, "closed-set-writers")) {
752
+ problems.push(...(await closedSets(config, tree, lines)));
753
+ }
754
+
755
+ if (enabled(config.gates, "doc-claims")) {
756
+ problems.push(...(await docClaims(config, lines)));
757
+ }
758
+
632
759
  return { problems, lines };
633
760
  }
@@ -0,0 +1,94 @@
1
+ // A commit message is conventional, English, and carries the attribution trailer when a team asks
2
+ // for one. The conventional rules are commitlint's, loaded from the repository's own node_modules,
3
+ // so the harness gains no runtime dependency and no rule set of its own.
4
+
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import path from "node:path";
8
+ import { pathToFileURL } from "node:url";
9
+ import { scriptPattern } from "../gates/english-source.mjs";
10
+
11
+ export const INSTALL_HINT = "pnpm add -D @commitlint/lint @commitlint/config-conventional";
12
+ const TRAILER = /^co-authored-by:\s*\S/im;
13
+
14
+ const importPath = async (file) => (await import(pathToFileURL(file).href)).default;
15
+
16
+ /** @returns the ESM entry of a package installed beside a file, which require.resolve cannot read from an import-only exports map. */
17
+ function importEntry(fromFile, name) {
18
+ for (let dir = path.dirname(fromFile); path.dirname(dir) !== dir; dir = path.dirname(dir)) {
19
+ const manifest = path.join(dir, "node_modules", name, "package.json");
20
+ if (!existsSync(manifest)) continue;
21
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
22
+ let entry = pkg.exports?.["."] ?? pkg.exports ?? pkg.main ?? "index.js";
23
+ while (typeof entry === "object" && entry !== null) entry = entry.import ?? entry.default;
24
+ return path.join(path.dirname(manifest), entry);
25
+ }
26
+ return null;
27
+ }
28
+
29
+ /** The parser options of the config's preset, so `feat!:` parses. Undefined keeps commitlint's default parser. */
30
+ async function parserOptions(configPath, preset) {
31
+ if (typeof preset !== "string") return preset?.parserOpts;
32
+ const entry = importEntry(configPath, preset);
33
+ if (!entry) return undefined;
34
+ const created = await (await importPath(entry))();
35
+ return created.parser ?? created.parserOpts;
36
+ }
37
+
38
+ /** @returns commitlint's lint function and the conventional config from the repository, or null when either is missing. */
39
+ export async function loadCommitlint(root) {
40
+ const require = createRequire(path.join(root, "package.json"));
41
+ let lintPath;
42
+ let configPath;
43
+ try {
44
+ lintPath = require.resolve("@commitlint/lint");
45
+ configPath = require.resolve("@commitlint/config-conventional");
46
+ } catch (error) {
47
+ if (error.code === "MODULE_NOT_FOUND") return null;
48
+ throw error;
49
+ }
50
+ const config = await importPath(configPath);
51
+ return { lint: await importPath(lintPath), rules: config.rules, parserOpts: await parserOptions(configPath, config.parserPreset) };
52
+ }
53
+
54
+ /**
55
+ * @param {string} raw the message file as git wrote it
56
+ * @param {{conventional?: boolean, attribution?: boolean, scripts?: string[]}} options
57
+ * @param {{lint: Function, rules: object, parserOpts?: object} | null} commitlint
58
+ * @returns {Promise<{rule: string, detail: string}[]>}
59
+ */
60
+ export async function checkCommitMessage(raw, options, commitlint) {
61
+ const message = raw
62
+ .split(/\r?\n/)
63
+ .filter((line) => !line.startsWith("#"))
64
+ .join("\n")
65
+ .trim();
66
+ const problems = [];
67
+ if (options.conventional !== false) {
68
+ if (commitlint) {
69
+ const report = await commitlint.lint(message, commitlint.rules, commitlint.parserOpts ? { parserOpts: commitlint.parserOpts } : {});
70
+ for (const error of report.errors) problems.push({ rule: `conventional/${error.name}`, detail: error.message });
71
+ } else {
72
+ problems.push({
73
+ rule: "commitlint-missing",
74
+ detail: `commitlint is not installed here. Run \`${INSTALL_HINT}\`, or set commitMessage.conventional to false.`,
75
+ });
76
+ }
77
+ }
78
+ const script = scriptPattern(options.scripts ?? ["cjk"]);
79
+ message.split("\n").forEach((line, index) => {
80
+ if (script.test(line)) problems.push({ rule: "english", detail: `line ${index + 1} is not English. A commit message is English.` });
81
+ });
82
+ if (options.attribution === true && !TRAILER.test(message)) {
83
+ problems.push({ rule: "attribution", detail: "the message has no Co-Authored-By trailer, and commitMessage.attribution requires one." });
84
+ }
85
+ return problems;
86
+ }
87
+
88
+ export async function runCommitMsg(config, file) {
89
+ const options = { ...config.commitMessage, scripts: config.language?.scripts };
90
+ const commitlint = options.conventional === false ? null : await loadCommitlint(config.root);
91
+ const problems = await checkCommitMessage(readFileSync(file, "utf8"), options, commitlint);
92
+ for (const problem of problems) console.error(`FAIL commit-msg ${problem.rule}: ${problem.detail}`);
93
+ return problems.length > 0 ? 1 : 0;
94
+ }
@@ -0,0 +1,60 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { fileURLToPath } from "node:url";
7
+ import { defaults } from "../config.mjs";
8
+ import { INSTALL_HINT, checkCommitMessage, loadCommitlint, runCommitMsg } from "./commit-msg.mjs";
9
+
10
+ // The harness package installs commitlint as a dev dependency, as an adopting repository would.
11
+ const HARNESS = fileURLToPath(new URL("../..", import.meta.url));
12
+ const TRAILER = "\n\nCo-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>\n";
13
+
14
+ function emptyDir(t) {
15
+ const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-commit-msg-")));
16
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
17
+ return dir;
18
+ }
19
+
20
+ test("a conventional subject passes, and a subject that is not one fails with commitlint's rule", async () => {
21
+ const commitlint = await loadCommitlint(HARNESS);
22
+ assert.deepEqual(await checkCommitMessage("feat(cli): add qc pr-check\n", {}, commitlint), []);
23
+ assert.deepEqual(await checkCommitMessage("feat(cli)!: drop the tools list\n", {}, commitlint), []);
24
+ const rules = (await checkCommitMessage("Added some stuff\n", {}, commitlint)).map((problem) => problem.rule);
25
+ assert.ok(rules.includes("conventional/type-empty"), rules.join());
26
+ });
27
+
28
+ test("a message that is not English fails, whatever commitlint says", async () => {
29
+ const commitlint = await loadCommitlint(HARNESS);
30
+ const problems = await checkCommitMessage("fix(ui): 写真を保存する\n", {}, commitlint);
31
+ assert.deepEqual(problems.map((problem) => problem.rule), ["english"]);
32
+ });
33
+
34
+ test("with no commitlint installed, the check fails with the install command, unless conventional is off", async (t) => {
35
+ const commitlint = await loadCommitlint(emptyDir(t));
36
+ assert.equal(commitlint, null);
37
+ const problems = await checkCommitMessage("feat: x\n", {}, commitlint);
38
+ assert.deepEqual(problems.map((problem) => problem.rule), ["commitlint-missing"]);
39
+ assert.ok(problems[0].detail.includes(INSTALL_HINT));
40
+ assert.deepEqual(await checkCommitMessage("feat: x\n", { conventional: false }, null), []);
41
+ });
42
+
43
+ test("attribution is off by default, so a Claude trailer passes; on, a message without the trailer fails", async () => {
44
+ const commitlint = await loadCommitlint(HARNESS);
45
+ assert.equal(defaults.commitMessage.attribution, false);
46
+ assert.deepEqual(await checkCommitMessage(`feat: x${TRAILER}`, defaults.commitMessage, commitlint), []);
47
+ const on = { ...defaults.commitMessage, attribution: true };
48
+ assert.deepEqual((await checkCommitMessage("feat: x\n", on, commitlint)).map((problem) => problem.rule), ["attribution"]);
49
+ assert.deepEqual(await checkCommitMessage(`feat: x${TRAILER}`, on, commitlint), []);
50
+ });
51
+
52
+ test("qc commit-msg reads the file git wrote, and ignores its comment lines", async (t) => {
53
+ const file = path.join(emptyDir(t), "COMMIT_EDITMSG");
54
+ writeFileSync(file, "fix(hooks): read the installed harness\n# Please enter the commit message\n");
55
+ const config = { root: HARNESS, commitMessage: defaults.commitMessage, language: {} };
56
+ assert.equal(await runCommitMsg(config, file), 0);
57
+ writeFileSync(file, "WIP\n");
58
+ t.mock.method(console, "error", () => {});
59
+ assert.equal(await runCommitMsg(config, file), 1);
60
+ });
@@ -9,6 +9,7 @@ import { execFile } from "node:child_process";
9
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
10
10
  import path from "node:path";
11
11
  import { promisify } from "node:util";
12
+ import { hookDrift } from "./git-hooks.mjs";
12
13
 
13
14
  const execFileAsync = promisify(execFile);
14
15
 
@@ -38,9 +39,11 @@ export function versionOf(harnessRoot) {
38
39
  * own files -- that verdict is worthless and has to stop the turn. A copy *ahead* is what every
39
40
  * day of developing this kit looks like; it is merely stricter, and anything it reports is a real
40
41
  * finding to act on. Blocking on that direction would make the kit unable to grow.
42
+ * A plugin whose hooks run the installed copy never judges the repository with its own gates, so
43
+ * a copy behind is then a note.
41
44
  * @returns null when the two agree, else a report carrying `blocking`.
42
45
  */
43
- export function drift(installed, plugin) {
46
+ export function drift(installed, plugin, { hooksRunInstalled = false } = {}) {
44
47
  if (!plugin || !installed) return null;
45
48
  const missing = installed.gates.filter((name) => !plugin.gates.includes(name));
46
49
  const extra = plugin.gates.filter((name) => !installed.gates.includes(name));
@@ -48,20 +51,25 @@ export function drift(installed, plugin) {
48
51
  return {
49
52
  missing,
50
53
  extra,
51
- blocking: missing.length > 0,
54
+ blocking: missing.length > 0 && !hooksRunInstalled,
52
55
  installedVersion: installed.version,
53
56
  pluginVersion: plugin.version,
54
57
  };
55
58
  }
56
59
 
57
60
  export function driftReport(found, pluginRoot, checkoutRoot = pluginRoot) {
58
- const label = found.blocking ? "FAIL harness " : "WARN harness ";
61
+ const behindOnly = found.missing.length > 0 && !found.blocking;
62
+ const label = found.blocking ? "FAIL harness " : behindOnly ? "NOTE harness " : "WARN harness ";
59
63
  const lines = [
60
64
  `${label} the hooks and the lockfile run different harnesses`,
61
65
  ` installed ${found.installedVersion ?? "?"} — what \`pnpm check\` and CI enforce`,
62
66
  ` plugin ${found.pluginVersion ?? "?"} — what the agent hooks enforce, from ${pluginRoot}`,
63
67
  ];
64
- if (found.missing.length > 0) {
68
+ if (behindOnly) {
69
+ lines.push(` the plugin copy is missing: ${found.missing.join(", ")}`);
70
+ lines.push(` the hooks run the installed copy, so the structure check is unaffected`);
71
+ lines.push(` update the plugin and restart the session to get its newer guards`);
72
+ } else if (found.missing.length > 0) {
65
73
  lines.push(` the plugin copy is missing: ${found.missing.join(", ")}`);
66
74
  lines.push(` so its \`qc check\` reports unknown-check for rules your docs correctly list`);
67
75
  lines.push(` fix the checkout, never the repository: git -C ${checkoutRoot} log --oneline -1`);
@@ -86,6 +94,17 @@ async function behindMain(root) {
86
94
  }
87
95
  }
88
96
 
97
+ /** True when the plugin's stop gate prefers the repository's installed harness over its own copy. */
98
+ export function hooksRunInstalled(pluginCheckout, read = readFileSync) {
99
+ try {
100
+ return read(path.join(pluginCheckout, "hooks", "stop-gate.sh"), "utf8").includes(
101
+ "node_modules/architecture-harness/src/cli/qc.mjs",
102
+ );
103
+ } catch {
104
+ return false;
105
+ }
106
+ }
107
+
89
108
  function pluginHarnessRoot() {
90
109
  const root = process.env.CLAUDE_PLUGIN_ROOT;
91
110
  if (!root) return null;
@@ -99,6 +118,21 @@ function installedHarnessRoot(configRoot) {
99
118
  }
100
119
 
101
120
  export async function runDoctor(config) {
121
+ const hooksFailed = reportHooks(config);
122
+ const harnessCode = await compareHarnesses(config);
123
+ return hooksFailed ? 1 : harnessCode;
124
+ }
125
+
126
+ /** @returns true when an installed git hook lacks a call `hooks.required` names. */
127
+ function reportHooks(config) {
128
+ const { problems, notes } = hookDrift(config.root, config.hooks?.required ?? {});
129
+ for (const problem of problems) console.error(`FAIL hooks ${problem.path}: ${problem.detail}`);
130
+ for (const note of notes) console.log(`NOTE hooks ${note}`);
131
+ if (problems.length === 0) console.log("OK hooks each git hook makes the calls hooks.required names");
132
+ return problems.length > 0;
133
+ }
134
+
135
+ async function compareHarnesses(config) {
102
136
  const installedRoot = installedHarnessRoot(config.root);
103
137
  const pluginRoot = pluginHarnessRoot();
104
138
 
@@ -116,7 +150,7 @@ export async function runDoctor(config) {
116
150
  const plugin = { gates: gateNames(pluginRoot), version: versionOf(pluginRoot) };
117
151
  const checkoutRoot = path.resolve(pluginRoot, "..", "..");
118
152
  const position = await behindMain(checkoutRoot);
119
- const found = drift(installed, plugin);
153
+ const found = drift(installed, plugin, { hooksRunInstalled: hooksRunInstalled(checkoutRoot) });
120
154
  if (!found) {
121
155
  console.log(`OK plugin the same ${plugin.gates.length} gate(s) as the lockfile pins`);
122
156
  return 0;