@imdeadpool/guardex 7.1.0 → 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 +122 -322
- package/package.json +25 -5
- package/scripts/prepublish-bump-version.js +191 -0
- package/skills/gitguardex/SKILL.md +83 -3
- package/src/agents/activity.js +279 -0
- package/src/agents/finish.js +15 -0
- package/src/ci-init/index.js +0 -1
- package/src/cli/args.js +203 -6
- package/src/cli/commands/agents.js +17 -0
- 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 +111 -12
- package/src/mcp/server.js +10 -4
- 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/agent-worktree-prep.js +9 -2
- package/src/scaffold/index.js +4 -16
- package/src/scaffold/provision-config.js +314 -0
- package/src/shared-git-state.js +566 -0
- package/src/terminal/kitty.js +20 -0
- package/src/terminal/tmux.js +9 -0
- package/templates/AGENTS.multiagent-safety.md +73 -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 +363 -26
- package/templates/scripts/agent-branch-start.sh +76 -25
- package/templates/scripts/agent-claude-stop-finish.sh +194 -0
- package/templates/scripts/agent-file-locks.py +390 -52
- 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
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
const { spawn: spawnProcess } = require('node:child_process');
|
|
2
|
+
const fs = require('node:fs');
|
|
3
|
+
|
|
4
|
+
const FRAMES = ['◐', '◓', '◑', '◒'];
|
|
5
|
+
const DEFAULT_INTERVAL_MS = 15_000;
|
|
6
|
+
|
|
7
|
+
function formatElapsed(elapsedMs) {
|
|
8
|
+
const numericElapsed = Number(elapsedMs);
|
|
9
|
+
const totalSeconds = Number.isFinite(numericElapsed)
|
|
10
|
+
? Math.max(0, Math.floor(numericElapsed / 1_000))
|
|
11
|
+
: 0;
|
|
12
|
+
const seconds = totalSeconds % 60;
|
|
13
|
+
const totalMinutes = Math.floor(totalSeconds / 60);
|
|
14
|
+
const minutes = totalMinutes % 60;
|
|
15
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
16
|
+
const twoDigits = (value) => String(value).padStart(2, '0');
|
|
17
|
+
return hours > 0
|
|
18
|
+
? `${hours}:${twoDigits(minutes)}:${twoDigits(seconds)}`
|
|
19
|
+
: `${twoDigits(minutes)}:${twoDigits(seconds)}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function renderHeartbeat({ index, total, label, detail, elapsedMs, frame = 0 }) {
|
|
23
|
+
const symbol = FRAMES[Math.abs(Number(frame) || 0) % FRAMES.length];
|
|
24
|
+
const normalizedDetail = String(detail || '').trim();
|
|
25
|
+
return `[gx:finish] ├─ ${symbol} ${index}/${total} ${label}`
|
|
26
|
+
+ `${normalizedDetail ? ` · ${normalizedDetail}` : ''}`
|
|
27
|
+
+ ` · ⏱ ${formatElapsed(elapsedMs)}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function processIsAlive(pid) {
|
|
31
|
+
try {
|
|
32
|
+
process.kill(pid, 0);
|
|
33
|
+
return true;
|
|
34
|
+
} catch (_error) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function normalizePositiveInteger(value, fallback) {
|
|
40
|
+
const parsed = Number(value);
|
|
41
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : fallback;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function runWorker(rawConfig) {
|
|
45
|
+
let config;
|
|
46
|
+
try {
|
|
47
|
+
config = JSON.parse(rawConfig);
|
|
48
|
+
} catch (_error) {
|
|
49
|
+
process.exitCode = 1;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const parentPid = normalizePositiveInteger(config.parentPid, 0);
|
|
54
|
+
const intervalMs = normalizePositiveInteger(config.intervalMs, DEFAULT_INTERVAL_MS);
|
|
55
|
+
const startAt = Number.isFinite(Number(config.startAt)) ? Number(config.startAt) : Date.now();
|
|
56
|
+
if (parentPid === 0) {
|
|
57
|
+
process.exitCode = 1;
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let lastSlot = 0;
|
|
62
|
+
const timer = setInterval(() => {
|
|
63
|
+
if (!processIsAlive(parentPid)) {
|
|
64
|
+
clearInterval(timer);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const elapsedMs = Math.max(0, Date.now() - startAt);
|
|
68
|
+
const slot = Math.floor(elapsedMs / intervalMs);
|
|
69
|
+
if (slot <= lastSlot) return;
|
|
70
|
+
lastSlot = slot;
|
|
71
|
+
process.stderr.write(`${renderHeartbeat({ ...config, elapsedMs, frame: slot - 1 })}\n`);
|
|
72
|
+
if (config.eventFd === 3 && config.event) {
|
|
73
|
+
try {
|
|
74
|
+
fs.writeSync(config.eventFd, `${JSON.stringify({
|
|
75
|
+
...config.event,
|
|
76
|
+
timestamp: new Date().toISOString(),
|
|
77
|
+
kind: 'heartbeat',
|
|
78
|
+
stage: config.stage,
|
|
79
|
+
state: 'running',
|
|
80
|
+
index: config.index,
|
|
81
|
+
total: config.total,
|
|
82
|
+
label: config.label,
|
|
83
|
+
detail: config.detail,
|
|
84
|
+
elapsedMs,
|
|
85
|
+
})}\n`);
|
|
86
|
+
} catch (_error) {
|
|
87
|
+
// Structured progress is best-effort, just like terminal progress.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}, Math.min(intervalMs, 1_000));
|
|
91
|
+
|
|
92
|
+
const stop = () => {
|
|
93
|
+
clearInterval(timer);
|
|
94
|
+
process.exit(0);
|
|
95
|
+
};
|
|
96
|
+
process.once('SIGINT', stop);
|
|
97
|
+
process.once('SIGTERM', stop);
|
|
98
|
+
process.once('SIGHUP', stop);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function startHeartbeat({
|
|
102
|
+
stage,
|
|
103
|
+
index,
|
|
104
|
+
total,
|
|
105
|
+
label,
|
|
106
|
+
detail = '',
|
|
107
|
+
intervalMs = DEFAULT_INTERVAL_MS,
|
|
108
|
+
startAt = Date.now(),
|
|
109
|
+
eventDescriptor,
|
|
110
|
+
event,
|
|
111
|
+
spawn = spawnProcess,
|
|
112
|
+
} = {}) {
|
|
113
|
+
const config = {
|
|
114
|
+
parentPid: process.pid,
|
|
115
|
+
stage: String(stage || ''),
|
|
116
|
+
index: normalizePositiveInteger(index, 0),
|
|
117
|
+
total: normalizePositiveInteger(total, 0),
|
|
118
|
+
label: String(label || ''),
|
|
119
|
+
detail: String(detail || ''),
|
|
120
|
+
intervalMs: normalizePositiveInteger(intervalMs, DEFAULT_INTERVAL_MS),
|
|
121
|
+
startAt: Number.isFinite(Number(startAt)) ? Number(startAt) : Date.now(),
|
|
122
|
+
};
|
|
123
|
+
const stdio = ['ignore', 'ignore', 'inherit'];
|
|
124
|
+
if (Number.isInteger(eventDescriptor) && eventDescriptor >= 0 && event) {
|
|
125
|
+
config.eventFd = 3;
|
|
126
|
+
config.event = {
|
|
127
|
+
schemaVersion: Number(event.schemaVersion) || 1,
|
|
128
|
+
runId: String(event.runId || ''),
|
|
129
|
+
branch: String(event.branch || ''),
|
|
130
|
+
baseBranch: String(event.baseBranch || ''),
|
|
131
|
+
};
|
|
132
|
+
stdio.push(eventDescriptor);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let child;
|
|
136
|
+
try {
|
|
137
|
+
child = spawn(process.execPath, [__filename, '--worker', JSON.stringify(config)], {
|
|
138
|
+
stdio,
|
|
139
|
+
});
|
|
140
|
+
child.on('error', () => {});
|
|
141
|
+
child.unref();
|
|
142
|
+
} catch (_error) {
|
|
143
|
+
return () => {};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
let stopped = false;
|
|
147
|
+
return () => {
|
|
148
|
+
if (stopped) return;
|
|
149
|
+
stopped = true;
|
|
150
|
+
if (child.exitCode === null && !child.killed) {
|
|
151
|
+
try {
|
|
152
|
+
child.kill('SIGTERM');
|
|
153
|
+
} catch (_error) {
|
|
154
|
+
// Progress is observability only; never fail finish while stopping it.
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (require.main === module && process.argv[2] === '--worker') {
|
|
161
|
+
runWorker(process.argv[3] || '');
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = {
|
|
165
|
+
formatElapsed,
|
|
166
|
+
renderHeartbeat,
|
|
167
|
+
runWorker,
|
|
168
|
+
startHeartbeat,
|
|
169
|
+
};
|
package/src/finish/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
const { TOOL_NAME, LOCK_FILE_RELATIVE, path, fs } = require('../context');
|
|
3
3
|
const { isTerseMode } = require('../output');
|
|
4
|
-
const { run, runPackageAsset } = require('../core/runtime');
|
|
4
|
+
const { run, runPackageAsset, assetStdio } = require('../core/runtime');
|
|
5
5
|
const {
|
|
6
6
|
resolveRepoRoot,
|
|
7
7
|
uniquePreserveOrder,
|
|
@@ -31,6 +31,7 @@ const {
|
|
|
31
31
|
const submoduleModule = require('../submodule');
|
|
32
32
|
const { runPreflight, summarizePreflight } = require('./preflight');
|
|
33
33
|
const { runReviewGate } = require('./review-gate');
|
|
34
|
+
const { createFinishProgress } = require('./progress');
|
|
34
35
|
|
|
35
36
|
/**
|
|
36
37
|
* Options recognized by {@link autoCommitWorktreeForFinish} and the public
|
|
@@ -54,6 +55,14 @@ const { runReviewGate } = require('./review-gate');
|
|
|
54
55
|
* @property {string} [target] Path inside the target repo (defaults to cwd).
|
|
55
56
|
*/
|
|
56
57
|
|
|
58
|
+
/**
|
|
59
|
+
* Whether the caller explicitly requested that the legacy branch-finish script
|
|
60
|
+
* skip its full repository-defined preflight.
|
|
61
|
+
*/
|
|
62
|
+
function shouldSkipBranchPreflight(options = {}) {
|
|
63
|
+
return options.skipPreflight === true;
|
|
64
|
+
}
|
|
65
|
+
|
|
57
66
|
/**
|
|
58
67
|
* Outcome of an auto-commit attempt for a single branch.
|
|
59
68
|
*
|
|
@@ -324,6 +333,20 @@ function merge(rawArgs) {
|
|
|
324
333
|
* @returns {void}
|
|
325
334
|
* @throws {Error} When `--branch` references an unknown ref, or when any branch fails to finish (after the loop completes).
|
|
326
335
|
*/
|
|
336
|
+
/**
|
|
337
|
+
* Decide whether a finish run should sweep merged-but-stranded worktree dirs
|
|
338
|
+
* after the per-lane loop. Only for bulk `--all`, never on a dry run, only when
|
|
339
|
+
* every lane succeeded (failed === 0), and honoring the --no-sweep-orphans
|
|
340
|
+
* opt-out. Pure so the guard can be tested without the gh/PR finish flow.
|
|
341
|
+
*
|
|
342
|
+
* @param {{all?: boolean, sweepOrphans?: boolean, dryRun?: boolean}} options
|
|
343
|
+
* @param {number} failed Count of lanes that failed to finish.
|
|
344
|
+
* @returns {boolean}
|
|
345
|
+
*/
|
|
346
|
+
function shouldSweepOrphans(options, failed) {
|
|
347
|
+
return Boolean(options.all && options.sweepOrphans && !options.dryRun && failed === 0);
|
|
348
|
+
}
|
|
349
|
+
|
|
327
350
|
function finish(rawArgs, defaults = {}) {
|
|
328
351
|
const activeCwd = process.cwd();
|
|
329
352
|
const options = parseFinishArgs(rawArgs, defaults);
|
|
@@ -375,6 +398,12 @@ function finish(rawArgs, defaults = {}) {
|
|
|
375
398
|
|
|
376
399
|
for (const candidate of candidates) {
|
|
377
400
|
const { branch, baseBranch, worktreePath } = candidate;
|
|
401
|
+
const progress = createFinishProgress({
|
|
402
|
+
repoRoot,
|
|
403
|
+
branch,
|
|
404
|
+
baseBranch,
|
|
405
|
+
persistEvents: !options.dryRun,
|
|
406
|
+
});
|
|
378
407
|
// In terse mode, defer the "Finishing X -> Y" line until we know whether
|
|
379
408
|
// we also need to announce an auto-commit, then emit a single combined
|
|
380
409
|
// line per branch. Keep branch + base + worktree path so agents still see
|
|
@@ -386,6 +415,7 @@ function finish(rawArgs, defaults = {}) {
|
|
|
386
415
|
}
|
|
387
416
|
|
|
388
417
|
try {
|
|
418
|
+
progress.start('prepare', worktreePath ? 'checking worktree and pending changes' : 'checking branch');
|
|
389
419
|
let commitState = { changed: false, committed: false };
|
|
390
420
|
if (worktreePath) {
|
|
391
421
|
commitState = autoCommitWorktreeForFinish(repoRoot, worktreePath, branch, options);
|
|
@@ -407,6 +437,12 @@ function finish(rawArgs, defaults = {}) {
|
|
|
407
437
|
} else if (commitState.changed && commitState.dryRun) {
|
|
408
438
|
console.log(`[${TOOL_NAME}] [dry-run] Would auto-commit pending changes on '${branch}'.`);
|
|
409
439
|
}
|
|
440
|
+
progress.complete(
|
|
441
|
+
'prepare',
|
|
442
|
+
commitState.committed
|
|
443
|
+
? 'pending changes auto-committed'
|
|
444
|
+
: (commitState.changed && commitState.dryRun ? 'would auto-commit pending changes' : 'branch ready'),
|
|
445
|
+
);
|
|
410
446
|
|
|
411
447
|
if (options.advanceSubmodules && worktreePath) {
|
|
412
448
|
const gitmodulesPath = path.join(worktreePath, '.gitmodules');
|
|
@@ -455,6 +491,13 @@ function finish(rawArgs, defaults = {}) {
|
|
|
455
491
|
finishArgs.push(options.parentGitlinkCommit ? '--parent-gitlink-commit' : '--no-parent-gitlink-commit');
|
|
456
492
|
|
|
457
493
|
if (options.dryRun) {
|
|
494
|
+
progress.skip('preflight', 'dry run');
|
|
495
|
+
progress.skip('pr', 'dry run');
|
|
496
|
+
progress.skip('review', 'dry run');
|
|
497
|
+
progress.skip('autofix', 'dry run');
|
|
498
|
+
progress.skip('ci', 'dry run');
|
|
499
|
+
progress.skip('merge', 'dry run');
|
|
500
|
+
progress.skip('cleanup', 'dry run');
|
|
458
501
|
console.log(`[${TOOL_NAME}] [dry-run] Would run: gx branch finish ${finishArgs.join(' ')}`);
|
|
459
502
|
succeeded += 1;
|
|
460
503
|
continue;
|
|
@@ -463,11 +506,13 @@ function finish(rawArgs, defaults = {}) {
|
|
|
463
506
|
// Preflight: typecheck + lint touched workspace packages before opening
|
|
464
507
|
// a PR. Only enforced for PR-mode finishes; bypass with --skip-preflight.
|
|
465
508
|
if (options.mergeMode === 'pr' && !options.skipPreflight) {
|
|
509
|
+
progress.start('preflight', 'running targeted local verification');
|
|
466
510
|
const preflight = runPreflight(repoRoot, worktreePath, branch, baseBranch, {
|
|
467
511
|
verbose: !terse,
|
|
468
512
|
});
|
|
469
513
|
console.log(`[${TOOL_NAME}] ${summarizePreflight(preflight)}`);
|
|
470
514
|
if (preflight.status === 'failed') {
|
|
515
|
+
progress.fail('preflight', `${preflight.failures.length} script(s) failed`);
|
|
471
516
|
for (const f of preflight.failures) {
|
|
472
517
|
console.error(`[${TOOL_NAME}] preflight failure: ${f.label} (exit ${f.status})`);
|
|
473
518
|
if (f.stderr && f.stderr.trim()) {
|
|
@@ -480,20 +525,53 @@ function finish(rawArgs, defaults = {}) {
|
|
|
480
525
|
`preflight failed for ${preflight.failures.length} script(s). Fix the failures or rerun with --skip-preflight to bypass.`,
|
|
481
526
|
);
|
|
482
527
|
}
|
|
528
|
+
progress.complete('preflight', preflight.status);
|
|
529
|
+
} else {
|
|
530
|
+
progress.skip(
|
|
531
|
+
'preflight',
|
|
532
|
+
options.skipPreflight ? 'disabled by flag' : 'not a PR finish',
|
|
533
|
+
);
|
|
483
534
|
}
|
|
484
535
|
|
|
485
536
|
// Opt-in merge gate (--gate-review / gx ship): enforce a clean AI review +
|
|
486
537
|
// green CI + GitHub-mergeable verdict BEFORE the shell merge runs. Throws on
|
|
487
538
|
// failure, which the catch below turns into a finish failure (no merge).
|
|
488
539
|
if (options.mergeMode === 'pr' && options.gateReview) {
|
|
489
|
-
runReviewGate({
|
|
540
|
+
runReviewGate({
|
|
541
|
+
repoRoot, worktreePath, branch, baseBranch, options, progress,
|
|
542
|
+
});
|
|
543
|
+
} else {
|
|
544
|
+
progress.skip('review', 'review gate disabled');
|
|
545
|
+
progress.skip('autofix', 'review gate disabled');
|
|
546
|
+
progress.skip('ci', 'review gate disabled; repository policy controls merge readiness');
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
if (shouldSkipBranchPreflight(options)) {
|
|
550
|
+
finishArgs.push('--no-preflight');
|
|
490
551
|
}
|
|
491
552
|
|
|
553
|
+
// Streamed, not piped: the script can sit for minutes waiting on the PR
|
|
554
|
+
// merge, and buffering means the operator sees nothing until it exits —
|
|
555
|
+
// and sees NOTHING AT ALL if the process is killed while waiting, since
|
|
556
|
+
// the buffer dies with it. Streaming cannot interleave two branches'
|
|
557
|
+
// output, because lanes run sequentially here.
|
|
558
|
+
//
|
|
559
|
+
// The exception is `gx agents finish --json`, which reads this script's
|
|
560
|
+
// output through a process.stdout.write patch to recover the merged-PR
|
|
561
|
+
// URL — a child on 'inherit' writes past that patch. assetStdio owns that
|
|
562
|
+
// decision for every caller, so this path and invokePackageAsset cannot
|
|
563
|
+
// drift apart.
|
|
492
564
|
const finishResult = runPackageAsset('branchFinish', finishArgs, {
|
|
493
565
|
cwd: repoRoot,
|
|
494
|
-
stdio: '
|
|
495
|
-
env: {
|
|
566
|
+
stdio: assetStdio('branchFinish'),
|
|
567
|
+
env: {
|
|
568
|
+
GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
|
|
569
|
+
GUARDEX_FINISH_CHECKLIST: '1',
|
|
570
|
+
GUARDEX_FINISH_GATE_DONE: options.gateReview ? '1' : '0',
|
|
571
|
+
...progress.eventEnv,
|
|
572
|
+
},
|
|
496
573
|
});
|
|
574
|
+
// Null under 'inherit'; kept so an explicit pipe still prints.
|
|
497
575
|
if (finishResult.stdout) {
|
|
498
576
|
process.stdout.write(finishResult.stdout);
|
|
499
577
|
}
|
|
@@ -518,6 +596,28 @@ function finish(rawArgs, defaults = {}) {
|
|
|
518
596
|
`[${TOOL_NAME}] Finish summary: total=${candidates.length}, success=${succeeded}, failed=${failed}, autoCommitted=${autoCommitted}`,
|
|
519
597
|
);
|
|
520
598
|
|
|
599
|
+
// Bulk `--all` finish self-cleans: sweep merged-but-stranded worktree dirs
|
|
600
|
+
// whose branch was merged out-of-band and never reaped (the post-merge
|
|
601
|
+
// "retained for now" gap in agent-branch-finish.sh). Only when every lane
|
|
602
|
+
// succeeded, never on a dry run, and opt-out via --no-sweep-orphans. The
|
|
603
|
+
// sweep is best-effort: a failure warns but does not fail the finish.
|
|
604
|
+
if (shouldSweepOrphans(options, failed)) {
|
|
605
|
+
const baseForSweep = options.base || candidates[0].baseBranch;
|
|
606
|
+
const sweepArgs = ['--include-pr-merged', '--delete-branches'];
|
|
607
|
+
if (baseForSweep) {
|
|
608
|
+
sweepArgs.push('--base', baseForSweep);
|
|
609
|
+
}
|
|
610
|
+
console.log(`[${TOOL_NAME}] Sweeping merged-but-stranded worktrees...`);
|
|
611
|
+
const sweep = runPackageAsset('worktreePrune', sweepArgs, {
|
|
612
|
+
cwd: repoRoot,
|
|
613
|
+
stdio: 'inherit',
|
|
614
|
+
env: { GUARDEX_PRUNE_ACTIVE_CWD: activeCwd },
|
|
615
|
+
});
|
|
616
|
+
if (sweep.status !== 0) {
|
|
617
|
+
console.error(`[${TOOL_NAME}] Warning: orphan sweep failed (non-fatal).`);
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
|
|
521
621
|
if (failed > 0) {
|
|
522
622
|
throw new Error('finish command failed for one or more agent branches');
|
|
523
623
|
}
|
|
@@ -701,4 +801,6 @@ module.exports = {
|
|
|
701
801
|
finish,
|
|
702
802
|
sync,
|
|
703
803
|
autoCommitWorktreeForFinish,
|
|
804
|
+
shouldSweepOrphans,
|
|
805
|
+
shouldSkipBranchPreflight,
|
|
704
806
|
};
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
const STAGES = [
|
|
2
|
+
['prepare', 'Prepare branch'],
|
|
3
|
+
['preflight', 'Local preflight'],
|
|
4
|
+
['pr', 'Push and open PR'],
|
|
5
|
+
['review', 'AI review'],
|
|
6
|
+
['autofix', 'Review autofix'],
|
|
7
|
+
['ci', 'CI checks'],
|
|
8
|
+
['merge', 'Merge'],
|
|
9
|
+
['cleanup', 'Cleanup'],
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
const SYMBOLS = {
|
|
13
|
+
pending: '⬜',
|
|
14
|
+
running: '🔄',
|
|
15
|
+
complete: '✅',
|
|
16
|
+
skipped: '⏭',
|
|
17
|
+
failed: '❌',
|
|
18
|
+
finished: '🏁',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const TIMED_STAGES = new Set(['review', 'autofix']);
|
|
22
|
+
|
|
23
|
+
function createRunId(branch) {
|
|
24
|
+
const digest = crypto.createHash('sha256').update(String(branch || '')).digest('hex').slice(0, 8);
|
|
25
|
+
return `finish-${Date.now().toString(36)}-${process.pid}-${digest}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function createPrivateDirectory(repoRoot, components) {
|
|
29
|
+
let current = repoRoot;
|
|
30
|
+
for (const component of components) {
|
|
31
|
+
current = path.join(current, component);
|
|
32
|
+
try {
|
|
33
|
+
fs.mkdirSync(current, { mode: 0o700 });
|
|
34
|
+
} catch (error) {
|
|
35
|
+
if (error.code !== 'EEXIST') throw error;
|
|
36
|
+
}
|
|
37
|
+
const stat = fs.lstatSync(current);
|
|
38
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
39
|
+
throw new Error(`unsafe finish progress directory: ${current}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return current;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function createEventStream(repoRoot, branch, baseBranch) {
|
|
46
|
+
if (!repoRoot) return null;
|
|
47
|
+
try {
|
|
48
|
+
const directory = createPrivateDirectory(repoRoot, ['.omx', 'state', 'finish-runs']);
|
|
49
|
+
const directoryDescriptor = fs.openSync(
|
|
50
|
+
directory,
|
|
51
|
+
fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW,
|
|
52
|
+
);
|
|
53
|
+
try {
|
|
54
|
+
fs.fchmodSync(directoryDescriptor, 0o700);
|
|
55
|
+
} finally {
|
|
56
|
+
fs.closeSync(directoryDescriptor);
|
|
57
|
+
}
|
|
58
|
+
const runId = createRunId(branch);
|
|
59
|
+
const filePath = path.join(directory, `${runId}.jsonl`);
|
|
60
|
+
const descriptor = fs.openSync(
|
|
61
|
+
filePath,
|
|
62
|
+
fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_EXCL
|
|
63
|
+
| fs.constants.O_WRONLY | fs.constants.O_NOFOLLOW,
|
|
64
|
+
0o600,
|
|
65
|
+
);
|
|
66
|
+
try {
|
|
67
|
+
fs.fchmodSync(descriptor, 0o600);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
fs.closeSync(descriptor);
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
// Keep one race-free append target for this one-shot CLI process. Heartbeat
|
|
73
|
+
// children inherit this descriptor; the OS closes it when the command exits.
|
|
74
|
+
return {
|
|
75
|
+
runId,
|
|
76
|
+
filePath,
|
|
77
|
+
relativePath: path.relative(repoRoot, filePath),
|
|
78
|
+
descriptor,
|
|
79
|
+
event: {
|
|
80
|
+
schemaVersion: 1,
|
|
81
|
+
runId,
|
|
82
|
+
branch,
|
|
83
|
+
baseBranch,
|
|
84
|
+
},
|
|
85
|
+
write(event) {
|
|
86
|
+
try {
|
|
87
|
+
fs.writeSync(descriptor, `${JSON.stringify({
|
|
88
|
+
schemaVersion: 1,
|
|
89
|
+
runId,
|
|
90
|
+
timestamp: new Date().toISOString(),
|
|
91
|
+
branch,
|
|
92
|
+
baseBranch,
|
|
93
|
+
...event,
|
|
94
|
+
})}\n`);
|
|
95
|
+
} catch (_error) {
|
|
96
|
+
// Observability remains fail-open after initialization too (disk
|
|
97
|
+
// full, state directory removed mid-run, or transient I/O failure).
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
} catch (_error) {
|
|
102
|
+
// Progress persistence is observability only. It must never block a merge
|
|
103
|
+
// gate or turn a successful cleanup into a failed finish.
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Append-only finish progress for terminals and agent transcripts. Rewriting a
|
|
110
|
+
* single ANSI dashboard looks good in a TTY but disappears from Codex's
|
|
111
|
+
* captured tool output, so every transition is a durable line instead.
|
|
112
|
+
*/
|
|
113
|
+
function createFinishProgress({
|
|
114
|
+
repoRoot,
|
|
115
|
+
branch,
|
|
116
|
+
baseBranch,
|
|
117
|
+
write,
|
|
118
|
+
persistEvents = true,
|
|
119
|
+
now = Date.now,
|
|
120
|
+
heartbeat,
|
|
121
|
+
heartbeatIntervalMs = 15_000,
|
|
122
|
+
} = {}) {
|
|
123
|
+
const output = write || ((line) => process.stderr.write(`${line}\n`));
|
|
124
|
+
const heartbeatFactory = heartbeat === undefined
|
|
125
|
+
? (write ? null : startStageHeartbeat)
|
|
126
|
+
: heartbeat;
|
|
127
|
+
const clock = typeof now === 'function' ? now : Date.now;
|
|
128
|
+
const eventStream = persistEvents ? createEventStream(repoRoot, branch, baseBranch) : null;
|
|
129
|
+
const stageMap = new Map(STAGES.map(([id, label], index) => [id, {
|
|
130
|
+
index: index + 1,
|
|
131
|
+
label,
|
|
132
|
+
state: 'pending',
|
|
133
|
+
detail: '',
|
|
134
|
+
}]));
|
|
135
|
+
const stageStartedAt = new Map();
|
|
136
|
+
let activeTimedStage = '';
|
|
137
|
+
let stopActiveHeartbeat = null;
|
|
138
|
+
|
|
139
|
+
output(`[gx:finish] ╭─ 🚀 GX FINISH · ${branch || 'current branch'} → ${baseBranch || 'configured base'}`);
|
|
140
|
+
if (eventStream) {
|
|
141
|
+
eventStream.write({ stage: 'finish', state: 'started', index: 0, total: STAGES.length, label: 'GX Finish', detail: '' });
|
|
142
|
+
}
|
|
143
|
+
for (const [, stage] of stageMap) {
|
|
144
|
+
output(`[gx:finish] │ ${SYMBOLS.pending} ${stage.index}/${STAGES.length} ${stage.label}`);
|
|
145
|
+
if (eventStream) {
|
|
146
|
+
eventStream.write({
|
|
147
|
+
stage: STAGES[stage.index - 1][0],
|
|
148
|
+
state: 'pending',
|
|
149
|
+
index: stage.index,
|
|
150
|
+
total: STAGES.length,
|
|
151
|
+
label: stage.label,
|
|
152
|
+
detail: '',
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
output(`[gx:finish] ╰─ 0/${STAGES.length} ready`);
|
|
157
|
+
if (eventStream) {
|
|
158
|
+
output(`[gx:finish] 📡 events · ${eventStream.relativePath}`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function stopTimedStage() {
|
|
162
|
+
try {
|
|
163
|
+
if (stopActiveHeartbeat) stopActiveHeartbeat();
|
|
164
|
+
} catch (_error) {
|
|
165
|
+
// Progress is observability only; teardown errors remain fail-open.
|
|
166
|
+
}
|
|
167
|
+
stopActiveHeartbeat = null;
|
|
168
|
+
if (activeTimedStage) stageStartedAt.delete(activeTimedStage);
|
|
169
|
+
activeTimedStage = '';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function update(id, state, detail = '', displaySuffix = '') {
|
|
173
|
+
const stage = stageMap.get(id);
|
|
174
|
+
if (!stage) return false;
|
|
175
|
+
const normalizedDetail = String(detail || '').trim();
|
|
176
|
+
if (stage.state === state && stage.detail === normalizedDetail) return false;
|
|
177
|
+
stage.state = state;
|
|
178
|
+
stage.detail = normalizedDetail;
|
|
179
|
+
const connector = id === 'cleanup' && state !== 'running' ? '╰─' : '├─';
|
|
180
|
+
output(
|
|
181
|
+
`[gx:finish] ${connector} ${SYMBOLS[state]} ${stage.index}/${STAGES.length} ${stage.label}`
|
|
182
|
+
+ `${normalizedDetail ? ` · ${normalizedDetail}` : ''}${displaySuffix}`,
|
|
183
|
+
);
|
|
184
|
+
if (eventStream) {
|
|
185
|
+
eventStream.write({
|
|
186
|
+
stage: id,
|
|
187
|
+
state,
|
|
188
|
+
index: stage.index,
|
|
189
|
+
total: STAGES.length,
|
|
190
|
+
label: stage.label,
|
|
191
|
+
detail: normalizedDetail,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function start(id, detail) {
|
|
198
|
+
const stage = stageMap.get(id);
|
|
199
|
+
if (!stage) return;
|
|
200
|
+
const normalizedDetail = String(detail || '').trim();
|
|
201
|
+
if (stage.state === 'running' && stage.detail === normalizedDetail) return;
|
|
202
|
+
|
|
203
|
+
stopTimedStage();
|
|
204
|
+
const startAt = clock();
|
|
205
|
+
if (!update(id, 'running', normalizedDetail) || !TIMED_STAGES.has(id)) return;
|
|
206
|
+
|
|
207
|
+
activeTimedStage = id;
|
|
208
|
+
stageStartedAt.set(id, startAt);
|
|
209
|
+
if (!heartbeatFactory) return;
|
|
210
|
+
try {
|
|
211
|
+
stopActiveHeartbeat = heartbeatFactory({
|
|
212
|
+
stage: id,
|
|
213
|
+
index: stage.index,
|
|
214
|
+
total: STAGES.length,
|
|
215
|
+
label: stage.label,
|
|
216
|
+
detail: normalizedDetail,
|
|
217
|
+
intervalMs: heartbeatIntervalMs,
|
|
218
|
+
startAt,
|
|
219
|
+
...(eventStream ? {
|
|
220
|
+
eventDescriptor: eventStream.descriptor,
|
|
221
|
+
event: eventStream.event,
|
|
222
|
+
} : {}),
|
|
223
|
+
});
|
|
224
|
+
} catch (_error) {
|
|
225
|
+
// Progress is observability only; a heartbeat failure cannot block finish.
|
|
226
|
+
stopActiveHeartbeat = null;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function settle(id, state, detail) {
|
|
231
|
+
let displaySuffix = '';
|
|
232
|
+
if (TIMED_STAGES.has(id) && stageStartedAt.has(id)) {
|
|
233
|
+
displaySuffix = ` · ⏱ ${formatElapsed(clock() - stageStartedAt.get(id))}`;
|
|
234
|
+
}
|
|
235
|
+
if (activeTimedStage === id) stopTimedStage();
|
|
236
|
+
update(id, state, detail, displaySuffix);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return {
|
|
240
|
+
start,
|
|
241
|
+
complete: (id, detail) => settle(id, 'complete', detail),
|
|
242
|
+
skip: (id, detail) => settle(id, 'skipped', detail),
|
|
243
|
+
fail: (id, detail) => settle(id, 'failed', detail),
|
|
244
|
+
finish: (id, detail) => settle(id, 'finished', detail),
|
|
245
|
+
eventEnv: eventStream ? {
|
|
246
|
+
GUARDEX_FINISH_EVENT_FILE: eventStream.filePath,
|
|
247
|
+
GUARDEX_FINISH_RUN_ID: eventStream.runId,
|
|
248
|
+
GUARDEX_FINISH_EVENT_BRANCH: String(branch || ''),
|
|
249
|
+
GUARDEX_FINISH_EVENT_BASE: String(baseBranch || ''),
|
|
250
|
+
} : {},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
module.exports = {
|
|
255
|
+
STAGES,
|
|
256
|
+
createEventStream,
|
|
257
|
+
createFinishProgress,
|
|
258
|
+
};
|
|
259
|
+
const crypto = require('node:crypto');
|
|
260
|
+
const fs = require('node:fs');
|
|
261
|
+
const path = require('node:path');
|
|
262
|
+
const { formatElapsed, startHeartbeat: startStageHeartbeat } = require('./heartbeat');
|