@imdeadpool/guardex 7.1.1 → 8.1.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/README.md +115 -324
- package/package.json +23 -5
- package/skills/gitguardex/SKILL.md +83 -3
- package/src/agents/finish.js +15 -0
- package/src/ci-init/index.js +0 -1
- package/src/cli/args.js +137 -3
- package/src/cli/commands/branch.js +267 -14
- package/src/cli/commands/claude.js +15 -0
- package/src/cli/commands/doctor.js +26 -0
- package/src/cli/commands/onboard.js +293 -0
- package/src/cli/commands/prompt.js +15 -3
- package/src/cli/commands/review.js +18 -0
- package/src/cli/commands/setup.js +8 -6
- package/src/cli/commands/status.js +12 -0
- package/src/cli/main.js +2 -0
- package/src/cli/shared-locks.js +304 -0
- package/src/context.js +21 -3
- package/src/core/runtime.js +33 -1
- package/src/doctor/index.js +58 -5
- package/src/finish/heartbeat.js +169 -0
- package/src/finish/index.js +106 -4
- package/src/finish/progress.js +262 -0
- package/src/finish/review-gate.js +453 -32
- package/src/github-api.js +59 -0
- package/src/mcp/collect.js +87 -12
- package/src/output/index.js +210 -0
- package/src/pr-checks.js +121 -0
- package/src/pr-review.js +581 -51
- package/src/pr.js +143 -21
- package/src/provider-binary.js +101 -0
- package/src/review-diff.js +116 -0
- package/src/review-fix.js +229 -0
- package/src/sandbox/index.js +11 -5
- package/src/scaffold/index.js +4 -16
- package/src/shared-git-state.js +566 -0
- package/templates/AGENTS.multiagent-safety.md +63 -11
- package/templates/AGENTS.multiagent-safety.min.md +1 -0
- package/templates/codex/skills/gitguardex/SKILL.md +83 -3
- package/templates/githooks/post-checkout +4 -9
- package/templates/githooks/pre-commit +17 -1
- package/templates/github/workflows/README.md +30 -23
- package/templates/scripts/agent-autofinish-watch.sh +280 -0
- package/templates/scripts/agent-branch-finish.sh +354 -23
- package/templates/scripts/agent-branch-start.sh +49 -22
- package/templates/scripts/agent-claude-stop-finish.sh +194 -0
- package/templates/scripts/agent-file-locks.py +167 -24
- package/templates/scripts/agent-preflight.sh +14 -2
- package/templates/scripts/agent-stalled-report.sh +40 -0
- package/templates/scripts/codex-agent.sh +10 -63
- package/templates/github/workflows/cr.yml +0 -46
package/src/pr.js
CHANGED
|
@@ -15,6 +15,8 @@ const {
|
|
|
15
15
|
hasOriginRemote,
|
|
16
16
|
detectDefaultBaseBranch,
|
|
17
17
|
} = require('./git');
|
|
18
|
+
const { repoApiPath } = require('./github-api');
|
|
19
|
+
const { FAILING_CONCLUSIONS, summarizeStatusCheckRollup } = require('./pr-checks');
|
|
18
20
|
|
|
19
21
|
const DEFAULT_POLL_INTERVAL_MS = 5_000;
|
|
20
22
|
const DEFAULT_POLL_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -64,7 +66,7 @@ function findOpenPrForBranch(repoRoot, branch) {
|
|
|
64
66
|
'pr', 'list',
|
|
65
67
|
'--head', branch,
|
|
66
68
|
'--state', 'open',
|
|
67
|
-
'--json', 'number,url,state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefName,baseRefName,title,statusCheckRollup',
|
|
69
|
+
'--json', 'number,url,state,isDraft,mergeable,mergeStateStatus,reviewDecision,headRefName,headRefOid,baseRefName,title,statusCheckRollup',
|
|
68
70
|
'--limit', '5',
|
|
69
71
|
]);
|
|
70
72
|
if (!result.ok) {
|
|
@@ -190,12 +192,12 @@ function openPullRequest(options) {
|
|
|
190
192
|
});
|
|
191
193
|
}
|
|
192
194
|
|
|
193
|
-
//
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
195
|
+
// Push BEFORE looking for an existing PR, not only on the create path. The
|
|
196
|
+
// merge gate calls this on every run and then reviews the PR's REMOTE head,
|
|
197
|
+
// so skipping the push once a PR exists made a rerun re-review the old head:
|
|
198
|
+
// the gate's own "fix the findings, rerun" loop could never converge, and it
|
|
199
|
+
// reported the identical finding while the fix sat unpushed on disk
|
|
200
|
+
// (lifted.sk-storefront #512). `push: false` still opts out.
|
|
199
201
|
if (options.push !== false) {
|
|
200
202
|
const push = pushBranch(repoRoot, branch);
|
|
201
203
|
if (!push.ok) {
|
|
@@ -203,6 +205,12 @@ function openPullRequest(options) {
|
|
|
203
205
|
}
|
|
204
206
|
}
|
|
205
207
|
|
|
208
|
+
// Try to find an existing open PR first.
|
|
209
|
+
const existing = findOpenPrForBranch(repoRoot, branch);
|
|
210
|
+
if (existing) {
|
|
211
|
+
return { created: false, pr: existing };
|
|
212
|
+
}
|
|
213
|
+
|
|
206
214
|
const base = options.base || detectDefaultBaseBranch(repoRoot);
|
|
207
215
|
const title = options.title || defaultPrTitleFromCommit(repoRoot, branch);
|
|
208
216
|
const body = options.body || defaultPrBodyFromCommits(repoRoot, branch, base);
|
|
@@ -241,19 +249,7 @@ function getPullRequestStatus(repoRoot, branch) {
|
|
|
241
249
|
const pr = findOpenPrForBranch(repoRoot, branch);
|
|
242
250
|
if (!pr) return null;
|
|
243
251
|
|
|
244
|
-
const
|
|
245
|
-
const summary = checks.reduce(
|
|
246
|
-
(acc, check) => {
|
|
247
|
-
const state = String(check?.conclusion || check?.status || '').toUpperCase();
|
|
248
|
-
if (state === 'SUCCESS') acc.success += 1;
|
|
249
|
-
else if (state === 'FAILURE' || state === 'ERROR' || state === 'TIMED_OUT') acc.failed += 1;
|
|
250
|
-
else if (state === 'PENDING' || state === 'IN_PROGRESS' || state === 'QUEUED') acc.pending += 1;
|
|
251
|
-
else if (state === 'CANCELLED') acc.cancelled += 1;
|
|
252
|
-
else acc.other += 1;
|
|
253
|
-
return acc;
|
|
254
|
-
},
|
|
255
|
-
{ success: 0, failed: 0, pending: 0, cancelled: 0, other: 0, total: checks.length },
|
|
256
|
-
);
|
|
252
|
+
const rollup = summarizeStatusCheckRollup(pr.statusCheckRollup);
|
|
257
253
|
|
|
258
254
|
return {
|
|
259
255
|
number: pr.number,
|
|
@@ -265,8 +261,121 @@ function getPullRequestStatus(repoRoot, branch) {
|
|
|
265
261
|
reviewDecision: pr.reviewDecision,
|
|
266
262
|
title: pr.title,
|
|
267
263
|
head: pr.headRefName,
|
|
264
|
+
// The commit the rollup above describes. Callers that pushed during the run
|
|
265
|
+
// need it to tell "CI is green on my code" from "CI is green on the commit
|
|
266
|
+
// my push replaced".
|
|
267
|
+
headSha: pr.headRefOid || '',
|
|
268
268
|
base: pr.baseRefName,
|
|
269
|
-
checks: summary,
|
|
269
|
+
checks: rollup.summary,
|
|
270
|
+
failedNames: rollup.failedNames,
|
|
271
|
+
supersededChecks: rollup.supersededCount,
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Check outcomes recorded against `ref` (a branch name or SHA).
|
|
277
|
+
*
|
|
278
|
+
* Returns `{ failing, total }` — `total` matters as much as `failing`, because
|
|
279
|
+
* "no checks ran here" and "checks ran and all passed" are different facts and
|
|
280
|
+
* only the second one is a usable baseline. Covers check-runs (GitHub Actions)
|
|
281
|
+
* and legacy commit statuses (external CI).
|
|
282
|
+
*
|
|
283
|
+
* Best effort: an unreachable API yields `{ failing: ∅, total: 0 }`, which the
|
|
284
|
+
* caller reads as "unknown", never as "green".
|
|
285
|
+
*/
|
|
286
|
+
function checkOutcomes(repoRoot, ref, runner = run) {
|
|
287
|
+
const failing = new Set();
|
|
288
|
+
let total = 0;
|
|
289
|
+
const collect = (result) => {
|
|
290
|
+
if (result.status !== 0) return;
|
|
291
|
+
for (const line of String(result.stdout || '').split('\n')) {
|
|
292
|
+
if (!line.trim()) continue;
|
|
293
|
+
const [state, ...rest] = line.split('\t');
|
|
294
|
+
const name = rest.join('\t').trim();
|
|
295
|
+
if (!name) continue;
|
|
296
|
+
total += 1;
|
|
297
|
+
if (FAILING_CONCLUSIONS.has(String(state || '').trim().toUpperCase())) {
|
|
298
|
+
failing.add(name);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
collect(runner(GH_BIN, [
|
|
304
|
+
'api', '--paginate',
|
|
305
|
+
repoApiPath(repoRoot, `commits/${ref}/check-runs?per_page=100`, runner),
|
|
306
|
+
'-q', '.check_runs[] | select(.status == "completed") | "\\(.conclusion)\\t\\(.name)"',
|
|
307
|
+
], { cwd: repoRoot, timeout: 60_000, allowFailure: true }));
|
|
308
|
+
|
|
309
|
+
collect(runner(GH_BIN, [
|
|
310
|
+
'api',
|
|
311
|
+
repoApiPath(repoRoot, `commits/${ref}/status`, runner),
|
|
312
|
+
'-q', '.statuses[] | "\\(.state)\\t\\(.context)"',
|
|
313
|
+
], { cwd: repoRoot, timeout: 60_000, allowFailure: true }));
|
|
314
|
+
|
|
315
|
+
return { failing, total };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Head SHA of the most recently merged PR into `baseBranch`, or ''. */
|
|
319
|
+
function lastMergedPrHead(repoRoot, baseBranch, runner = run) {
|
|
320
|
+
const result = runner(GH_BIN, [
|
|
321
|
+
'api',
|
|
322
|
+
// GitHub cannot sort by merge time; `updated` desc correlates with it far
|
|
323
|
+
// better than the `created` desc default, which would rank a long-lived PR
|
|
324
|
+
// by when it was opened.
|
|
325
|
+
repoApiPath(
|
|
326
|
+
repoRoot,
|
|
327
|
+
`pulls?base=${encodeURIComponent(baseBranch)}&state=closed&sort=updated&direction=desc&per_page=10`,
|
|
328
|
+
runner,
|
|
329
|
+
),
|
|
330
|
+
'-q', '[.[] | select(.merged_at != null)][0].head.sha // ""',
|
|
331
|
+
], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
|
|
332
|
+
if (result.status !== 0) return '';
|
|
333
|
+
return String(result.stdout || '').trim();
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* The set of check names already failing on the base — the baseline a PR's
|
|
338
|
+
* failures are measured against.
|
|
339
|
+
*
|
|
340
|
+
* Reads TWO sources and unions them:
|
|
341
|
+
*
|
|
342
|
+
* 1. the base branch's own HEAD, and
|
|
343
|
+
* 2. the head of the most recently merged PR into that base.
|
|
344
|
+
*
|
|
345
|
+
* Both are needed. Many repos (this one included) trigger CI only on
|
|
346
|
+
* `pull_request`, so the base branch HEAD never gets the jobs that matter —
|
|
347
|
+
* yet it may still carry an unrelated check-run or two, which makes any
|
|
348
|
+
* "does the base have checks?" heuristic answer yes and hide the gap. The last
|
|
349
|
+
* merged PR is the newest CI verdict on what is now base code, so a failure
|
|
350
|
+
* there is by definition already in the base.
|
|
351
|
+
*
|
|
352
|
+
* @returns {{failing: Set<string>, source: string}} `source` is for logging.
|
|
353
|
+
*/
|
|
354
|
+
function baselineFailures(repoRoot, baseBranch, runner = run) {
|
|
355
|
+
const sources = [];
|
|
356
|
+
const failing = new Set();
|
|
357
|
+
let observed = 0;
|
|
358
|
+
|
|
359
|
+
const direct = checkOutcomes(repoRoot, baseBranch, runner);
|
|
360
|
+
if (direct.total > 0) {
|
|
361
|
+
observed += direct.total;
|
|
362
|
+
for (const name of direct.failing) failing.add(name);
|
|
363
|
+
sources.push(`branch '${baseBranch}'`);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const sha = lastMergedPrHead(repoRoot, baseBranch, runner);
|
|
367
|
+
if (sha) {
|
|
368
|
+
const merged = checkOutcomes(repoRoot, sha, runner);
|
|
369
|
+
if (merged.total > 0) {
|
|
370
|
+
observed += merged.total;
|
|
371
|
+
for (const name of merged.failing) failing.add(name);
|
|
372
|
+
sources.push(`last merged PR (${sha.slice(0, 7)})`);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return {
|
|
377
|
+
failing,
|
|
378
|
+
source: observed > 0 ? sources.join(' + ') : 'unavailable',
|
|
270
379
|
};
|
|
271
380
|
}
|
|
272
381
|
|
|
@@ -294,6 +403,16 @@ function markPullRequestReady(repoRoot, prNumber) {
|
|
|
294
403
|
};
|
|
295
404
|
}
|
|
296
405
|
|
|
406
|
+
function markPullRequestDraft(repoRoot, prNumber) {
|
|
407
|
+
const result = run(GH_BIN, ['pr', 'ready', '--undo', String(prNumber)], {
|
|
408
|
+
cwd: repoRoot, allowFailure: true,
|
|
409
|
+
});
|
|
410
|
+
return {
|
|
411
|
+
ok: result.status === 0,
|
|
412
|
+
output: ((result.stdout || '') + (result.stderr || '')).trim(),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
|
|
297
416
|
/**
|
|
298
417
|
* Watch a PR's CI + merge state until it merges, fails, or times out.
|
|
299
418
|
*
|
|
@@ -372,8 +491,11 @@ module.exports = {
|
|
|
372
491
|
pushBranch,
|
|
373
492
|
openPullRequest,
|
|
374
493
|
getPullRequestStatus,
|
|
494
|
+
checkOutcomes,
|
|
495
|
+
baselineFailures,
|
|
375
496
|
enableAutoMerge,
|
|
376
497
|
markPullRequestReady,
|
|
498
|
+
markPullRequestDraft,
|
|
377
499
|
watchPullRequest,
|
|
378
500
|
resolveRepoAndBranch,
|
|
379
501
|
defaultPrTitleFromCommit,
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
const os = require('node:os');
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const AGENTS = new Set(['claude', 'codex']);
|
|
6
|
+
const CODEX_REVIEW_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh']);
|
|
7
|
+
const DEFAULT_CODEX_REVIEW_EFFORT = 'medium';
|
|
8
|
+
|
|
9
|
+
/** Keep bounded code-assist runs independent of a user's interactive effort. */
|
|
10
|
+
function codexReviewEffort(env = process.env) {
|
|
11
|
+
const requested = String(env.GUARDEX_REVIEW_CODEX_EFFORT || '').trim().toLowerCase();
|
|
12
|
+
return CODEX_REVIEW_EFFORTS.has(requested) ? requested : DEFAULT_CODEX_REVIEW_EFFORT;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function cueShimDir(env = process.env) {
|
|
16
|
+
const configHome = env.XDG_CONFIG_HOME && String(env.XDG_CONFIG_HOME).trim()
|
|
17
|
+
? String(env.XDG_CONFIG_HOME).trim()
|
|
18
|
+
: path.join(os.homedir(), '.config');
|
|
19
|
+
return path.resolve(configHome, 'cue', 'shims');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function isExecutableFile(candidate) {
|
|
23
|
+
try {
|
|
24
|
+
const stat = fs.statSync(candidate);
|
|
25
|
+
return stat.isFile() && (stat.mode & 0o111) !== 0;
|
|
26
|
+
} catch (_error) {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function smallTextFile(candidate) {
|
|
32
|
+
try {
|
|
33
|
+
const stat = fs.statSync(candidate);
|
|
34
|
+
if (!stat.isFile() || stat.size >= 64_000) return '';
|
|
35
|
+
return fs.readFileSync(candidate, 'utf8');
|
|
36
|
+
} catch (_error) {
|
|
37
|
+
return '';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function isCueAgentShim(content, provider) {
|
|
42
|
+
const text = String(content || '');
|
|
43
|
+
return text.includes('cue')
|
|
44
|
+
&& new RegExp(`\\blaunch\\s+${provider}\\b`).test(text);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function isCodexGuard(content) {
|
|
48
|
+
const text = String(content || '');
|
|
49
|
+
return text.includes('codex-guard') && text.includes('find_real_codex');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function providerOverride(provider, env = process.env) {
|
|
53
|
+
const key = provider === 'claude' ? 'GUARDEX_REVIEW_CLAUDE_BIN' : 'GUARDEX_REVIEW_CODEX_BIN';
|
|
54
|
+
const explicit = String(env[key] || '').trim();
|
|
55
|
+
if (explicit) return explicit;
|
|
56
|
+
|
|
57
|
+
if (provider === 'claude') {
|
|
58
|
+
for (const fallbackKey of ['CUE_REAL_CLAUDE', 'CLAUDE_CODE_EXECPATH']) {
|
|
59
|
+
const candidate = String(env[fallbackKey] || '').trim();
|
|
60
|
+
if (candidate && isExecutableFile(candidate)) return candidate;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if (provider === 'codex') {
|
|
65
|
+
const candidate = String(env.CUE_REAL_CODEX || '').trim();
|
|
66
|
+
if (candidate && isExecutableFile(candidate)) return candidate;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return '';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function findRealProviderBin(provider, env = process.env) {
|
|
73
|
+
if (!AGENTS.has(provider)) return '';
|
|
74
|
+
const dirs = String(env.PATH || '').split(path.delimiter).filter(Boolean);
|
|
75
|
+
const shimDir = cueShimDir(env);
|
|
76
|
+
for (const dir of dirs) {
|
|
77
|
+
if (path.resolve(dir) === shimDir) continue;
|
|
78
|
+
const candidate = path.join(dir, provider);
|
|
79
|
+
if (!isExecutableFile(candidate)) continue;
|
|
80
|
+
const content = smallTextFile(candidate);
|
|
81
|
+
if (content && isCueAgentShim(content, provider)) continue;
|
|
82
|
+
if (provider === 'codex' && content && isCodexGuard(content)) continue;
|
|
83
|
+
return candidate;
|
|
84
|
+
}
|
|
85
|
+
return '';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function resolveProviderBin(provider, env = process.env) {
|
|
89
|
+
const normalized = String(provider || '').trim().toLowerCase();
|
|
90
|
+
const override = providerOverride(normalized, env);
|
|
91
|
+
if (override) return override;
|
|
92
|
+
return findRealProviderBin(normalized, env) || normalized;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
module.exports = {
|
|
96
|
+
codexReviewEffort,
|
|
97
|
+
cueShimDir,
|
|
98
|
+
findRealProviderBin,
|
|
99
|
+
isCueAgentShim,
|
|
100
|
+
resolveProviderBin,
|
|
101
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Unified-diff -> the RIGHT-side line numbers GitHub will accept an inline
|
|
2
|
+
// review comment on.
|
|
3
|
+
//
|
|
4
|
+
// Why this exists: `POST /pulls/{n}/reviews` rejects the ENTIRE review with 422
|
|
5
|
+
// when a single comment anchors outside the diff. In gate mode that throw turns
|
|
6
|
+
// into a merge block, so one hallucinated line number from the review provider
|
|
7
|
+
// would block a perfectly good PR. Findings are validated against this map and
|
|
8
|
+
// the unanchorable ones are demoted to the summary body instead of dropped.
|
|
9
|
+
|
|
10
|
+
const HUNK_RE = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
|
|
11
|
+
const GIT_HEADER_RE = /^diff --git a\/(.+) b\/(.+)$/;
|
|
12
|
+
|
|
13
|
+
function stripPathPrefix(raw) {
|
|
14
|
+
const value = String(raw || '').trim();
|
|
15
|
+
if (!value || value === '/dev/null') return '';
|
|
16
|
+
// git emits `+++ b/path`; `--src-prefix=`/`--no-prefix` builds emit a bare path.
|
|
17
|
+
return value.replace(/^[ab]\//, '');
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function addLine(map, filePath, line) {
|
|
21
|
+
let lines = map.get(filePath);
|
|
22
|
+
if (!lines) {
|
|
23
|
+
lines = new Set();
|
|
24
|
+
map.set(filePath, lines);
|
|
25
|
+
}
|
|
26
|
+
lines.add(line);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Parse a unified diff into `Map<path, Set<rightSideLine>>`.
|
|
31
|
+
*
|
|
32
|
+
* Hunk bodies are consumed by the exact old/new line counts declared in the
|
|
33
|
+
* `@@` header rather than by line-prefix sniffing, so a literal `+++ `/`--- `
|
|
34
|
+
* inside patched content is never misread as a file header.
|
|
35
|
+
*
|
|
36
|
+
* Both added and context lines are addressable: GitHub accepts a `side: RIGHT`
|
|
37
|
+
* comment anywhere inside a hunk, and being permissive here means fewer
|
|
38
|
+
* legitimate findings get demoted out of the inline view.
|
|
39
|
+
*/
|
|
40
|
+
function parseDiffLineMap(diff) {
|
|
41
|
+
const map = new Map();
|
|
42
|
+
let currentPath = '';
|
|
43
|
+
let newLine = 0;
|
|
44
|
+
let oldRemaining = 0;
|
|
45
|
+
let newRemaining = 0;
|
|
46
|
+
|
|
47
|
+
for (const raw of String(diff || '').split('\n')) {
|
|
48
|
+
if (oldRemaining <= 0 && newRemaining <= 0) {
|
|
49
|
+
// `diff --git` gives a provisional path so an emitter that omits the
|
|
50
|
+
// `+++` header still anchors; a real `+++` line overrides it.
|
|
51
|
+
const gitHeader = GIT_HEADER_RE.exec(raw);
|
|
52
|
+
if (gitHeader) {
|
|
53
|
+
currentPath = gitHeader[2].trim();
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (raw.startsWith('+++ ')) {
|
|
57
|
+
currentPath = stripPathPrefix(raw.slice(4).split('\t')[0]);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const hunk = HUNK_RE.exec(raw);
|
|
61
|
+
if (hunk) {
|
|
62
|
+
newLine = Number.parseInt(hunk[3], 10);
|
|
63
|
+
oldRemaining = hunk[2] === undefined ? 1 : Number.parseInt(hunk[2], 10);
|
|
64
|
+
newRemaining = hunk[4] === undefined ? 1 : Number.parseInt(hunk[4], 10);
|
|
65
|
+
}
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (raw.startsWith('\\')) continue; // ""
|
|
70
|
+
if (raw.startsWith('-')) {
|
|
71
|
+
oldRemaining -= 1;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (raw.startsWith('+')) {
|
|
75
|
+
if (currentPath) addLine(map, currentPath, newLine);
|
|
76
|
+
newLine += 1;
|
|
77
|
+
newRemaining -= 1;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
// Context line (leading space, or the bare empty line some emitters produce).
|
|
81
|
+
if (currentPath) addLine(map, currentPath, newLine);
|
|
82
|
+
newLine += 1;
|
|
83
|
+
oldRemaining -= 1;
|
|
84
|
+
newRemaining -= 1;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return map;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** True when `line` (and `startLine`, when set) can carry an inline comment. */
|
|
91
|
+
function isAnchored(lineMap, finding) {
|
|
92
|
+
const lines = lineMap.get(finding.path);
|
|
93
|
+
if (!lines || !lines.has(finding.line)) return false;
|
|
94
|
+
if (finding.startLine && !lines.has(finding.startLine)) return false;
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Split findings into the ones GitHub will accept inline and the ones that must
|
|
100
|
+
* be reported in the review summary instead.
|
|
101
|
+
*/
|
|
102
|
+
function partitionByAnchor(findings, diff) {
|
|
103
|
+
const lineMap = parseDiffLineMap(diff);
|
|
104
|
+
const anchored = [];
|
|
105
|
+
const unanchored = [];
|
|
106
|
+
for (const finding of findings) {
|
|
107
|
+
(isAnchored(lineMap, finding) ? anchored : unanchored).push(finding);
|
|
108
|
+
}
|
|
109
|
+
return { anchored, unanchored, lineMap };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
module.exports = {
|
|
113
|
+
parseDiffLineMap,
|
|
114
|
+
isAnchored,
|
|
115
|
+
partitionByAnchor,
|
|
116
|
+
};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// Auto-correct for code-assist findings.
|
|
2
|
+
//
|
|
3
|
+
// The review side only ever DESCRIBED problems; applying the fix was always a
|
|
4
|
+
// human click on a GitHub suggestion. This module closes that loop: it feeds the
|
|
5
|
+
// selected findings back to the provider in edit mode, inside the agent
|
|
6
|
+
// worktree, and commits whatever changed as one reviewable commit.
|
|
7
|
+
//
|
|
8
|
+
// Deliberate constraints:
|
|
9
|
+
// - never runs on a protected branch (fixes land on `agent/*`, like all agent work);
|
|
10
|
+
// - refuses a dirty tree, so unrelated working-tree WIP is never swept into the commit;
|
|
11
|
+
// - fixing is a SEPARATE provider invocation from reviewing, and the caller must
|
|
12
|
+
// re-review with a fresh run — a model must not grade its own homework;
|
|
13
|
+
// - no push, no merge: the finish flow still owns those.
|
|
14
|
+
|
|
15
|
+
const { run } = require('./core/runtime');
|
|
16
|
+
const { gitRun, currentBranchName, readProtectedBranches } = require('./git');
|
|
17
|
+
const { codexReviewEffort, resolveProviderBin } = require('./provider-binary');
|
|
18
|
+
|
|
19
|
+
const DEFAULT_FIX_TIMEOUT_MS = 15 * 60 * 1000;
|
|
20
|
+
const TOOL_PREFIX = '[gitguardex]';
|
|
21
|
+
const CODEX_AUTOMATION_ARGS = ['--ephemeral', '--ignore-user-config', '--ignore-rules'];
|
|
22
|
+
|
|
23
|
+
function resolveFixModel(model, env = process.env) {
|
|
24
|
+
const explicit = String(model || '').trim();
|
|
25
|
+
if (explicit) return explicit;
|
|
26
|
+
return String(env.GUARDEX_REVIEW_MODEL || '').trim();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function inheritCodexConfig(env = process.env) {
|
|
30
|
+
return ['1', 'true', 'yes', 'on'].includes(
|
|
31
|
+
String(env.GUARDEX_REVIEW_INHERIT_CODEX_CONFIG || '').trim().toLowerCase(),
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function commandForFix(provider, prompt, settings = {}) {
|
|
36
|
+
const cmd = String(settings.bin || '').trim() || provider;
|
|
37
|
+
const model = String(settings.model || '').trim();
|
|
38
|
+
if (provider === 'claude') {
|
|
39
|
+
// Print mode defaults to asking for permission; acceptEdits lets it write.
|
|
40
|
+
return {
|
|
41
|
+
cmd,
|
|
42
|
+
args: model
|
|
43
|
+
? ['--safe-mode', '--model', model, '-p', '--permission-mode', 'acceptEdits', prompt]
|
|
44
|
+
: ['--safe-mode', '-p', '--permission-mode', 'acceptEdits', prompt],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
// `codex exec` sandboxes to read-only by default; workspace-write allows edits
|
|
48
|
+
// inside the worktree and nowhere else.
|
|
49
|
+
const automationArgs = settings.inheritConfig === true ? [] : CODEX_AUTOMATION_ARGS;
|
|
50
|
+
const requestedEffort = settings.effort || process.env.GUARDEX_REVIEW_CODEX_EFFORT;
|
|
51
|
+
const effortArgs = settings.inheritConfig === true && !requestedEffort
|
|
52
|
+
? []
|
|
53
|
+
: ['-c', `model_reasoning_effort="${codexReviewEffort({ GUARDEX_REVIEW_CODEX_EFFORT: requestedEffort })}"`];
|
|
54
|
+
return {
|
|
55
|
+
cmd,
|
|
56
|
+
args: [
|
|
57
|
+
'exec', ...automationArgs, ...effortArgs,
|
|
58
|
+
...(model ? ['-m', model] : []),
|
|
59
|
+
'--sandbox', 'workspace-write', prompt,
|
|
60
|
+
],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function describeFinding(finding, index) {
|
|
65
|
+
const location = finding.startLine
|
|
66
|
+
? `${finding.path}:${finding.startLine}-${finding.line}`
|
|
67
|
+
: `${finding.path}:${finding.line}`;
|
|
68
|
+
const lines = [`${index + 1}. [${String(finding.severity).toUpperCase()}] ${location} — ${finding.message}`];
|
|
69
|
+
if (finding.suggestion) {
|
|
70
|
+
lines.push(' Proposed replacement for those lines:', ' ---', ...String(finding.suggestion).split('\n').map((l) => ` ${l}`), ' ---');
|
|
71
|
+
}
|
|
72
|
+
return lines.join('\n');
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function fixPrompt(findings) {
|
|
76
|
+
return [
|
|
77
|
+
'You are gitguardex-code-assist in FIX mode.',
|
|
78
|
+
'Apply the minimal source edits that resolve every finding below, in this repository.',
|
|
79
|
+
'Rules:',
|
|
80
|
+
'- Change only what a finding requires. No refactors, no reformatting, no unrelated cleanup.',
|
|
81
|
+
'- When a finding carries a proposed replacement, apply it unless it is wrong; then apply the correct minimal fix instead.',
|
|
82
|
+
'- If a finding is a false positive or cannot be fixed safely, leave that code untouched and say so in your final message.',
|
|
83
|
+
'- Do not run git commit, git push, or any git history command. Leave the changes in the working tree.',
|
|
84
|
+
'- Keep the project building: update call sites, imports, and tests that your edit breaks.',
|
|
85
|
+
'- Run only the smallest focused test needed for the edited surface. Never run the full test suite, a broad linter, or a build.',
|
|
86
|
+
'- Finish promptly: the finish flow runs the repository preflight and CI after this fix.',
|
|
87
|
+
'',
|
|
88
|
+
'Findings:',
|
|
89
|
+
...findings.map(describeFinding),
|
|
90
|
+
].join('\n');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Working-tree state as `{ tracked: string[], untracked: string[] }`.
|
|
95
|
+
*
|
|
96
|
+
* Uses `-z` so paths with spaces or non-ASCII characters arrive unquoted. A
|
|
97
|
+
* rename/copy entry carries its source path as an extra field, which is
|
|
98
|
+
* consumed and discarded — only the destination is a path we would stage.
|
|
99
|
+
*/
|
|
100
|
+
function treeState(repoRoot) {
|
|
101
|
+
const tracked = [];
|
|
102
|
+
const untracked = [];
|
|
103
|
+
const result = gitRun(repoRoot, ['status', '--porcelain', '-z'], { allowFailure: true });
|
|
104
|
+
if (result.status !== 0) return { tracked, untracked };
|
|
105
|
+
|
|
106
|
+
const fields = String(result.stdout || '').split('\0');
|
|
107
|
+
for (let index = 0; index < fields.length; index += 1) {
|
|
108
|
+
const entry = fields[index];
|
|
109
|
+
if (!entry || entry.length < 4) continue;
|
|
110
|
+
const status = entry.slice(0, 2);
|
|
111
|
+
const filePath = entry.slice(3);
|
|
112
|
+
if (status === '??') {
|
|
113
|
+
untracked.push(filePath);
|
|
114
|
+
} else {
|
|
115
|
+
tracked.push(filePath);
|
|
116
|
+
// Rename/copy entries are followed by the source path.
|
|
117
|
+
if (status.includes('R') || status.includes('C')) index += 1;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return { tracked, untracked };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function commitMessage(findings) {
|
|
124
|
+
const subject = `fix(review): address ${findings.length} code-assist finding(s)`;
|
|
125
|
+
const body = findings.map((f) => `- ${String(f.severity).toUpperCase()} ${f.path}:${f.line} ${f.message.split('\n')[0]}`);
|
|
126
|
+
return [subject, '', ...body].join('\n');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Run one auto-fix round for `findings`.
|
|
131
|
+
*
|
|
132
|
+
* @returns {{status: 'fixed'|'no-op'|'skipped', changedFiles: string[], sha?: string, reason?: string}}
|
|
133
|
+
* `no-op` means the provider ran but changed nothing (the caller should stop
|
|
134
|
+
* iterating rather than loop on an unfixable finding).
|
|
135
|
+
*/
|
|
136
|
+
function runReviewFix({
|
|
137
|
+
repoRoot,
|
|
138
|
+
provider = 'codex',
|
|
139
|
+
findings = [],
|
|
140
|
+
timeoutMs = DEFAULT_FIX_TIMEOUT_MS,
|
|
141
|
+
expectBranch = '',
|
|
142
|
+
model = '',
|
|
143
|
+
}, deps = {}) {
|
|
144
|
+
const runner = deps.run || run;
|
|
145
|
+
if (findings.length === 0) {
|
|
146
|
+
return { status: 'skipped', changedFiles: [], reason: 'no findings to fix' };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const branch = currentBranchName(repoRoot);
|
|
150
|
+
const protectedBranches = readProtectedBranches(repoRoot);
|
|
151
|
+
if (protectedBranches.includes(branch)) {
|
|
152
|
+
return {
|
|
153
|
+
status: 'skipped',
|
|
154
|
+
changedFiles: [],
|
|
155
|
+
reason: `refusing to auto-fix on protected branch '${branch}' — run from an agent worktree`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
// The caller resolved a worktree for a specific branch; if that resolution
|
|
159
|
+
// fell back to some other checkout, fixing here would edit the wrong branch.
|
|
160
|
+
if (expectBranch && expectBranch !== branch) {
|
|
161
|
+
return {
|
|
162
|
+
status: 'skipped',
|
|
163
|
+
changedFiles: [],
|
|
164
|
+
reason: `checkout is on '${branch}' but the fix targets '${expectBranch}'`,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
// Uncommitted TRACKED edits are the real hazard: `git add` would sweep them
|
|
168
|
+
// into the fix commit. Pre-existing untracked files (node_modules, scratch
|
|
169
|
+
// notes) are recorded instead of blocking, and simply never staged.
|
|
170
|
+
const before = treeState(repoRoot);
|
|
171
|
+
if (before.tracked.length > 0) {
|
|
172
|
+
return {
|
|
173
|
+
status: 'skipped',
|
|
174
|
+
changedFiles: [],
|
|
175
|
+
reason: `working tree has ${before.tracked.length} uncommitted change(s) — commit or stash first so the fix commit stays scoped`,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
const preExistingUntracked = new Set(before.untracked);
|
|
179
|
+
|
|
180
|
+
const selectedModel = resolveFixModel(model);
|
|
181
|
+
const command = commandForFix(provider, fixPrompt(findings), {
|
|
182
|
+
bin: resolveProviderBin(provider),
|
|
183
|
+
model: selectedModel,
|
|
184
|
+
inheritConfig: inheritCodexConfig(),
|
|
185
|
+
});
|
|
186
|
+
const startedAt = Date.now();
|
|
187
|
+
console.log(
|
|
188
|
+
`${TOOL_PREFIX} code-assist ${provider} auto-fix started for ${findings.length} finding(s)`
|
|
189
|
+
+ `${selectedModel ? ` with model ${selectedModel}` : ''}; provider progress follows`,
|
|
190
|
+
);
|
|
191
|
+
const result = runner(command.cmd, command.args, {
|
|
192
|
+
cwd: repoRoot,
|
|
193
|
+
timeout: timeoutMs,
|
|
194
|
+
// No provider output is parsed in fix mode. Inherit both streams so edits,
|
|
195
|
+
// tool calls, and progress remain visible to the parent Codex session.
|
|
196
|
+
stdio: ['ignore', 'inherit', 'inherit'],
|
|
197
|
+
});
|
|
198
|
+
if (result.status !== 0) {
|
|
199
|
+
throw new Error(`${provider} fix run failed${result.stderr ? `\n${result.stderr.trim()}` : ''}`);
|
|
200
|
+
}
|
|
201
|
+
console.log(
|
|
202
|
+
`${TOOL_PREFIX} code-assist ${provider} auto-fix completed in ${Math.round((Date.now() - startedAt) / 1000)}s`,
|
|
203
|
+
);
|
|
204
|
+
|
|
205
|
+
const after = treeState(repoRoot);
|
|
206
|
+
const changedFiles = [
|
|
207
|
+
...after.tracked,
|
|
208
|
+
...after.untracked.filter((filePath) => !preExistingUntracked.has(filePath)),
|
|
209
|
+
];
|
|
210
|
+
if (changedFiles.length === 0) {
|
|
211
|
+
return { status: 'no-op', changedFiles: [], reason: 'provider made no edits' };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Stage exactly what the fix touched — never `add -A`, which would also pick
|
|
215
|
+
// up the untracked files that were already sitting in the tree.
|
|
216
|
+
gitRun(repoRoot, ['add', '--', ...changedFiles]);
|
|
217
|
+
gitRun(repoRoot, ['commit', '-m', commitMessage(findings)]);
|
|
218
|
+
const sha = gitRun(repoRoot, ['rev-parse', 'HEAD'], { allowFailure: true }).stdout.trim();
|
|
219
|
+
return { status: 'fixed', changedFiles, sha };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
module.exports = {
|
|
223
|
+
DEFAULT_FIX_TIMEOUT_MS,
|
|
224
|
+
commandForFix,
|
|
225
|
+
fixPrompt,
|
|
226
|
+
inheritCodexConfig,
|
|
227
|
+
resolveFixModel,
|
|
228
|
+
runReviewFix,
|
|
229
|
+
};
|
package/src/sandbox/index.js
CHANGED
|
@@ -284,12 +284,18 @@ function cleanupProtectedBaseSandbox(repoRoot, metadata) {
|
|
|
284
284
|
if (isSpawnFailure(removeResult)) {
|
|
285
285
|
throw removeResult.error;
|
|
286
286
|
}
|
|
287
|
-
if (removeResult.status
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
287
|
+
if (removeResult.status === 0) {
|
|
288
|
+
result.worktree = 'removed';
|
|
289
|
+
} else {
|
|
290
|
+
// The path exists but git no longer tracks it as a registered worktree
|
|
291
|
+
// (common after a crash or a partial/manual cleanup). Treating this as
|
|
292
|
+
// fatal stranded the agent branch — the branch-delete step below never
|
|
293
|
+
// ran. Recover instead: prune stale worktree metadata, remove the
|
|
294
|
+
// leftover directory, and continue. Both operations are idempotent.
|
|
295
|
+
run('git', ['-C', repoRoot, 'worktree', 'prune'], { timeout: 20_000 });
|
|
296
|
+
fs.rmSync(metadata.worktreePath, { recursive: true, force: true });
|
|
297
|
+
result.worktree = 'pruned';
|
|
291
298
|
}
|
|
292
|
-
result.worktree = 'removed';
|
|
293
299
|
} else {
|
|
294
300
|
result.worktree = 'missing';
|
|
295
301
|
}
|