architecture-harness 0.23.1 → 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 (45) hide show
  1. package/package.json +3 -1
  2. package/src/cli/budget-guard.mjs +1 -0
  3. package/src/cli/budget-guard.test.mjs +7 -1
  4. package/src/cli/budget.mjs +3 -4
  5. package/src/cli/budget.test.mjs +5 -5
  6. package/src/cli/ci-template.test.mjs +17 -27
  7. package/src/cli/cli.test.mjs +22 -2
  8. package/src/cli/commit-msg.mjs +7 -10
  9. package/src/cli/commit-msg.test.mjs +10 -7
  10. package/src/cli/generated-file-guard.mjs +1 -1
  11. package/src/cli/generated-file-guard.test.mjs +4 -2
  12. package/src/cli/init.mjs +70 -25
  13. package/src/cli/lint-changed.mjs +157 -0
  14. package/src/cli/lint-changed.test.mjs +102 -0
  15. package/src/cli/plugin-agents.test.mjs +1 -1
  16. package/src/cli/post-edit-gate.test.mjs +3 -1
  17. package/src/cli/qc.mjs +23 -3
  18. package/src/cli/scaffold.mjs +23 -2
  19. package/src/cli/scaffold.test.mjs +51 -0
  20. package/src/cli/stop-gate.test.mjs +32 -128
  21. package/src/cli/typecheck.mjs +46 -0
  22. package/src/cli/typecheck.test.mjs +43 -0
  23. package/src/cli/user-config-package.mjs +16 -0
  24. package/src/cli/user-config-toml.mjs +144 -0
  25. package/src/cli/user-config.mjs +155 -0
  26. package/src/cli/user-config.test.mjs +274 -0
  27. package/src/cli/worktree-gate.mjs +11 -12
  28. package/src/cli/worktree-gate.test.mjs +28 -29
  29. package/src/cli/worktree-isolation.mjs +3 -3
  30. package/src/cli/worktree-isolation.test.mjs +1 -1
  31. package/src/cli/worktree.mjs +9 -1
  32. package/src/cli/worktree.test.mjs +16 -1
  33. package/src/config.mjs +13 -11
  34. package/src/eslint/preset.mjs +8 -3
  35. package/src/eslint/preset.test.mjs +15 -8
  36. package/src/vale-style.test.mjs +5 -5
  37. package/templates/CLAUDE.md +2 -2
  38. package/templates/githooks/pre-commit +7 -10
  39. package/templates/github/workflows/ci.yml +22 -89
  40. package/templates/github/workflows/pr-policy.yml +36 -0
  41. package/user-config/claude/settings.shared.json +74 -0
  42. package/user-config/claude/statusline.js +323 -0
  43. package/user-config/codex/config.shared.toml +19 -0
  44. package/src/cli/edit-batch-guard.mjs +0 -77
  45. package/src/cli/edit-batch-guard.test.mjs +0 -131
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.23.1",
3
+ "version": "0.25.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -47,9 +47,11 @@
47
47
  "files": [
48
48
  "src",
49
49
  "templates",
50
+ "user-config",
50
51
  "README.md"
51
52
  ],
52
53
  "scripts": {
54
+ "prepack": "node src/cli/user-config-package.mjs",
53
55
  "test": "node src/eslint/rules.test.mjs && node --test \"src/**/*.test.mjs\"",
54
56
  "test:browser": "node --test \"src/**/*.browser-test.mjs\""
55
57
  },
@@ -33,6 +33,7 @@ export function decide(call, tmp = os.tmpdir()) {
33
33
  // A config typo must not stop every agent; the agent sees the error and reports it.
34
34
  return context(`Tool-call budget is off: ${error.message}`);
35
35
  }
36
+ if (budget === null) return null;
36
37
  let count;
37
38
  try {
38
39
  count = bumpCount(counterFileOf(call.session_id ?? "session", agentId, tmp));
@@ -81,8 +81,14 @@ test("in a linked worktree, the budget from qc.config.json denies the call that
81
81
  assert.equal(runGuard(ws, callOf(ws.linked, "agent-1", "Bash", { command: "git push" })), null);
82
82
  });
83
83
 
84
- test("the default budget reminds at its seventieth call", (t) => {
84
+ test("with no budget set, the guard counts nothing and stays silent", (t) => {
85
85
  const ws = workspace(t, {});
86
+ assert.equal(runGuard(ws, callOf(ws.linked, "agent-1")), null);
87
+ assert.equal(existsSync(ws.counters), false);
88
+ });
89
+
90
+ test("a budget of one hundred reminds at its seventieth call", (t) => {
91
+ const ws = workspace(t, { toolCallBudget: 100 });
86
92
  mkdirSync(ws.counters, { recursive: true });
87
93
  writeFileSync(path.join(ws.counters, "session-aaaa-agent-1.json"), JSON.stringify({ count: 69 }));
88
94
  const output = runGuard(ws, callOf(ws.linked, "agent-1"));
@@ -2,18 +2,17 @@
2
2
  // An agent does not count its own calls, and each call re-sends its whole transcript, so the hook
3
3
  // counts for it and closes every tool except the hand-off once the budget is spent.
4
4
 
5
- import { defaults } from "../config.mjs";
6
5
  import { gitCall, isReadOnly, segmentsOf, writesRedirect } from "./shell-command.mjs";
7
6
 
8
- export const DEFAULT_BUDGET = defaults.swarm.toolCallBudget;
9
7
  const REMIND_PERCENT = 70;
10
8
  const REMIND_EVERY = 10;
11
9
  const KEY = "swarm.toolCallBudget";
12
10
  const HANDOFF_GIT = new Set(["status", "diff", "log", "add", "commit", "push"]);
13
11
 
14
- /** @returns the budget from the `swarm` config section, or throws naming the key a repository got wrong. */
12
+ /** @returns the budget from the `swarm` config section, null when it is off, or throws naming the key a repository got wrong. */
15
13
  export function budgetOf(swarm = {}) {
16
- const budget = swarm.toolCallBudget ?? DEFAULT_BUDGET;
14
+ const budget = swarm.toolCallBudget ?? null;
15
+ if (budget === null) return null;
17
16
  if (!Number.isInteger(budget) || budget < 1) {
18
17
  throw new Error(`${KEY} in qc.config.json must be a positive whole number, got ${JSON.stringify(swarm.toolCallBudget)}`);
19
18
  }
@@ -1,16 +1,16 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
- import { DEFAULT_BUDGET, budgetOf, budgetVerdict, isHandoffCall } from "./budget.mjs";
3
+ import { budgetOf, budgetVerdict, isHandoffCall } from "./budget.mjs";
4
4
 
5
5
  const bash = (command) => ({ tool_name: "Bash", tool_input: { command } });
6
6
  const write = (file_path) => ({ tool_name: "Write", tool_input: { file_path, content: "x" } });
7
7
  const edit = (file_path) => ({ tool_name: "Edit", tool_input: { file_path, old_string: "a", new_string: "b" } });
8
8
  const verdict = (count, call = bash("npm test"), budget = 100) => budgetVerdict({ count, budget, call });
9
9
 
10
- test("the budget is swarm.toolCallBudget, and one hundred calls without it", () => {
11
- assert.equal(DEFAULT_BUDGET, 100);
12
- assert.equal(budgetOf(), 100);
13
- assert.equal(budgetOf({}), 100);
10
+ test("the budget is swarm.toolCallBudget, and off without it", () => {
11
+ assert.equal(budgetOf(), null);
12
+ assert.equal(budgetOf({}), null);
13
+ assert.equal(budgetOf({ toolCallBudget: null }), null);
14
14
  assert.equal(budgetOf({ toolCallBudget: 40 }), 40);
15
15
  });
16
16
 
@@ -5,36 +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);
15
- });
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"/);
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/);
21
15
  });
22
16
 
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);
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/);
28
24
  });
29
25
 
30
- test("the gates job typechecks and lints on every push, with no step left commented out", () => {
31
- const text = readFileSync(WORKFLOW, "utf8");
32
- const runs = parse(text).jobs.gates.steps.map((step) => step.run ?? "").join("\n");
33
- assert.match(runs, /pnpm run typecheck/);
34
- assert.match(runs, /tsc -b/);
35
- assert.match(runs, /pnpm run lint/);
36
- assert.match(runs, /eslint \. --max-warnings 0/);
37
- assert.match(runs, /typecheck skipped: /);
38
- assert.match(runs, /lint skipped: /);
39
- assert.doesNotMatch(text, /^\s*# - run:/m);
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);
40
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"),
@@ -67,16 +67,10 @@ export async function checkCommitMessage(raw, options, commitlint) {
67
67
  .join("\n")
68
68
  .trim();
69
69
  const problems = [];
70
- if (options.conventional !== false) {
71
- if (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 });
74
- } else {
75
- problems.push({
76
- rule: "commitlint-missing",
77
- detail: `commitlint is not installed here. Run \`${INSTALL_HINT}\`, or set commitMessage.conventional to false.`,
78
- });
79
- }
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 });
80
74
  }
81
75
  const script = scriptPattern(options.scripts ?? ["cjk"]);
82
76
  message.split("\n").forEach((line, index) => {
@@ -91,6 +85,9 @@ export async function checkCommitMessage(raw, options, commitlint) {
91
85
  export async function runCommitMsg(config, file) {
92
86
  const options = { ...config.commitMessage, scripts: config.language?.scripts };
93
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
+ }
94
91
  const problems = await checkCommitMessage(readFileSync(file, "utf8"), options, commitlint);
95
92
  for (const problem of problems) console.error(`FAIL commit-msg ${problem.rule}: ${problem.detail}`);
96
93
  return problems.length > 0 ? 1 : 0;
@@ -43,13 +43,16 @@ test("the diff that git commit -v puts under the scissors line is not part of th
43
43
  assert.deepEqual(await checkCommitMessage(raw, {}, commitlint), []);
44
44
  });
45
45
 
46
- test("with no commitlint installed, the check fails with the install command, unless conventional is off", async (t) => {
47
- const commitlint = await loadCommitlint(emptyDir(t));
48
- assert.equal(commitlint, null);
49
- const problems = await checkCommitMessage("feat: x\n", {}, commitlint);
50
- assert.deepEqual(problems.map((problem) => problem.rule), ["commitlint-missing"]);
51
- assert.ok(problems[0].detail.includes(INSTALL_HINT));
52
- assert.deepEqual(await checkCommitMessage("feat: x\n", { conventional: false }, null), []);
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"));
53
56
  });
54
57
 
55
58
  test("attribution is off by default, so a Claude trailer passes; on, a message without the trailer fails", async () => {
@@ -60,7 +60,7 @@ export function decide(call) {
60
60
  return null;
61
61
  }
62
62
  const rel = path.relative(root, file).split(path.sep).join("/");
63
- 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.";
64
64
  if (globMatcher(generated.globs)(rel)) {
65
65
  return deny(`Generated-file guard: ${rel} is generated. ${rerun}`);
66
66
  }
@@ -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) => {
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
  }
@@ -0,0 +1,157 @@
1
+ // `qc lint`: ESLint on the lines a change adds. A problem on a line the change leaves alone belongs
2
+ // to the code before it, so it never blocks: an agent that is refused for it edits code its task
3
+ // never named. The hooks, the pre-commit hook and CI all call this one command.
4
+
5
+ import { spawnSync } from "node:child_process";
6
+ import { createRequire } from "node:module";
7
+ import { existsSync } from "node:fs";
8
+ import path from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { gitOut, gitStatusWithin } from "./git-read.mjs";
11
+
12
+ const LINTABLE = /\.(?:[cm]?[jt]sx?)$/;
13
+ const DIFF_TIMEOUT_MS = 30_000;
14
+
15
+ /**
16
+ * The new-side line numbers of each file in a `git diff -U0` text. A deleted file is absent.
17
+ * @returns {Map<string, Set<number>>}
18
+ */
19
+ export function parseDiff(text) {
20
+ const changed = new Map();
21
+ let current = null;
22
+ for (const line of text.split(/\r?\n/)) {
23
+ if (line.startsWith("+++ ")) {
24
+ const target = line.slice(4);
25
+ current = target === "/dev/null" ? null : target.replace(/^b\//, "");
26
+ if (current !== null && !changed.has(current)) changed.set(current, new Set());
27
+ continue;
28
+ }
29
+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
30
+ if (hunk && current !== null) {
31
+ const start = Number(hunk[1]);
32
+ const count = hunk[2] === undefined ? 1 : Number(hunk[2]);
33
+ for (let n = start; n < start + count; n++) changed.get(current).add(n);
34
+ }
35
+ }
36
+ return changed;
37
+ }
38
+
39
+ /** The ref a change is measured from: the merge base with `ref` when it resolves, else HEAD, else null for a repository with no commit. */
40
+ export function baseOf(root, ref) {
41
+ if (ref) {
42
+ const mergeBase = gitOut(root, "merge-base", "HEAD", ref);
43
+ if (mergeBase) return mergeBase;
44
+ }
45
+ return gitOut(root, "rev-parse", "--verify", "--quiet", "HEAD");
46
+ }
47
+
48
+ /**
49
+ * Each changed file and its changed lines. `all` marks a file that is new as a whole.
50
+ * Staged reads the index against HEAD; otherwise the working tree against `base`, with untracked files.
51
+ * @returns {Map<string, Set<number> | "all">}
52
+ */
53
+ export function changedLines(root, { staged = false, base = null } = {}) {
54
+ const args = ["diff", "-U0", "--no-color", "--no-ext-diff", "--diff-filter=ACMR"];
55
+ if (staged) args.push("--cached");
56
+ // With no commit yet every file is new, so there is nothing to diff against.
57
+ const head = gitOut(root, "rev-parse", "--verify", "--quiet", "HEAD");
58
+ if (head === null) {
59
+ const listed = gitOut(root, "ls-files", ...(staged ? [] : ["--others", "--cached", "--exclude-standard"])) ?? "";
60
+ return new Map(listed.split(/\r?\n/).filter(Boolean).map((file) => [file, "all"]));
61
+ }
62
+ if (!staged) args.push(base ?? head);
63
+ const diff = gitStatusWithin(DIFF_TIMEOUT_MS, root, ...args);
64
+ if (diff.error || diff.status !== 0) throw new Error(`git ${args.join(" ")} failed: ${diff.error ?? diff.stdout}`);
65
+ const changed = parseDiff(diff.stdout);
66
+ if (!staged) {
67
+ for (const file of (gitOut(root, "ls-files", "--others", "--exclude-standard") ?? "").split(/\r?\n/).filter(Boolean)) changed.set(file, "all");
68
+ }
69
+ return changed;
70
+ }
71
+
72
+ /**
73
+ * The problems of each ESLint result that sit on a changed line. A fatal message, such as a parse
74
+ * error, has no line of its own and always counts.
75
+ * @returns {{ kept: Array<{ file: string, message: object }>, skipped: number }}
76
+ */
77
+ export function onChangedLines(results, changed, root) {
78
+ const kept = [];
79
+ let skipped = 0;
80
+ for (const result of results) {
81
+ const file = path.relative(root, result.filePath).split(path.sep).join("/");
82
+ const lines = changed.get(file);
83
+ for (const message of result.messages) {
84
+ if (message.fatal || lines === "all" || lines?.has(message.line)) kept.push({ file, message });
85
+ else skipped++;
86
+ }
87
+ }
88
+ return { kept, skipped };
89
+ }
90
+
91
+ /** The file as the index holds it, untrimmed so its line numbers stay, or null when git cannot read it. */
92
+ function stagedText(root, file) {
93
+ const result = spawnSync("git", ["show", `:${file}`], { cwd: root, encoding: "utf8", windowsHide: true, maxBuffer: 1 << 26 });
94
+ return result.status === 0 ? result.stdout : null;
95
+ }
96
+
97
+ async function loadEslint(root) {
98
+ let resolved;
99
+ try {
100
+ resolved = createRequire(path.join(root, "package.json")).resolve("eslint");
101
+ } catch {
102
+ return null;
103
+ }
104
+ return (await import(pathToFileURL(resolved).href)).ESLint;
105
+ }
106
+
107
+ function parseArgs(args) {
108
+ const options = { staged: false, base: undefined, files: [] };
109
+ for (let i = 0; i < args.length; i++) {
110
+ if (args[i] === "--staged") options.staged = true;
111
+ else if (args[i] === "--base") options.base = args[++i];
112
+ else options.files.push(args[i]);
113
+ }
114
+ return options;
115
+ }
116
+
117
+ /** @returns the exit code: 1 when an error sits on a changed line, else 0. Warnings print and pass. */
118
+ export async function runLintChanged(config, args) {
119
+ const root = config.root;
120
+ const options = parseArgs(args);
121
+ const ESLint = await loadEslint(root);
122
+ if (ESLint === null) {
123
+ console.log("lint skipped: eslint is not installed in this repository");
124
+ return 0;
125
+ }
126
+ const base = options.staged ? null : baseOf(root, options.base ?? config.check.base);
127
+ const changed = changedLines(root, { staged: options.staged, base });
128
+ const wanted = options.files.map((file) => path.relative(root, path.resolve(file)).split(path.sep).join("/"));
129
+ const eslint = new ESLint({ cwd: root });
130
+ const files = [];
131
+ for (const file of changed.keys()) {
132
+ if (!LINTABLE.test(file) || (wanted.length > 0 && !wanted.includes(file))) continue;
133
+ if (!existsSync(path.join(root, file)) || (await eslint.isPathIgnored(path.join(root, file)))) continue;
134
+ files.push(file);
135
+ }
136
+ if (files.length === 0) return 0;
137
+
138
+ const results = [];
139
+ for (const file of files) {
140
+ const filePath = path.join(root, file);
141
+ // A staged commit is judged as it will be stored, not as the working tree holds it now.
142
+ const staged = options.staged ? stagedText(root, file) : null;
143
+ results.push(...(staged === null ? await eslint.lintFiles([filePath]) : await eslint.lintText(staged, { filePath })));
144
+ }
145
+ const { kept, skipped } = onChangedLines(results, changed, root);
146
+ const errors = kept.filter(({ message }) => message.fatal || message.severity === 2);
147
+ for (const { file, message } of kept) {
148
+ const kind = message.fatal || message.severity === 2 ? "error" : "warning";
149
+ console.error(`${file}:${message.line ?? 0}:${message.column ?? 0} ${kind} ${message.message} ${message.ruleId ?? ""}`.trimEnd());
150
+ }
151
+ if (kept.length > 0) {
152
+ console.error(`\n${errors.length} error(s) and ${kept.length - errors.length} warning(s) on the changed lines.`);
153
+ }
154
+ // Said once, so a reader knows the gate saw them and chose not to count them.
155
+ if (skipped > 0) console.error(`${skipped} older problem(s) on lines this change leaves alone are not counted. Leave them alone.`);
156
+ return errors.length > 0 ? 1 : 0;
157
+ }