architecture-harness 0.12.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.
@@ -0,0 +1,85 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { copyFileSync, mkdirSync, 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 { fileURLToPath } from "node:url";
8
+ import { hookDrift } from "./git-hooks.mjs";
9
+
10
+ const TEMPLATES = fileURLToPath(new URL("../../templates/githooks/", import.meta.url));
11
+ const REQUIRED = { "pre-commit": ["qc work-order-check"], "pre-push": ["qc check"] };
12
+
13
+ function repo(t) {
14
+ const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-git-hooks-")));
15
+ t.after(() => rmSync(root, { recursive: true, force: true }));
16
+ execFileSync("git", ["init", "-q"], { cwd: root, stdio: "pipe" });
17
+ const git = (...args) => execFileSync("git", args, { cwd: root, stdio: "pipe" });
18
+ const hook = (dir, name, text) => {
19
+ mkdirSync(path.join(root, dir), { recursive: true });
20
+ writeFileSync(path.join(root, dir, name), text);
21
+ };
22
+ return { root, git, hook };
23
+ }
24
+
25
+
26
+ test("the kit's template hooks, installed through core.hooksPath, carry every required step", (t) => {
27
+ const r = repo(t);
28
+ mkdirSync(path.join(r.root, "hooks-here"));
29
+ for (const name of ["pre-commit", "pre-push", "commit-msg"]) copyFileSync(path.join(TEMPLATES, name), path.join(r.root, "hooks-here", name));
30
+ r.git("config", "core.hooksPath", "hooks-here");
31
+ assert.deepEqual(hookDrift(r.root, REQUIRED).problems, []);
32
+ });
33
+
34
+ test("a pre-commit that never calls qc work-order-check fails, as quality-control-mono's did", (t) => {
35
+ const r = repo(t);
36
+ r.hook(".githooks", "pre-commit", "#!/usr/bin/env bash\nset -euo pipefail\nnpx eslint $STAGED --max-warnings 0\n");
37
+ r.hook(".githooks", "pre-push", "#!/usr/bin/env bash\nnpx qc check\n");
38
+ r.git("config", "core.hooksPath", ".githooks");
39
+ const found = hookDrift(r.root, REQUIRED);
40
+ assert.equal(found.problems.length, 1);
41
+ assert.equal(found.problems[0].rule, "hook-drift");
42
+ assert.match(found.problems[0].detail, /pre-commit never calls `qc work-order-check`/);
43
+ });
44
+
45
+ test("a call in a comment is no call, and a missing hook in a tracked folder fails", (t) => {
46
+ const r = repo(t);
47
+ r.hook(".githooks", "pre-commit", "#!/usr/bin/env bash\n# npx qc work-order-check\n");
48
+ const found = hookDrift(r.root, REQUIRED);
49
+ assert.deepEqual(found.problems.map((problem) => problem.detail.split(" ").slice(0, 2).join(" ")), ["pre-commit never", "pre-push is"]);
50
+ });
51
+
52
+ test("with no core.hooksPath, the tracked .githooks folder is read, since every clone installs it", (t) => {
53
+ const r = repo(t);
54
+ r.hook(".githooks", "pre-commit", "npx qc work-order-check\n");
55
+ r.hook(".githooks", "pre-push", "npx qc check\n");
56
+ assert.deepEqual(hookDrift(r.root, REQUIRED).problems, []);
57
+ });
58
+
59
+ test("with neither, git's own hooks folder is read, and a hook not installed there is a note", (t) => {
60
+ const r = repo(t);
61
+ r.hook(".git/hooks", "pre-push", "#!/bin/sh\nexit 0\n");
62
+ const found = hookDrift(r.root, REQUIRED);
63
+ assert.equal(found.problems.length, 1);
64
+ assert.match(found.problems[0].detail, /pre-push never calls `qc check`/);
65
+ assert.match(found.notes.join("\n"), /pre-commit is not installed/);
66
+ });
67
+
68
+ test("an emptied entry requires nothing of that hook", (t) => {
69
+ const r = repo(t);
70
+ r.hook(".githooks", "pre-commit", "npx qc work-order-check\n");
71
+ assert.deepEqual(hookDrift(r.root, { ...REQUIRED, "pre-push": [] }).problems, []);
72
+ });
73
+
74
+ test("qc doctor fails on hook drift, and passes the kit's template", async (t) => {
75
+ const { runDoctor } = await import("./doctor.mjs");
76
+ const r = repo(t);
77
+ r.hook(".githooks", "pre-commit", "npx eslint .\n");
78
+ r.hook(".githooks", "pre-push", "npx qc check\n");
79
+ const quiet = t.mock.method(console, "error", () => {});
80
+ t.mock.method(console, "log", () => {});
81
+ assert.equal(await runDoctor({ root: r.root, hooks: { required: REQUIRED } }), 1);
82
+ assert.match(quiet.mock.calls.map((call) => call.arguments[0]).join("\n"), /pre-commit never calls `qc work-order-check`/);
83
+ copyFileSync(path.join(TEMPLATES, "pre-commit"), path.join(r.root, ".githooks", "pre-commit"));
84
+ assert.equal(await runDoctor({ root: r.root, hooks: { required: REQUIRED } }), 0);
85
+ });
@@ -73,3 +73,13 @@ test("a feature file in the session's own project is checked from the project",
73
73
  assert.equal(runHook(ws, path.join(ws.project, "backend", "src")), 2);
74
74
  assert.deepEqual(ws.ranIn(), [ws.project]);
75
75
  });
76
+
77
+ test("a checkout with its own installed harness is checked by that copy, not the plugin's", (t) => {
78
+ const ws = workspace();
79
+ t.after(ws.cleanup);
80
+ const cli = path.join(ws.linked, "node_modules", "architecture-harness", "src", "cli");
81
+ mkdirSync(cli, { recursive: true });
82
+ writeFileSync(path.join(cli, "qc.mjs"), "process.exit(0);\n");
83
+ assert.equal(runHook(ws, path.join(ws.linked, "backend", "src")), 0);
84
+ assert.deepEqual(ws.ranIn(), []);
85
+ });
@@ -4,6 +4,9 @@
4
4
  import { GIT_READS, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
5
5
 
6
6
  const DIALECT = { escape: "`" };
7
+
8
+ /** Splits a PowerShell command line into segments, with the backtick as its escape. */
9
+ export const powershellSegments = (command) => segmentsOf(command, DIALECT);
7
10
  const NULL_DEVICES = new Set(["$null", "/dev/null", "nul"]);
8
11
 
9
12
  /** Approved verbs that only read, and the cmdlets and aliases that only read or print. */
@@ -0,0 +1,74 @@
1
+ // A git hook cannot see a pull request's body, so this half of "register the work first" runs in CI:
2
+ // the body names an issue, the issue exists, and it was opened before the pull request.
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { readFileSync } from "node:fs";
6
+
7
+ const REFERENCE = /\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?|refs?)\s*:?\s+(?:([\w.-]+\/[\w.-]+))?#(\d+)\b/gi;
8
+ const NO_ISSUE = /could not resolve to an? (issue|pull request)/i;
9
+ // The CI token sees only its own repository, so another repository reads as missing.
10
+ const NO_REPOSITORY = /could not resolve to a repository|HTTP 404/i;
11
+
12
+ /** @returns each issue a body names with a closing keyword or `Refs`, as `{repo, number}`. */
13
+ export function issueReferences(body, repo) {
14
+ return [...(body ?? "").matchAll(REFERENCE)].map((match) => ({ repo: match[1] ?? repo, number: Number(match[2]) }));
15
+ }
16
+
17
+ /** Runs gh, and never throws: a missing binary is a failed call like any other. */
18
+ function runGh(args) {
19
+ return new Promise((resolve) => {
20
+ execFile("gh", args, { encoding: "utf8" }, (error, stdout, stderr) => {
21
+ resolve(error ? { ok: false, stderr: `${stderr || error.message}` } : { ok: true, stdout });
22
+ });
23
+ });
24
+ }
25
+
26
+ /**
27
+ * @param {object} event the GitHub event payload
28
+ * @param {{gh?: (args: string[]) => Promise<{ok: boolean, stdout?: string, stderr?: string}>, hasToken: boolean}} options
29
+ * @returns {Promise<{problems: string[], notes: string[]}>}
30
+ */
31
+ export async function checkPullRequest(event, { gh = runGh, hasToken }) {
32
+ const pr = event?.pull_request;
33
+ if (!pr) return { problems: [], notes: ["the event is not a pull request, so there is no body to read"] };
34
+ const references = issueReferences(pr.body, event.repository?.full_name);
35
+ if (references.length === 0) {
36
+ return {
37
+ problems: [`pull request #${pr.number} names no issue. Add "Fixes #<n>" or "Refs #<n>" to its body, after you open the issue.`],
38
+ notes: [],
39
+ };
40
+ }
41
+ if (!hasToken) return { problems: [], notes: ["no GH_TOKEN, so the issues were not looked up"] };
42
+
43
+ const problems = [];
44
+ const notes = [];
45
+ for (const { repo, number } of references) {
46
+ const name = `${repo}#${number}`;
47
+ const result = await gh(["issue", "view", String(number), "-R", repo, "--json", "createdAt"]);
48
+ if (!result.ok) {
49
+ const stderr = result.stderr ?? "";
50
+ if (NO_ISSUE.test(stderr)) problems.push(`${name} does not exist. Open the issue, then reference it.`);
51
+ else if (NO_REPOSITORY.test(stderr)) notes.push(`the token cannot see ${repo}, so ${name} was not looked up`);
52
+ else notes.push(`could not reach GitHub for ${name}: ${(result.stderr ?? "").trim().split("\n")[0]}`);
53
+ continue;
54
+ }
55
+ const created = JSON.parse(result.stdout).createdAt;
56
+ if (Date.parse(created) > Date.parse(pr.created_at)) {
57
+ problems.push(`${name} was opened after the pull request. Register the work before it starts.`);
58
+ }
59
+ }
60
+ return { problems, notes };
61
+ }
62
+
63
+ export async function runPrCheck(env = process.env) {
64
+ if (!env.GITHUB_EVENT_PATH) {
65
+ console.log("SKIP pr-check no GITHUB_EVENT_PATH, so this is not a CI run");
66
+ return 0;
67
+ }
68
+ const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, "utf8"));
69
+ const { problems, notes } = await checkPullRequest(event, { hasToken: Boolean(env.GH_TOKEN || env.GITHUB_TOKEN) });
70
+ for (const note of notes) console.log(`NOTE pr-check ${note}`);
71
+ for (const problem of problems) console.error(`FAIL pr-check ${problem}`);
72
+ if (problems.length === 0) console.log("OK pr-check the pull request names an issue opened before it");
73
+ return problems.length > 0 ? 1 : 0;
74
+ }
@@ -0,0 +1,59 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkPullRequest, issueReferences } from "./pr-check.mjs";
4
+
5
+ const event = (body) => ({
6
+ repository: { full_name: "acme/app" },
7
+ pull_request: { number: 9, body, created_at: "2026-05-02T00:00:00Z" },
8
+ });
9
+ /** A gh runner that knows the issues given, by `owner/repo#n`, with their creation times. */
10
+ const ghKnowing = (issues) => async (args) => {
11
+ const repo = args[args.indexOf("-R") + 1];
12
+ const created = issues[`${repo}#${args[2]}`];
13
+ if (!created) return { ok: false, stderr: "GraphQL: Could not resolve to an issue or pull request with the number of 404." };
14
+ return { ok: true, stdout: JSON.stringify({ createdAt: created }) };
15
+ };
16
+
17
+ test("a PR body names its issue as Fixes #n, Refs #n, or a cross-repository Refs owner/repo#n", () => {
18
+ assert.deepEqual(issueReferences("Fixes #12\nrefs #3, and Refs other/lib#7", "acme/app"), [
19
+ { repo: "acme/app", number: 12 },
20
+ { repo: "acme/app", number: 3 },
21
+ { repo: "other/lib", number: 7 },
22
+ ]);
23
+ assert.deepEqual(issueReferences("Mentions #12 in passing", "acme/app"), []);
24
+ });
25
+
26
+ test("a PR body with no reference fails", async () => {
27
+ const result = await checkPullRequest(event("Tidy the readme."), { gh: ghKnowing({}), hasToken: true });
28
+ assert.match(result.problems.join("\n"), /names no issue/);
29
+ });
30
+
31
+ test("an issue that exists and predates the PR passes; a missing or newer one fails", async () => {
32
+ const gh = ghKnowing({ "acme/app#12": "2026-05-01T00:00:00Z", "acme/app#13": "2026-05-03T00:00:00Z" });
33
+ assert.deepEqual((await checkPullRequest(event("Fixes #12"), { gh, hasToken: true })).problems, []);
34
+ assert.match((await checkPullRequest(event("Fixes #404"), { gh, hasToken: true })).problems.join(), /acme\/app#404 does not exist/);
35
+ assert.match((await checkPullRequest(event("Refs #13"), { gh, hasToken: true })).problems.join(), /was opened after the pull request/);
36
+ });
37
+
38
+ test("with no token, or no network, the issue lookup skips with a note, but the reference is still required", async () => {
39
+ const noToken = await checkPullRequest(event("Fixes #12"), { gh: ghKnowing({}), hasToken: false });
40
+ assert.deepEqual(noToken.problems, []);
41
+ assert.match(noToken.notes.join(), /no GH_TOKEN/);
42
+ const offline = await checkPullRequest(event("Fixes #12"), { gh: async () => ({ ok: false, stderr: "dial tcp: lookup api.github.com: no such host" }), hasToken: true });
43
+ assert.deepEqual(offline.problems, []);
44
+ assert.match(offline.notes.join(), /could not reach GitHub/);
45
+ assert.match((await checkPullRequest(event(""), { gh: ghKnowing({}), hasToken: false })).problems.join(), /names no issue/);
46
+ });
47
+
48
+ test("a repository the token cannot see is a note, never a missing issue", async () => {
49
+ const gh = async () => ({ ok: false, stderr: "GraphQL: Could not resolve to a Repository with the name 'acme/private'. (repository)" });
50
+ const result = await checkPullRequest(event("Refs acme/private#5"), { gh, hasToken: true });
51
+ assert.deepEqual(result.problems, []);
52
+ assert.match(result.notes.join(), /the token cannot see acme.private/);
53
+ });
54
+
55
+ test("an event that is no pull request is skipped", async () => {
56
+ const result = await checkPullRequest({ repository: { full_name: "acme/app" } }, { gh: ghKnowing({}), hasToken: true });
57
+ assert.deepEqual(result.problems, []);
58
+ assert.match(result.notes.join(), /not a pull request/);
59
+ });
package/src/cli/qc.mjs CHANGED
@@ -15,7 +15,8 @@ const USAGE = `qc — architecture gates
15
15
  qc work-order-check refuse to commit on the wrong branch, per .claude/work-order.local.json
16
16
  qc lease status [path] who holds this worktree's lease, since when, and when it lapses
17
17
  qc lease release [path] remove it: --session <id> for your own, --force for another's
18
- qc commit-msg <file> refuse a commit message that credits a tool as an author
18
+ qc pr-check in CI: the pull request names an issue that exists and predates it
19
+ qc commit-msg <file> conventional (commitlint), English, and the trailer when attribution is on
19
20
  qc decisions [id] where decisions are cited; --squash closes the gaps
20
21
  qc worktree add <name> <branch> [--from <ref>]
21
22
  fetch, add ../<name> beside the main checkout, install, print the path
@@ -72,12 +73,13 @@ async function main() {
72
73
  const { runWorkOrderCheck } = await import("./work-order-guard.mjs");
73
74
  process.exit(await runWorkOrderCheck(config.root));
74
75
  }
76
+ case "pr-check": {
77
+ const { runPrCheck } = await import("./pr-check.mjs");
78
+ process.exit(await runPrCheck());
79
+ }
75
80
  case "commit-msg": {
76
- const { readFileSync } = await import("node:fs");
77
- const { checkCommitAttribution } = await import("./commit-attribution.mjs");
78
- const problems = checkCommitAttribution(readFileSync(rest[0], "utf8"), config.commitMessage);
79
- for (const problem of problems) console.error(`FAIL commit-msg ${problem.rule}: ${problem.detail}`);
80
- process.exit(problems.length > 0 ? 1 : 0);
81
+ const { runCommitMsg } = await import("./commit-msg.mjs");
82
+ process.exit(await runCommitMsg(config, rest[0]));
81
83
  }
82
84
  case "decisions": {
83
85
  const { runDecisions } = await import("./decisions.mjs");
@@ -0,0 +1,113 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, 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 { fileURLToPath } from "node:url";
8
+
9
+ const HOOK = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..", "hooks", "stop-gate.sh");
10
+
11
+ /**
12
+ * A qc CLI stub that logs `<label> <command>` and exits with the code given for that command.
13
+ * `withDoctor` ships the doctor.mjs file the stop gate probes for.
14
+ */
15
+ function stubHarness(cliDir, label, log, codes, withDoctor, outputs = {}) {
16
+ mkdirSync(cliDir, { recursive: true });
17
+ writeFileSync(
18
+ path.join(cliDir, "qc.mjs"),
19
+ [
20
+ `import { appendFileSync } from "node:fs";`,
21
+ `const command = process.argv[2];`,
22
+ `appendFileSync(${JSON.stringify(log)}, ${JSON.stringify(label)} + " " + command + String.fromCharCode(10));`,
23
+ `const codes = ${JSON.stringify(codes)};`,
24
+ `const outputs = ${JSON.stringify(outputs)};`,
25
+ `if (codes[command]) console.error(outputs[command] ?? "FAIL " + command + " from " + ${JSON.stringify(label)});`,
26
+ `process.exit(codes[command] ?? 0);`,
27
+ ].join("\n"),
28
+ );
29
+ if (withDoctor) writeFileSync(path.join(cliDir, "doctor.mjs"), "");
30
+ }
31
+
32
+ /** A repository that adopted the kit, and a plugin whose bundled copy is older: its `check` fails. */
33
+ function workspace(t, installed) {
34
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-stop-gate-")));
35
+ t.after(() => rmSync(base, { recursive: true, force: true }));
36
+ const repo = path.join(base, "repo");
37
+ mkdirSync(repo, { recursive: true });
38
+ writeFileSync(path.join(repo, "qc.config.json"), "{}");
39
+ const log = path.join(base, "qc-ran.log");
40
+ const pluginRoot = path.join(base, "plugin");
41
+ stubHarness(path.join(pluginRoot, "packages", "qc-harness", "src", "cli"), "plugin", log, { check: 1 }, false);
42
+ if (installed) {
43
+ const cli = path.join(repo, "node_modules", "architecture-harness", "src", "cli");
44
+ stubHarness(cli, "installed", log, installed.codes, installed.withDoctor, installed.outputs);
45
+ }
46
+ const ran = () => (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []);
47
+ const run = (input = {}) =>
48
+ spawnSync("bash", [HOOK], {
49
+ input: JSON.stringify({ hook_event_name: "Stop", ...input }),
50
+ env: { ...process.env, CLAUDE_PROJECT_DIR: repo, CLAUDE_PLUGIN_ROOT: pluginRoot, QC_STOP_EXTRA: "" },
51
+ encoding: "utf8",
52
+ });
53
+ return { ran, run };
54
+ }
55
+
56
+ test("an installed harness newer than the bundled one judges the repository, and the stop passes", (t) => {
57
+ const ws = workspace(t, { codes: {}, withDoctor: false });
58
+ const result = ws.run();
59
+ assert.equal(result.status, 0, result.stderr);
60
+ assert.deepEqual(ws.ran(), ["installed check"]);
61
+ });
62
+
63
+ test("with no installed harness, the bundled copy judges the repository", (t) => {
64
+ const ws = workspace(t, null);
65
+ const result = ws.run();
66
+ assert.equal(result.status, 2);
67
+ assert.deepEqual(ws.ran(), ["plugin check"]);
68
+ assert.match(result.stderr, /FAIL {2}check from plugin/);
69
+ });
70
+
71
+ test("drift alone refuses the first stop, and names the setup, not the code", (t) => {
72
+ const ws = workspace(t, { codes: { doctor: 1 }, withDoctor: true });
73
+ const result = ws.run();
74
+ assert.equal(result.status, 2);
75
+ assert.deepEqual(ws.ran(), ["installed doctor", "installed check"]);
76
+ assert.match(result.stderr, /FAIL {2}doctor from installed/);
77
+ assert.match(result.stderr, /kit setup, not in your code/);
78
+ });
79
+
80
+ test("drift alone after a refused stop lets the session end with a note, so a stale plugin never loops it", (t) => {
81
+ const ws = workspace(t, { codes: { doctor: 1 }, withDoctor: true });
82
+ const result = ws.run({ stop_hook_active: true });
83
+ assert.equal(result.status, 0, result.stderr);
84
+ assert.match(JSON.parse(result.stdout).systemMessage, /The kit setup still drifts/);
85
+ });
86
+
87
+ test("a red check after a refused stop still refuses, because only drift is excused", (t) => {
88
+ const ws = workspace(t, { codes: { doctor: 1, check: 1 }, withDoctor: true });
89
+ const result = ws.run({ stop_hook_active: true });
90
+ assert.equal(result.status, 2);
91
+ assert.match(result.stderr, /FAIL {2}check from installed/);
92
+ });
93
+
94
+ const HOOK_DRIFT = "FAIL .githooks/pre-commit hook-drift: pre-commit never calls `qc work-order-check`, so that step is off.";
95
+
96
+ test("hook drift reported only through qc check is drift, so a refused stop may end with a note", (t) => {
97
+ const output = [HOOK_DRIFT, "", "1 problem(s). docs/enforcement.md"].join("\n");
98
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: output } });
99
+ const refused = ws.run();
100
+ assert.equal(refused.status, 2);
101
+ assert.match(refused.stderr, /kit setup, not in your code/);
102
+ const result = ws.run({ stop_hook_active: true });
103
+ assert.equal(result.status, 0, result.stderr);
104
+ assert.match(JSON.parse(result.stdout).systemMessage, /The kit setup still drifts/);
105
+ });
106
+
107
+ test("hook drift beside a real gate failure still refuses a stop after a refused one", (t) => {
108
+ const output = [HOOK_DRIFT, "FAIL orders citations: ADR-0099 is cited but not defined", "", "2 problem(s)."].join("\n");
109
+ const ws = workspace(t, { codes: { check: 1 }, withDoctor: false, outputs: { check: output } });
110
+ const result = ws.run({ stop_hook_active: true });
111
+ assert.equal(result.status, 2);
112
+ assert.match(result.stderr, /citations: ADR-0099/);
113
+ });
@@ -0,0 +1,9 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { readFileSync } from "node:fs";
3
+ import { test } from "node:test";
4
+
5
+ const template = (name) => readFileSync(new URL(`../../templates/${name}`, import.meta.url), "utf8");
6
+
7
+ test("the template workflow checks out full history, so the threshold ratchet has a merge base", () => {
8
+ assert.match(template("github/workflows/ci.yml"), /uses: actions\/checkout@v\d+\s*\n\s*with: \{ fetch-depth: 0 \}/);
9
+ });
@@ -19,7 +19,7 @@ import path from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { promisify } from "node:util";
21
21
  import { load } from "../config.mjs";
22
- import { globToRegExp } from "../glob.mjs";
22
+ import { globMatcher, globToRegExp } from "../glob.mjs";
23
23
  import { ignoredPaths } from "./ignored-paths.mjs";
24
24
  import { claimLease, leaseFileOf, readLease } from "./lease-file.mjs";
25
25
  import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
@@ -211,11 +211,35 @@ async function warnOnBranchMismatch(root, manifest) {
211
211
  }
212
212
 
213
213
  /** The pre-commit git hook's own check — refuses the commit itself, not just an edit. */
214
+ /** @returns why a branch name breaks `branches.pattern`, or null. A detached HEAD and an allowed branch pass. */
215
+ export function branchNameRefusal(branch, { pattern, allow = [] }) {
216
+ if (!branch || !pattern || globMatcher(allow)(branch) || new RegExp(pattern).test(branch)) return null;
217
+ return (
218
+ `Branch "${branch}" names no issue: it must match branches.pattern ${pattern}, as in feat/340-roles. ` +
219
+ "Open the issue first, then rename the branch: git branch -m <type>/<issue>-<slug>."
220
+ );
221
+ }
222
+
223
+ /** The commit-time branch-name rule. @returns true when the commit must be refused. */
224
+ async function branchNameCommitRefusal(root) {
225
+ let state;
226
+ try {
227
+ state = await gitState(root);
228
+ } catch {
229
+ return false;
230
+ }
231
+ if (inSpecialGitOperation(state.gitDir)) return false;
232
+ const reason = branchNameRefusal(state.branch, load(root).branches);
233
+ if (reason) console.error(reason);
234
+ return reason !== null;
235
+ }
236
+
214
237
  export async function runWorkOrderCheck(root) {
215
238
  // Isolation is checked here as well as at edit time, and this is the check that binds: the
216
239
  // PreToolUse hook only sees the Write and Edit tools, so an agent writing through a shell
217
240
  // -- sed, a heredoc, a script -- never reaches it. A commit cannot be made without git.
218
241
  if (await isolationCommitRefusal(root)) return 1;
242
+ if (await branchNameCommitRefusal(root)) return 1;
219
243
 
220
244
  const manifest = readManifest(root);
221
245
  if (!manifest?.branch) return 0;
package/src/config.mjs CHANGED
@@ -237,13 +237,16 @@ export const defaults = {
237
237
  // Switching a shipped check off names the decision that says why, or "off-by-design".
238
238
  floor: { exemptions: {} },
239
239
 
240
- // A tool is not an author. These may never appear in a commit's attribution trailer.
241
- commitMessage: {
242
- tools: [
243
- "claude", "anthropic", "copilot", "chatgpt", "openai", "gpt-4", "gpt-5", "gemini",
244
- "cursor", "codeium", "devin", "aider", "windsurf", "bot@", "noreply@anthropic.com",
245
- ],
246
- },
240
+ // The calls each git hook must make. `qc doctor` and the config-floor gate read the hooks git runs.
241
+ // A branch names its issue, as in feat/340-roles. `allow` holds globs for the branches with none.
242
+ // A null `pattern` switches the rule off.
243
+ branches: { pattern: "^[a-z]+/[0-9]+-", allow: ["main", "master", "release/**"] },
244
+
245
+ hooks: { required: { "pre-commit": ["qc work-order-check"], "pre-push": ["qc check"] } },
246
+
247
+ // `conventional` runs commitlint's conventional rules, an optional peer dependency the repository
248
+ // installs. `attribution` requires a Co-Authored-By trailer. The English rule always runs.
249
+ commitMessage: { conventional: true, attribution: false },
247
250
 
248
251
  // A named pattern is a pointer. `patterns` adds a repository's own vocabulary to the defaults.
249
252
  patterns: { maxWords: 20, extra: [] },
@@ -13,6 +13,22 @@ export function switchedOff(shipped, configured) {
13
13
  .sort();
14
14
  }
15
15
 
16
+ /** @returns each hook whose required calls lack one the kit ships. */
17
+ export function weakenedHooks(shipped = {}, configured = {}) {
18
+ return Object.keys(shipped)
19
+ .filter((name) => shipped[name].some((call) => !(configured[name] ?? []).includes(call)))
20
+ .sort();
21
+ }
22
+
23
+ /** Every shipped check this repository has switched off, by kind. A hook's exemption key is `hooks.<name>`. */
24
+ function offByKind(shipped, configured) {
25
+ return {
26
+ gates: switchedOff(shipped.gates ?? {}, configured.gates ?? {}),
27
+ rules: switchedOff(shipped.rules ?? {}, configured.rules ?? {}),
28
+ hooks: weakenedHooks(shipped.hooks?.required, configured.hooks?.required).map((name) => `hooks.${name}`),
29
+ };
30
+ }
31
+
16
32
  /**
17
33
  * @param {{gates: object, rules: object}} shipped the kit's own defaults
18
34
  * @param {{gates: object, rules: object}} configured this repository's resolved config
@@ -23,15 +39,17 @@ export function checkConfigFloor(shipped, configured, options = {}) {
23
39
  const pattern = options.pattern ?? /^[A-Z]{2,5}-\d{3,4}$/;
24
40
  const problems = [];
25
41
 
26
- for (const kind of ["gates", "rules"]) {
27
- for (const name of switchedOff(shipped[kind] ?? {}, configured[kind] ?? {})) {
42
+ const off = offByKind(shipped, configured);
43
+ for (const kind of ["gates", "rules", "hooks"]) {
44
+ for (const name of off[kind]) {
45
+ const shown = kind === "hooks" ? name : `${kind}.${name}`;
28
46
  const cited = exemptions[name];
29
47
  if (cited === undefined) {
30
48
  problems.push({
31
49
  path: "qc.config.json",
32
50
  rule: "unexempted-opt-out",
33
51
  detail:
34
- `${kind}.${name} is switched off, and the kit ships it on. Name the decision that says ` +
52
+ `${shown} is switched off, and the kit ships it on. Name the decision that says ` +
35
53
  `why under floor.exemptions, or "${OFF_BY_DESIGN}" when the rule cannot apply to this repository's shape.`,
36
54
  });
37
55
  continue;
@@ -46,12 +64,9 @@ export function checkConfigFloor(shipped, configured, options = {}) {
46
64
  }
47
65
  }
48
66
  // An exemption for something that is not off is a stale reason nobody will notice going wrong.
49
- const off = new Set([
50
- ...switchedOff(shipped.gates ?? {}, configured.gates ?? {}),
51
- ...switchedOff(shipped.rules ?? {}, configured.rules ?? {}),
52
- ]);
67
+ const inForce = new Set([...off.gates, ...off.rules, ...off.hooks]);
53
68
  for (const name of Object.keys(exemptions).sort()) {
54
- if (!off.has(name)) {
69
+ if (!inForce.has(name)) {
55
70
  problems.push({
56
71
  path: "qc.config.json",
57
72
  rule: "stale-exemption",
@@ -50,3 +50,13 @@ test("a check the kit does not ship on is not held to the floor", () => {
50
50
  test("cited ids are collected for the citations gate, and off-by-design is not one", () => {
51
51
  assert.deepEqual(exemptionIds({ a: "QC-011", b: "off-by-design", c: "ADR-0031" }), ["QC-011", "ADR-0031"]);
52
52
  });
53
+
54
+ test("a weakened hooks.required entry is an opt-out, held to the same floor", () => {
55
+ const shipped = { gates: {}, rules: {}, hooks: { required: { "pre-commit": ["qc work-order-check"], "pre-push": ["qc check"] } } };
56
+ const weakened = { gates: {}, rules: {}, hooks: { required: { "pre-commit": ["qc work-order-check"], "pre-push": [] } } };
57
+ const problems = checkConfigFloor(shipped, weakened);
58
+ assert.deepEqual(problems.map((problem) => problem.rule), ["unexempted-opt-out"]);
59
+ assert.match(problems[0].detail, /^hooks\.pre-push is switched off/);
60
+ assert.deepEqual(checkConfigFloor(shipped, weakened, { exemptions: { "hooks.pre-push": "off-by-design" } }), []);
61
+ assert.deepEqual(checkConfigFloor(shipped, shipped, { exemptions: { "hooks.pre-push": "off-by-design" } }).map((p) => p.rule), ["stale-exemption"]);
62
+ });
@@ -15,7 +15,7 @@ const SCRIPTS = {
15
15
  fullwidth: "\\uff00-\\uffef",
16
16
  };
17
17
 
18
- function scriptPattern(scripts) {
18
+ export function scriptPattern(scripts) {
19
19
  const ranges = scripts.map((name) => SCRIPTS[name] ?? name).join("");
20
20
  if (ranges === "") throw new Error("language.scripts must name at least one script range");
21
21
  return new RegExp(`[${ranges}]`);
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env bash
2
- # A tool is not an author. Checked here because a trailer is added at commit time and nowhere else.
2
+ # Conventional, English, and the attribution trailer when qc.config.json asks for it. Checked here,
3
+ # because a message is written at commit time and nowhere else.
3
4
  set -euo pipefail
4
5
  npx qc commit-msg "$1" || exit 1
@@ -5,7 +5,9 @@ jobs:
5
5
  gates:
6
6
  runs-on: ubuntu-latest
7
7
  steps:
8
+ # Full history: the threshold ratchet compares the registry with the merge base.
8
9
  - uses: actions/checkout@v5
10
+ with: { fetch-depth: 0 }
9
11
  - uses: actions/setup-node@v5
10
12
  with: { node-version-file: package.json }
11
13
  - run: corepack enable
@@ -14,6 +16,11 @@ jobs:
14
16
  # The structural gates. This step needs no package script of its own.
15
17
  - run: npx qc check
16
18
 
19
+ # A pull request names the issue it closes, and the issue predates it.
20
+ - if: github.event_name == 'pull_request'
21
+ run: npx qc pr-check
22
+ env: { GH_TOKEN: "${{ github.token }}" }
23
+
17
24
  # Uncomment each as the repository grows the thing it checks.
18
25
  # - run: pnpm typecheck
19
26
  # - run: pnpm lint