architecture-harness 0.23.0 → 0.25.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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +20 -5
  3. package/src/cli/bash-command-guard.mjs +44 -5
  4. package/src/cli/bash-command-guard.test.mjs +35 -1
  5. package/src/cli/budget-guard.mjs +1 -0
  6. package/src/cli/budget-guard.test.mjs +7 -1
  7. package/src/cli/budget.mjs +3 -4
  8. package/src/cli/budget.test.mjs +5 -5
  9. package/src/cli/check-commands.mjs +82 -0
  10. package/src/cli/check-commands.test.mjs +190 -0
  11. package/src/cli/check.mjs +34 -13
  12. package/src/cli/ci-template.test.mjs +17 -15
  13. package/src/cli/cli.test.mjs +33 -2
  14. package/src/cli/commit-msg.mjs +12 -12
  15. package/src/cli/commit-msg.test.mjs +22 -7
  16. package/src/cli/generated-file-guard.mjs +11 -2
  17. package/src/cli/generated-file-guard.test.mjs +14 -2
  18. package/src/cli/init.mjs +70 -25
  19. package/src/cli/lint-changed.mjs +157 -0
  20. package/src/cli/lint-changed.test.mjs +102 -0
  21. package/src/cli/plugin-agents.test.mjs +1 -1
  22. package/src/cli/post-edit-gate.test.mjs +12 -3
  23. package/src/cli/pr-check.mjs +15 -2
  24. package/src/cli/pr-check.test.mjs +19 -9
  25. package/src/cli/qc.mjs +38 -7
  26. package/src/cli/scaffold.mjs +23 -2
  27. package/src/cli/scaffold.test.mjs +51 -0
  28. package/src/cli/shell-command.mjs +3 -1
  29. package/src/cli/stop-gate.test.mjs +49 -128
  30. package/src/cli/typecheck.mjs +46 -0
  31. package/src/cli/typecheck.test.mjs +43 -0
  32. package/src/cli/user-config-package.mjs +16 -0
  33. package/src/cli/user-config-toml.mjs +144 -0
  34. package/src/cli/user-config.mjs +155 -0
  35. package/src/cli/user-config.test.mjs +274 -0
  36. package/src/cli/work-order-guard.mjs +2 -2
  37. package/src/cli/worktree-gate.mjs +11 -12
  38. package/src/cli/worktree-gate.test.mjs +28 -29
  39. package/src/cli/worktree-isolation.mjs +3 -3
  40. package/src/cli/worktree-isolation.test.mjs +1 -1
  41. package/src/cli/worktree.mjs +9 -1
  42. package/src/cli/worktree.test.mjs +16 -1
  43. package/src/config.mjs +28 -11
  44. package/src/config.test.mjs +33 -1
  45. package/src/eslint/preset.mjs +8 -3
  46. package/src/eslint/preset.test.mjs +15 -8
  47. package/src/eslint/rules/no-raw-fetch.mjs +42 -2
  48. package/src/eslint/rules.test.mjs +15 -0
  49. package/src/gates/audit-append-only.mjs +18 -4
  50. package/src/gates/audit-append-only.test.mjs +19 -0
  51. package/src/gates/tenant-predicate.mjs +147 -7
  52. package/src/gates/tenant-predicate.test.mjs +55 -0
  53. package/src/gates/tenant-tables.mjs +5 -2
  54. package/src/gates/tenant-tables.test.mjs +8 -0
  55. package/src/gates/threshold-ratchet.mjs +12 -9
  56. package/src/gates/threshold-ratchet.test.mjs +16 -0
  57. package/src/plugin.test.mjs +28 -0
  58. package/src/screens/auth-run.test.mjs +20 -17
  59. package/src/screens/capture-idle.test.mjs +2 -1
  60. package/src/screens/catalog.test.mjs +3 -3
  61. package/src/screens/chrome.mjs +21 -0
  62. package/src/vale-style.test.mjs +5 -5
  63. package/templates/CLAUDE.md +2 -2
  64. package/templates/githooks/pre-commit +7 -10
  65. package/templates/github/workflows/ci.yml +25 -84
  66. package/templates/github/workflows/pr-policy.yml +36 -0
  67. package/user-config/claude/settings.shared.json +74 -0
  68. package/user-config/claude/statusline.js +323 -0
  69. package/user-config/codex/config.shared.toml +19 -0
  70. package/src/cli/edit-batch-guard.mjs +0 -77
  71. package/src/cli/edit-batch-guard.test.mjs +0 -131
package/src/cli/check.mjs CHANGED
@@ -308,6 +308,12 @@ async function sqlAgreement(config, tree, taken, lines) {
308
308
  const scoped = scanned.map(({ path: file, source }) => ({ path: file, statements: sqlStatements(source) }));
309
309
  taken.push(...exemptions(scoped));
310
310
 
311
+ lines.push(
312
+ migrations.length === 0 && scoped.every((resource) => resource.statements.length === 0)
313
+ ? `OK sql skipped: no migration under ${migrationDir} and no sql statement in a resource`
314
+ : "OK sql every column is declared, every statement and every exempt helper's caller carries the tenant",
315
+ );
316
+
311
317
  const tenantOptions = { column: config.tenant.sqlColumn };
312
318
  const problems = [];
313
319
  if (enabled(config.gates, "audit-append-only")) {
@@ -374,7 +380,7 @@ async function triggers(config, tree) {
374
380
  /** Every unit's definition of done ends here: a claim a route makes must be backed. */
375
381
  async function claimAgreement(config, routes) {
376
382
  const entries = await registered(path.join(config.root, config.paths.traceability));
377
- if (entries.length === 0) return [];
383
+ if (entries.length === 0) return null;
378
384
  const tests = new Map(entries.map((entry) => [entry.id, entry.tests ?? []]));
379
385
  return checkClaimedRequirements(routes, tests);
380
386
  }
@@ -383,7 +389,7 @@ async function claimAgreement(config, routes) {
383
389
  async function publicRouteAgreement(config, routes) {
384
390
  const file = path.join(config.root, config.paths.publicRoutes);
385
391
  const allowed = await read(file);
386
- if (allowed === null) return [];
392
+ if (allowed === null) return null;
387
393
  return checkPublicRoutes(
388
394
  declaredPublicRoutes(routes.map((route) => route.source)),
389
395
  allowedPublicRoutes(allowed),
@@ -400,7 +406,7 @@ async function internalRouteAgreement(config, tree, routes) {
400
406
  .map((worker) => `${join(root, worker)}/${config.paths.workerEntry}`)
401
407
  .filter((rel) => tree.isFile(rel));
402
408
  const entries = (await readEach(config.root, rels)).map(({ path: file, contents }) => ({ path: file, source: contents }));
403
- if (entries.length === 0) return [];
409
+ if (entries.length === 0) return null;
404
410
  return checkInternalRoutes(
405
411
  declaredInternalRoutes(routes.map((route) => route.source)),
406
412
  calledInternalRoutes(entries),
@@ -750,7 +756,6 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
750
756
  }
751
757
 
752
758
  if (enabled(config.gates, "sql-identifiers") || enabled(config.gates, "tenant-predicate")) {
753
- lines.push("OK sql every column is declared, every statement and every exempt helper's caller carries the tenant");
754
759
  problems.push(...(await sqlAgreement(config, tree, taken, lines)));
755
760
  // An exemption is counted and named, so it stays a decision rather than a habit.
756
761
  for (const exemption of taken) lines.push(` exempt ${exemption.path}: ${exemption.reason}`);
@@ -775,7 +780,9 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
775
780
  sources,
776
781
  }),
777
782
  );
778
- lines.push(`OK sagas ${sagas.length} workflow(s), each named by a test that runs without a view`);
783
+ lines.push(sagas.length === 0
784
+ ? "OK sagas skipped: no workflow declared"
785
+ : `OK sagas ${sagas.length} workflow(s), each named by a test that runs without a view`);
779
786
  }
780
787
 
781
788
  if (enabled(config.gates, "tenant-isolation-test")) {
@@ -788,7 +795,10 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
788
795
  column: config.tenant.column,
789
796
  };
790
797
  problems.push(...checkTenantIsolationTests(features, isolation));
791
- lines.push(`OK tenancy ${tenantFeatures(features, isolation).length} feature(s) with tenant tables, each with a two-tenant test`);
798
+ const tenanted = tenantFeatures(features, isolation).length;
799
+ lines.push(tenanted === 0
800
+ ? "OK tenancy skipped: no feature declares a tenant table"
801
+ : `OK tenancy ${tenanted} feature(s) with tenant tables, each with a two-tenant test`);
792
802
  }
793
803
 
794
804
  if (enabled(config.gates, "gate-tests")) {
@@ -818,16 +828,25 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
818
828
 
819
829
  const routes = await triggers(config, tree);
820
830
  if (enabled(config.gates, "claimed-requirements")) {
821
- problems.push(...(await claimAgreement(config, routes)));
822
- lines.push("OK claims every requirement a route claims names a test that proves it");
831
+ const found = await claimAgreement(config, routes);
832
+ problems.push(...(found ?? []));
833
+ lines.push(found === null
834
+ ? `OK claims skipped: no requirement in ${config.paths.traceability}`
835
+ : "OK claims every requirement a route claims names a test that proves it");
823
836
  }
824
837
  if (enabled(config.gates, "public-routes")) {
825
- problems.push(...(await publicRouteAgreement(config, routes)));
826
- lines.push("OK public the edge lets through exactly the routes the api serves without a session");
838
+ const found = await publicRouteAgreement(config, routes);
839
+ problems.push(...(found ?? []));
840
+ lines.push(found === null
841
+ ? `OK public skipped: no ${config.paths.publicRoutes}`
842
+ : "OK public the edge lets through exactly the routes the api serves without a session");
827
843
  }
828
844
  if (enabled(config.gates, "internal-routes")) {
829
- problems.push(...(await internalRouteAgreement(config, tree, routes)));
830
- lines.push("OK internal every path a worker posts to is a route the api serves");
845
+ const found = await internalRouteAgreement(config, tree, routes);
846
+ problems.push(...(found ?? []));
847
+ lines.push(found === null
848
+ ? `OK internal skipped: no worker entry under ${config.paths.workers}`
849
+ : "OK internal every path a worker posts to is a route the api serves");
831
850
  }
832
851
  if (enabled(config.gates, "headless-sagas")) {
833
852
  lines.push("OK headless pipelines are headless and triggers remain thin presenters");
@@ -855,7 +874,9 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
855
874
  problems.push(...mirrorProblems);
856
875
  if (mirrorProblems.length === 0) {
857
876
  const judged = mirrorRoots.map((root) => root.tests).join(", ") || "no configured root";
858
- lines.push(`OK mirror tests mirror src paths 1:1, no orphaned test, in ${judged}`);
877
+ lines.push(all.length === 0
878
+ ? `OK mirror skipped: no file under ${judged}`
879
+ : `OK mirror tests mirror src paths 1:1, no orphaned test, in ${judged}`);
859
880
  }
860
881
  }
861
882
 
@@ -5,24 +5,26 @@ import { fileURLToPath } from "node:url";
5
5
  import { parse } from "yaml";
6
6
 
7
7
  const WORKFLOW = fileURLToPath(new URL("../../templates/github/workflows/ci.yml", import.meta.url));
8
+ const runs = () => parse(readFileSync(WORKFLOW, "utf8")).jobs.gates.steps.map((step) => step.run ?? "").join("\n");
8
9
 
9
- test("the template runs unit tests in eight shards and integration tests in two, all on hosted runners", () => {
10
- const workflow = parse(readFileSync(WORKFLOW, "utf8"));
11
- assert.deepEqual(workflow.jobs.unit.strategy.matrix.shard, [1, 2, 3, 4, 5, 6, 7, 8]);
12
- assert.deepEqual(workflow.jobs.integration.strategy.matrix.shard, [1, 2]);
13
- assert.equal(workflow.jobs.unit.strategy["fail-fast"], false);
14
- for (const [name, job] of Object.entries(workflow.jobs)) assert.equal(job["runs-on"], "ubuntu-latest", name);
10
+ test("the template installs with the package manager of the lockfile, so no one tool is assumed", () => {
11
+ const text = runs();
12
+ assert.match(text, /pnpm-lock\.yaml.*pnpm install --frozen-lockfile/);
13
+ assert.match(text, /yarn\.lock.*yarn install --immutable/);
14
+ assert.match(text, /package-lock\.json.*npm ci/);
15
15
  });
16
16
 
17
- test("the template runs the affected browser tests on a pull request and every one on a push", () => {
18
- const steps = JSON.stringify(parse(readFileSync(WORKFLOW, "utf8")).jobs.e2e.steps);
19
- assert.match(steps, /pnpm e2e:affected/);
20
- assert.match(steps, /pnpm e2e"/);
17
+ test("the template runs the three checks the hooks run, and lints only the lines a change adds", () => {
18
+ const workflow = parse(readFileSync(WORKFLOW, "utf8"));
19
+ const text = runs();
20
+ for (const command of ["npx qc check", "npx qc typecheck", 'npx qc lint --base "$BASE"']) assert.ok(text.includes(command), command);
21
+ const lint = workflow.jobs.gates.steps.find((step) => /qc lint/.test(step.run ?? ""));
22
+ assert.match(lint.env.BASE, /github\.base_ref/);
23
+ assert.doesNotMatch(text, /eslint \. --max-warnings 0/);
21
24
  });
22
25
 
23
- test("the e2e job installs the browsers before it runs a spec", () => {
24
- const steps = parse(readFileSync(WORKFLOW, "utf8")).jobs.e2e.steps;
25
- const install = steps.findIndex((step) => /playwright install --with-deps/.test(step.run ?? ""));
26
- const run = steps.findIndex((step) => /pnpm e2e/.test(step.run ?? ""));
27
- assert.ok(install >= 0 && install < run);
26
+ test("the policy checks of a pull request are opt-in, not steps of the template", () => {
27
+ const text = runs();
28
+ assert.doesNotMatch(text, /qc pr-check|qc prose/);
29
+ assert.doesNotMatch(readFileSync(WORKFLOW, "utf8"), /^\s*# - run:/m);
28
30
  });
@@ -28,15 +28,34 @@ const quiet = (run) => {
28
28
  }
29
29
  };
30
30
 
31
- test("init writes the documents the gates read", async () => {
31
+ test("init writes the config, the hooks, CI, and an empty register, and the reference docs only with --full", async () => {
32
32
  const dir = repo();
33
33
  await quiet(() => runInit(load(dir)));
34
- for (const file of ["qc.config.json", "docs/decisions.md", "docs/enforcement.md", "docs/pagination.md", ".githooks/pre-commit", ".githooks/commit-msg", ".githooks/pre-push"]) {
34
+ for (const file of ["qc.config.json", "docs/decisions.md", ".githooks/pre-commit", ".githooks/commit-msg", ".githooks/pre-push", ".github/workflows/ci.yml"]) {
35
35
  assert.ok(existsSync(path.join(dir, file)), `${file} is missing`);
36
36
  }
37
+ for (const file of ["docs/enforcement.md", "docs/pagination.md", ".vale/.vale.ini", ".github/workflows/pr-policy.yml"]) assert.equal(existsSync(path.join(dir, file)), false, file);
38
+ assert.doesNotMatch(readFileSync(path.join(dir, "docs/decisions.md"), "utf8"), /ADR-\d+/);
39
+ await quiet(() => runInit(load(dir), ["--full"]));
40
+ for (const file of ["docs/enforcement.md", "docs/pagination.md", ".github/workflows/pr-policy.yml"]) assert.ok(existsSync(path.join(dir, file)), `${file} is missing`);
37
41
  rmSync(dir, { recursive: true, force: true });
38
42
  });
39
43
 
44
+ test("init sets featureRoots to the feature folders the repository has, and to none on a flat one", async () => {
45
+ const flat = repo();
46
+ mkdirSync(path.join(flat, "src"));
47
+ writeFileSync(path.join(flat, "src", "index.ts"), "export {};\n");
48
+ await quiet(() => runInit(load(flat)));
49
+ assert.deepEqual(JSON.parse(readFileSync(path.join(flat, "qc.config.json"), "utf8")).featureRoots, []);
50
+ const { problems } = await runCheck(load(flat));
51
+ assert.deepEqual(problems, [], "a flat repository passes qc check right after init");
52
+ const sliced = repo();
53
+ for (const dir of ["api/src/features/orders", "web/src/features/cart", "node_modules/x/features"]) mkdirSync(path.join(sliced, dir), { recursive: true });
54
+ await quiet(() => runInit(load(sliced)));
55
+ assert.deepEqual(JSON.parse(readFileSync(path.join(sliced, "qc.config.json"), "utf8")).featureRoots, ["api/src/features", "web/src/features"]);
56
+ for (const root of [flat, sliced]) rmSync(root, { recursive: true, force: true });
57
+ });
58
+
40
59
  // The examples cite ids the shipped register does not define; a repository that
41
60
  // took them would fail its own citations gate on the first run.
42
61
  test("init does not copy the decision examples", async () => {
@@ -96,6 +115,7 @@ test("install-hooks refuses before init rather than configuring nothing", async
96
115
  test("a config whose every feature root is missing is a problem", async () => {
97
116
  const dir = repo();
98
117
  await quiet(() => runInit(load(dir)));
118
+ writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ featureRoots: ["backend/src/features", "frontend/src/features"] }));
99
119
  const { problems, lines } = await runCheck(load(dir));
100
120
  assert.ok(
101
121
  problems.some((problem) => problem.rule === "unfound-root"),
@@ -280,6 +300,17 @@ test("a fresh init repository with the default config passes the hooks check", a
280
300
  rmSync(dir, { recursive: true, force: true });
281
301
  });
282
302
 
303
+ test("a gate with nothing to judge says skipped and names what is missing, never a bare OK", async () => {
304
+ const dir = repo();
305
+ await quiet(() => runInit(load(dir)));
306
+ const { lines } = await runCheck(load(dir));
307
+ for (const name of ["sql", "claims", "public", "internal", "mirror"]) {
308
+ const line = lines.find((entry) => entry.startsWith(`OK ${name} `));
309
+ assert.match(line ?? "", /skipped: no /, `${name} line: ${line}`);
310
+ }
311
+ rmSync(dir, { recursive: true, force: true });
312
+ });
313
+
283
314
  test("a config with only extraExemptHelpers checks the kit defaults and the extra helper", async () => {
284
315
  const dir = repo();
285
316
  await quiet(() => runInit(load(dir)));
@@ -10,6 +10,8 @@ import { scriptPattern } from "../gates/english-source.mjs";
10
10
 
11
11
  export const INSTALL_HINT = "pnpm add -D @commitlint/lint @commitlint/config-conventional";
12
12
  const TRAILER = /^co-authored-by:\s*\S/im;
13
+ // `git commit -v` puts the diff under this line, after the comment character, and git drops it all.
14
+ const SCISSORS = /^\S -{24} >8 -{24}\s*$/;
13
15
 
14
16
  const importPath = async (file) => (await import(pathToFileURL(file).href)).default;
15
17
 
@@ -58,22 +60,17 @@ export async function loadCommitlint(root) {
58
60
  * @returns {Promise<{rule: string, detail: string}[]>}
59
61
  */
60
62
  export async function checkCommitMessage(raw, options, commitlint) {
61
- const message = raw
62
- .split(/\r?\n/)
63
+ const lines = raw.split(/\r?\n/);
64
+ const cut = lines.findIndex((line) => SCISSORS.test(line));
65
+ const message = (cut === -1 ? lines : lines.slice(0, cut))
63
66
  .filter((line) => !line.startsWith("#"))
64
67
  .join("\n")
65
68
  .trim();
66
69
  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
- }
70
+ // A repository without commitlint has chosen no commit convention, so the conventional rules skip.
71
+ if (options.conventional !== false && commitlint) {
72
+ const report = await commitlint.lint(message, commitlint.rules, commitlint.parserOpts ? { parserOpts: commitlint.parserOpts } : {});
73
+ for (const error of report.errors) problems.push({ rule: `conventional/${error.name}`, detail: error.message });
77
74
  }
78
75
  const script = scriptPattern(options.scripts ?? ["cjk"]);
79
76
  message.split("\n").forEach((line, index) => {
@@ -88,6 +85,9 @@ export async function checkCommitMessage(raw, options, commitlint) {
88
85
  export async function runCommitMsg(config, file) {
89
86
  const options = { ...config.commitMessage, scripts: config.language?.scripts };
90
87
  const commitlint = options.conventional === false ? null : await loadCommitlint(config.root);
88
+ if (options.conventional !== false && !commitlint) {
89
+ console.error(`NOTE commit-msg commitlint is not installed, so the conventional rules skip. Run \`${INSTALL_HINT}\` to turn them on.`);
90
+ }
91
91
  const problems = await checkCommitMessage(readFileSync(file, "utf8"), options, commitlint);
92
92
  for (const problem of problems) console.error(`FAIL commit-msg ${problem.rule}: ${problem.detail}`);
93
93
  return problems.length > 0 ? 1 : 0;
@@ -31,13 +31,28 @@ test("a message that is not English fails, whatever commitlint says", async () =
31
31
  assert.deepEqual(problems.map((problem) => problem.rule), ["english"]);
32
32
  });
33
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), []);
34
+ test("the diff that git commit -v puts under the scissors line is not part of the message", async () => {
35
+ const commitlint = await loadCommitlint(HARNESS);
36
+ const raw = [
37
+ "fix(ui): save the photo",
38
+ "# ------------------------ >8 ------------------------",
39
+ "# Do not modify or remove the line above.",
40
+ "diff --git a/x.ts b/x.ts",
41
+ `+const label = "写真を保存する"; ${"x".repeat(120)}`,
42
+ ].join("\n");
43
+ assert.deepEqual(await checkCommitMessage(raw, {}, commitlint), []);
44
+ });
45
+
46
+ test("with no commitlint installed, the conventional rules skip and the hook names the install command", async (t) => {
47
+ const dir = emptyDir(t);
48
+ assert.equal(await loadCommitlint(dir), null);
49
+ assert.deepEqual(await checkCommitMessage("WIP\n", {}, null), []);
50
+ const file = path.join(dir, "COMMIT_EDITMSG");
51
+ writeFileSync(file, "WIP\n");
52
+ const notes = [];
53
+ t.mock.method(console, "error", (line) => notes.push(line));
54
+ assert.equal(await runCommitMsg({ root: dir, commitMessage: defaults.commitMessage, language: {} }, file), 0);
55
+ assert.ok(notes.some((line) => line.startsWith("NOTE") && line.includes(INSTALL_HINT)), notes.join("\n"));
41
56
  });
42
57
 
43
58
  test("attribution is off by default, so a Claude trailer passes; on, a message without the trailer fails", async () => {
@@ -36,6 +36,14 @@ function editsRegion(file, input) {
36
36
  return edits.some((one) => typeof one?.old_string === "string" && one.old_string !== "" && touchesRegion(text, lf(one.old_string), regions));
37
37
  }
38
38
 
39
+ /** True when a Write of the Markdown file changes or drops a generated region. Text outside them is free. */
40
+ function writesRegion(file, content) {
41
+ if (!existsSync(file) || typeof content !== "string") return false;
42
+ const regionsOf = (text) => generatedRegions(text).map(([start, end]) => text.slice(start, end));
43
+ const after = regionsOf(lf(content));
44
+ return regionsOf(lf(readFileSync(file, "utf8"))).some((region) => !after.includes(region));
45
+ }
46
+
39
47
  /** The verdict on one edit. @returns the hook output, or null to let the call run with no message. */
40
48
  export function decide(call) {
41
49
  const input = call.tool_input ?? {};
@@ -52,11 +60,12 @@ export function decide(call) {
52
60
  return null;
53
61
  }
54
62
  const rel = path.relative(root, file).split(path.sep).join("/");
55
- const rerun = `Change its source, then run \`${generated.command}\`.`;
63
+ const rerun = generated.command ? `Change its source, then run \`${generated.command}\`.` : "Change its source, then run the generator that writes it.";
56
64
  if (globMatcher(generated.globs)(rel)) {
57
65
  return deny(`Generated-file guard: ${rel} is generated. ${rerun}`);
58
66
  }
59
- if (call.tool_name !== "Write" && MARKDOWN.test(rel) && editsRegion(file, input)) {
67
+ const changesRegion = call.tool_name === "Write" ? writesRegion(file, input.content) : editsRegion(file, input);
68
+ if (MARKDOWN.test(rel) && changesRegion) {
60
69
  return deny(`Generated-file guard: the edit changes the generated region of ${rel}. ${rerun}`);
61
70
  }
62
71
  return null;
@@ -46,13 +46,15 @@ const edit = (file, old_string, tool_input = {}) => ({
46
46
  const write = (file) => ({ ...edit(file, ""), tool_name: "Write", tool_input: { file_path: file, content: "x" } });
47
47
  const reasonOf = (output) => (output?.hookSpecificOutput?.permissionDecision === "deny" ? output.hookSpecificOutput.permissionDecisionReason : null);
48
48
 
49
- test("an edit of a generated file is denied, and the reason names the command that writes it", (t) => {
50
- const ws = workspace(t);
49
+ test("an edit of a generated file is denied, and the reason names the command that writes it, when set", (t) => {
50
+ const ws = workspace(t, { generated: { command: "pnpm codegen" } });
51
51
  for (const call of [edit(ws.at("src/routes.generated.ts"), "a"), write(ws.at("src/routes.generated.ts"))]) {
52
52
  const reason = reasonOf(decide(call));
53
53
  assert.match(reason, /src\/routes\.generated\.ts is generated/);
54
54
  assert.match(reason, /`pnpm codegen`/);
55
55
  }
56
+ const unset = workspace(t);
57
+ assert.match(reasonOf(decide(write(unset.at("src/routes.generated.ts")))), /run the generator that writes it\.$/);
56
58
  });
57
59
 
58
60
  test("a generated file at the repository root is denied too", (t) => {
@@ -85,6 +87,16 @@ test("an edit whose old_string lies in or across a generated region is denied",
85
87
  assert.ok(reasonOf(decide({ ...edit(doc, ""), ...multi })));
86
88
  });
87
89
 
90
+ test("a Write of the whole doc that changes or drops its generated region is denied, and one that keeps it passes", (t) => {
91
+ const ws = workspace(t);
92
+ const doc = ws.at("docs/enforcement.md");
93
+ const writeOf = (content) => ({ ...write(doc), tool_input: { file_path: doc, content } });
94
+ assert.ok(reasonOf(decide(writeOf(ENFORCEMENT.replace("qc/comment-style", "qc/other")))));
95
+ assert.ok(reasonOf(decide(writeOf("# Enforcement\n"))));
96
+ assert.equal(decide(writeOf(ENFORCEMENT.replace("Hand-written intro.", "A new intro."))), null);
97
+ assert.equal(decide(writeOf(`${ENFORCEMENT}\n<!-- generated: more. pnpm codegen. -->\n<!-- /generated -->\n`)), null);
98
+ });
99
+
88
100
  test("an edit outside the generated region passes", (t) => {
89
101
  const ws = workspace(t);
90
102
  assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written judgement calls.")), null);
package/src/cli/init.mjs CHANGED
@@ -1,8 +1,8 @@
1
- // Scaffold the documents and configuration a new repository needs before any gate
2
- // can pass. The citations gate reads docs/decisions.md; without it, gate one fails
3
- // on every file. So `init` is not a convenience — it is the gate's own precondition.
1
+ // Scaffold what a repository needs before any gate can pass: the config, the git hooks, the CI
2
+ // workflow, and an empty decision register. `--full` adds the reference architecture docs and
3
+ // the policy of the reference stack. Those docs cite the reference decisions, so they come together.
4
4
 
5
- import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
5
+ import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises";
6
6
  import { withEnforcementMap } from "../enforcement-map.mjs";
7
7
  import { existsSync, readdirSync } from "node:fs";
8
8
  import path from "node:path";
@@ -10,12 +10,17 @@ import { fileURLToPath } from "node:url";
10
10
 
11
11
  const templates = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../templates");
12
12
 
13
- // Copied into the repository root. `../decisions.examples.md` sits outside this list on
14
- // purpose: it cites ids the shipped register does not define, so a repository that took it
15
- // would fail the citations gate. A new
16
- // repository should not carry somebody else's domain decisions.
17
- const FILES = [
18
- ["qc.config.json", "qc.config.json"],
13
+ // Every repository gets these. They judge the change, not the layout.
14
+ const CORE = [
15
+ ["githooks/pre-commit", ".githooks/pre-commit"],
16
+ ["githooks/commit-msg", ".githooks/commit-msg"],
17
+ ["githooks/pre-push", ".githooks/pre-push"],
18
+ ["github/workflows/ci.yml", ".github/workflows/ci.yml"],
19
+ ];
20
+
21
+ // `--full` only: the reference architecture, its decisions, and its policy. `../decisions.examples.md`
22
+ // stays out: it cites ids the shipped register does not define, so it would fail the citations gate.
23
+ const FULL = [
19
24
  ["quality-thresholds.json", "quality-thresholds.json"],
20
25
  [".jscpd.json", ".jscpd.json"],
21
26
  ["docs/decisions.md", "docs/decisions.md"],
@@ -26,15 +31,53 @@ const FILES = [
26
31
  ["docs/pagination.md", "docs/pagination.md"],
27
32
  ["docs/glossary.md", "docs/glossary.md"],
28
33
  ["docs/ui.md", "docs/ui.md"],
29
- ["githooks/pre-commit", ".githooks/pre-commit"],
30
- ["githooks/commit-msg", ".githooks/commit-msg"],
31
- ["githooks/pre-push", ".githooks/pre-push"],
32
- ["github/workflows/ci.yml", ".github/workflows/ci.yml"],
34
+ ["github/workflows/pr-policy.yml", ".github/workflows/pr-policy.yml"],
33
35
  // The prose style `qc prose` hands to Vale: one config and one file per rule.
34
36
  ["vale/.vale.ini", ".vale/.vale.ini"],
35
37
  ...readdirSync(path.join(templates, "vale/styles/Qc")).map((rule) => [`vale/styles/Qc/${rule}`, `.vale/styles/Qc/${rule}`]),
36
38
  ];
37
39
 
40
+ const EMPTY_REGISTER = `# Decisions
41
+
42
+ Every id cited in this repository's code or docs is defined here. A citation to an id that is
43
+ not listed fails the citations gate. Ids are stable: never renumber one.
44
+
45
+ | id | decision | the rule it imposes |
46
+ |---|---|---|
47
+ `;
48
+
49
+ // Folders that hold no source of the repository's own.
50
+ const SKIP = new Set(["node_modules", "dist", "build", "out", "coverage", "vendor"]);
51
+
52
+ /** Every folder named `featureDir` within four levels of the root, as a POSIX path. None found is an empty list. */
53
+ export function detectFeatureRoots(root, featureDir) {
54
+ const found = [];
55
+ const walk = (dir, depth) => {
56
+ let entries;
57
+ try {
58
+ entries = readdirSync(dir, { withFileTypes: true });
59
+ } catch {
60
+ return;
61
+ }
62
+ for (const entry of entries) {
63
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIP.has(entry.name)) continue;
64
+ const full = path.join(dir, entry.name);
65
+ if (entry.name === featureDir) found.push(path.relative(root, full).split(path.sep).join("/"));
66
+ else if (depth < 4) walk(full, depth + 1);
67
+ }
68
+ };
69
+ walk(root, 1);
70
+ return found.sort();
71
+ }
72
+
73
+ async function writeIfAbsent(to, text, force) {
74
+ if (existsSync(to) && !force) return { to, status: "kept" };
75
+ const overwriting = existsSync(to);
76
+ await mkdir(path.dirname(to), { recursive: true });
77
+ await writeFile(to, text);
78
+ return { to, status: overwriting ? "overwritten" : "written" };
79
+ }
80
+
38
81
  // The enforcement map is filled in on the way out, so a rule added to the kit cannot ship a
39
82
  // template that fails the kit's own enforcement-map gate.
40
83
  async function copyTemplate(from, to, force, config) {
@@ -51,7 +94,6 @@ async function copyTemplate(from, to, force, config) {
51
94
 
52
95
  const SCRIPTS = {
53
96
  "spec:check": "qc check",
54
- "gen:feature": "qc feature",
55
97
  prepare: "qc install-hooks",
56
98
  };
57
99
 
@@ -81,18 +123,24 @@ async function ignoreWorktrees(config) {
81
123
 
82
124
  export async function runInit(config, args = []) {
83
125
  const force = args.includes("--force");
126
+ const full = args.includes("--full");
84
127
  const results = [];
85
- for (const [source, target] of FILES) {
128
+
129
+ // The roots this repository has, not the reference layout: a root that matches nothing fails `qc check`.
130
+ const featureRoots = detectFeatureRoots(config.root, config.featureDir);
131
+ const qcConfig = { $comment: "Every key is optional. `qc config` prints what is in force.", featureRoots, foreign: [], agreements: [] };
132
+ results.push(await writeIfAbsent(path.join(config.root, "qc.config.json"), `${JSON.stringify(qcConfig, null, 2)}\n`, force));
133
+
134
+ for (const [source, target] of [...CORE, ...(full ? FULL : [])]) {
86
135
  results.push(await copyTemplate(path.join(templates, source), path.join(config.root, target), force, config));
87
136
  }
137
+ if (!full) results.push(await writeIfAbsent(path.join(config.root, config.docs.decisions), EMPTY_REGISTER, force));
88
138
 
89
139
  for (const name of ["pre-commit", "commit-msg", "pre-push"]) {
90
140
  const hook = path.join(config.root, ".githooks", name);
91
141
  if (existsSync(hook)) await writeFile(hook, await readFile(hook, "utf8"), { mode: 0o755 });
92
142
  }
93
143
 
94
- // The docs and the CI workflow both tell a reader to run these, so `init` puts them
95
- // where a reader will look rather than leaving the instruction dangling.
96
144
  results.push(...(await addScripts(config)));
97
145
  results.push(await ignoreWorktrees(config));
98
146
 
@@ -103,12 +151,9 @@ export async function runInit(config, args = []) {
103
151
  const kept = results.filter((result) => result.status === "kept").length;
104
152
  if (kept > 0) console.log(`\n${kept} file(s) already existed and were left alone. --force overwrites.`);
105
153
  console.log(`
154
+ featureRoots: ${featureRoots.length > 0 ? featureRoots.join(", ") : "none found, so no feature gate runs"}.
106
155
  Next:
107
- 1. Edit docs/decisions.md — delete what does not apply, add your own. Ids are stable;
108
- never renumber, because every citation points at a number.
109
- 2. Edit docs/glossary.md and the per-surface table in docs/performance.md.
110
- 3. Point qc.config.json at your layout if it differs from the reference. \`qc config\`
111
- prints what is in force — featureRoots matching nothing is a failed check, not a pass.
112
- 4. \`qc install-hooks\` to bind the pre-commit, commit-msg and pre-push hooks.
113
- 5. \`qc feature <domain-name>\` to scaffold the first slice, then \`qc check\`.`);
156
+ 1. \`qc install-hooks\` to bind the pre-commit, commit-msg, and pre-push hooks.
157
+ 2. \`qc check\`, \`qc typecheck\`, and \`qc lint\` to see the gates pass.${full ? "" : `
158
+ 3. \`qc init --full\` adds the reference architecture docs, their decisions, and the PR policy workflow.`}`);
114
159
  }