architecture-harness 0.25.0 → 0.26.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 -22
- package/src/cli/ask.mjs +42 -0
- package/src/cli/ask.test.mjs +40 -0
- package/src/cli/branch-sync.mjs +126 -0
- package/src/cli/branch-sync.test.mjs +428 -0
- package/src/cli/budget-guard.mjs +74 -5
- package/src/cli/budget-guard.test.mjs +185 -2
- package/src/cli/budget-report.mjs +85 -0
- package/src/cli/budget-report.test.mjs +173 -0
- package/src/cli/budget.mjs +8 -5
- package/src/cli/check-commands.mjs +123 -11
- package/src/cli/check-commands.test.mjs +360 -6
- package/src/cli/check-feature-switches.test.mjs +110 -0
- package/src/cli/check-full.test.mjs +152 -0
- package/src/cli/check-verdict.mjs +46 -0
- package/src/cli/check-verdict.test.mjs +32 -0
- package/src/cli/check.mjs +137 -4
- package/src/cli/check.test.mjs +45 -0
- package/src/cli/checkpoint.mjs +143 -0
- package/src/cli/checkpoint.test.mjs +146 -0
- package/src/cli/child-run.mjs +7 -2
- package/src/cli/child-run.test.mjs +17 -2
- package/src/cli/ci-failures.mjs +304 -0
- package/src/cli/ci-failures.test.mjs +615 -0
- package/src/cli/ci-preview.mjs +62 -0
- package/src/cli/ci-preview.test.mjs +85 -0
- package/src/cli/ci-state.mjs +25 -29
- package/src/cli/ci-state.test.mjs +174 -2
- package/src/cli/ci-template.test.mjs +86 -0
- package/src/cli/claude-core.test.mjs +37 -0
- package/src/cli/codex-implement.mjs +580 -47
- package/src/cli/codex-implement.test.mjs +1946 -29
- package/src/cli/codex-limit.mjs +85 -0
- package/src/cli/codex-limit.test.mjs +179 -0
- package/src/cli/codex-reset.mjs +78 -0
- package/src/cli/codex-reset.test.mjs +192 -0
- package/src/cli/codex-verify.mjs +230 -0
- package/src/cli/codex-verify.test.mjs +402 -0
- package/src/cli/comment-watch.mjs +391 -0
- package/src/cli/comment-watch.test.mjs +392 -0
- package/src/cli/commit-guard.mjs +219 -0
- package/src/cli/commit-guard.test.mjs +809 -0
- package/src/cli/context-budgets.mjs +47 -0
- package/src/cli/context-budgets.test.mjs +96 -0
- package/src/cli/context-watch.mjs +116 -0
- package/src/cli/context-watch.test.mjs +395 -0
- package/src/cli/contract-history.mjs +1 -1
- package/src/cli/controller-guard.mjs +38 -0
- package/src/cli/controller-guard.test.mjs +66 -2
- package/src/cli/cost-stop.mjs +5 -1
- package/src/cli/cost-stop.test.mjs +26 -0
- package/src/cli/diff-shape.mjs +162 -0
- package/src/cli/diff-shape.test.mjs +200 -0
- package/src/cli/direct-lane.mjs +32 -19
- package/src/cli/direct-lane.test.mjs +21 -3
- package/src/cli/dispatch-guard.mjs +11 -0
- package/src/cli/dispatch-guard.test.mjs +145 -10
- package/src/cli/dispatch-reminder.mjs +23 -10
- package/src/cli/dispatch-reminder.test.mjs +63 -11
- package/src/cli/dispatch-route.mjs +54 -0
- package/src/cli/dispatch-route.test.mjs +101 -0
- package/src/cli/dispatch-slot.mjs +2 -2
- package/src/cli/dispatch-slot.test.mjs +18 -19
- package/src/cli/dispatch.test.mjs +3 -3
- package/src/cli/e2e-affected.mjs +15 -0
- package/src/cli/e2e-affected.test.mjs +73 -0
- package/src/cli/fleet.mjs +180 -0
- package/src/cli/fleet.test.mjs +213 -0
- package/src/cli/gate-slot.mjs +2 -1
- package/src/cli/gh-merge-command.mjs +96 -31
- package/src/cli/gh-merge-command.test.mjs +74 -0
- package/src/cli/gh-run.mjs +64 -3
- package/src/cli/gh-run.test.mjs +66 -1
- package/src/cli/git-hooks.test.mjs +25 -3
- package/src/cli/git-read.mjs +2 -1
- package/src/cli/integrate-tree.mjs +47 -0
- package/src/cli/integrate.mjs +143 -40
- package/src/cli/integrate.test.mjs +347 -1
- package/src/cli/integration-lane.mjs +62 -0
- package/src/cli/integration-lane.test.mjs +213 -0
- package/src/cli/ledger.mjs +4 -2
- package/src/cli/ledger.test.mjs +12 -3
- package/src/cli/legs.mjs +53 -0
- package/src/cli/legs.test.mjs +70 -0
- package/src/cli/lint-changed.mjs +59 -10
- package/src/cli/lint-changed.test.mjs +112 -1
- package/src/cli/locked-tests.mjs +134 -0
- package/src/cli/locked-tests.test.mjs +188 -0
- package/src/cli/merge-guard.mjs +234 -62
- package/src/cli/merge-guard.test.mjs +768 -39
- package/src/cli/metrics.mjs +53 -0
- package/src/cli/metrics.test.mjs +73 -0
- package/src/cli/milestone.mjs +297 -0
- package/src/cli/milestone.test.mjs +294 -0
- package/src/cli/mutate.mjs +203 -0
- package/src/cli/mutate.test.mjs +134 -0
- package/src/cli/output-redaction.mjs +26 -0
- package/src/cli/output-redaction.test.mjs +117 -0
- package/src/cli/overview.mjs +131 -0
- package/src/cli/overview.test.mjs +137 -0
- package/src/cli/pause.mjs +93 -0
- package/src/cli/pause.test.mjs +109 -0
- package/src/cli/plan-check.mjs +84 -12
- package/src/cli/plan-check.test.mjs +152 -2
- package/src/cli/plan-stop.mjs +7 -4
- package/src/cli/plan-stop.test.mjs +87 -0
- package/src/cli/platform-risk.mjs +46 -0
- package/src/cli/platform-risk.test.mjs +38 -0
- package/src/cli/plugin-skills.test.mjs +25 -0
- package/src/cli/pr-guard.mjs +128 -0
- package/src/cli/pr-guard.test.mjs +154 -0
- package/src/cli/promotion-branch.mjs +2 -0
- package/src/cli/qc.mjs +160 -27
- package/src/cli/qc.test.mjs +93 -0
- package/src/cli/report-stop.mjs +5 -0
- package/src/cli/report-stop.test.mjs +23 -1
- package/src/cli/retry-failed.mjs +3 -1
- package/src/cli/review-gate.mjs +24 -6
- package/src/cli/review-gate.test.mjs +116 -0
- package/src/cli/review-promotion.mjs +107 -0
- package/src/cli/review-promotion.test.mjs +251 -0
- package/src/cli/role-budget.mjs +50 -0
- package/src/cli/role-budget.test.mjs +91 -0
- package/src/cli/run-log.mjs +73 -0
- package/src/cli/run-log.test.mjs +121 -0
- package/src/cli/secret-patterns.mjs +16 -0
- package/src/cli/secret-patterns.test.mjs +73 -0
- package/src/cli/setup-block.mjs +24 -0
- package/src/cli/setup-block.test.mjs +96 -0
- package/src/cli/setup-checks.mjs +65 -0
- package/src/cli/setup-checks.test.mjs +158 -0
- package/src/cli/setup-compaction.mjs +55 -0
- package/src/cli/setup-compaction.test.mjs +115 -0
- package/src/cli/setup-skills.mjs +65 -0
- package/src/cli/setup-skills.test.mjs +171 -0
- package/src/cli/setup.mjs +107 -0
- package/src/cli/setup.test.mjs +275 -0
- package/src/cli/skill-length.test.mjs +8 -0
- package/src/cli/spawn-command.mjs +47 -0
- package/src/cli/spawn-command.test.mjs +64 -0
- package/src/cli/task-gate-review.test.mjs +21 -2
- package/src/cli/task-gate.mjs +25 -12
- package/src/cli/task-gate.test.mjs +43 -5
- package/src/cli/tokens.mjs +46 -3
- package/src/cli/tokens.test.mjs +103 -3
- package/src/cli/tools.mjs +49 -0
- package/src/cli/tools.test.mjs +89 -0
- package/src/cli/transcript-usage.mjs +27 -0
- package/src/cli/transcript-usage.test.mjs +34 -0
- package/src/cli/user-config-package.mjs +1 -1
- package/src/cli/user-config-toml.mjs +63 -7
- package/src/cli/user-config.mjs +39 -7
- package/src/cli/user-config.test.mjs +238 -5
- package/src/cli/watch-arm.mjs +39 -0
- package/src/cli/watch-arm.test.mjs +87 -0
- package/src/cli/watch.mjs +80 -35
- package/src/cli/watch.test.mjs +233 -27
- package/src/cli/work-order-guard.mjs +2 -1
- package/src/cli/workflow-hooks.test.mjs +18 -4
- package/src/cli/workflow-settings.mjs +44 -8
- package/src/cli/workflow-settings.test.mjs +124 -1
- package/src/cli/worktree.mjs +14 -1
- package/src/cli/worktree.test.mjs +20 -1
- package/src/config.mjs +174 -7
- package/src/config.test.mjs +327 -5
- package/src/consumer-package.mjs +31 -0
- package/src/consumer-package.test.mjs +54 -0
- package/src/descriptions.mjs +2 -0
- package/src/eslint/index.mjs +12 -0
- package/src/eslint/jsx.mjs +20 -0
- package/src/eslint/preset.mjs +26 -2
- package/src/eslint/preset.test.mjs +104 -2
- package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
- package/src/eslint/rules/no-literal-color.mjs +94 -0
- package/src/eslint/rules/no-static-inline-style.mjs +41 -0
- package/src/eslint/rules/one-component-per-file.mjs +70 -0
- package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
- package/src/eslint/rules/timeless-comment.mjs +92 -0
- package/src/eslint/rules.test.mjs +189 -0
- package/src/eslint/ui-regressions.test.mjs +39 -0
- package/src/gates/contract-operations.mjs +3 -3
- package/src/gates/contract-operations.test.mjs +28 -0
- package/src/gates/feature-switches.mjs +19 -0
- package/src/gates/feature-switches.test.mjs +55 -0
- package/src/gates/plain-language.mjs +396 -0
- package/src/gates/plain-language.test.mjs +210 -0
- package/src/gates/runtime-imports.test.mjs +114 -0
- package/src/gates/saga-key.test.mjs +1 -1
- package/src/global-skills.mjs +9 -0
- package/src/global-skills.test.mjs +53 -0
- package/src/plugin.test.mjs +3 -2
- package/src/ui/class-sites.mjs +38 -6
- package/src/ui/codemod.mjs +4 -1
- package/src/ui/codemod.test.mjs +52 -0
- package/src/ui/components.mjs +5 -3
- package/src/ui/components.test.mjs +8 -0
- package/src/ui/dupes.test.mjs +18 -0
- package/templates/docs/enforcement.md +12 -2
- package/templates/docs/ui.md +33 -0
- package/templates/githooks/pre-commit +1 -0
- package/templates/githooks/pre-push +11 -2
- package/templates/github/workflows/ci.yml +57 -3
- package/user-config/claude/CLAUDE.core.md +28 -0
- package/user-config/claude/settings.shared.json +41 -1
- package/src/cli/screens-discovery.mjs +0 -60
- package/src/cli/screens.mjs +0 -84
- package/src/cli/stack.mjs +0 -14
- package/src/cli/throwaway-db.mjs +0 -127
- package/src/cli/throwaway-db.test.mjs +0 -83
- package/src/screens/auth-context.test.mjs +0 -41
- package/src/screens/auth-run.test.mjs +0 -147
- package/src/screens/auth.mjs +0 -223
- package/src/screens/auth.test.mjs +0 -76
- package/src/screens/capture-idle.test.mjs +0 -27
- package/src/screens/capture.browser-test.mjs +0 -73
- package/src/screens/capture.mjs +0 -175
- package/src/screens/capture.test.mjs +0 -28
- package/src/screens/catalog.browser-test.mjs +0 -32
- package/src/screens/catalog.mjs +0 -72
- package/src/screens/catalog.test.mjs +0 -36
- package/src/screens/chrome.mjs +0 -21
- package/src/screens/compare.mjs +0 -40
- package/src/screens/compare.test.mjs +0 -30
- package/src/screens/discovery.browser-test.mjs +0 -29
- package/src/screens/discovery.mjs +0 -158
- package/src/screens/discovery.test.mjs +0 -27
- package/src/screens/inventory.mjs +0 -69
- package/src/screens/inventory.test.mjs +0 -10
- package/src/screens/map.mjs +0 -63
- package/src/screens/map.test.mjs +0 -35
- package/src/screens/open.browser-test.mjs +0 -50
- package/src/screens/regions.mjs +0 -137
- package/src/screens/regions.test.mjs +0 -38
- package/src/screens/session-files.mjs +0 -39
- package/src/screens/session-files.test.mjs +0 -39
- package/src/screens/setup.browser-test.mjs +0 -49
- package/src/screens/setup.mjs +0 -78
- package/src/screens/stack-auth.browser-test.mjs +0 -30
- package/src/screens/stack-auth.mjs +0 -106
- package/src/screens/stack-auth.test.mjs +0 -65
- package/src/screens/write-guard.mjs +0 -26
- package/src/stack/stack.mjs +0 -131
- package/src/stack/stack.test.mjs +0 -40
- package/src/stack/supervisor.mjs +0 -30
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { watchedItems } from "./comment-watch.mjs";
|
|
5
|
+
import { PARSERS } from "./bash-command-guard.mjs";
|
|
6
|
+
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import os from "node:os";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
11
|
+
|
|
12
|
+
test("watch detection keeps closed issues, PR output, and body references", () => {
|
|
13
|
+
const items = watchedItems({
|
|
14
|
+
tool_name: "Bash",
|
|
15
|
+
tool_input: { command: 'gh issue close 4 -R owner/repo; gh pr create --body "Fixes #5, #6"' },
|
|
16
|
+
tool_response: { stdout: "https://github.com/owner/repo/pull/7" },
|
|
17
|
+
}, "owner/repo", PARSERS.Bash);
|
|
18
|
+
assert.deepEqual(items.map(({ repo, number }) => `${repo}#${number}`).sort(),
|
|
19
|
+
["owner/repo#4", "owner/repo#5", "owner/repo#6", "owner/repo#7"]);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
test("PowerShell detects explicit repositories, body files, and commit references", (t) => {
|
|
23
|
+
const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-comment-detection-"));
|
|
24
|
+
t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
|
|
25
|
+
writeFileSync(path.join(cwd, "body.txt"), "Refs #8");
|
|
26
|
+
for (const tool_name of ["Bash", "PowerShell"]) {
|
|
27
|
+
const items = watchedItems({ cwd, tool_name, tool_input: {
|
|
28
|
+
command: 'gh -R owner/other pr comment 3 --body-file body.txt; git commit -m "Fixes #9"',
|
|
29
|
+
} }, "owner/repo");
|
|
30
|
+
assert.deepEqual(items.map(({ repo, number }) => `${repo}#${number}`).sort(), ["owner/other#3", "owner/other#8", "owner/repo#9"]);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
function fixture(t) {
|
|
35
|
+
const cwd = mkdtempSync(path.join(os.tmpdir(), "qc-comment-watch-"));
|
|
36
|
+
t.after(() => rmSync(cwd, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
|
|
37
|
+
const env = { ...process.env, GIT_CONFIG_GLOBAL: path.join(cwd, "empty-gitconfig"), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_COUNT: "0" };
|
|
38
|
+
delete env.GH_CONFIG_DIR;
|
|
39
|
+
writeFileSync(env.GIT_CONFIG_GLOBAL, "");
|
|
40
|
+
for (const args of [["init", "-q"], ["-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "--allow-empty", "-qm", "fixture"], ["remote", "add", "origin", "https://github.com/shawrylk/example.git"]]) {
|
|
41
|
+
assert.equal(spawnSync("git", args, { cwd, env }).status, 0);
|
|
42
|
+
}
|
|
43
|
+
const baseOid = spawnSync("git", ["rev-parse", "HEAD"], { cwd, env, encoding: "utf8" }).stdout.trim();
|
|
44
|
+
const mock = path.join(cwd, "mock.mjs");
|
|
45
|
+
const data = path.join(cwd, "data.json");
|
|
46
|
+
const calls = path.join(cwd, "calls.jsonl");
|
|
47
|
+
writeFileSync(mock, `
|
|
48
|
+
import cp from 'node:child_process';
|
|
49
|
+
import { syncBuiltinESMExports } from 'node:module';
|
|
50
|
+
import { appendFileSync, readFileSync } from 'node:fs';
|
|
51
|
+
const original = cp.spawnSync;
|
|
52
|
+
cp.spawnSync = (program, args, options) => {
|
|
53
|
+
if (program === 'git' && args.join(' ') === 'remote get-url origin') return { status: 0, stdout: 'https://github.com/shawrylk/example.git' };
|
|
54
|
+
if (program !== 'gh') return original(program, args, options);
|
|
55
|
+
appendFileSync(process.env.CALLS, JSON.stringify({args, config: options.env.GH_CONFIG_DIR}) + '\\n');
|
|
56
|
+
const data = JSON.parse(readFileSync(process.env.DATA, 'utf8'));
|
|
57
|
+
if (data.fail || args.some(arg => arg.includes(data.failEndpoint ?? 'NEVER_MATCH'))) return { status: 1, stderr: 'TOKEN_MUST_STAY_SECRET' };
|
|
58
|
+
if (args[0] === 'api' && args[1].includes('/git/ref/heads/') && args.at(-2) === '--jq' && args.at(-1) === '.object.sha') return { status: 0, stdout: data.baseOid };
|
|
59
|
+
let result;
|
|
60
|
+
if (args[0] === 'pr') result = { baseRefName: 'main', baseRefOid: data.baseOid, labels: [], number: 7, body: data.body ?? 'Fixes #4; https://github.com/ArentInc/other/issues/8', commits: data.commits ?? [] };
|
|
61
|
+
else if (args[1] === 'user') result = { login: 'self' };
|
|
62
|
+
else if (args[1] === 'graphql') result = { data: { node: { number: 7, repository: { nameWithOwner: 'shawrylk/example' } } } };
|
|
63
|
+
else {
|
|
64
|
+
const endpoint = args.at(-1);
|
|
65
|
+
if (/issues\\/7$/.test(endpoint)) result = { pull_request: {} };
|
|
66
|
+
else if (/issues\\/\\d+$/.test(endpoint)) result = {};
|
|
67
|
+
else result = [[], data.rows.filter(row => endpoint.includes(row.endpoint)).map(({endpoint, ...row}) => row)];
|
|
68
|
+
}
|
|
69
|
+
return {status: 0, stdout: args.includes('--paginate') ? result.map(page => JSON.stringify(page)).join('\\n') : JSON.stringify(result)};
|
|
70
|
+
};
|
|
71
|
+
cp.execFile = (program, args, options, callback) => {
|
|
72
|
+
const data = JSON.parse(readFileSync(process.env.DATA, 'utf8'));
|
|
73
|
+
appendFileSync(process.env.CALLS, JSON.stringify({ start: Date.now(), args, config: options.env.GH_CONFIG_DIR }) + '\\n');
|
|
74
|
+
const result = cp.spawnSync(program, args, options);
|
|
75
|
+
setTimeout(() => callback(result.status ? new Error('gh failed') : null, result.stdout, result.stderr), data.delay ?? 0);
|
|
76
|
+
};
|
|
77
|
+
syncBuiltinESMExports();
|
|
78
|
+
`);
|
|
79
|
+
const row = (id, endpoint, login = "other") => ({ id, endpoint, user: { login }, body: `Comment ${id}`, html_url: `https://github.com/comments/${id}`, updated_at: "2026-01-01T00:00:00Z" });
|
|
80
|
+
const rows = [row(1, "issues/4/comments"), row(2, "pulls/7/reviews"), row(3, "pulls/7/comments"), row(4, "issues/7/comments", "self"), row(5, "issues/8/comments")];
|
|
81
|
+
const update = (extra = {}) => writeFileSync(data, JSON.stringify({ rows, baseOid, ...extra }));
|
|
82
|
+
update();
|
|
83
|
+
const run = (event, command = "", script = "comment-watch.mjs", session = "session-a", tool_response = "", tool_name = "PowerShell", parentCwd = cwd) => {
|
|
84
|
+
const cli = fileURLToPath(new URL(script, import.meta.url));
|
|
85
|
+
const result = spawnSync(process.execPath, ["--import", pathToFileURL(mock).href, cli], {
|
|
86
|
+
cwd: parentCwd, encoding: "utf8", env: { ...env, DATA: data, CALLS: calls },
|
|
87
|
+
input: JSON.stringify({ cwd, hook_event_name: event, session_id: session, tool_name, tool_response, tool_input: { command } }),
|
|
88
|
+
});
|
|
89
|
+
assert.equal(result.status, 0, result.stderr);
|
|
90
|
+
return result.stdout.trim() ? JSON.parse(result.stdout) : null;
|
|
91
|
+
};
|
|
92
|
+
return { cwd, rows, update, run, calls };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
for (const exists of [false, true]) {
|
|
96
|
+
test(`a mapped config folder that ${exists ? "exists sets GH_CONFIG_DIR" : "does not exist leaves GH_CONFIG_DIR unset"}`, (t) => {
|
|
97
|
+
const f = fixture(t);
|
|
98
|
+
const folder = path.join(f.cwd, "gh-config");
|
|
99
|
+
if (exists) mkdirSync(folder);
|
|
100
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ github: { configDirs: { shawrylk: `~/${path.relative(os.homedir(), folder).split(path.sep).join("/")}` } } }));
|
|
101
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
102
|
+
f.run("UserPromptSubmit");
|
|
103
|
+
const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
|
|
104
|
+
const mapped = calls.filter(call => call.args.some(arg => arg.includes("shawrylk/example")));
|
|
105
|
+
assert.ok(mapped.length > 0);
|
|
106
|
+
for (const call of mapped) assert.equal(call.config, exists ? folder : undefined);
|
|
107
|
+
const unmapped = calls.filter(call => call.args.some(arg => arg.includes("ArentInc/other")));
|
|
108
|
+
assert.ok(unmapped.length > 0);
|
|
109
|
+
for (const call of unmapped) assert.equal(call.config, undefined);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
test("a relative mapped config folder is checked against the checkout root", (t) => {
|
|
114
|
+
for (const existsInRoot of [true, false]) {
|
|
115
|
+
const f = fixture(t);
|
|
116
|
+
const parent = mkdtempSync(path.join(os.tmpdir(), "qc-comment-parent-"));
|
|
117
|
+
t.after(() => rmSync(parent, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
|
|
118
|
+
mkdirSync(path.join(existsInRoot ? f.cwd : parent, "packages"));
|
|
119
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ github: { configDirs: { shawrylk: "packages" } } }));
|
|
120
|
+
const parentCwd = existsInRoot ? path.parse(f.cwd).root : parent;
|
|
121
|
+
f.run("PostToolUse", "gh pr view 7", "comment-watch.mjs", "session-a", "", "PowerShell", parentCwd);
|
|
122
|
+
f.run("UserPromptSubmit", "", "comment-watch.mjs", "session-a", "", "PowerShell", parentCwd);
|
|
123
|
+
const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
|
|
124
|
+
const mapped = calls.filter(call => call.args.some(arg => arg.includes("shawrylk/example")));
|
|
125
|
+
assert.ok(mapped.length > 0);
|
|
126
|
+
for (const call of mapped) assert.equal(call.config, existsInRoot ? "packages" : undefined);
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("prompts show shared-login feedback once, retain failures, and isolate sessions and accounts", (t) => {
|
|
131
|
+
const f = fixture(t);
|
|
132
|
+
const folder = path.join(f.cwd, "gh-personal");
|
|
133
|
+
mkdirSync(folder);
|
|
134
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ github: { configDirs: { shawrylk: folder } } }));
|
|
135
|
+
f.run("PostToolUse", "gh issue close 4");
|
|
136
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
137
|
+
f.update({ fail: true });
|
|
138
|
+
const note = JSON.stringify(f.run("UserPromptSubmit"));
|
|
139
|
+
assert.match(note, /could not be checked/);
|
|
140
|
+
assert.doesNotMatch(note, /TOKEN_MUST_STAY_SECRET/);
|
|
141
|
+
f.update();
|
|
142
|
+
const output = f.run("UserPromptSubmit").hookSpecificOutput.additionalContext;
|
|
143
|
+
for (const id of [1, 2, 3, 4, 5]) assert.match(output, new RegExp(`Comment ${id}`));
|
|
144
|
+
assert.equal(f.run("UserPromptSubmit"), null);
|
|
145
|
+
f.rows.push({ ...f.rows[0], body: "Edited comment" });
|
|
146
|
+
f.update();
|
|
147
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Edited comment/);
|
|
148
|
+
assert.equal(f.run("UserPromptSubmit", "", "comment-watch.mjs", "other-session"), null);
|
|
149
|
+
const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse);
|
|
150
|
+
assert.ok(calls.some(call => call.args.some(arg => arg.includes("ArentInc/other")) && call.config === undefined));
|
|
151
|
+
assert.ok(calls.some(call => call.config === folder));
|
|
152
|
+
const customFolder = path.join(f.cwd, "custom-gh");
|
|
153
|
+
mkdirSync(customFolder);
|
|
154
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ github: { configDirs: { shawrylk: customFolder } } }));
|
|
155
|
+
f.run("UserPromptSubmit");
|
|
156
|
+
assert.match(readFileSync(f.calls, "utf8"), /custom-gh/);
|
|
157
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ commentWatch: false }));
|
|
158
|
+
f.update({ fail: true });
|
|
159
|
+
assert.equal(f.run("UserPromptSubmit"), null);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test("merge guard names unseen PR and linked issue comments until a prompt acknowledges them", (t) => {
|
|
163
|
+
const f = fixture(t);
|
|
164
|
+
const command = "gh pr merge 7 -R shawrylk/example";
|
|
165
|
+
f.update({ fail: true });
|
|
166
|
+
assert.match(f.run("PreToolUse", command, "merge-guard.mjs").hookSpecificOutput.permissionDecisionReason, /could not be checked/);
|
|
167
|
+
f.update();
|
|
168
|
+
const denied = f.run("PreToolUse", command, "merge-guard.mjs").hookSpecificOutput;
|
|
169
|
+
assert.equal(denied.permissionDecision, "deny");
|
|
170
|
+
for (const id of [1, 2, 3, 5]) assert.match(denied.permissionDecisionReason, new RegExp(`Comment ${id}`));
|
|
171
|
+
assert.equal(f.run("PreToolUse", command, "merge-guard.mjs").hookSpecificOutput.permissionDecision, "deny");
|
|
172
|
+
f.run("UserPromptSubmit");
|
|
173
|
+
const passed = f.run("PreToolUse", command, "merge-guard.mjs");
|
|
174
|
+
assert.notEqual(passed?.hookSpecificOutput?.permissionDecision, "deny", JSON.stringify(passed));
|
|
175
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ commentWatch: false }));
|
|
176
|
+
assert.notEqual(f.run("PreToolUse", command, "merge-guard.mjs", "other-session")?.hookSpecificOutput?.permissionDecision, "deny");
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test("combined message flags and numbered commands register watches in both shells", () => {
|
|
180
|
+
for (const tool_name of ["Bash", "PowerShell"]) {
|
|
181
|
+
for (const flag of ["-am", "-qam", "-sm"]) {
|
|
182
|
+
assert.equal(watchedItems({ tool_name, tool_input: { command: `git commit ${flag} "Refs #9"` } }, "owner/repo")[0]?.number, 9);
|
|
183
|
+
}
|
|
184
|
+
for (const command of ["gh pr review 7 --approve", "gh pr edit https://github.com/owner/repo/pull/7 --title title", "gh issue reopen 7"]) {
|
|
185
|
+
assert.equal(watchedItems({ tool_name, tool_input: { command } }, "owner/repo")[0]?.number, 7);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test("only session-created URLs are skipped, including reviews and PRs", (t) => {
|
|
191
|
+
const f = fixture(t);
|
|
192
|
+
for (const [command, output] of [
|
|
193
|
+
['gh issue comment 4 --body "Comment 1"', 'https://github.com/comments/1'],
|
|
194
|
+
['gh pr review --approve', { id: 2, body: 'https://github.com/comments/4' }],
|
|
195
|
+
['gh api -X POST repos/shawrylk/example/pulls/7/comments -f body="Comment 3"', { output: '{"id":3}' }],
|
|
196
|
+
['gh pr create --body "Fixes #4"', 'https://github.com/shawrylk/example/pull/7'],
|
|
197
|
+
]) f.run("PostToolUse", command, "comment-watch.mjs", "session-a", output);
|
|
198
|
+
const output = JSON.stringify(f.run("UserPromptSubmit"));
|
|
199
|
+
assert.doesNotMatch(output, /Comment [123]\b/);
|
|
200
|
+
assert.match(output, /Comment 4/);
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test("full reads acknowledge only the comment kinds their output contains", (t) => {
|
|
204
|
+
for (const [command, seen] of [
|
|
205
|
+
["gh issue view 4 --comments", [1]],
|
|
206
|
+
["gh api repos/shawrylk/example/issues/4/comments", [1]],
|
|
207
|
+
["gh api repos/shawrylk/example/issues/comments/1", [1]],
|
|
208
|
+
["gh api -X GET repos/shawrylk/example/issues/4", []],
|
|
209
|
+
["gh api -X POST repos/shawrylk/example/issues/4/comments", []],
|
|
210
|
+
["gh pr view 7 --comments", [2, 4]],
|
|
211
|
+
["gh api repos/shawrylk/example/pulls/7/comments", [3]],
|
|
212
|
+
["gh api repos/shawrylk/example/pulls/7/reviews", [2]],
|
|
213
|
+
["gh api repos/shawrylk/example/pulls/comments/3", [3]],
|
|
214
|
+
["gh api repos/shawrylk/example/pulls/7", []],
|
|
215
|
+
["gh api repos/shawrylk/example/pulls/7/reviews/2", []],
|
|
216
|
+
]) {
|
|
217
|
+
const f = fixture(t);
|
|
218
|
+
for (const row of f.rows) row.body = `Comment ${row.id} ` + "x".repeat(850) + "hidden request";
|
|
219
|
+
f.update();
|
|
220
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
221
|
+
const output = JSON.stringify(f.run("UserPromptSubmit"));
|
|
222
|
+
assert.match(output, /truncated/i, command);
|
|
223
|
+
assert.match(output, /gh api repos\/shawrylk\/example\/pulls\/7\/comments --paginate/, command);
|
|
224
|
+
assert.doesNotMatch(output, /hidden request/, command);
|
|
225
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
|
|
226
|
+
assert.equal(f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs")?.hookSpecificOutput?.permissionDecision, "deny", command);
|
|
227
|
+
f.run("PostToolUse", command, "comment-watch.mjs", "session-a", { exit_code: 1 });
|
|
228
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/i, command);
|
|
229
|
+
f.run("PostToolUse", command);
|
|
230
|
+
const remaining = JSON.stringify(f.run("UserPromptSubmit"));
|
|
231
|
+
for (const row of f.rows) assert.equal(remaining.includes(`Comment ${row.id} `), !seen.includes(row.id), command);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
for (const command of [
|
|
236
|
+
"cd /home/shawry/Documents/GitHub/architecture-kit; gh api repos/shawrylk/architecture-kit/issues/236/comments --paginate --jq '.[-1].body' | tail -c 600",
|
|
237
|
+
"gh api repos/shawrylk/architecture-kit/issues/236/comments --paginate --jq '.[].id'",
|
|
238
|
+
"gh api repos/shawrylk/architecture-kit/issues/236/comments --paginate -q '.[].id'",
|
|
239
|
+
"gh api repos/shawrylk/architecture-kit/issues/236/comments --paginate --template '{{range .}}{{.id}}{{end}}'",
|
|
240
|
+
"gh api repos/shawrylk/architecture-kit/issues/236/comments --paginate -t '{{range .}}{{.id}}{{end}}'",
|
|
241
|
+
"gh api --template 'repos/other/project/issues/9/comments' repos/shawrylk/architecture-kit/issues/236/comments --paginate",
|
|
242
|
+
]) test(`Bash full reads acknowledge pending stamps: ${command}`, (t) => {
|
|
243
|
+
const f = fixture(t);
|
|
244
|
+
f.rows[0].endpoint = "issues/236/comments";
|
|
245
|
+
f.rows[0].body = "x".repeat(850);
|
|
246
|
+
f.update();
|
|
247
|
+
f.run("PostToolUse", "gh issue view 236 -R shawrylk/architecture-kit");
|
|
248
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
|
|
249
|
+
const ledgerPath = path.join(f.cwd, ".git", "qc", `comment-watch-${createHash("sha256").update("session-a").digest("hex")}.jsonl`);
|
|
250
|
+
const records = () => readFileSync(ledgerPath, "utf8").split("\n").filter(Boolean).map(JSON.parse);
|
|
251
|
+
const pending = records().flatMap(record => record.pending ?? []);
|
|
252
|
+
assert.equal(pending.length, 1);
|
|
253
|
+
assert.ok(!records().some(record => record.seen?.includes(pending[0].stamp)));
|
|
254
|
+
f.run("PostToolUse", command, "comment-watch.mjs", "session-a", {
|
|
255
|
+
stdout: "1", stderr: "", interrupted: false, isImage: false,
|
|
256
|
+
}, "Bash");
|
|
257
|
+
assert.ok(records().some(record => record.seen?.includes(pending[0].stamp)));
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("review flags preserve the state and body in both shells", (t) => {
|
|
261
|
+
for (const tool of ["Bash", "PowerShell"]) {
|
|
262
|
+
for (const [flags, body, state] of [
|
|
263
|
+
["-ab LGTM", "LGTM", "APPROVED"],
|
|
264
|
+
["-abLGTM", "LGTM", "APPROVED"],
|
|
265
|
+
["-abconfirm", "confirm", "APPROVED"],
|
|
266
|
+
["-rbproblem", "problem", "CHANGES_REQUESTED"],
|
|
267
|
+
["-cbm", "m", "COMMENTED"],
|
|
268
|
+
["-ab-r", "-r", "APPROVED"],
|
|
269
|
+
["-ab=LGTM", "LGTM", "APPROVED"],
|
|
270
|
+
['-ab="line1\nline2"', "line1\nline2", "APPROVED"],
|
|
271
|
+
["-ab 'line1\nline2'", "line1\nline2", "APPROVED"],
|
|
272
|
+
['-ab "line1\nline2"', "line1\nline2", "APPROVED"],
|
|
273
|
+
["-rbNo", "No", "CHANGES_REQUESTED"],
|
|
274
|
+
['-rb "x"', "x", "CHANGES_REQUESTED"],
|
|
275
|
+
["-c -b x", "x", "COMMENTED"],
|
|
276
|
+
["--approve --body x", "x", "APPROVED"],
|
|
277
|
+
['-ab "-rb"', "-rb", "APPROVED"],
|
|
278
|
+
["-a -b=text", "text", "APPROVED"],
|
|
279
|
+
["--request-changes --body=text", "text", "CHANGES_REQUESTED"],
|
|
280
|
+
["-a", "", "APPROVED"],
|
|
281
|
+
["-r", "", "CHANGES_REQUESTED"],
|
|
282
|
+
]) {
|
|
283
|
+
const f = fixture(t);
|
|
284
|
+
const command = `gh pr review 7 ${flags}`;
|
|
285
|
+
f.run("PreToolUse", command, "comment-watch.mjs", "session-a", "", tool);
|
|
286
|
+
f.run("PostToolUse", command, "comment-watch.mjs", "session-a", "", tool);
|
|
287
|
+
const dir = path.join(f.cwd, ".git", "qc");
|
|
288
|
+
const file = readdirSync(dir).find(name => name.startsWith("comment-watch-"));
|
|
289
|
+
const records = readFileSync(path.join(dir, file), "utf8").trim().split("\n").filter(Boolean).map(JSON.parse);
|
|
290
|
+
const review = records.find(record => record.review)?.review;
|
|
291
|
+
assert.equal(review?.state, state, `${tool}: ${flags}`);
|
|
292
|
+
assert.equal(review?.bodyHash, createHash("sha256").update(body).digest("hex"), `${tool}: ${flags}`);
|
|
293
|
+
assert.equal(review?.empty, body.length === 0, `${tool}: ${flags}`);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test("pending session reviews match body or empty-body state once after the start", (t) => {
|
|
299
|
+
const f = fixture(t);
|
|
300
|
+
for (const [id, body, state, submitted_at] of [
|
|
301
|
+
[20, "session body", "COMMENTED", "2000-01-01T00:00:00Z"],
|
|
302
|
+
[21, "other body", "COMMENTED", "2099-01-01T00:00:00Z"],
|
|
303
|
+
[22, "session body", "COMMENTED", "2099-01-01T00:00:00Z"],
|
|
304
|
+
[23, "", "CHANGES_REQUESTED", "2099-01-01T00:00:00Z"],
|
|
305
|
+
[24, "", "APPROVED", "2099-01-01T00:00:00Z"],
|
|
306
|
+
[25, "", "APPROVED", "2099-01-01T00:00:00Z"],
|
|
307
|
+
]) f.rows.push({ id, body, state, submitted_at, endpoint: "pulls/7/reviews", html_url: `https://github.com/reviews/${id}` });
|
|
308
|
+
f.update();
|
|
309
|
+
f.run("PreToolUse", 'gh pr review 7 --comment --body "session body"');
|
|
310
|
+
f.run("PostToolUse", 'gh pr review 7 --comment --body "session body"');
|
|
311
|
+
f.run("PreToolUse", "gh pr review 7 --approve");
|
|
312
|
+
f.run("PostToolUse", "gh pr review 7 --approve");
|
|
313
|
+
const output = JSON.stringify(f.run("UserPromptSubmit"));
|
|
314
|
+
for (const id of [20, 21, 23, 25]) assert.ok(output.includes(`/reviews/${id}`));
|
|
315
|
+
for (const id of [22, 24]) assert.ok(!output.includes(`/reviews/${id}`));
|
|
316
|
+
f.rows.find(row => row.id === 22).body = "edited session review";
|
|
317
|
+
f.rows.push({ ...f.rows.find(row => row.id === 22), id: 26, html_url: "https://github.com/reviews/26", body: "session body" });
|
|
318
|
+
f.update();
|
|
319
|
+
const next = JSON.stringify(f.run("UserPromptSubmit"));
|
|
320
|
+
assert.doesNotMatch(next, /edited session review/);
|
|
321
|
+
assert.match(next, /reviews\/26/);
|
|
322
|
+
});
|
|
323
|
+
|
|
324
|
+
test("references inside code spans and fences name no issue", () => {
|
|
325
|
+
const body = "Fixes #5. The button is `#128282`.\n\n```css\ncolor: #1d6496; /* #9 */\n```\n\nRefs #6";
|
|
326
|
+
const items = watchedItems({ tool_name: "Bash", tool_input: { command: `gh pr create --body '${body}'` } }, "owner/repo", PARSERS.Bash);
|
|
327
|
+
assert.deepEqual(items.map(({ number }) => number).sort((a, b) => a - b), [5, 6]);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
test("a PR body read at merge skips hex colours in code spans", (t) => {
|
|
331
|
+
const f = fixture(t);
|
|
332
|
+
f.update({ body: "Fixes #4. Teal is `#128282`." });
|
|
333
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
334
|
+
f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
|
|
335
|
+
assert.doesNotMatch(readFileSync(f.calls, "utf8"), /issues\/128282/);
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
test("merge targets include commit-only references and previously watched issues", (t) => {
|
|
339
|
+
const f = fixture(t);
|
|
340
|
+
f.rows.length = 0;
|
|
341
|
+
f.rows.push(...[9, 10].map(id => ({ id, endpoint: `issues/${id}/comments`, body: `Comment ${id}`, html_url: `https://github.com/comments/${id}` })));
|
|
342
|
+
f.update({ commits: [{ messageHeadline: "Fixes #9", messageBody: "Refs #11" }] });
|
|
343
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
344
|
+
f.run("PostToolUse", 'git commit -m "Refs #10"');
|
|
345
|
+
const output = f.run("PreToolUse", "gh pr merge 7", "merge-guard.mjs");
|
|
346
|
+
assert.match(JSON.stringify(output), /Comment 9/);
|
|
347
|
+
assert.match(JSON.stringify(output), /Comment 10/);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
test("full reads acknowledge truncated previews from a merge refusal or Stop", (t) => {
|
|
351
|
+
for (const event of ["PreToolUse", "Stop"]) {
|
|
352
|
+
const f = fixture(t);
|
|
353
|
+
f.rows[0].body = "x".repeat(850);
|
|
354
|
+
f.update();
|
|
355
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
356
|
+
assert.match(JSON.stringify(f.run(event, "gh pr merge 7", event === "PreToolUse" ? "merge-guard.mjs" : "comment-watch.mjs")), /truncated/);
|
|
357
|
+
f.run("PostToolUse", "gh issue view 4 --comments");
|
|
358
|
+
assert.doesNotMatch(JSON.stringify(f.run("UserPromptSubmit")), /truncated/);
|
|
359
|
+
}
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
test("API merges check comments with dispatch on and off in both shells", (t) => {
|
|
363
|
+
const f = fixture(t);
|
|
364
|
+
for (const dispatch of [false, true]) {
|
|
365
|
+
writeFileSync(path.join(f.cwd, "qc.config.json"), JSON.stringify({ swarm: dispatch ? { dispatch: {} } : {} }));
|
|
366
|
+
for (const tool of ["Bash", "PowerShell"]) {
|
|
367
|
+
for (const command of ["gh api -X PUT repos/shawrylk/example/pulls/7/merge", 'gh api graphql -f query=\'mutation { mergePullRequest(input: {pullRequestId: "PR_7"}) { clientMutationId } }\'']) {
|
|
368
|
+
const output = f.run("PreToolUse", command, "merge-guard.mjs", "session-a", "", tool);
|
|
369
|
+
assert.equal(output?.hookSpecificOutput?.permissionDecision, "deny");
|
|
370
|
+
assert.match(JSON.stringify(output), /Comment 4/);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
test("polls use one issue request and three PR requests in parallel", (t) => {
|
|
377
|
+
const f = fixture(t);
|
|
378
|
+
f.run("PostToolUse", "gh pr view 7");
|
|
379
|
+
writeFileSync(f.calls, "");
|
|
380
|
+
f.update({ delay: 250 });
|
|
381
|
+
f.run("UserPromptSubmit");
|
|
382
|
+
const calls = readFileSync(f.calls, "utf8").trim().split("\n").map(JSON.parse).filter(call => call.start);
|
|
383
|
+
assert.equal(calls.length, 5);
|
|
384
|
+
assert.ok(Math.max(...calls.map(call => call.start)) - Math.min(...calls.map(call => call.start)) < 200);
|
|
385
|
+
assert.ok(calls.every(call => call.args.includes("--paginate")));
|
|
386
|
+
assert.ok(calls.every(call => !call.args.includes("--slurp")));
|
|
387
|
+
f.rows[0].body = "Retry this item";
|
|
388
|
+
f.update({ failEndpoint: "issues/4/comments" });
|
|
389
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /shawrylk\/example#4 could not be checked; retry on the next prompt/);
|
|
390
|
+
f.update();
|
|
391
|
+
assert.match(JSON.stringify(f.run("UserPromptSubmit")), /Retry this item/);
|
|
392
|
+
});
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pathMatcher } from "../glob.mjs";
|
|
6
|
+
import { findSecrets } from "./secret-patterns.mjs";
|
|
7
|
+
|
|
8
|
+
/** Fragment: reads the brief's explicit exceptions to the protected path policy. */
|
|
9
|
+
export function protectedAllow(brief) {
|
|
10
|
+
return [...brief.matchAll(/^Protected:[ \t]*(.*)$/gm)]
|
|
11
|
+
.flatMap((match) => match[1].split(",").map((glob) => glob.trim()).filter(Boolean));
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Fragment: decodes Git's quoted patch paths, including control bytes. */
|
|
15
|
+
function patchPath(header) {
|
|
16
|
+
let file = header.replace(/\t$/, "");
|
|
17
|
+
if (file.startsWith('"')) {
|
|
18
|
+
file = JSON.parse(file.replace(/\\([0-7]{1,3})/g, (_, octal) => `\\u${parseInt(octal, 8).toString(16).padStart(4, "0")}`)
|
|
19
|
+
.replace(/\\a/g, "\\u0007").replace(/\\v/g, "\\u000b"));
|
|
20
|
+
}
|
|
21
|
+
return file === "/dev/null" ? null : file.slice(2);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Branch: judges added lines and protected paths without disclosing their contents. */
|
|
25
|
+
export function checkDiff(diff, { protectedPaths = [], role, allow = [], paths = [] } = {}) {
|
|
26
|
+
const findings = [];
|
|
27
|
+
const changed = new Set(paths);
|
|
28
|
+
let file;
|
|
29
|
+
let addedLine = 0;
|
|
30
|
+
let inHunk = false;
|
|
31
|
+
let columns = 1;
|
|
32
|
+
for (const line of diff.split("\n")) {
|
|
33
|
+
if (/^diff --(?:git|cc|combined) /.test(line)) {
|
|
34
|
+
file = undefined;
|
|
35
|
+
inHunk = false;
|
|
36
|
+
} else if (!inHunk && (line.startsWith("--- ") || line.startsWith("+++ "))) {
|
|
37
|
+
const parsed = patchPath(line.slice(4));
|
|
38
|
+
if (parsed !== null) { file = parsed; changed.add(file); }
|
|
39
|
+
} else if (/^@@+ /.test(line)) {
|
|
40
|
+
const hunk = /^(@{2,}) .*?\+(\d+)(?:,\d+)? \1/.exec(line);
|
|
41
|
+
if (!hunk) throw new Error("cannot parse the guard diff hunk");
|
|
42
|
+
columns = hunk[1].length - 1;
|
|
43
|
+
addedLine = Number(hunk[2]);
|
|
44
|
+
inHunk = true;
|
|
45
|
+
} else if (inHunk && line.startsWith("+".repeat(columns))) {
|
|
46
|
+
if (file === undefined) throw new Error("cannot identify the guard diff path");
|
|
47
|
+
const content = line.slice(columns);
|
|
48
|
+
const rules = findSecrets(content);
|
|
49
|
+
if (/^(<<<<<<< |>>>>>>> )/.test(content)) rules.push("conflict-marker");
|
|
50
|
+
for (const rule of rules) findings.push({ path: file, line: addedLine, rule });
|
|
51
|
+
addedLine += 1;
|
|
52
|
+
} else if (inHunk && line.length >= columns && /^[ +]+$/.test(line.slice(0, columns))) {
|
|
53
|
+
addedLine += 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (role === "implementer") {
|
|
57
|
+
const protectedPath = pathMatcher(protectedPaths);
|
|
58
|
+
const allowedPath = pathMatcher(allow);
|
|
59
|
+
for (const file of changed) {
|
|
60
|
+
if (protectedPath(file) && !allowedPath(file)) findings.push({ path: file, rule: "protected-path" });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return findings;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let mergeDiffOption;
|
|
67
|
+
|
|
68
|
+
// A resource: ends the Git process tree before the synchronous caller's deadline.
|
|
69
|
+
const remoteReadScript = `
|
|
70
|
+
const { spawn, spawnSync } = require("node:child_process");
|
|
71
|
+
const [deadline, cleanupBudget, command, ...args] = process.argv.slice(1);
|
|
72
|
+
const child = spawn(command, args, { stdio: ["ignore", "inherit", "inherit"], windowsHide: true, detached: process.platform !== "win32" });
|
|
73
|
+
child.on("error", () => process.exit(1));
|
|
74
|
+
child.on("close", (code) => process.exit(code ?? 1));
|
|
75
|
+
setTimeout(() => {
|
|
76
|
+
if (process.platform === "win32") {
|
|
77
|
+
spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: Number(cleanupBudget) });
|
|
78
|
+
child.kill();
|
|
79
|
+
} else {
|
|
80
|
+
try { process.kill(-child.pid, "SIGKILL"); } catch {}
|
|
81
|
+
}
|
|
82
|
+
process.exit(124);
|
|
83
|
+
}, Number(deadline)).unref();
|
|
84
|
+
`;
|
|
85
|
+
|
|
86
|
+
/** Resource: selects the merge diff format once for the process's Git version. */
|
|
87
|
+
function mergeDiff(root) {
|
|
88
|
+
if (mergeDiffOption === undefined) {
|
|
89
|
+
const version = /^git version (\d+)\.(\d+)/.exec(git(root, ["--version"]));
|
|
90
|
+
if (!version) throw new Error("cannot read the Git version for merge scanning");
|
|
91
|
+
const major = Number(version[1]);
|
|
92
|
+
const minor = Number(version[2]);
|
|
93
|
+
mergeDiffOption = major > 2 || (major === 2 && minor >= 36) ? "--diff-merges=remerge" : "--cc";
|
|
94
|
+
}
|
|
95
|
+
return mergeDiffOption;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Resource: reads Git without external diff drivers, text converters, or rename folding. */
|
|
99
|
+
function git(root, args, input) {
|
|
100
|
+
const remote = args[0] === "ls-remote";
|
|
101
|
+
const words = ["-c", "core.quotePath=false", ...(root === null ? [] : ["-C", root]), ...args];
|
|
102
|
+
const directory = root === null ? mkdtempSync(path.join(os.tmpdir(), "qc-guard-base-")) : null;
|
|
103
|
+
try {
|
|
104
|
+
return execFileSync(remote ? process.execPath : "git",
|
|
105
|
+
remote ? ["-e", remoteReadScript, "--", "24000", "5000", "git", ...words] : words, {
|
|
106
|
+
encoding: "utf8", input, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024, windowsHide: true,
|
|
107
|
+
...(directory === null ? {} : { cwd: directory }),
|
|
108
|
+
...(remote ? { timeout: 30_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" } } : {}),
|
|
109
|
+
});
|
|
110
|
+
} finally {
|
|
111
|
+
if (directory !== null) rmSync(directory, { recursive: true, force: true });
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Resource: reads the effective origin URL without opening an interactive prompt. */
|
|
116
|
+
function originUrl(root) {
|
|
117
|
+
try { return git(root, ["ls-remote", "--get-url", "origin"]).trim(); }
|
|
118
|
+
catch { return null; }
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Fragment: captures the commit boundary before the child runs. */
|
|
122
|
+
export function guardHead(root) {
|
|
123
|
+
git(root, ["rev-parse", "--git-dir"]);
|
|
124
|
+
try { return git(root, ["rev-parse", "--verify", "HEAD"]).trim(); }
|
|
125
|
+
catch (error) { if (error.status === 128) return null; throw error; }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Resource: records every ref tip, including remote-tracking refs, before the child runs. */
|
|
129
|
+
export function guardRefs(root) {
|
|
130
|
+
const refs = Object.fromEntries(git(root, ["for-each-ref", "--format=%(refname) %(objectname)"]).trim().split("\n").filter(Boolean).map((line) => line.split(" ")));
|
|
131
|
+
return { head: guardHead(root), branch: git(root, ["branch", "--show-current"]).trim(), refs: [...new Set(Object.values(refs))], recordedRefs: refs, originUrl: originUrl(root) };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Fragment: excludes commits reached by the configured remote base. */
|
|
135
|
+
function baseExclusion(root, base = "origin/main", recordedRefs = {}, recordedUrl) {
|
|
136
|
+
const branch = base.replace(/^origin\//, "");
|
|
137
|
+
const push = recordedUrl === undefined;
|
|
138
|
+
let recorded = recordedRefs[`refs/remotes/origin/${branch}`];
|
|
139
|
+
if (push) {
|
|
140
|
+
try { recorded = git(root, ["rev-parse", "--verify", `refs/remotes/origin/${branch}`]).trim(); }
|
|
141
|
+
catch { recorded = undefined; }
|
|
142
|
+
}
|
|
143
|
+
const fallback = recorded ? [recorded] : [];
|
|
144
|
+
const currentUrl = originUrl(root);
|
|
145
|
+
if (recordedUrl === null || currentUrl === null || (!push && currentUrl !== recordedUrl)) return fallback;
|
|
146
|
+
const url = push ? currentUrl : recordedUrl;
|
|
147
|
+
const remoteUrl = url.includes("://") || /^[^/\\]+:/.test(url) || path.isAbsolute(url)
|
|
148
|
+
? url : path.resolve(root, url);
|
|
149
|
+
try {
|
|
150
|
+
const refname = `refs/heads/${branch}`;
|
|
151
|
+
const tip = git(null, ["ls-remote", remoteUrl, refname]).trim().split(/\r?\n/)
|
|
152
|
+
.map((line) => line.split(/\s+/)).find(([, ref]) => ref === refname)?.[0];
|
|
153
|
+
return tip ? [tip] : [];
|
|
154
|
+
} catch {
|
|
155
|
+
return fallback;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Branch: scans every commit added during one run, including intermediate commits. */
|
|
160
|
+
export function checkRunCommits(root, before, options) {
|
|
161
|
+
const head = typeof before === "object" && before !== null ? before.head : before;
|
|
162
|
+
if (head) git(root, ["merge-base", "--is-ancestor", head, "HEAD"]);
|
|
163
|
+
const refs = typeof before === "object" && before !== null ? before.refs : [];
|
|
164
|
+
const branch = options.branch ?? git(root, ["branch", "--show-current"]).trim();
|
|
165
|
+
const runRefs = branch ? [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`] : [];
|
|
166
|
+
const tips = Object.fromEntries(git(root, ["for-each-ref", "--format=%(refname) %(objectname)", ...runRefs]).trim().split("\n").filter(Boolean).map((line) => line.split(" ")));
|
|
167
|
+
const revisions = [...(guardHead(root) ? ["HEAD"] : []), ...runRefs.map((ref) => tips[ref]).filter(Boolean)];
|
|
168
|
+
return scanCommits(root, revisions, [...refs, ...(head ? [head] : [])], options, before?.recordedRefs, before?.originUrl);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Pipeline: scans the selected commits with one shared content and path policy. */
|
|
172
|
+
function scanCommits(root, revisions, excluded, options, recordedRefs, recordedUrl) {
|
|
173
|
+
const boundary = new Set([...excluded, ...baseExclusion(root, options.base, recordedRefs, recordedUrl)]);
|
|
174
|
+
const input = [...new Set(revisions), ...[...boundary].map((oid) => `^${oid}`)].join("\n") + "\n";
|
|
175
|
+
const commits = git(root, ["rev-list", "--reverse", "--parents", "--stdin"], input).trim().split("\n").filter(Boolean);
|
|
176
|
+
const findings = [];
|
|
177
|
+
for (const entry of commits) {
|
|
178
|
+
const [commit, ...parents] = entry.split(" ");
|
|
179
|
+
const args = ["show", "--format=", "--root", ...(parents.length > 1 ? [mergeDiff(root)] : []), "--src-prefix=a/", "--dst-prefix=b/", "--no-ext-diff", "--no-textconv", "--no-renames"];
|
|
180
|
+
const paths = git(root, [...args, "--name-only", "-z", commit, "--"]).split("\0").filter(Boolean);
|
|
181
|
+
const diff = git(root, [...args, "--unified=0", "--no-color", commit, "--"]);
|
|
182
|
+
findings.push(...checkDiff(diff, { ...options, paths }).map((finding) => ({ ...finding, commit })));
|
|
183
|
+
}
|
|
184
|
+
return findings;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Fragment: formats locations and rule names while keeping secret values out of logs. */
|
|
188
|
+
export const findingName = ({ path, line, rule, commit }) => `${commit ? `${commit} ` : ""}${path}${line ? `:${line}` : ""}: ${rule}`;
|
|
189
|
+
|
|
190
|
+
/** Trigger: refuses staged findings before the commit can leave the index. */
|
|
191
|
+
export function runCommitGuard(config, { env = process.env, say = (line) => console.error(line), argv = process.argv.slice(3) } = {}) {
|
|
192
|
+
try {
|
|
193
|
+
const options = { protectedPaths: config.guard.protectedPaths, role: env.QC_ROLE, allow: protectedAllow(`Protected: ${env.QC_PROTECTED_ALLOW ?? ""}`), base: config.worktree?.base };
|
|
194
|
+
if (argv.length) {
|
|
195
|
+
const [mode, local, remote] = argv;
|
|
196
|
+
if (mode !== "--push" || argv.length !== 3 || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(local) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(remote)) throw new Error("expected --push <local oid> <remote oid>");
|
|
197
|
+
const findings = scanCommits(config.root, [local], /^0+$/.test(remote) ? [] : [remote], options);
|
|
198
|
+
for (const finding of findings) say(`qc commit-guard: guard refused: ${findingName(finding)}`);
|
|
199
|
+
return findings.length ? 4 : 0;
|
|
200
|
+
}
|
|
201
|
+
const mergeFile = path.resolve(config.root, git(config.root, ["rev-parse", "--git-path", "MERGE_HEAD"]).trim());
|
|
202
|
+
const parents = existsSync(mergeFile) ? ["HEAD", ...readFileSync(mergeFile, "utf8").trim().split(/\s+/)] : [null];
|
|
203
|
+
let findings;
|
|
204
|
+
for (const parent of parents) {
|
|
205
|
+
const args = ["diff", "--cached", "--src-prefix=a/", "--dst-prefix=b/", "--no-ext-diff", "--no-textconv", "--no-renames"];
|
|
206
|
+
const revision = parent ? [parent] : [];
|
|
207
|
+
const paths = git(config.root, [...args, "--name-only", "-z", ...revision, "--"]).split("\0").filter(Boolean);
|
|
208
|
+
const diff = git(config.root, [...args, "--unified=0", "--no-color", ...revision, "--"]);
|
|
209
|
+
const current = checkDiff(diff, { ...options, paths });
|
|
210
|
+
const keys = new Set(current.map(findingName));
|
|
211
|
+
findings = findings === undefined ? current : findings.filter((finding) => keys.has(findingName(finding)));
|
|
212
|
+
}
|
|
213
|
+
for (const finding of findings) say(`qc commit-guard: guard refused: ${findingName(finding)}`);
|
|
214
|
+
return findings.length ? 4 : 0;
|
|
215
|
+
} catch (error) {
|
|
216
|
+
say(`qc commit-guard: cannot check changes: ${error.message}`);
|
|
217
|
+
return 4;
|
|
218
|
+
}
|
|
219
|
+
}
|