architecture-harness 0.25.1 → 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 +2 -18
- package/src/cli/ask.mjs +42 -0
- package/src/cli/ask.test.mjs +40 -0
- package/src/cli/check-commands.mjs +104 -7
- package/src/cli/check-commands.test.mjs +281 -7
- package/src/cli/check-full.test.mjs +152 -0
- package/src/cli/check.mjs +113 -0
- package/src/cli/check.test.mjs +45 -0
- package/src/cli/child-run.mjs +7 -2
- package/src/cli/child-run.test.mjs +17 -2
- package/src/cli/ci-failures.mjs +47 -9
- package/src/cli/ci-failures.test.mjs +116 -10
- package/src/cli/ci-preview.mjs +62 -0
- package/src/cli/ci-preview.test.mjs +85 -0
- package/src/cli/ci-state.mjs +2 -2
- package/src/cli/ci-state.test.mjs +8 -8
- package/src/cli/ci-template.test.mjs +79 -1
- package/src/cli/codex-implement.mjs +373 -44
- package/src/cli/codex-implement.test.mjs +775 -14
- package/src/cli/codex-limit.test.mjs +1 -1
- 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 +3 -3
- package/src/cli/commit-guard.test.mjs +9 -3
- package/src/cli/diff-shape.mjs +162 -0
- package/src/cli/diff-shape.test.mjs +200 -0
- package/src/cli/dispatch-guard.test.mjs +7 -7
- package/src/cli/dispatch-reminder.mjs +18 -8
- package/src/cli/dispatch-reminder.test.mjs +46 -10
- 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/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 +5 -3
- package/src/cli/gh-merge-command.test.mjs +4 -0
- package/src/cli/gh-run.mjs +50 -7
- package/src/cli/gh-run.test.mjs +35 -5
- package/src/cli/git-read.mjs +2 -1
- package/src/cli/integrate-tree.mjs +47 -0
- package/src/cli/integrate.mjs +35 -26
- package/src/cli/integration-lane.mjs +3 -5
- package/src/cli/integration-lane.test.mjs +2 -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/locked-tests.mjs +134 -0
- package/src/cli/locked-tests.test.mjs +188 -0
- package/src/cli/merge-guard.mjs +96 -43
- package/src/cli/merge-guard.test.mjs +272 -111
- 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/overview.mjs +131 -0
- package/src/cli/overview.test.mjs +137 -0
- package/src/cli/platform-risk.mjs +46 -0
- package/src/cli/platform-risk.test.mjs +38 -0
- package/src/cli/pr-guard.mjs +128 -0
- package/src/cli/pr-guard.test.mjs +154 -0
- package/src/cli/qc.mjs +76 -20
- package/src/cli/qc.test.mjs +35 -1
- package/src/cli/retry-failed.mjs +3 -1
- package/src/cli/run-log.mjs +73 -0
- package/src/cli/run-log.test.mjs +121 -0
- package/src/cli/skill-length.test.mjs +8 -0
- package/src/cli/tools.mjs +49 -0
- package/src/cli/tools.test.mjs +89 -0
- package/src/cli/watch.mjs +21 -8
- package/src/cli/watch.test.mjs +45 -21
- package/src/cli/work-order-guard.mjs +2 -1
- package/src/cli/workflow-hooks.test.mjs +1 -1
- package/src/cli/workflow-settings.mjs +3 -2
- package/src/cli/workflow-settings.test.mjs +11 -1
- package/src/config.mjs +64 -2
- package/src/config.test.mjs +93 -20
- package/src/consumer-package.test.mjs +3 -18
- package/src/descriptions.mjs +1 -0
- package/src/eslint/index.mjs +2 -0
- package/src/eslint/preset.mjs +12 -1
- package/src/eslint/preset.test.mjs +1 -1
- package/src/eslint/rules/timeless-comment.mjs +92 -0
- package/src/eslint/rules.test.mjs +34 -0
- package/src/gates/plain-language.mjs +396 -0
- package/src/gates/plain-language.test.mjs +210 -0
- package/src/global-skills.test.mjs +0 -1
- package/templates/docs/enforcement.md +12 -2
- package/templates/github/workflows/ci.yml +51 -4
- package/src/cli/screens-discovery.mjs +0 -60
- package/src/cli/screens.mjs +0 -85
- package/src/cli/stack.mjs +0 -14
- package/src/cli/throwaway-db.mjs +0 -133
- package/src/cli/throwaway-db.test.mjs +0 -137
- 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 -176
- 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 -41
- 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 -138
- 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 -79
- package/src/screens/stack-auth.browser-test.mjs +0 -30
- package/src/screens/stack-auth.mjs +0 -107
- 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 -60
- 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
|
+
});
|
package/src/cli/commit-guard.mjs
CHANGED
|
@@ -68,13 +68,13 @@ let mergeDiffOption;
|
|
|
68
68
|
// A resource: ends the Git process tree before the synchronous caller's deadline.
|
|
69
69
|
const remoteReadScript = `
|
|
70
70
|
const { spawn, spawnSync } = require("node:child_process");
|
|
71
|
-
const [deadline, command, ...args] = process.argv.slice(1);
|
|
71
|
+
const [deadline, cleanupBudget, command, ...args] = process.argv.slice(1);
|
|
72
72
|
const child = spawn(command, args, { stdio: ["ignore", "inherit", "inherit"], windowsHide: true, detached: process.platform !== "win32" });
|
|
73
73
|
child.on("error", () => process.exit(1));
|
|
74
74
|
child.on("close", (code) => process.exit(code ?? 1));
|
|
75
75
|
setTimeout(() => {
|
|
76
76
|
if (process.platform === "win32") {
|
|
77
|
-
spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout:
|
|
77
|
+
spawnSync("taskkill", ["/PID", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: Number(cleanupBudget) });
|
|
78
78
|
child.kill();
|
|
79
79
|
} else {
|
|
80
80
|
try { process.kill(-child.pid, "SIGKILL"); } catch {}
|
|
@@ -102,7 +102,7 @@ function git(root, args, input) {
|
|
|
102
102
|
const directory = root === null ? mkdtempSync(path.join(os.tmpdir(), "qc-guard-base-")) : null;
|
|
103
103
|
try {
|
|
104
104
|
return execFileSync(remote ? process.execPath : "git",
|
|
105
|
-
remote ? ["-e", remoteReadScript, "--", "
|
|
105
|
+
remote ? ["-e", remoteReadScript, "--", "24000", "5000", "git", ...words] : words, {
|
|
106
106
|
encoding: "utf8", input, stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024, windowsHide: true,
|
|
107
107
|
...(directory === null ? {} : { cwd: directory }),
|
|
108
108
|
...(remote ? { timeout: 30_000, env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" } } : {}),
|
|
@@ -450,9 +450,12 @@ for (const platform of ["Windows", "POSIX"]) test(`a stalled ${platform} remote
|
|
|
450
450
|
server.stdout.once("data", (chunk) => resolve(Number(chunk.toString().trim())));
|
|
451
451
|
});
|
|
452
452
|
let timer;
|
|
453
|
+
let armSocketTimer;
|
|
453
454
|
const closed = new Promise((resolve, reject) => {
|
|
454
455
|
server.stdout.on("data", (chunk) => { if (chunk.toString().includes("closed")) resolve(); });
|
|
455
|
-
|
|
456
|
+
armSocketTimer = () => {
|
|
457
|
+
timer = setTimeout(() => reject(new Error("the remote transport kept its socket open")), 10_000);
|
|
458
|
+
};
|
|
456
459
|
});
|
|
457
460
|
t.after(() => clearTimeout(timer));
|
|
458
461
|
const r = repo(t);
|
|
@@ -467,13 +470,16 @@ for (const platform of ["Windows", "POSIX"]) test(`a stalled ${platform} remote
|
|
|
467
470
|
interceptGit(t, (command, args, options, execute) => {
|
|
468
471
|
if (args.includes("ls-remote") && !args.includes("--get-url")) {
|
|
469
472
|
assert.equal(command, process.execPath);
|
|
470
|
-
|
|
473
|
+
assert.deepEqual(args.slice(2, 6), ["--", "24000", "5000", "git"]);
|
|
474
|
+
return execute(command, args.map((word, index) => index === 3 ? "1000" : word), options);
|
|
471
475
|
}
|
|
472
476
|
return execute(command, args, options);
|
|
473
477
|
});
|
|
474
478
|
const started = Date.now();
|
|
475
479
|
assert.deepEqual(checkRunCommits(r.root, before, { base: "main" }).map((finding) => finding.commit), [bad]);
|
|
476
|
-
|
|
480
|
+
armSocketTimer();
|
|
481
|
+
const bound = 1000 + 5000 + 2000;
|
|
482
|
+
assert.ok(Date.now() - started < bound);
|
|
477
483
|
await closed;
|
|
478
484
|
});
|
|
479
485
|
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { lstatSync, readFileSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const normalize = (file) => file.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
6
|
+
const splitNames = (text) => text.split("\0").filter(Boolean);
|
|
7
|
+
|
|
8
|
+
/** Fragment: matches owned files, folder boundaries and the brief's globs. */
|
|
9
|
+
function ownership(paths) {
|
|
10
|
+
const patterns = paths.map(normalize).flatMap((file) => {
|
|
11
|
+
const name = file.replace(/\/$/, "");
|
|
12
|
+
return file.includes("*") ? [file] : [name, `${name}/**`];
|
|
13
|
+
}).map((glob) => {
|
|
14
|
+
// Each recursive directory segment can independently consume zero or more folders.
|
|
15
|
+
const body = glob.replace(/[.+?^${}()|[\]\\]/g, "\\$&")
|
|
16
|
+
.replace(/\*\*\/|\*\*|\*/g, (token) => token === "**/" ? "(?:[^/]+/)*" : token === "**" ? ".*" : "[^/]*");
|
|
17
|
+
return new RegExp(`^${body}$`, process.platform === "win32" ? "i" : "");
|
|
18
|
+
});
|
|
19
|
+
return (file) => patterns.some((pattern) => pattern.test(file));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Fragment: parses NUL-delimited numstat without Git's quoted-path ambiguity. */
|
|
23
|
+
function changedLines(text, totals) {
|
|
24
|
+
for (const entry of splitNames(text)) {
|
|
25
|
+
const match = /^(\d+|-)\t(\d+|-)\t([\s\S]+)$/.exec(entry);
|
|
26
|
+
if (!match) continue;
|
|
27
|
+
const count = (Number(match[1]) || 0) + (Number(match[2]) || 0);
|
|
28
|
+
totals.set(match[3], Math.max(totals.get(match[3]) ?? 0, count));
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Fragment: manifest failures identify the file, without printing its contents. */
|
|
33
|
+
function manifest(text, file) {
|
|
34
|
+
try {
|
|
35
|
+
const value = JSON.parse(text);
|
|
36
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error();
|
|
37
|
+
for (const key of ["dependencies", "devDependencies"]) {
|
|
38
|
+
if (value[key] !== undefined && (!value[key] || typeof value[key] !== "object" || Array.isArray(value[key]))) throw new Error();
|
|
39
|
+
}
|
|
40
|
+
return value;
|
|
41
|
+
} catch {
|
|
42
|
+
throw new Error(`${file}: invalid package manifest JSON`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Branch: new dependency keys (including aliases) need their exact names in Design. */
|
|
47
|
+
function dependencyProblems(file, originalOf, versions, design) {
|
|
48
|
+
const problems = new Set();
|
|
49
|
+
const approved = new Set((design.match(/[@\w][@\w./-]*/g) ?? []).flatMap((name) => [name, name.replace(/\.+$/, "")]));
|
|
50
|
+
for (const { text, tip } of versions) {
|
|
51
|
+
const original = originalOf(tip);
|
|
52
|
+
const current = manifest(text, file);
|
|
53
|
+
for (const section of ["dependencies", "devDependencies"]) {
|
|
54
|
+
for (const name of Object.keys(current[section] ?? {})) {
|
|
55
|
+
if (!Object.hasOwn(original[section] ?? {}, name) && !approved.has(name)) problems.add(`${file}: added ${section} ${name} is absent from Design`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return [...problems];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Branch: checks every changed path, manifest addition and added/deleted line against a frozen brief. */
|
|
63
|
+
export function checkDiffShape({ worktree, base, baseRef, paths, design = "", maxDiffLines = 400 }) {
|
|
64
|
+
const git = (...args) => execFileSync("git", ["--literal-pathspecs", ...args], { cwd: worktree, encoding: "utf8", stdio: ["pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 * 1024 });
|
|
65
|
+
const empty = git("hash-object", "-w", "-t", "tree", "--stdin").trim();
|
|
66
|
+
const contains = (ancestor, revision) => {
|
|
67
|
+
try { git("merge-base", "--is-ancestor", ancestor, revision); return true; }
|
|
68
|
+
catch (error) { if (error.status === 1) return false; throw error; }
|
|
69
|
+
};
|
|
70
|
+
const hasHead = git("rev-parse", "--revs-only", "HEAD").trim();
|
|
71
|
+
const boundaries = new Map();
|
|
72
|
+
const boundaryOf = (revision) => {
|
|
73
|
+
let tip;
|
|
74
|
+
if (base && baseRef && revision) {
|
|
75
|
+
try { tip = git("merge-base", revision, baseRef).trim(); } catch { /* Missing or invalid base refs keep the frozen boundary. */ }
|
|
76
|
+
}
|
|
77
|
+
if (!tip) return { boundary: base || empty };
|
|
78
|
+
if (boundaries.has(tip)) return boundaries.get(tip);
|
|
79
|
+
let result = { boundary: base };
|
|
80
|
+
if (!contains(tip, base)) {
|
|
81
|
+
let merged;
|
|
82
|
+
try { merged = git("merge-tree", "--write-tree", base, tip); }
|
|
83
|
+
catch (error) { if (error.status !== 1) throw error; merged = error.stdout; }
|
|
84
|
+
result = { boundary: merged.split("\n")[0].trim(), tip };
|
|
85
|
+
}
|
|
86
|
+
boundaries.set(tip, result);
|
|
87
|
+
return result;
|
|
88
|
+
};
|
|
89
|
+
const { boundary, tip } = boundaryOf(hasHead ? "HEAD" : undefined);
|
|
90
|
+
// Incoming commits belong to the base; retain the run's commits on either side of the merge.
|
|
91
|
+
const commits = hasHead ? git("rev-list", "--reverse", ...(base ? [`${base}..HEAD`] : ["HEAD"]), ...(tip ? [`^${tip}`] : [])).trim().split("\n").filter(Boolean) : [];
|
|
92
|
+
const changed = new Set();
|
|
93
|
+
const totals = new Map();
|
|
94
|
+
const versions = new Map();
|
|
95
|
+
const collect = (args, revision, versionTip) => {
|
|
96
|
+
const files = splitNames(git("diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", ...args, "--"));
|
|
97
|
+
changedLines(git("diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--numstat", "-z", ...args, "--"), totals);
|
|
98
|
+
for (const file of files) {
|
|
99
|
+
changed.add(file);
|
|
100
|
+
if (path.posix.basename(file) !== "package.json" || revision === undefined) continue;
|
|
101
|
+
const exists = splitNames(git("ls-tree", "-r", "--name-only", "-z", revision, "--", file)).includes(file);
|
|
102
|
+
if (exists) {
|
|
103
|
+
const list = versions.get(file) ?? [];
|
|
104
|
+
list.push({ text: git("show", `${revision}:${file}`), tip: versionTip }); versions.set(file, list);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
for (const commit of commits) {
|
|
109
|
+
const commitBoundary = tip ? boundaryOf(commit) : { boundary };
|
|
110
|
+
collect([commitBoundary.boundary, commit], commit, commitBoundary.tip);
|
|
111
|
+
}
|
|
112
|
+
collect(["--cached", boundary]);
|
|
113
|
+
collect([boundary]);
|
|
114
|
+
const staged = splitNames(git("diff", "--cached", "--no-renames", "--name-only", "-z", boundary, "--"));
|
|
115
|
+
for (const file of staged.filter((name) => path.posix.basename(name) === "package.json")) {
|
|
116
|
+
const entries = splitNames(git("ls-files", "-z", "--", file));
|
|
117
|
+
if (entries.includes(file)) {
|
|
118
|
+
const list = versions.get(file) ?? []; list.push({ text: git("show", `:${file}`), tip }); versions.set(file, list);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const untracked = splitNames(git("ls-files", "--others", "--exclude-standard", "-z"));
|
|
122
|
+
for (const file of untracked) {
|
|
123
|
+
changed.add(file);
|
|
124
|
+
const target = path.join(worktree, file);
|
|
125
|
+
const stat = lstatSync(target);
|
|
126
|
+
const text = stat.isSymbolicLink() ? "link\n" : readFileSync(target, "utf8");
|
|
127
|
+
const lines = text.includes("\0") ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
|
128
|
+
totals.set(file, (totals.get(file) ?? 0) + lines);
|
|
129
|
+
}
|
|
130
|
+
const owns = ownership(Array.isArray(paths) ? paths : [paths]);
|
|
131
|
+
const problems = [...changed].filter((file) => !owns(normalize(file))).map((file) => `${file}: outside Paths`);
|
|
132
|
+
for (const file of [...changed].filter((name) => path.posix.basename(name) === "package.json")) {
|
|
133
|
+
try {
|
|
134
|
+
const originals = new Map();
|
|
135
|
+
const originalOf = (versionTip) => {
|
|
136
|
+
if (originals.has(versionTip)) return originals.get(versionTip);
|
|
137
|
+
const original = {};
|
|
138
|
+
// A merge tree can contain conflict markers; read dependency keys from its parents instead.
|
|
139
|
+
for (const revision of [base || empty, ...(versionTip ? [versionTip] : [])]) {
|
|
140
|
+
const exists = splitNames(git("ls-tree", "-r", "--name-only", "-z", revision, "--", file)).includes(file);
|
|
141
|
+
if (!exists) continue;
|
|
142
|
+
const value = manifest(git("show", `${revision}:${file}`), file);
|
|
143
|
+
for (const section of ["dependencies", "devDependencies"]) {
|
|
144
|
+
original[section] = { ...original[section], ...value[section] };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
originals.set(versionTip, original);
|
|
148
|
+
return original;
|
|
149
|
+
};
|
|
150
|
+
const list = versions.get(file) ?? [];
|
|
151
|
+
try {
|
|
152
|
+
const target = path.join(worktree, file);
|
|
153
|
+
if (lstatSync(target).isSymbolicLink()) throw new Error(`${file}: package manifest must be a regular file`);
|
|
154
|
+
list.push({ text: readFileSync(target, "utf8"), tip });
|
|
155
|
+
} catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
156
|
+
problems.push(...dependencyProblems(file, originalOf, list, design));
|
|
157
|
+
} catch (error) { problems.push(error.message); }
|
|
158
|
+
}
|
|
159
|
+
const lines = [...totals.values()].reduce((sum, count) => sum + count, 0);
|
|
160
|
+
if (lines > maxDiffLines) problems.push(`${lines} changed lines exceeds codex.maxDiffLines ${maxDiffLines}; split the issue`);
|
|
161
|
+
return { problems: [...new Set(problems)] };
|
|
162
|
+
}
|