architecture-harness 0.23.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/package.json +20 -5
- package/src/cli/bash-command-guard.mjs +44 -5
- package/src/cli/bash-command-guard.test.mjs +35 -1
- package/src/cli/budget-guard.mjs +1 -0
- package/src/cli/budget-guard.test.mjs +7 -1
- package/src/cli/budget.mjs +3 -4
- package/src/cli/budget.test.mjs +5 -5
- package/src/cli/check-commands.mjs +82 -0
- package/src/cli/check-commands.test.mjs +190 -0
- package/src/cli/check.mjs +34 -13
- package/src/cli/ci-template.test.mjs +17 -15
- package/src/cli/cli.test.mjs +33 -2
- package/src/cli/commit-msg.mjs +12 -12
- package/src/cli/commit-msg.test.mjs +22 -7
- package/src/cli/generated-file-guard.mjs +11 -2
- package/src/cli/generated-file-guard.test.mjs +14 -2
- package/src/cli/init.mjs +70 -25
- package/src/cli/lint-changed.mjs +157 -0
- package/src/cli/lint-changed.test.mjs +102 -0
- package/src/cli/plugin-agents.test.mjs +1 -1
- package/src/cli/post-edit-gate.test.mjs +12 -3
- package/src/cli/pr-check.mjs +15 -2
- package/src/cli/pr-check.test.mjs +19 -9
- package/src/cli/qc.mjs +38 -7
- package/src/cli/scaffold.mjs +23 -2
- package/src/cli/scaffold.test.mjs +51 -0
- package/src/cli/shell-command.mjs +3 -1
- package/src/cli/stop-gate.test.mjs +49 -128
- package/src/cli/typecheck.mjs +46 -0
- package/src/cli/typecheck.test.mjs +43 -0
- package/src/cli/user-config-package.mjs +16 -0
- package/src/cli/user-config-toml.mjs +144 -0
- package/src/cli/user-config.mjs +155 -0
- package/src/cli/user-config.test.mjs +274 -0
- package/src/cli/work-order-guard.mjs +2 -2
- package/src/cli/worktree-gate.mjs +11 -12
- package/src/cli/worktree-gate.test.mjs +28 -29
- package/src/cli/worktree-isolation.mjs +3 -3
- package/src/cli/worktree-isolation.test.mjs +1 -1
- package/src/cli/worktree.mjs +9 -1
- package/src/cli/worktree.test.mjs +16 -1
- package/src/config.mjs +28 -11
- package/src/config.test.mjs +33 -1
- package/src/eslint/preset.mjs +8 -3
- package/src/eslint/preset.test.mjs +15 -8
- package/src/eslint/rules/no-raw-fetch.mjs +42 -2
- package/src/eslint/rules.test.mjs +15 -0
- package/src/gates/audit-append-only.mjs +18 -4
- package/src/gates/audit-append-only.test.mjs +19 -0
- package/src/gates/tenant-predicate.mjs +147 -7
- package/src/gates/tenant-predicate.test.mjs +55 -0
- package/src/gates/tenant-tables.mjs +5 -2
- package/src/gates/tenant-tables.test.mjs +8 -0
- package/src/gates/threshold-ratchet.mjs +12 -9
- package/src/gates/threshold-ratchet.test.mjs +16 -0
- package/src/plugin.test.mjs +28 -0
- package/src/screens/auth-run.test.mjs +20 -17
- package/src/screens/capture-idle.test.mjs +2 -1
- package/src/screens/catalog.test.mjs +3 -3
- package/src/screens/chrome.mjs +21 -0
- package/src/vale-style.test.mjs +5 -5
- package/templates/CLAUDE.md +2 -2
- package/templates/githooks/pre-commit +7 -10
- package/templates/github/workflows/ci.yml +25 -84
- package/templates/github/workflows/pr-policy.yml +36 -0
- package/user-config/claude/settings.shared.json +74 -0
- package/user-config/claude/statusline.js +323 -0
- package/user-config/codex/config.shared.toml +19 -0
- package/src/cli/edit-batch-guard.mjs +0 -77
- package/src/cli/edit-batch-guard.test.mjs +0 -131
package/src/config.test.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import { readdirSync } from "node:fs";
|
|
3
|
+
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
5
6
|
import path from "node:path";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
7
8
|
import { defaults, load, merge, requiredHooks } from "./config.mjs";
|
|
@@ -9,6 +10,37 @@ import { rules } from "./eslint/index.mjs";
|
|
|
9
10
|
|
|
10
11
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
11
12
|
|
|
13
|
+
test("check defaults leave repository commands off", () => {
|
|
14
|
+
assert.deepEqual(load(here).check, { related: null, commands: [], base: "origin/main" });
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("check configuration accepts commands and preserves omitted defaults", (t) => {
|
|
18
|
+
const root = mkdtempSync(path.join(tmpdir(), "qc-check-config-"));
|
|
19
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
20
|
+
const check = { related: "pnpm exec vitest related --run", commands: ["node script/check-comments.mjs --base origin/dev"] };
|
|
21
|
+
writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check }));
|
|
22
|
+
assert.deepEqual(load(root).check, { ...check, base: "origin/main" });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("check configuration rejects invalid types and empty commands or refs", (t) => {
|
|
26
|
+
const root = mkdtempSync(path.join(tmpdir(), "qc-check-config-"));
|
|
27
|
+
t.after(() => rmSync(root, { recursive: true, force: true }));
|
|
28
|
+
for (const check of [null, [], false, "command"]) {
|
|
29
|
+
writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check }));
|
|
30
|
+
assert.throws(() => load(root), /check must be an object/);
|
|
31
|
+
}
|
|
32
|
+
for (const [key, values] of Object.entries({
|
|
33
|
+
related: [false, 1, [], {}, "", " "],
|
|
34
|
+
commands: [null, false, "node", [1], [null], [""], [" "]],
|
|
35
|
+
base: [null, false, 1, [], "", " "],
|
|
36
|
+
})) {
|
|
37
|
+
for (const value of values) {
|
|
38
|
+
writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ check: { [key]: value } }));
|
|
39
|
+
assert.throws(() => load(root), new RegExp(`check\\.${key}`));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
|
|
12
44
|
// A switch naming a rule that no longer exists silently stops switching anything.
|
|
13
45
|
// This is the test that catches the next rename, not the last one.
|
|
14
46
|
test("every lint rule has a switch, and every switch names a rule", () => {
|
package/src/eslint/preset.mjs
CHANGED
|
@@ -77,13 +77,17 @@ function ruleOptions(config) {
|
|
|
77
77
|
};
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
// Rules on the style of a comment: a finding is advice, so it prints and never fails a change.
|
|
81
|
+
const ADVICE = new Set(["no-comment-paragraph", "no-number-in-comment", "no-supersession-trail"]);
|
|
82
|
+
|
|
80
83
|
function entries(config, names) {
|
|
81
84
|
const options = ruleOptions(config);
|
|
82
85
|
const out = {};
|
|
83
86
|
for (const name of names) {
|
|
84
87
|
if (!enabled(config.rules, name)) continue;
|
|
85
88
|
const given = options[name];
|
|
86
|
-
|
|
89
|
+
const level = ADVICE.has(name) ? "warn" : "error";
|
|
90
|
+
out[`qc/${name}`] = given && Object.keys(given).length > 0 ? [level, given] : level;
|
|
87
91
|
}
|
|
88
92
|
return out;
|
|
89
93
|
}
|
|
@@ -128,8 +132,9 @@ export function preset(options = {}) {
|
|
|
128
132
|
const max = (id) => gates[id]?.value;
|
|
129
133
|
const { tseslint, boundaries, sonarjs } = options.plugins ?? {};
|
|
130
134
|
|
|
131
|
-
//
|
|
132
|
-
|
|
135
|
+
// A disable comment is allowed, and one that disables nothing is an error. `qc lint` judges only the
|
|
136
|
+
// changed lines, so a new disable comment is part of the change a reviewer reads.
|
|
137
|
+
const blocks = [{ ignores: ignoresOf(config) }, { linterOptions: { reportUnusedDisableDirectives: "error" } }];
|
|
133
138
|
|
|
134
139
|
const base = {
|
|
135
140
|
files: ["**/*.{ts,tsx,mjs}"],
|
|
@@ -153,7 +153,7 @@ test("a session lifetime in code fails outside its reader, through the whole pre
|
|
|
153
153
|
});
|
|
154
154
|
|
|
155
155
|
test("the ime config reaches qc/ime-safe-key", () => {
|
|
156
|
-
const setting = emitted(preset({ config: config({ ime: { guards: ["isImeComposing"] } }) })).get("qc/ime-safe-key");
|
|
156
|
+
const setting = emitted(preset({ config: config({ ime: { guards: ["isImeComposing"] }, rules: { "ime-safe-key": true } }) })).get("qc/ime-safe-key");
|
|
157
157
|
assert.deepEqual(setting[1], { components: [], guards: ["isImeComposing"] });
|
|
158
158
|
});
|
|
159
159
|
|
|
@@ -175,18 +175,25 @@ test("the mutationControl config reaches qc/mutation-control-pending", () => {
|
|
|
175
175
|
assert.deepEqual(setting[1], { button: "Action", prop: "busy", handlers: ["onClick", "onSelect", "onConfirm"] });
|
|
176
176
|
});
|
|
177
177
|
|
|
178
|
-
test("the preset
|
|
178
|
+
test("the preset reports an unused disable comment in every file", () => {
|
|
179
179
|
const block = preset({ config: config() }).find((b) => b.linterOptions);
|
|
180
180
|
assert.ok(block, "no linterOptions block emitted");
|
|
181
181
|
assert.equal(block.files, undefined, "linterOptions must reach every file");
|
|
182
|
-
assert.deepEqual(block.linterOptions, {
|
|
182
|
+
assert.deepEqual(block.linterOptions, { reportUnusedDisableDirectives: "error" });
|
|
183
183
|
});
|
|
184
184
|
|
|
185
|
-
test("
|
|
186
|
-
const
|
|
187
|
-
assert.equal(byRule(
|
|
188
|
-
const
|
|
189
|
-
assert.ok(
|
|
185
|
+
test("a disable comment silences its rule, and one that silences nothing is an error", () => {
|
|
186
|
+
const used = lint("// eslint-disable-next-line qc/no-sql-raw\nawait db.execute(sql.raw(text));\n", RESOURCE);
|
|
187
|
+
assert.equal(byRule(used, "qc/no-sql-raw").length, 0);
|
|
188
|
+
const unused = lint("// eslint-disable-next-line qc/no-sql-raw\nconst a = 1;\n", RESOURCE);
|
|
189
|
+
assert.ok(unused.some((m) => m.ruleId === null && m.severity === 2 && /Unused eslint-disable/.test(m.message)), JSON.stringify(unused));
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
test("a comment-style rule warns, and a rule of the reference stack is off until a repository turns it on", () => {
|
|
193
|
+
const rules = emitted(preset({ config: config() }));
|
|
194
|
+
for (const name of ["no-comment-paragraph", "no-number-in-comment", "no-supersession-trail"]) assert.equal([rules.get(`qc/${name}`)].flat()[0], "warn", name);
|
|
195
|
+
for (const name of ["no-offset-pagination", "no-status-literal", "no-promise-then", "signal-last-param", "ime-safe-key"]) assert.equal(rules.get(`qc/${name}`), undefined, name);
|
|
196
|
+
assert.equal([emitted(preset({ config: config({ rules: { "no-offset-pagination": true } }) })).get("qc/no-offset-pagination")].flat()[0], "error");
|
|
190
197
|
});
|
|
191
198
|
|
|
192
199
|
test("sql.raw fails, and sqlRaw.allow lets one reviewed file through", () => {
|
|
@@ -3,6 +3,27 @@
|
|
|
3
3
|
import { filenameOf, optionsOf, pathSuffix, schemaOf } from "../options.mjs";
|
|
4
4
|
|
|
5
5
|
const DEFAULT_CLIENT = "platform/api-client.ts";
|
|
6
|
+
// The names of the global object, so `window.fetch` and `globalThis["fetch"]` are the same fetch.
|
|
7
|
+
const GLOBAL_OBJECTS = new Set(["window", "globalThis", "self", "global"]);
|
|
8
|
+
|
|
9
|
+
/** The property a member or a destructured key names, when the code spells it literally. */
|
|
10
|
+
function keyName(node, computed) {
|
|
11
|
+
if (!computed && node.type === "Identifier") return node.name;
|
|
12
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
13
|
+
if (node.type === "TemplateLiteral" && node.expressions.length === 0) return node.quasis[0].value.cooked;
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** True when the name resolves to no declaration in the code: an undeclared global, or one the config declares. */
|
|
18
|
+
function isGlobalName(sourceCode, identifier) {
|
|
19
|
+
for (let scope = sourceCode.getScope(identifier); scope; scope = scope.upper) {
|
|
20
|
+
const variable = scope.set.get(identifier.name);
|
|
21
|
+
if (variable) return variable.defs.length === 0;
|
|
22
|
+
}
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const isGlobalObject = (sourceCode, node) => node?.type === "Identifier" && GLOBAL_OBJECTS.has(node.name) && isGlobalName(sourceCode, node);
|
|
6
27
|
|
|
7
28
|
export default {
|
|
8
29
|
meta: {
|
|
@@ -16,8 +37,27 @@ export default {
|
|
|
16
37
|
if (pathSuffix(client).test(filenameOf(context))) return {};
|
|
17
38
|
const report = (node) => context.report({ node, messageId: "raw", data: { client } });
|
|
18
39
|
return {
|
|
19
|
-
|
|
20
|
-
|
|
40
|
+
// Every use of the global fetch, not only a call: `const f = fetch` hands the same function on.
|
|
41
|
+
// A local binding named fetch is not the global, and a `typeof fetch` type reads no value.
|
|
42
|
+
// A global the config declares, as browser globals declare fetch, holds its references itself
|
|
43
|
+
// and leaves `through`, so both lists are read.
|
|
44
|
+
"Program:exit"() {
|
|
45
|
+
const { globalScope } = context.sourceCode.scopeManager;
|
|
46
|
+
const declared = globalScope.set.get("fetch");
|
|
47
|
+
const references = [...globalScope.through, ...(declared?.defs.length === 0 ? declared.references : [])];
|
|
48
|
+
for (const { identifier } of references) {
|
|
49
|
+
if (identifier.name !== "fetch" || identifier.parent?.type === "TSTypeQuery") continue;
|
|
50
|
+
report(identifier);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
MemberExpression(node) {
|
|
54
|
+
if (isGlobalObject(context.sourceCode, node.object) && keyName(node.property, node.computed) === "fetch") report(node);
|
|
55
|
+
},
|
|
56
|
+
VariableDeclarator(node) {
|
|
57
|
+
if (node.id.type !== "ObjectPattern" || !isGlobalObject(context.sourceCode, node.init)) return;
|
|
58
|
+
for (const property of node.id.properties) {
|
|
59
|
+
if (property.type === "Property" && keyName(property.key, property.computed) === "fetch") report(property);
|
|
60
|
+
}
|
|
21
61
|
},
|
|
22
62
|
NewExpression(node) {
|
|
23
63
|
if (node.callee.type === "Identifier" && node.callee.name === "URL") report(node);
|
|
@@ -103,10 +103,25 @@ tester.run("no-raw-fetch", rules["no-raw-fetch"], {
|
|
|
103
103
|
valid: [
|
|
104
104
|
{ code: "await fetch(url);", filename: "/a/platform/api-client.ts" },
|
|
105
105
|
{ code: "await client.get(path);", filename: "/a/features/pins/index.ts" },
|
|
106
|
+
{ code: "function load(fetch) { return fetch(url); }", filename: "/a/features/pins/index.ts" },
|
|
107
|
+
{ code: "await client.fetch(url);", filename: "/a/features/pins/index.ts" },
|
|
108
|
+
{ code: "const options = { fetch: true };", filename: "/a/features/pins/index.ts" },
|
|
109
|
+
{ code: "const self = { fetch() {} }; self.fetch();", filename: "/a/features/pins/index.ts" },
|
|
110
|
+
{ code: "function load(window) { return window.fetch(url); }", filename: "/a/features/pins/index.ts" },
|
|
106
111
|
],
|
|
107
112
|
invalid: [
|
|
108
113
|
{ code: "await fetch(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
114
|
+
{
|
|
115
|
+
code: "await fetch(url); await window.fetch(url);",
|
|
116
|
+
filename: "/a/features/pins/index.ts",
|
|
117
|
+
languageOptions: { globals: { fetch: "readonly", window: "readonly" } },
|
|
118
|
+
errors: [{ messageId: "raw" }, { messageId: "raw" }],
|
|
119
|
+
},
|
|
109
120
|
{ code: "new URL(path);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
121
|
+
{ code: "await window.fetch(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
122
|
+
{ code: "await globalThis['fetch'](url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
123
|
+
{ code: "const f = fetch; f(url);", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
124
|
+
{ code: "const { fetch: f } = globalThis;", filename: "/a/features/pins/index.ts", errors: [{ messageId: "raw" }] },
|
|
110
125
|
],
|
|
111
126
|
});
|
|
112
127
|
|
|
@@ -14,18 +14,32 @@ const DEFAULT_TABLE = "audit_log";
|
|
|
14
14
|
*/
|
|
15
15
|
export function checkAuditAppendOnly(resources, options = {}) {
|
|
16
16
|
const table = options.table ?? DEFAULT_TABLE;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
17
|
+
// The table as SQL can name it: quoted or not, under a schema or not, after `only` or not.
|
|
18
|
+
const name = table.split(".").map((part) => `"?${escape(part)}"?`).join("\\s*\\.\\s*");
|
|
19
|
+
const ref = `(?:only\\s+)?(?:(?:"[^"]+"|\\w+)\\s*\\.\\s*)?${name}(?![\\w$"])`;
|
|
20
|
+
// The table in a mutating position. An insert naming it is the whole point, but an upsert rewrites a row.
|
|
21
|
+
const mutation = new RegExp(
|
|
22
|
+
[
|
|
23
|
+
`update\\s+${ref}`,
|
|
24
|
+
`delete\\s+from\\s+${ref}`,
|
|
25
|
+
`truncate\\s+(?:table\\s+)?(?:only\\s+)?(?:[\\w."]+\\s*,\\s*)*${ref}`,
|
|
26
|
+
`merge\\s+into\\s+${ref}`,
|
|
27
|
+
`insert\\s+into\\s+${ref}[^;]*?\\bon\\s+conflict\\b[^;]*?\\bdo\\s+update\\b`,
|
|
28
|
+
]
|
|
29
|
+
.map((form) => `\\b${form}`)
|
|
30
|
+
.join("|"),
|
|
31
|
+
"i",
|
|
32
|
+
);
|
|
20
33
|
const problems = [];
|
|
21
34
|
for (const { path, statements } of resources) {
|
|
22
35
|
for (const { sql } of statements) {
|
|
23
36
|
const found = mutation.exec(sql);
|
|
24
37
|
if (found !== null) {
|
|
38
|
+
const quoted = found[0].replace(/\s+/g, " ").trim();
|
|
25
39
|
problems.push({
|
|
26
40
|
path,
|
|
27
41
|
rule: "audit-mutated",
|
|
28
|
-
detail: `'${
|
|
42
|
+
detail: `'${quoted.length > 60 ? `${quoted.slice(0, 57)}...` : quoted}' — ${table} is append-only, so no repository may hold an update or delete path for it`,
|
|
29
43
|
});
|
|
30
44
|
}
|
|
31
45
|
}
|
|
@@ -28,6 +28,25 @@ test("a truncate fails", () => {
|
|
|
28
28
|
|
|
29
29
|
test("another table of a similar name is not the audit log", () => {
|
|
30
30
|
assert.deepEqual(checkAuditAppendOnly(resource("delete from audit_log_archive where id = $1")), []);
|
|
31
|
+
assert.deepEqual(checkAuditAppendOnly(resource('update "audit_logs" set actor = $1')), []);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("a quoted, schema-qualified or only name, a list truncate, a merge and an upsert fail", () => {
|
|
35
|
+
for (const sql of [
|
|
36
|
+
"update public.audit_log set actor = $1",
|
|
37
|
+
'delete from "audit_log" where id = $1',
|
|
38
|
+
'update "public"."audit_log" set actor = $1',
|
|
39
|
+
"update only audit_log set actor = $1",
|
|
40
|
+
"truncate sessions, audit_log",
|
|
41
|
+
"merge into audit_log using x on true when matched then update set actor = x.actor",
|
|
42
|
+
"insert into audit_log (id, actor) values ($1, $2) on conflict (id) do update set actor = excluded.actor",
|
|
43
|
+
]) {
|
|
44
|
+
assert.equal(checkAuditAppendOnly(resource(sql)).length, 1, sql);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
test("an insert that does nothing on conflict changes no row, and passes", () => {
|
|
49
|
+
assert.deepEqual(checkAuditAppendOnly(resource("insert into audit_log (id) values ($1) on conflict (id) do nothing")), []);
|
|
31
50
|
});
|
|
32
51
|
|
|
33
52
|
test("the table name comes from options", () => {
|
|
@@ -14,10 +14,147 @@ import { scrub } from "./scrub.mjs";
|
|
|
14
14
|
const DEFAULT_TENANT_COLUMN = "tenant_id";
|
|
15
15
|
const DEFAULT_TENANT_IDENTIFIER = "tenantId";
|
|
16
16
|
|
|
17
|
-
// Naming the column is not scoping by it: a select list
|
|
18
|
-
// column
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
// Naming the column is not scoping by it: a select list or a `set` clause that names the tenant
|
|
18
|
+
// column reaches every tenant's rows just as happily. Only a condition in a `where` clause, or in
|
|
19
|
+
// the `on` clause of a join, counts. The condition compares the column with a value, or with the
|
|
20
|
+
// tenant column of another row as a correlated subquery does, but never with itself. No top-level
|
|
21
|
+
// `or` sits beside it. A comment in the SQL is no condition.
|
|
22
|
+
function equalsTenant(condition, column) {
|
|
23
|
+
const equals = topLevelEquals(condition);
|
|
24
|
+
if (equals === -1) return false;
|
|
25
|
+
const side = new RegExp(`^(?:(\\w+)\\.)?${escape(column)}$`);
|
|
26
|
+
const left = side.exec(condition.slice(0, equals).trim());
|
|
27
|
+
const right = side.exec(condition.slice(equals + 1).trim());
|
|
28
|
+
// Either side may hold the column, as in `$1 = tenant_id`.
|
|
29
|
+
if (!left || !right) return Boolean(left || right);
|
|
30
|
+
// Two rows of one tenant: both sides name their row, and the rows differ.
|
|
31
|
+
return Boolean(left[1] && right[1] && left[1] !== right[1]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The index of the first `=` outside parentheses that is no part of `<=`, `>=`, `!=`, `:=` or `==`, or -1. */
|
|
35
|
+
function topLevelEquals(condition) {
|
|
36
|
+
let depth = 0;
|
|
37
|
+
for (let i = 0; i < condition.length; i += 1) {
|
|
38
|
+
if (condition[i] === "(") depth += 1;
|
|
39
|
+
else if (condition[i] === ")") depth -= 1;
|
|
40
|
+
else if (depth === 0 && condition[i] === "=" && !"<>!:=".includes(condition[i - 1] ?? " ") && condition[i + 1] !== "=") return i;
|
|
41
|
+
}
|
|
42
|
+
return -1;
|
|
43
|
+
}
|
|
44
|
+
// A word that ends a `where` or `on` clause at its own depth.
|
|
45
|
+
const CLAUSE_END =
|
|
46
|
+
/^(?:where|on|group\s+by|order\s+by|limit|offset|returning|having|window|union|intersect|except|for\s+(?:update|share)|(?:(?:inner|left|right|full|cross)\s+(?:outer\s+)?)?join)\b/i;
|
|
47
|
+
|
|
48
|
+
/** The index of the last `}` of the `${` that opens at `from`. */
|
|
49
|
+
function interpolationEnd(sql, from) {
|
|
50
|
+
let depth = 1;
|
|
51
|
+
let i = from + 2;
|
|
52
|
+
while (i < sql.length && depth > 0) {
|
|
53
|
+
if (sql[i] === "{") depth += 1;
|
|
54
|
+
else if (sql[i] === "}") depth -= 1;
|
|
55
|
+
i += 1;
|
|
56
|
+
}
|
|
57
|
+
return i - 1;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The SQL with each interpolation and each string literal as one opaque value, and each comment gone. */
|
|
61
|
+
function plainSql(sql) {
|
|
62
|
+
let out = "";
|
|
63
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
64
|
+
if (sql.startsWith("${", i)) {
|
|
65
|
+
i = interpolationEnd(sql, i);
|
|
66
|
+
out += "$x";
|
|
67
|
+
} else if (sql[i] === "'") {
|
|
68
|
+
// A quote inside the literal is doubled, and a `${}` inside it is code with quotes of its own.
|
|
69
|
+
for (i += 1; i < sql.length && !(sql[i] === "'" && sql[i + 1] !== "'"); i += 1) {
|
|
70
|
+
if (sql.startsWith("${", i)) i = interpolationEnd(sql, i);
|
|
71
|
+
else if (sql[i] === "'") i += 1;
|
|
72
|
+
}
|
|
73
|
+
out += "$s";
|
|
74
|
+
} else if (sql.startsWith("--", i)) {
|
|
75
|
+
while (i < sql.length && sql[i] !== "\n") i += 1;
|
|
76
|
+
out += " ";
|
|
77
|
+
} else if (sql.startsWith("/*", i)) {
|
|
78
|
+
const end = sql.indexOf("*/", i + 2);
|
|
79
|
+
i = end === -1 ? sql.length : end + 1;
|
|
80
|
+
out += " ";
|
|
81
|
+
} else {
|
|
82
|
+
out += sql[i];
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The parts of a condition between each top-level `word`, or the whole condition when it has none. */
|
|
89
|
+
function splitTopLevel(condition, word) {
|
|
90
|
+
const parts = [];
|
|
91
|
+
const pattern = new RegExp(`^${word}\\b`, "i");
|
|
92
|
+
let depth = 0;
|
|
93
|
+
let start = 0;
|
|
94
|
+
for (let i = 0; i < condition.length; i += 1) {
|
|
95
|
+
if (condition[i] === "(") depth += 1;
|
|
96
|
+
else if (condition[i] === ")") depth -= 1;
|
|
97
|
+
else if (depth === 0 && /\W/.test(condition[i - 1] ?? " ") && pattern.test(condition.slice(i))) {
|
|
98
|
+
parts.push(condition.slice(start, i));
|
|
99
|
+
start = i + word.length;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
parts.push(condition.slice(start));
|
|
103
|
+
return parts.map((part) => part.trim());
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A condition without the parentheses that wrap all of it. */
|
|
107
|
+
function unwrap(condition) {
|
|
108
|
+
let text = condition.trim();
|
|
109
|
+
while (text.startsWith("(") && text.endsWith(")")) {
|
|
110
|
+
let depth = 0;
|
|
111
|
+
let closesAtEnd = true;
|
|
112
|
+
for (let i = 0; i < text.length - 1; i += 1) {
|
|
113
|
+
if (text[i] === "(") depth += 1;
|
|
114
|
+
else if (text[i] === ")") depth -= 1;
|
|
115
|
+
if (depth === 0) {
|
|
116
|
+
closesAtEnd = false;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (!closesAtEnd) break;
|
|
121
|
+
text = text.slice(1, -1).trim();
|
|
122
|
+
}
|
|
123
|
+
return text;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** True when every row the condition admits has the tenant column equal to one value. */
|
|
127
|
+
function conditionScopes(condition, column) {
|
|
128
|
+
const text = unwrap(condition);
|
|
129
|
+
if (splitTopLevel(text, "or").length > 1) return false;
|
|
130
|
+
const conjuncts = splitTopLevel(text, "and");
|
|
131
|
+
if (conjuncts.length > 1) return conjuncts.some((conjunct) => conditionScopes(conjunct, column));
|
|
132
|
+
return equalsTenant(text, column);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Each `where` clause, and each `on` clause of a join, with the text up to its end. */
|
|
136
|
+
function conditionClauses(sql) {
|
|
137
|
+
const clauses = [];
|
|
138
|
+
const keyword = /\b(where|on)\b(?!\s+conflict\b)/gi;
|
|
139
|
+
for (let match = keyword.exec(sql); match !== null; match = keyword.exec(sql)) {
|
|
140
|
+
let depth = 0;
|
|
141
|
+
let end = sql.length;
|
|
142
|
+
for (let i = match.index + match[0].length; i < sql.length; i += 1) {
|
|
143
|
+
if (sql[i] === "(") depth += 1;
|
|
144
|
+
else if (sql[i] === ")") {
|
|
145
|
+
if (depth === 0) {
|
|
146
|
+
end = i;
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
depth -= 1;
|
|
150
|
+
} else if (depth === 0 && /\W/.test(sql[i - 1]) && CLAUSE_END.test(sql.slice(i))) {
|
|
151
|
+
end = i;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
clauses.push(sql.slice(match.index + match[0].length, end));
|
|
156
|
+
}
|
|
157
|
+
return clauses;
|
|
21
158
|
}
|
|
22
159
|
// Nine of eleven features write their generic helpers with the table name as a
|
|
23
160
|
// runtime value — `from ${table}`. Matching only literal names skipped those
|
|
@@ -28,9 +165,12 @@ const DYNAMIC_TABLE = /\b(?:from|join|into|update)\s+\$\{/;
|
|
|
28
165
|
|
|
29
166
|
/** True when the statement actually filters or writes the tenant, not merely names it. */
|
|
30
167
|
function scopedBy(sql, column) {
|
|
31
|
-
|
|
32
|
-
const inserted = /insert\s+into\s+(?:\w
|
|
33
|
-
|
|
168
|
+
const plain = plainSql(sql);
|
|
169
|
+
const inserted = /insert\s+into\s+(?:\w+|\$x)\s*\(([^)]*)\)/i.exec(plain);
|
|
170
|
+
if (inserted && new RegExp(`\\b${escape(column)}\\b`).test(inserted[1])) return true;
|
|
171
|
+
// Each side of a set operation reads rows of its own, so each side carries the tenant.
|
|
172
|
+
const operands = ["union", "intersect", "except"].reduce((parts, word) => parts.flatMap((part) => splitTopLevel(part, word)), [plain]);
|
|
173
|
+
return operands.every((operand) => conditionClauses(operand).some((clause) => conditionScopes(clause, column)));
|
|
34
174
|
}
|
|
35
175
|
|
|
36
176
|
/** A statement that reads only a bound name touches no table and needs no predicate. */
|
|
@@ -28,6 +28,61 @@ test("an update that does not carry the tenant is a finding", () => {
|
|
|
28
28
|
assert.equal(problems.length, 1);
|
|
29
29
|
});
|
|
30
30
|
|
|
31
|
+
test("a tenant in the set clause of an update is not a predicate: the row may belong to any tenant", () => {
|
|
32
|
+
assert.equal(checkTenantPredicate(one("update projects set tenant_id = $1 where id = $2"), owned).length, 1);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
test("a tenant beside a top-level or admits every tenant's rows, and is a finding", () => {
|
|
36
|
+
assert.equal(checkTenantPredicate(one("select id from projects where id = $1 or tenant_id = $2"), owned).length, 1);
|
|
37
|
+
assert.equal(checkTenantPredicate(one("select id from projects where tenant_id = $1 or true"), owned).length, 1);
|
|
38
|
+
assert.equal(checkTenantPredicate(one("select id from projects where (tenant_id = $1 or id = $2) and code = $3"), owned).length, 1);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("an or nested inside a conjunct beside the tenant passes", () => {
|
|
42
|
+
const sql = "select id from projects where tenant_id = $1 and (status = $2 or status = $3)";
|
|
43
|
+
assert.deepEqual(checkTenantPredicate(one(sql), owned), []);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("a tenant column compared with itself is a finding", () => {
|
|
47
|
+
assert.equal(checkTenantPredicate(one("select id from projects where tenant_id = tenant_id"), owned).length, 1);
|
|
48
|
+
assert.equal(checkTenantPredicate(one("select id from projects p where p.tenant_id = p.tenant_id"), owned).length, 1);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test("a string literal is one value: an or or a comment marker inside it changes nothing", () => {
|
|
52
|
+
const count = (sql) => checkTenantPredicate(one(sql), owned).length;
|
|
53
|
+
assert.equal(count("select * from projects where tenant_id = $1 and status <> 'draft or review'"), 0);
|
|
54
|
+
assert.equal(count("select * from projects where note = 'a -- b' and tenant_id = $1"), 0);
|
|
55
|
+
assert.equal(count("select * from projects where note = 'it''s' and tenant_id = $1"), 0);
|
|
56
|
+
assert.equal(count("select * from projects where tenant_id = $1 and note = '/*' or true or note = '*/'"), 1);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("each side of a union, intersect or except carries the tenant", () => {
|
|
60
|
+
const count = (sql) => checkTenantPredicate(one(sql), owned).length;
|
|
61
|
+
assert.equal(count("select id from projects where tenant_id = $1 union select id from projects"), 1);
|
|
62
|
+
assert.equal(count("select id from projects where tenant_id = $1 except select id from projects"), 1);
|
|
63
|
+
assert.equal(count("select id from projects where tenant_id = $1 union all select id from projects where tenant_id = $1"), 0);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("the tenant column may stand on either side of the equals sign", () => {
|
|
67
|
+
assert.equal(checkTenantPredicate(one("select * from projects where $1 = tenant_id"), owned).length, 0);
|
|
68
|
+
assert.equal(checkTenantPredicate(one("select * from projects where tenant_id <= $1"), owned).length, 1);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("a correlated subquery that matches the tenant of the outer row passes", () => {
|
|
72
|
+
const sql = "exists (select 1 from projects v where v.tenant_id = outer_row.tenant_id and v.id = outer_row.project_id)";
|
|
73
|
+
assert.deepEqual(checkTenantPredicate(one(sql), owned), []);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("a tenant inside an sql comment is no predicate", () => {
|
|
77
|
+
assert.equal(checkTenantPredicate(one("delete from projects where id = $1 -- tenant_id = $2"), owned).length, 1);
|
|
78
|
+
assert.equal(checkTenantPredicate(one("delete from projects where id = $1 /* and tenant_id = $2 */"), owned).length, 1);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test("an interpolated tenant value passes, and an interpolation cannot hide an or", () => {
|
|
82
|
+
assert.deepEqual(checkTenantPredicate(one("select id from projects where tenant_id = ${tenantId}"), owned), []);
|
|
83
|
+
assert.equal(checkTenantPredicate(one("select id from projects where tenant_id = ${f(\"a\")} or id = $2"), owned).length, 1);
|
|
84
|
+
});
|
|
85
|
+
|
|
31
86
|
test("a statement reading only a common table expression needs no predicate", () => {
|
|
32
87
|
const bound = new Set(["projects"]);
|
|
33
88
|
assert.deepEqual(checkTenantPredicate(one("select id from projects", bound), owned), []);
|
|
@@ -34,14 +34,17 @@ function block(source, open) {
|
|
|
34
34
|
*/
|
|
35
35
|
export function tenantScopedTables(source, options = {}) {
|
|
36
36
|
const factory = escape(options.tableFactory ?? DEFAULT_TABLE_FACTORY);
|
|
37
|
-
|
|
37
|
+
// Either quote, and the columns as an object or as drizzle's callback, `(t) => ({ ... })`. A table this
|
|
38
|
+
// misses gets no policy and no finding, so the forms it reads are wide on purpose.
|
|
39
|
+
const callback = `(?:(?:\\(\\s*\\w*\\s*\\)|\\w+)\\s*=>\\s*\\(?\\s*)?`;
|
|
40
|
+
const tablePattern = new RegExp(`\\b${factory}\\(\\s*(["'\`])([a-z_][a-z0-9_]*)\\1\\s*,\\s*${callback}\\{`, "g");
|
|
38
41
|
const column = new RegExp(`\\b${escape(options.column ?? DEFAULT_COLUMN)}\\b`);
|
|
39
42
|
|
|
40
43
|
const found = new Set();
|
|
41
44
|
let match = tablePattern.exec(source);
|
|
42
45
|
while (match !== null) {
|
|
43
46
|
const body = block(source, match.index + match[0].length - 1);
|
|
44
|
-
if (column.test(body)) found.add(match[
|
|
47
|
+
if (column.test(body)) found.add(match[2]);
|
|
45
48
|
match = tablePattern.exec(source);
|
|
46
49
|
}
|
|
47
50
|
return [...found].sort();
|
|
@@ -31,6 +31,14 @@ test("a nested object inside a column definition does not end the table early",
|
|
|
31
31
|
assert.deepEqual(tenantScopedTables(source), ["photos"]);
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
+
test("a single-quoted name and drizzle's callback form are listed too", () => {
|
|
35
|
+
const source = `export const b = pgTable('b', { tenantId: uuid() });
|
|
36
|
+
export const c = pgTable("c", (t) => ({ tenantId: t.uuid() }));
|
|
37
|
+
export const d = pgTable(\`d\`, t => ({ tenantId: t.uuid() }));
|
|
38
|
+
export const e = myPgTable("e", { tenantId: uuid() });`;
|
|
39
|
+
assert.deepEqual(tenantScopedTables(source), ["b", "c", "d"]);
|
|
40
|
+
});
|
|
41
|
+
|
|
34
42
|
test("a source with no table yields nothing", () => {
|
|
35
43
|
assert.deepEqual(tenantScopedTables("export const queries = {};"), []);
|
|
36
44
|
});
|
|
@@ -23,15 +23,18 @@ export function checkThresholdRatchet(before, after, adrs, { registry }) {
|
|
|
23
23
|
};
|
|
24
24
|
for (const [key, entry] of Object.entries(after)) {
|
|
25
25
|
const was = before[key];
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
if (
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
26
|
+
if (typeof was?.value !== "number" || citedByAdr(key)) continue;
|
|
27
|
+
// A limit with no number, or one that now points the other way, no longer holds the old line.
|
|
28
|
+
let detail = null;
|
|
29
|
+
if (typeof entry?.value !== "number") {
|
|
30
|
+
detail = `'${key}' (${was.comparator} ${was.value}) no longer has a number, so it limits nothing`;
|
|
31
|
+
} else if (entry.comparator !== was.comparator) {
|
|
32
|
+
detail = `'${key}' changes from ${was.comparator} ${was.value} to ${entry.comparator} ${entry.value}, which is no longer the same limit`;
|
|
33
|
+
} else if (loosened(was.comparator, was.value, entry.value)) {
|
|
34
|
+
// The comparator in force before the change is the policy the change answers to.
|
|
35
|
+
detail = `'${key}' moves from ${was.value} to ${entry.value}, and a ${was.comparator} that moves this way loosens`;
|
|
36
|
+
}
|
|
37
|
+
if (detail) problems.push({ path: registry, rule: "loosened-threshold", detail: `${detail}; a changed ADR must name '${key}'` });
|
|
35
38
|
}
|
|
36
39
|
// Dropping a limit is the widest loosening of all, so it answers to the same rule.
|
|
37
40
|
for (const [key, was] of Object.entries(before)) {
|
|
@@ -58,3 +58,19 @@ test("the comparator in force at the base judges the change", () => {
|
|
|
58
58
|
const after = { ...base, filelength: { value: 550, comparator: "min" } };
|
|
59
59
|
assert.equal(check(after).length, 1);
|
|
60
60
|
});
|
|
61
|
+
|
|
62
|
+
test("a comparator that flips at the same value fails, since the limit now points the other way", () => {
|
|
63
|
+
const problems = check({ ...base, filelength: { value: 500, comparator: "min" } });
|
|
64
|
+
assert.equal(problems.length, 1);
|
|
65
|
+
assert.match(problems[0].detail, /from max 500 to min 500/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("a value that is no longer a number fails, as a removal does, unless a changed ADR names it", () => {
|
|
69
|
+
for (const value of [null, "500", undefined]) {
|
|
70
|
+
const problems = check(moved("filelength", value));
|
|
71
|
+
assert.equal(problems.length, 1, String(value));
|
|
72
|
+
assert.match(problems[0].detail, /no longer has a number/);
|
|
73
|
+
}
|
|
74
|
+
const adrs = [{ path: "docs/decisions/0033-files.md", text: "We drop `filelength`." }];
|
|
75
|
+
assert.deepEqual(check(moved("filelength", null), adrs), []);
|
|
76
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
3
|
+
import { test } from "node:test";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const PLUGIN = fileURLToPath(new URL("../../../", import.meta.url));
|
|
7
|
+
const EDIT_TOOLS = ["Write", "Edit", "MultiEdit", "NotebookEdit"];
|
|
8
|
+
|
|
9
|
+
test("every skill applies only where qc.config.json exists, in its description and in its body", () => {
|
|
10
|
+
const skills = readdirSync(`${PLUGIN}skills`);
|
|
11
|
+
assert.ok(skills.length > 0);
|
|
12
|
+
for (const skill of skills) {
|
|
13
|
+
const text = readFileSync(`${PLUGIN}skills/${skill}/SKILL.md`, "utf8");
|
|
14
|
+
const description = /^description: (.+)$/m.exec(text)?.[1] ?? "";
|
|
15
|
+
assert.match(description, /only in a repository with a `qc\.config\.json`/, skill);
|
|
16
|
+
assert.match(text, /This skill applies only to a repository with a `qc\.config\.json` at its root/, skill);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("each guard that keeps an edit inside its paths runs on every edit tool", () => {
|
|
21
|
+
const { hooks } = JSON.parse(readFileSync(`${PLUGIN}hooks/hooks.json`, "utf8"));
|
|
22
|
+
for (const guard of ["pre-edit-guard.sh", "controller-guard.mjs", "slot-guard.mjs"]) {
|
|
23
|
+
const entry = hooks.PreToolUse.find((group) => group.hooks.some((hook) => hook.command.includes(guard)));
|
|
24
|
+
assert.ok(entry, guard);
|
|
25
|
+
const tools = entry.matcher.split("|");
|
|
26
|
+
for (const tool of EDIT_TOOLS) assert.ok(tools.includes(tool), `${guard} misses ${tool}`);
|
|
27
|
+
}
|
|
28
|
+
});
|