architecture-harness 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -2
- package/src/cli/bash-command-guard.mjs +129 -0
- package/src/cli/bash-command-guard.test.mjs +96 -0
- package/src/cli/bash-edit-guard.mjs +10 -8
- package/src/cli/bash-edit-guard.test.mjs +16 -0
- package/src/cli/check.mjs +10 -1
- package/src/cli/edit-batch-guard.mjs +77 -0
- package/src/cli/edit-batch-guard.test.mjs +131 -0
- package/src/cli/edit-batch-state.mjs +57 -0
- package/src/cli/generated-file-guard.mjs +81 -0
- package/src/cli/generated-file-guard.test.mjs +104 -0
- package/src/cli/powershell-command.mjs +57 -0
- package/src/cli/powershell-command.test.mjs +52 -0
- package/src/cli/repo-files.mjs +2 -6
- package/src/cli/shell-command.mjs +25 -15
- package/src/cli/shell-command.test.mjs +24 -1
- package/src/config.mjs +24 -0
- package/src/descriptions.mjs +1 -0
- package/src/enforcement-map.mjs +2 -1
- package/src/eslint/index.mjs +6 -0
- package/src/eslint/preset.mjs +23 -8
- package/src/eslint/preset.test.mjs +62 -0
- package/src/eslint/rules/ime-safe-key.mjs +179 -0
- package/src/eslint/rules/no-sql-raw.mjs +30 -0
- package/src/eslint/rules/registry-literal.mjs +66 -0
- package/src/eslint/rules.test.mjs +151 -0
- package/src/gates/registry-readers.mjs +24 -0
- package/src/gates/registry-readers.test.mjs +35 -0
- package/src/generated-markers.mjs +16 -0
- package/src/glob.mjs +11 -0
- package/templates/quality-thresholds.json +1 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The PreToolUse trigger that refuses a hand edit of a generated file, or of a generated region of a
|
|
3
|
+
// Markdown file, and names the command that writes it. That command writes through the shell, never here.
|
|
4
|
+
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { CONFIG_FILE, load } from "../config.mjs";
|
|
9
|
+
import { generatedRegions } from "../generated-markers.mjs";
|
|
10
|
+
import { globMatcher } from "../glob.mjs";
|
|
11
|
+
import { checkoutRootOf } from "./checkout-root.mjs";
|
|
12
|
+
|
|
13
|
+
const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit"]);
|
|
14
|
+
const MARKDOWN = /\.mdx?$/i;
|
|
15
|
+
const lf = (text) => text.replace(/\r\n/g, "\n");
|
|
16
|
+
|
|
17
|
+
const deny = (reason) => ({
|
|
18
|
+
hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason },
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
/** True when any occurrence of `needle` overlaps a region. */
|
|
22
|
+
function touchesRegion(text, needle, regions) {
|
|
23
|
+
for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) {
|
|
24
|
+
if (regions.some(([start, end]) => at < end && at + needle.length > start)) return true;
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** True when an Edit or MultiEdit changes text inside a generated region of the Markdown file. */
|
|
30
|
+
function editsRegion(file, input) {
|
|
31
|
+
if (!existsSync(file)) return false;
|
|
32
|
+
const text = lf(readFileSync(file, "utf8"));
|
|
33
|
+
const regions = generatedRegions(text);
|
|
34
|
+
if (regions.length === 0) return false;
|
|
35
|
+
const edits = Array.isArray(input.edits) ? input.edits : [input];
|
|
36
|
+
return edits.some((one) => typeof one?.old_string === "string" && one.old_string !== "" && touchesRegion(text, lf(one.old_string), regions));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The verdict on one edit. @returns the hook output, or null to let the call run with no message. */
|
|
40
|
+
export function decide(call) {
|
|
41
|
+
const input = call.tool_input ?? {};
|
|
42
|
+
if (!EDIT_TOOLS.has(call.tool_name) || typeof input.file_path !== "string" || input.file_path === "") return null;
|
|
43
|
+
const file = path.resolve(call.cwd ?? process.cwd(), input.file_path);
|
|
44
|
+
const root = checkoutRootOf(path.dirname(file));
|
|
45
|
+
if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
|
|
46
|
+
|
|
47
|
+
let generated;
|
|
48
|
+
try {
|
|
49
|
+
generated = load(root).generated;
|
|
50
|
+
} catch {
|
|
51
|
+
// A config error is the edit guard's to name; this guard judges the path alone.
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
const rel = path.relative(root, file).split(path.sep).join("/");
|
|
55
|
+
const rerun = `Change its source, then run \`${generated.command}\`.`;
|
|
56
|
+
if (globMatcher(generated.globs)(rel)) {
|
|
57
|
+
return deny(`Generated-file guard: ${rel} is generated. ${rerun}`);
|
|
58
|
+
}
|
|
59
|
+
if (call.tool_name !== "Write" && MARKDOWN.test(rel) && editsRegion(file, input)) {
|
|
60
|
+
return deny(`Generated-file guard: the edit changes the generated region of ${rel}. ${rerun}`);
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function readStdin() {
|
|
66
|
+
let data = "";
|
|
67
|
+
for await (const chunk of process.stdin) data += chunk;
|
|
68
|
+
return data;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
|
|
72
|
+
if (isEntryPoint) {
|
|
73
|
+
let call = null;
|
|
74
|
+
try {
|
|
75
|
+
call = JSON.parse(await readStdin());
|
|
76
|
+
} catch {
|
|
77
|
+
// Not hook input, so there is nothing to judge.
|
|
78
|
+
}
|
|
79
|
+
const output = call ? decide(call) : null;
|
|
80
|
+
if (output) process.stdout.write(JSON.stringify(output));
|
|
81
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { 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 { decide } from "./generated-file-guard.mjs";
|
|
9
|
+
|
|
10
|
+
const GUARD = fileURLToPath(new URL("./generated-file-guard.mjs", import.meta.url));
|
|
11
|
+
|
|
12
|
+
const ENFORCEMENT = [
|
|
13
|
+
"# Enforcement",
|
|
14
|
+
"",
|
|
15
|
+
"Hand-written intro.",
|
|
16
|
+
"",
|
|
17
|
+
"<!-- generated: rule-to-check. pnpm codegen. -->",
|
|
18
|
+
"",
|
|
19
|
+
"| Rule | Check |",
|
|
20
|
+
"| A comment is one line | `qc/comment-style` |",
|
|
21
|
+
"",
|
|
22
|
+
"<!-- /generated -->",
|
|
23
|
+
"",
|
|
24
|
+
"Hand-written judgement calls.",
|
|
25
|
+
"",
|
|
26
|
+
].join("\n");
|
|
27
|
+
|
|
28
|
+
/** A checkout with the given config, holding a generated file, its source, and a doc with a generated region. */
|
|
29
|
+
function workspace(t, config = {}) {
|
|
30
|
+
const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-generated-")));
|
|
31
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
32
|
+
execFileSync("git", ["init", "-q"], { cwd: root, stdio: "pipe" });
|
|
33
|
+
if (config !== null) writeFileSync(path.join(root, "qc.config.json"), JSON.stringify(config));
|
|
34
|
+
for (const dir of ["src", "docs", "gen"]) mkdirSync(path.join(root, dir));
|
|
35
|
+
writeFileSync(path.join(root, "docs", "enforcement.md"), ENFORCEMENT);
|
|
36
|
+
writeFileSync(path.join(root, "docs", "crlf.md"), ENFORCEMENT.replace(/\n/g, "\r\n"));
|
|
37
|
+
return { root, at: (rel) => path.join(root, rel) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const edit = (file, old_string, tool_input = {}) => ({
|
|
41
|
+
hook_event_name: "PreToolUse",
|
|
42
|
+
tool_name: "Edit",
|
|
43
|
+
cwd: path.dirname(file),
|
|
44
|
+
tool_input: { file_path: file, old_string, new_string: "x", ...tool_input },
|
|
45
|
+
});
|
|
46
|
+
const write = (file) => ({ ...edit(file, ""), tool_name: "Write", tool_input: { file_path: file, content: "x" } });
|
|
47
|
+
const reasonOf = (output) => (output?.hookSpecificOutput?.permissionDecision === "deny" ? output.hookSpecificOutput.permissionDecisionReason : null);
|
|
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);
|
|
51
|
+
for (const call of [edit(ws.at("src/routes.generated.ts"), "a"), write(ws.at("src/routes.generated.ts"))]) {
|
|
52
|
+
const reason = reasonOf(decide(call));
|
|
53
|
+
assert.match(reason, /src\/routes\.generated\.ts is generated/);
|
|
54
|
+
assert.match(reason, /`pnpm codegen`/);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("a generated file at the repository root is denied too", (t) => {
|
|
59
|
+
const ws = workspace(t);
|
|
60
|
+
assert.match(reasonOf(decide(write(ws.at("routes.generated.ts")))), /routes\.generated\.ts is generated/);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test("an edit of the generated file's source passes", (t) => {
|
|
64
|
+
const ws = workspace(t);
|
|
65
|
+
assert.equal(decide(edit(ws.at("src/routes.ts"), "a")), null);
|
|
66
|
+
assert.equal(decide(write(ws.at("src/routes.ts"))), null);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("generated.globs and generated.command in qc.config.json replace the defaults", (t) => {
|
|
70
|
+
const ws = workspace(t, { generated: { globs: ["gen/**"], command: "npm run gen" } });
|
|
71
|
+
assert.match(reasonOf(decide(write(ws.at("gen/a.ts")))), /`npm run gen`/);
|
|
72
|
+
assert.equal(decide(write(ws.at("src/routes.generated.ts"))), null);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("an edit whose old_string lies in or across a generated region is denied", (t) => {
|
|
76
|
+
const ws = workspace(t);
|
|
77
|
+
const doc = ws.at("docs/enforcement.md");
|
|
78
|
+
assert.match(reasonOf(decide(edit(doc, "| A comment is one line | `qc/comment-style` |"))), /generated region of docs\/enforcement\.md/);
|
|
79
|
+
assert.ok(reasonOf(decide(edit(doc, "Hand-written intro.\n\n<!-- generated: rule-to-check."))));
|
|
80
|
+
assert.ok(reasonOf(decide(edit(ws.at("docs/crlf.md"), "| Rule | Check |\n| A comment"))));
|
|
81
|
+
const multi = {
|
|
82
|
+
tool_name: "MultiEdit",
|
|
83
|
+
tool_input: { file_path: doc, edits: [{ old_string: "Hand-written intro." }, { old_string: "| Rule | Check |" }] },
|
|
84
|
+
};
|
|
85
|
+
assert.ok(reasonOf(decide({ ...edit(doc, ""), ...multi })));
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("an edit outside the generated region passes", (t) => {
|
|
89
|
+
const ws = workspace(t);
|
|
90
|
+
assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written judgement calls.")), null);
|
|
91
|
+
assert.equal(decide(edit(ws.at("docs/enforcement.md"), "Hand-written intro.", { replace_all: true })), null);
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("a repository with no qc.config.json is never guarded", (t) => {
|
|
95
|
+
const ws = workspace(t, null);
|
|
96
|
+
assert.equal(decide(write(ws.at("src/routes.generated.ts"))), null);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test("the hook process prints the deny", (t) => {
|
|
100
|
+
const ws = workspace(t);
|
|
101
|
+
const result = spawnSync(process.execPath, [GUARD], { input: JSON.stringify(write(ws.at("src/a.generated.ts"))), encoding: "utf8" });
|
|
102
|
+
assert.equal(result.status, 0, result.stderr);
|
|
103
|
+
assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
|
|
104
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// A fragment that reads a PowerShell command the way shell-command.mjs reads a POSIX one, for the
|
|
2
|
+
// Bash edit guard. It shares that parser and its git vocabulary, and an unknown name counts as a write.
|
|
3
|
+
|
|
4
|
+
import { GIT_READS, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
|
|
5
|
+
|
|
6
|
+
const DIALECT = { escape: "`" };
|
|
7
|
+
const NULL_DEVICES = new Set(["$null", "/dev/null", "nul"]);
|
|
8
|
+
|
|
9
|
+
/** Approved verbs that only read, and the cmdlets and aliases that only read or print. */
|
|
10
|
+
const READ_VERBS = new Set([
|
|
11
|
+
"get", "test", "select", "measure", "format", "compare", "find", "resolve", "convertto",
|
|
12
|
+
"convertfrom", "sort", "group", "where", "join", "split",
|
|
13
|
+
]);
|
|
14
|
+
const READ_NAMES = new Set([
|
|
15
|
+
"write-output", "write-host", "out-null", "out-string", "out-host", "ls", "dir", "gci", "cat",
|
|
16
|
+
"gc", "type", "sls", "select", "where", "?", "sort", "measure", "pwd", "gl", "echo", "write",
|
|
17
|
+
"gi", "gp", "gcm", "gm", "ft", "fl", "popd", "pop-location",
|
|
18
|
+
]);
|
|
19
|
+
const LOCATION_NAMES = new Set(["cd", "chdir", "sl", "set-location", "pushd", "push-location"]);
|
|
20
|
+
const PATH_PARAMETERS = new Set(["-path", "-literalpath"]);
|
|
21
|
+
|
|
22
|
+
/** @returns the directory a location change moves to, or null when the segment is none. */
|
|
23
|
+
function locationTarget(segment) {
|
|
24
|
+
const [program, ...args] = commandWords(segment);
|
|
25
|
+
if (!LOCATION_NAMES.has(program?.toLowerCase())) return null;
|
|
26
|
+
for (let i = 0; i < args.length; i++) {
|
|
27
|
+
if (PATH_PARAMETERS.has(args[i].toLowerCase())) return args[i + 1] ?? "~";
|
|
28
|
+
if (!args[i].startsWith("-")) return args[i];
|
|
29
|
+
}
|
|
30
|
+
return "~";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function isReadOnly(segment) {
|
|
34
|
+
if (segment.redirects.some((file) => !NULL_DEVICES.has(file.toLowerCase()))) return false;
|
|
35
|
+
// A script block can hold any command, so a segment that carries one is judged a write.
|
|
36
|
+
if (segment.words.some((word) => word.includes("{"))) return false;
|
|
37
|
+
if (locationTarget(segment) !== null) return true;
|
|
38
|
+
const git = gitCall(segment);
|
|
39
|
+
if (git) return GIT_READS.has(git.sub);
|
|
40
|
+
const name = commandWords(segment)[0]?.toLowerCase() ?? "";
|
|
41
|
+
const [verb, noun] = name.split("-");
|
|
42
|
+
return READ_NAMES.has(name) || (noun !== undefined && READ_VERBS.has(verb));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** False only when every segment is known to read, so an unknown command counts as a write. */
|
|
46
|
+
export const mayWrite = (command) => !segmentsOf(command, DIALECT).every(isReadOnly);
|
|
47
|
+
|
|
48
|
+
/** Every directory the command names through a location change or `git -C`, in order, as written. */
|
|
49
|
+
export function checkoutDirs(command) {
|
|
50
|
+
const dirs = [];
|
|
51
|
+
for (const segment of segmentsOf(command, DIALECT)) {
|
|
52
|
+
const target = locationTarget(segment);
|
|
53
|
+
if (target !== null) dirs.push(target);
|
|
54
|
+
dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
|
|
55
|
+
}
|
|
56
|
+
return dirs;
|
|
57
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { checkoutDirs, mayWrite } from "./powershell-command.mjs";
|
|
4
|
+
|
|
5
|
+
test("a PowerShell command that only reads skips the check, in any letter case", () => {
|
|
6
|
+
for (const command of [
|
|
7
|
+
"Get-ChildItem -Recurse src",
|
|
8
|
+
"get-content a.txt | select-string foo",
|
|
9
|
+
"Test-Path C:\\repo\\a.txt",
|
|
10
|
+
"Get-Content a.txt | Measure-Object -Line",
|
|
11
|
+
"Get-Process | Format-Table Name",
|
|
12
|
+
"Write-Output done",
|
|
13
|
+
'git status; git diff --stat; git log --oneline -5',
|
|
14
|
+
"Get-Date > $null",
|
|
15
|
+
"Get-Item x 2>$null",
|
|
16
|
+
"Set-Location C:\\repo; Get-Location",
|
|
17
|
+
"ls; cat a.txt; pwd",
|
|
18
|
+
]) {
|
|
19
|
+
assert.equal(mayWrite(command), false, command);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("a PowerShell write, an unknown command and a script block are never skipped", () => {
|
|
24
|
+
for (const command of [
|
|
25
|
+
"Set-Content a.txt x",
|
|
26
|
+
"Add-Content a.txt x",
|
|
27
|
+
"Get-Content a.txt | Out-File b.txt",
|
|
28
|
+
"Get-Date > C:\\repo\\d.txt",
|
|
29
|
+
"Write-Output x >> log.txt",
|
|
30
|
+
"New-Item -ItemType File a.txt",
|
|
31
|
+
"Copy-Item a b",
|
|
32
|
+
"Move-Item a b",
|
|
33
|
+
"Remove-Item -Recurse -Force build",
|
|
34
|
+
"Rename-Item a b",
|
|
35
|
+
'git commit -m "x"',
|
|
36
|
+
"git checkout main -- src",
|
|
37
|
+
"node scripts/codemod.mjs",
|
|
38
|
+
"Get-ChildItem | Where-Object { Remove-Item $_ }",
|
|
39
|
+
"Get-ChildItem | ForEach-Object Name",
|
|
40
|
+
"& C:\\tools\\fix.ps1",
|
|
41
|
+
]) {
|
|
42
|
+
assert.equal(mayWrite(command), true, command);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("the checkout directories are each location change and each git -C directory, with backslashes kept", () => {
|
|
47
|
+
assert.deepEqual(
|
|
48
|
+
checkoutDirs('Set-Location C:\\repo\\a; git -C "C:\\b c" status; cd ..\\d; Push-Location -Path C:\\e; popd'),
|
|
49
|
+
["C:\\repo\\a", "C:\\b c", "..\\d", "C:\\e"],
|
|
50
|
+
);
|
|
51
|
+
assert.deepEqual(checkoutDirs("Get-ChildItem"), []);
|
|
52
|
+
});
|
package/src/cli/repo-files.mjs
CHANGED
|
@@ -5,17 +5,13 @@ import { execFile } from "node:child_process";
|
|
|
5
5
|
import { readdir, stat } from "node:fs/promises";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
|
-
import {
|
|
8
|
+
import { globMatcher } from "../glob.mjs";
|
|
9
9
|
|
|
10
10
|
const execFileAsync = promisify(execFile);
|
|
11
11
|
// The execFile default is 1 MB. A 30,000-file repository lists about 2 MB of paths.
|
|
12
12
|
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
function ignoredBy(globs) {
|
|
16
|
-
const patterns = globs.map(globToRegExp);
|
|
17
|
-
return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
|
|
18
|
-
}
|
|
14
|
+
const ignoredBy = globMatcher;
|
|
19
15
|
|
|
20
16
|
// `-t` tags each entry. `R` is a tracked file gone from the working tree and `S` is skip-worktree, so neither is on disk.
|
|
21
17
|
const NOT_ON_DISK = new Set(["R", "S"]);
|
|
@@ -25,8 +25,13 @@ function skipHeredocs(command, start, heredocs) {
|
|
|
25
25
|
return i;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
|
|
29
|
-
|
|
28
|
+
const POSIX_ESCAPE = "\\";
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* @param dialect `escape` is the escape character: a backslash for a POSIX shell, a backtick for PowerShell.
|
|
32
|
+
* @returns {Segment[]} the segments between unquoted `;`, `&`, `&&`, `|`, `||`, parentheses and newlines.
|
|
33
|
+
*/
|
|
34
|
+
export function segmentsOf(command, { escape = POSIX_ESCAPE } = {}) {
|
|
30
35
|
const segments = [];
|
|
31
36
|
let words = [];
|
|
32
37
|
let redirects = [];
|
|
@@ -61,7 +66,8 @@ export function segmentsOf(command) {
|
|
|
61
66
|
i++;
|
|
62
67
|
} else if (quote === '"') {
|
|
63
68
|
// Inside double quotes a backslash escapes only these, so a Windows path keeps its separators.
|
|
64
|
-
|
|
69
|
+
// A backtick escapes any character.
|
|
70
|
+
if (c === escape && next !== undefined && (escape !== POSIX_ESCAPE || '$`"\\\n'.includes(next))) {
|
|
65
71
|
word += next;
|
|
66
72
|
i += 2;
|
|
67
73
|
} else {
|
|
@@ -73,7 +79,7 @@ export function segmentsOf(command) {
|
|
|
73
79
|
quote = c;
|
|
74
80
|
inWord = true;
|
|
75
81
|
i++;
|
|
76
|
-
} else if (c ===
|
|
82
|
+
} else if (c === escape) {
|
|
77
83
|
if (next !== "\n") word += next ?? "";
|
|
78
84
|
inWord = next !== "\n" || inWord;
|
|
79
85
|
i += 2;
|
|
@@ -144,25 +150,29 @@ export function segmentsOf(command) {
|
|
|
144
150
|
const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
145
151
|
|
|
146
152
|
/** The words after any leading `NAME=value` assignments. */
|
|
147
|
-
const commandWords = (segment) => {
|
|
153
|
+
export const commandWords = (segment) => {
|
|
148
154
|
const start = segment.words.findIndex((word) => !ASSIGNMENT.test(word));
|
|
149
155
|
return start === -1 ? [] : segment.words.slice(start);
|
|
150
156
|
};
|
|
151
157
|
|
|
152
|
-
const isGit = (word) => /(^|[\\/])git(\.exe)
|
|
158
|
+
const isGit = (word) => /(^|[\\/])git(\.exe)?$/i.test(word ?? "");
|
|
153
159
|
|
|
154
|
-
/**
|
|
160
|
+
/**
|
|
161
|
+
* @returns the git subcommand, each `-C` directory, each `-c` setting and the words after the
|
|
162
|
+
* subcommand, or null when the segment is no git call.
|
|
163
|
+
*/
|
|
155
164
|
export function gitCall(segment) {
|
|
156
|
-
const [program, ...
|
|
165
|
+
const [program, ...words] = commandWords(segment);
|
|
157
166
|
if (!isGit(program)) return null;
|
|
158
167
|
const dirs = [];
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
else if (
|
|
168
|
+
const configs = [];
|
|
169
|
+
for (let i = 0; i < words.length; i++) {
|
|
170
|
+
const word = words[i];
|
|
171
|
+
if (word === "-C") dirs.push(words[++i]);
|
|
172
|
+
else if (word === "-c") configs.push(words[++i]);
|
|
173
|
+
else if (!word.startsWith("-")) return { sub: word, dirs, configs, args: words.slice(i + 1) };
|
|
164
174
|
}
|
|
165
|
-
return { sub: null, dirs };
|
|
175
|
+
return { sub: null, dirs, configs, args: [] };
|
|
166
176
|
}
|
|
167
177
|
|
|
168
178
|
/** @returns the directory a `cd` or `pushd` segment moves to, or null. */
|
|
@@ -176,7 +186,7 @@ const READ_PROGRAMS = new Set([
|
|
|
176
186
|
"cut", "tr", "jq", "which", "type", "stat", "file", "du", "df", "date", "basename",
|
|
177
187
|
"dirname", "realpath", "readlink", "diff", "cmp", "true", "false", "test", "[", "popd",
|
|
178
188
|
]);
|
|
179
|
-
const GIT_READS = new Set([
|
|
189
|
+
export const GIT_READS = new Set([
|
|
180
190
|
"status", "diff", "log", "show", "rev-parse", "ls-files", "grep", "blame", "branch", "remote",
|
|
181
191
|
"fetch", "describe", "shortlog", "config",
|
|
182
192
|
]);
|
|
@@ -34,7 +34,7 @@ test("a redirect target is recorded apart from the words, and a descriptor copy
|
|
|
34
34
|
|
|
35
35
|
test("a git call names its subcommand and every -C directory", () => {
|
|
36
36
|
const [segment] = segmentsOf(`GIT_PAGER=cat git -C "C:/a b" -c core.x=y --no-pager commit -m x`);
|
|
37
|
-
assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"] });
|
|
37
|
+
assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"], configs: ["core.x=y"], args: ["-m", "x"] });
|
|
38
38
|
assert.equal(gitCall(segmentsOf("gitk --all")[0]), null);
|
|
39
39
|
});
|
|
40
40
|
|
|
@@ -93,3 +93,26 @@ test("the checkout directories are every cd target and every git -C directory, i
|
|
|
93
93
|
]);
|
|
94
94
|
assert.deepEqual(checkoutDirs("ls"), []);
|
|
95
95
|
});
|
|
96
|
+
|
|
97
|
+
test("a git call carries each -c setting and the words after its subcommand", () => {
|
|
98
|
+
const [segment] = segmentsOf(`git -c core.hooksPath=/dev/null -C repo commit -m "a b" --no-verify`);
|
|
99
|
+
assert.deepEqual(gitCall(segment), {
|
|
100
|
+
sub: "commit",
|
|
101
|
+
dirs: ["repo"],
|
|
102
|
+
configs: ["core.hooksPath=/dev/null"],
|
|
103
|
+
args: ["-m", "a b", "--no-verify"],
|
|
104
|
+
});
|
|
105
|
+
assert.deepEqual(gitCall(segmentsOf("git --version")[0]), { sub: null, dirs: [], configs: [], args: [] });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("the PowerShell escape keeps a backslash literal and escapes with a backtick", () => {
|
|
109
|
+
const powershell = { escape: "`" };
|
|
110
|
+
assert.deepEqual(
|
|
111
|
+
segmentsOf('Set-Content C:\\a\\b.txt "x`"y" ; Get-Item `$HOME', powershell).map((segment) => segment.words),
|
|
112
|
+
[
|
|
113
|
+
["Set-Content", "C:\\a\\b.txt", 'x"y'],
|
|
114
|
+
["Get-Item", "$HOME"],
|
|
115
|
+
],
|
|
116
|
+
);
|
|
117
|
+
assert.deepEqual(segmentsOf("Get-Date > C:\\out\\d.txt", powershell)[0].redirects, ["C:\\out\\d.txt"]);
|
|
118
|
+
});
|
package/src/config.mjs
CHANGED
|
@@ -210,6 +210,9 @@ export const defaults = {
|
|
|
210
210
|
toolCallBudget: 100,
|
|
211
211
|
},
|
|
212
212
|
|
|
213
|
+
// Files a generator writes. The generated-file hook refuses a hand edit of one and names `command`.
|
|
214
|
+
generated: { globs: ["**/*.generated.*"], command: "pnpm codegen" },
|
|
215
|
+
|
|
213
216
|
// `qc worktree`. `install` runs in each new worktree. `base` is the default `--from`: the ref a
|
|
214
217
|
// branch starts at, and the ref `remove` checks a merge against.
|
|
215
218
|
worktree: { install: "pnpm install --frozen-lockfile", base: "origin/main" },
|
|
@@ -238,6 +241,13 @@ export const defaults = {
|
|
|
238
241
|
// racing against a cancellation, and observing a rejection nobody is waiting for any more.
|
|
239
242
|
promise: { allow: [] },
|
|
240
243
|
|
|
244
|
+
// Enter and Escape in text entry wait for the IME. `components` are a repository's own text
|
|
245
|
+
// inputs. `guards` name the one guard function; empty accepts an inline isComposing or keyCode check.
|
|
246
|
+
ime: { components: [], guards: [] },
|
|
247
|
+
|
|
248
|
+
// Files a person reviewed that may call sql.raw. Each one is a decision, so the list stays short.
|
|
249
|
+
sqlRaw: { allow: [] },
|
|
250
|
+
|
|
241
251
|
anatomy: {
|
|
242
252
|
// Bounded vertical slices.
|
|
243
253
|
slice: {
|
|
@@ -261,6 +271,7 @@ export const defaults = {
|
|
|
261
271
|
"eight-blocks": true,
|
|
262
272
|
citations: true,
|
|
263
273
|
"registry-agreement": true,
|
|
274
|
+
"registry-readers": true,
|
|
264
275
|
"sql-identifiers": true,
|
|
265
276
|
"tenant-predicate": true,
|
|
266
277
|
"claimed-requirements": true,
|
|
@@ -303,6 +314,9 @@ export const defaults = {
|
|
|
303
314
|
"tenant-scoped-table": true,
|
|
304
315
|
"signal-last-param": true,
|
|
305
316
|
"no-raw-fetch": true,
|
|
317
|
+
"no-sql-raw": true,
|
|
318
|
+
"ime-safe-key": true,
|
|
319
|
+
"registry-literal": true,
|
|
306
320
|
"durable-idempotency-key": true,
|
|
307
321
|
"no-supersession-trail": true,
|
|
308
322
|
},
|
|
@@ -373,6 +387,16 @@ export function thresholds(config) {
|
|
|
373
387
|
return createRequire(import.meta.url)(file).gates ?? {};
|
|
374
388
|
}
|
|
375
389
|
|
|
390
|
+
/**
|
|
391
|
+
* Registry entries that say who may hold their number. `names` are identifier patterns, each a
|
|
392
|
+
* regular expression matched against the whole identifier, case-insensitive. `readers` are paths.
|
|
393
|
+
*/
|
|
394
|
+
export function readerEntries(registry) {
|
|
395
|
+
return Object.entries(registry)
|
|
396
|
+
.filter(([, entry]) => entry.names?.length > 0 || entry.readers?.length > 0)
|
|
397
|
+
.map(([key, entry]) => ({ key, names: entry.names ?? [], readers: entry.readers ?? [] }));
|
|
398
|
+
}
|
|
399
|
+
|
|
376
400
|
export function enabled(map, id) {
|
|
377
401
|
return map[id] !== false;
|
|
378
402
|
}
|
package/src/descriptions.mjs
CHANGED
|
@@ -4,6 +4,7 @@ export const gateDescriptions = Object.freeze({
|
|
|
4
4
|
"eight-blocks": "A feature keeps the anatomy it declares, and no block or slice is empty",
|
|
5
5
|
citations: "Every cited id and doc path resolves, and nothing references another repository",
|
|
6
6
|
"registry-agreement": "A value written twice agrees with the registry that owns it",
|
|
7
|
+
"registry-readers": "Every reader a registry entry names exists and names the entry",
|
|
7
8
|
"sql-identifiers": "A query names a column a migration declares, and only its own feature's tables",
|
|
8
9
|
"tenant-predicate": "Every statement on a business table filters on the tenant",
|
|
9
10
|
"claimed-requirements": "A requirement a route claims names the test that proves it",
|
package/src/enforcement-map.mjs
CHANGED
|
@@ -3,9 +3,10 @@
|
|
|
3
3
|
import { enabled } from "./config.mjs";
|
|
4
4
|
import { gateDescriptions } from "./descriptions.mjs";
|
|
5
5
|
import { rules } from "./eslint/index.mjs";
|
|
6
|
+
import { GENERATED_CLOSE } from "./generated-markers.mjs";
|
|
6
7
|
|
|
7
8
|
export const OPEN = "<!-- generated: rule-to-check. -->";
|
|
8
|
-
export const CLOSE =
|
|
9
|
+
export const CLOSE = GENERATED_CLOSE;
|
|
9
10
|
// A repository may annotate the open marker with its own reminder (e.g. "pnpm codegen.") —
|
|
10
11
|
// matched by prefix, not by exact string, so that annotation does not break detection.
|
|
11
12
|
const OPEN_PATTERN = /<!--\s*generated:\s*rule-to-check\.[^>]*-->/;
|
package/src/eslint/index.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import durableIdempotencyKey from "./rules/durable-idempotency-key.mjs";
|
|
2
2
|
import externalServiceOnlyInAdapter from "./rules/external-service-only-in-adapter.mjs";
|
|
3
|
+
import imeSafeKey from "./rules/ime-safe-key.mjs";
|
|
3
4
|
import noCrossFeatureInternals from "./rules/no-cross-feature-internals.mjs";
|
|
5
|
+
import registryLiteral from "./rules/registry-literal.mjs";
|
|
4
6
|
import noCommentParagraph from "./rules/no-comment-paragraph.mjs";
|
|
5
7
|
import nameThePattern from "./rules/name-the-pattern.mjs";
|
|
6
8
|
import noPromiseThen from "./rules/no-promise-then.mjs";
|
|
@@ -8,6 +10,7 @@ import noNumberInComment from "./rules/no-number-in-comment.mjs";
|
|
|
8
10
|
import noOffsetPagination from "./rules/no-offset-pagination.mjs";
|
|
9
11
|
import noOrchestrationInTrigger from "./rules/no-orchestration-in-trigger.mjs";
|
|
10
12
|
import noRawFetch from "./rules/no-raw-fetch.mjs";
|
|
13
|
+
import noSqlRaw from "./rules/no-sql-raw.mjs";
|
|
11
14
|
import noStatusLiteral from "./rules/no-status-literal.mjs";
|
|
12
15
|
import noSupersessionTrail from "./rules/no-supersession-trail.mjs";
|
|
13
16
|
import scopedRepository from "./rules/scoped-repository.mjs";
|
|
@@ -18,7 +21,9 @@ import tenantScopedTable from "./rules/tenant-scoped-table.mjs";
|
|
|
18
21
|
export const rules = {
|
|
19
22
|
"durable-idempotency-key": durableIdempotencyKey,
|
|
20
23
|
"external-service-only-in-adapter": externalServiceOnlyInAdapter,
|
|
24
|
+
"ime-safe-key": imeSafeKey,
|
|
21
25
|
"no-cross-feature-internals": noCrossFeatureInternals,
|
|
26
|
+
"registry-literal": registryLiteral,
|
|
22
27
|
"no-comment-paragraph": noCommentParagraph,
|
|
23
28
|
"name-the-pattern": nameThePattern,
|
|
24
29
|
"no-promise-then": noPromiseThen,
|
|
@@ -26,6 +31,7 @@ export const rules = {
|
|
|
26
31
|
"no-offset-pagination": noOffsetPagination,
|
|
27
32
|
"no-orchestration-in-trigger": noOrchestrationInTrigger,
|
|
28
33
|
"no-raw-fetch": noRawFetch,
|
|
34
|
+
"no-sql-raw": noSqlRaw,
|
|
29
35
|
"no-status-literal": noStatusLiteral,
|
|
30
36
|
"no-supersession-trail": noSupersessionTrail,
|
|
31
37
|
"scoped-repository": scopedRepository,
|
package/src/eslint/preset.mjs
CHANGED
|
@@ -2,11 +2,14 @@
|
|
|
2
2
|
// Thresholds are imported, never restated — quality-thresholds.json is their one home.
|
|
3
3
|
|
|
4
4
|
import qc from "./index.mjs";
|
|
5
|
-
import { enabled, load, thresholds } from "../config.mjs";
|
|
5
|
+
import { enabled, load, readerEntries, thresholds } from "../config.mjs";
|
|
6
6
|
|
|
7
7
|
/** Options each rule needs, derived from one config so a name is written once. */
|
|
8
|
-
function ruleOptions(config) {
|
|
8
|
+
function ruleOptions(config, registry) {
|
|
9
9
|
return {
|
|
10
|
+
"no-sql-raw": { allow: config.sqlRaw.allow },
|
|
11
|
+
"ime-safe-key": { components: config.ime.components, guards: config.ime.guards },
|
|
12
|
+
"registry-literal": { entries: readerEntries(registry).filter((entry) => entry.names.length > 0) },
|
|
10
13
|
"no-comment-paragraph": {
|
|
11
14
|
doc: config.enforcement ?? "docs/enforcement.md",
|
|
12
15
|
decisions: config.docs.decisions,
|
|
@@ -48,8 +51,8 @@ function ruleOptions(config) {
|
|
|
48
51
|
};
|
|
49
52
|
}
|
|
50
53
|
|
|
51
|
-
function entries(config, names) {
|
|
52
|
-
const options = ruleOptions(config);
|
|
54
|
+
function entries(config, names, registry = {}) {
|
|
55
|
+
const options = ruleOptions(config, registry);
|
|
53
56
|
const out = {};
|
|
54
57
|
for (const name of names) {
|
|
55
58
|
if (!enabled(config.rules, name)) continue;
|
|
@@ -75,13 +78,16 @@ const UNIVERSAL = [
|
|
|
75
78
|
// Not a layered-architecture concern like the SERVER rules below — a worker or a
|
|
76
79
|
// composition root outside backend/src needs this exactly as much as backend/src does.
|
|
77
80
|
"external-service-only-in-adapter",
|
|
81
|
+
// A worker or a script builds a query and holds a number as much as a feature does.
|
|
82
|
+
"no-sql-raw",
|
|
83
|
+
"registry-literal",
|
|
78
84
|
];
|
|
79
85
|
|
|
80
86
|
/** Rules that only make sense where the server's storage and ports live. */
|
|
81
87
|
const SERVER = ["storage-only-in-resource", "tenant-scoped-table", "signal-last-param"];
|
|
82
88
|
|
|
83
89
|
/** Rules that only make sense in the browser. */
|
|
84
|
-
const CLIENT = ["no-raw-fetch", "storage-only-in-resource"];
|
|
90
|
+
const CLIENT = ["no-raw-fetch", "storage-only-in-resource", "ime-safe-key"];
|
|
85
91
|
|
|
86
92
|
/**
|
|
87
93
|
* The architecture as a flat config. Spread it, then append your own blocks.
|
|
@@ -96,13 +102,22 @@ export function preset(options = {}) {
|
|
|
96
102
|
const max = (id) => gates[id]?.value;
|
|
97
103
|
const { tseslint, boundaries, sonarjs } = options.plugins ?? {};
|
|
98
104
|
|
|
99
|
-
|
|
105
|
+
// No file carries its own exemption: a rule is switched off in config, where a reviewer sees it.
|
|
106
|
+
const blocks = [{ ignores: config.ignores }, { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: "error" } }];
|
|
100
107
|
|
|
101
108
|
const base = {
|
|
102
109
|
files: ["**/*.{ts,tsx,mjs}"],
|
|
103
110
|
plugins: { qc, ...(tseslint ? { "@typescript-eslint": tseslint } : {}), ...(sonarjs ? { sonarjs } : {}) },
|
|
104
111
|
rules: {
|
|
105
|
-
...(tseslint
|
|
112
|
+
...(tseslint
|
|
113
|
+
? {
|
|
114
|
+
"@typescript-eslint/no-explicit-any": "error",
|
|
115
|
+
"@typescript-eslint/ban-ts-comment": [
|
|
116
|
+
"error",
|
|
117
|
+
{ "ts-ignore": true, "ts-nocheck": true, "ts-check": false, "ts-expect-error": "allow-with-description" },
|
|
118
|
+
],
|
|
119
|
+
}
|
|
120
|
+
: {}),
|
|
106
121
|
...(sonarjs
|
|
107
122
|
? {
|
|
108
123
|
"sonarjs/no-identical-functions": "error",
|
|
@@ -116,7 +131,7 @@ export function preset(options = {}) {
|
|
|
116
131
|
? { "max-lines-per-function": ["error", { max: max("funclength"), skipBlankLines: true, skipComments: true }] }
|
|
117
132
|
: {}),
|
|
118
133
|
...(max("nesting") ? { "max-depth": ["error", max("nesting")] } : {}),
|
|
119
|
-
...entries(config, UNIVERSAL),
|
|
134
|
+
...entries(config, UNIVERSAL, gates),
|
|
120
135
|
},
|
|
121
136
|
};
|
|
122
137
|
if (options.languageOptions) base.languageOptions = options.languageOptions;
|