@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.
Files changed (58) hide show
  1. package/README.md +122 -322
  2. package/package.json +25 -5
  3. package/scripts/prepublish-bump-version.js +191 -0
  4. package/skills/gitguardex/SKILL.md +83 -3
  5. package/src/agents/activity.js +279 -0
  6. package/src/agents/finish.js +15 -0
  7. package/src/ci-init/index.js +0 -1
  8. package/src/cli/args.js +203 -6
  9. package/src/cli/commands/agents.js +17 -0
  10. package/src/cli/commands/branch.js +267 -14
  11. package/src/cli/commands/claude.js +15 -0
  12. package/src/cli/commands/doctor.js +26 -0
  13. package/src/cli/commands/onboard.js +293 -0
  14. package/src/cli/commands/prompt.js +15 -3
  15. package/src/cli/commands/review.js +18 -0
  16. package/src/cli/commands/setup.js +8 -6
  17. package/src/cli/commands/status.js +12 -0
  18. package/src/cli/main.js +2 -0
  19. package/src/cli/shared-locks.js +304 -0
  20. package/src/context.js +21 -3
  21. package/src/core/runtime.js +33 -1
  22. package/src/doctor/index.js +58 -5
  23. package/src/finish/heartbeat.js +169 -0
  24. package/src/finish/index.js +106 -4
  25. package/src/finish/progress.js +262 -0
  26. package/src/finish/review-gate.js +453 -32
  27. package/src/github-api.js +59 -0
  28. package/src/mcp/collect.js +111 -12
  29. package/src/mcp/server.js +10 -4
  30. package/src/output/index.js +210 -0
  31. package/src/pr-checks.js +121 -0
  32. package/src/pr-review.js +581 -51
  33. package/src/pr.js +143 -21
  34. package/src/provider-binary.js +101 -0
  35. package/src/review-diff.js +116 -0
  36. package/src/review-fix.js +229 -0
  37. package/src/sandbox/index.js +11 -5
  38. package/src/scaffold/agent-worktree-prep.js +9 -2
  39. package/src/scaffold/index.js +4 -16
  40. package/src/scaffold/provision-config.js +314 -0
  41. package/src/shared-git-state.js +566 -0
  42. package/src/terminal/kitty.js +20 -0
  43. package/src/terminal/tmux.js +9 -0
  44. package/templates/AGENTS.multiagent-safety.md +73 -11
  45. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  46. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  47. package/templates/githooks/post-checkout +4 -9
  48. package/templates/githooks/pre-commit +17 -1
  49. package/templates/github/workflows/README.md +30 -23
  50. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  51. package/templates/scripts/agent-branch-finish.sh +363 -26
  52. package/templates/scripts/agent-branch-start.sh +76 -25
  53. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  54. package/templates/scripts/agent-file-locks.py +390 -52
  55. package/templates/scripts/agent-preflight.sh +14 -2
  56. package/templates/scripts/agent-stalled-report.sh +40 -0
  57. package/templates/scripts/codex-agent.sh +10 -63
  58. package/templates/github/workflows/cr.yml +0 -46
@@ -0,0 +1,304 @@
1
+ 'use strict';
2
+
3
+ const { TOOL_NAME } = require('../context');
4
+ const { resolveRepoRoot } = require('../git');
5
+ const { run, extractTargetedArgs, runPackageAsset } = require('../core/runtime');
6
+ const sharedGitState = require('../shared-git-state');
7
+
8
+ function writeCommandResult(result) {
9
+ if (result.stdout) process.stdout.write(result.stdout);
10
+ if (result.stderr) process.stderr.write(result.stderr);
11
+ process.exitCode = result.status;
12
+ }
13
+
14
+ function parseSharedRemote(args) {
15
+ let remote = 'origin';
16
+ for (let index = 0; index < args.length; index += 1) {
17
+ const arg = args[index];
18
+ if (arg === '--remote') {
19
+ remote = args[index + 1] || '';
20
+ index += 1;
21
+ } else if (arg.startsWith('--remote=')) {
22
+ remote = arg.slice('--remote='.length);
23
+ } else {
24
+ throw new Error(`Unknown shared Git state option: ${arg}`);
25
+ }
26
+ }
27
+ if (!remote) throw new Error('--remote requires a configured Git remote name');
28
+ return remote;
29
+ }
30
+
31
+ function parseLockOperation(args) {
32
+ const [command, ...rest] = args;
33
+ const parsed = {
34
+ command,
35
+ branch: '',
36
+ agent: process.env.GUARDEX_AGENT_ID || '',
37
+ allowDelete: false,
38
+ staged: false,
39
+ files: []
40
+ };
41
+ let positionalOnly = false;
42
+ for (let index = 0; index < rest.length; index += 1) {
43
+ const arg = rest[index];
44
+ if (positionalOnly) {
45
+ parsed.files.push(arg);
46
+ } else if (arg === '--') {
47
+ positionalOnly = true;
48
+ } else if (arg === '--branch' || arg === '--agent') {
49
+ const value = rest[index + 1];
50
+ if (!value || value.startsWith('-')) throw new Error(`${arg} requires a value`);
51
+ parsed[arg === '--branch' ? 'branch' : 'agent'] = value;
52
+ index += 1;
53
+ } else if (arg.startsWith('--branch=')) {
54
+ parsed.branch = arg.slice('--branch='.length);
55
+ } else if (arg.startsWith('--agent=')) {
56
+ parsed.agent = arg.slice('--agent='.length);
57
+ } else if (arg === '--allow-delete') {
58
+ parsed.allowDelete = true;
59
+ } else if (arg === '--staged') {
60
+ parsed.staged = true;
61
+ } else if (arg.startsWith('-')) {
62
+ throw new Error(`Unknown ${command || 'lock'} option: ${arg}`);
63
+ } else {
64
+ parsed.files.push(arg);
65
+ }
66
+ }
67
+ if (['claim', 'allow-delete', 'release', 'validate'].includes(command) && !parsed.branch) {
68
+ throw new Error(`${command} requires --branch`);
69
+ }
70
+ if (['claim', 'allow-delete'].includes(command) && parsed.files.length === 0) {
71
+ throw new Error(`${command} requires one or more file paths`);
72
+ }
73
+ return parsed;
74
+ }
75
+
76
+ function rollbackShared(repoRoot, records, restore) {
77
+ const failures = [];
78
+ for (const record of records.slice().reverse()) {
79
+ try {
80
+ restore(repoRoot, record);
81
+ } catch (error) {
82
+ failures.push(error.message);
83
+ }
84
+ }
85
+ if (failures.length) {
86
+ process.stderr.write(
87
+ `[${TOOL_NAME}] Warning: shared Git rollback was incomplete: ${failures.join('; ')}\n`
88
+ );
89
+ }
90
+ }
91
+
92
+ function sharedFailure(error) {
93
+ process.stderr.write(`[${TOOL_NAME}] ${error.message || error}\n`);
94
+ process.exitCode = 1;
95
+ }
96
+
97
+ function stagedFiles(repoRoot) {
98
+ const result = run('git', ['diff', '--cached', '--name-only', '--diff-filter=ACMRDTUXB', '-z'], {
99
+ cwd: repoRoot
100
+ });
101
+ if (result.status !== 0) throw new Error(result.stderr || 'cannot inspect staged files');
102
+ return String(result.stdout || '')
103
+ .split('\0')
104
+ .filter(Boolean);
105
+ }
106
+
107
+ function sharedClaim(repoRoot, args, parsed) {
108
+ const claims = [];
109
+ try {
110
+ for (const file of parsed.files) {
111
+ claims.push(
112
+ sharedGitState.claimLock(repoRoot, {
113
+ file,
114
+ branch: parsed.branch,
115
+ agent: parsed.agent,
116
+ allowDelete: parsed.allowDelete
117
+ })
118
+ );
119
+ }
120
+ } catch (error) {
121
+ rollbackShared(repoRoot, claims, sharedGitState.restoreClaim);
122
+ sharedFailure(error);
123
+ return;
124
+ }
125
+
126
+ const local = runPackageAsset('lockTool', args, { cwd: repoRoot });
127
+ if (local.status !== 0) {
128
+ rollbackShared(repoRoot, claims, sharedGitState.restoreClaim);
129
+ writeCommandResult(local);
130
+ return;
131
+ }
132
+ writeCommandResult(local);
133
+ const remote = sharedGitState.settings(repoRoot).remote;
134
+ process.stdout.write(
135
+ `[${TOOL_NAME}] Shared Git lock claimed: ${parsed.files.length} file(s) via ${remote}.\n`
136
+ );
137
+ }
138
+
139
+ function sharedAllowDelete(repoRoot, args, parsed) {
140
+ const updates = [];
141
+ try {
142
+ for (const file of parsed.files) {
143
+ sharedGitState.validateLock(repoRoot, { file, branch: parsed.branch, agent: parsed.agent });
144
+ updates.push(
145
+ sharedGitState.claimLock(repoRoot, {
146
+ file,
147
+ branch: parsed.branch,
148
+ agent: parsed.agent,
149
+ allowDelete: true
150
+ })
151
+ );
152
+ }
153
+ } catch (error) {
154
+ rollbackShared(repoRoot, updates, sharedGitState.restoreClaim);
155
+ sharedFailure(error);
156
+ return;
157
+ }
158
+ const local = runPackageAsset('lockTool', args, { cwd: repoRoot });
159
+ if (local.status !== 0) {
160
+ rollbackShared(repoRoot, updates, sharedGitState.restoreClaim);
161
+ writeCommandResult(local);
162
+ return;
163
+ }
164
+ writeCommandResult(local);
165
+ process.stdout.write(
166
+ `[${TOOL_NAME}] Shared Git delete approval updated for ${parsed.files.length} file(s).\n`
167
+ );
168
+ }
169
+
170
+ function sharedRelease(repoRoot, args, parsed) {
171
+ let files = parsed.files;
172
+ const releases = [];
173
+ try {
174
+ if (files.length === 0) {
175
+ files = sharedGitState
176
+ .listLocks(repoRoot)
177
+ .filter((entry) => sharedGitState.ownerMatches(entry, parsed.branch, parsed.agent))
178
+ .map((entry) => entry.file);
179
+ }
180
+ for (const file of files) {
181
+ releases.push(
182
+ sharedGitState.releaseLock(repoRoot, {
183
+ file,
184
+ branch: parsed.branch,
185
+ agent: parsed.agent
186
+ })
187
+ );
188
+ }
189
+ } catch (error) {
190
+ rollbackShared(repoRoot, releases, sharedGitState.restoreRelease);
191
+ sharedFailure(error);
192
+ return;
193
+ }
194
+ const local = runPackageAsset('lockTool', args, { cwd: repoRoot });
195
+ if (local.status !== 0) {
196
+ rollbackShared(repoRoot, releases, sharedGitState.restoreRelease);
197
+ writeCommandResult(local);
198
+ return;
199
+ }
200
+ writeCommandResult(local);
201
+ process.stdout.write(
202
+ `[${TOOL_NAME}] Shared Git lock released: ${releases.filter((entry) => entry.released).length} file(s).\n`
203
+ );
204
+ }
205
+
206
+ function sharedValidate(repoRoot, args, parsed) {
207
+ const local = runPackageAsset('lockTool', args, { cwd: repoRoot });
208
+ if (local.status !== 0) {
209
+ writeCommandResult(local);
210
+ return;
211
+ }
212
+ const files = parsed.staged ? stagedFiles(repoRoot) : parsed.files;
213
+ try {
214
+ for (const file of files) {
215
+ sharedGitState.validateLock(repoRoot, { file, branch: parsed.branch, agent: parsed.agent });
216
+ }
217
+ } catch (error) {
218
+ if (local.stdout) process.stdout.write(local.stdout);
219
+ sharedFailure(error);
220
+ return;
221
+ }
222
+ writeCommandResult(local);
223
+ process.stdout.write(`[${TOOL_NAME}] Shared Git locks validated for ${files.length} file(s).\n`);
224
+ }
225
+
226
+ function sharedStatus(repoRoot, args, parsed) {
227
+ const local = runPackageAsset('lockTool', args, { cwd: repoRoot });
228
+ writeCommandResult(local);
229
+ if (local.status !== 0) return;
230
+ try {
231
+ const rows = sharedGitState
232
+ .listLocks(repoRoot)
233
+ .filter(
234
+ (entry) =>
235
+ (!parsed.branch || entry.branch === parsed.branch) &&
236
+ (!parsed.agent || entry.agent === parsed.agent)
237
+ );
238
+ const remote = sharedGitState.settings(repoRoot).remote;
239
+ if (!rows.length) {
240
+ process.stdout.write(`[${TOOL_NAME}] Shared Git locks: none (${remote}).\n`);
241
+ return;
242
+ }
243
+ process.stdout.write(`[${TOOL_NAME}] Shared Git locks (${remote}):\n`);
244
+ for (const entry of rows) {
245
+ process.stdout.write(
246
+ ` ${entry.file} ${entry.branch}${entry.agent ? ` as ${entry.agent}` : ''}\n`
247
+ );
248
+ }
249
+ } catch (error) {
250
+ sharedFailure(error);
251
+ }
252
+ }
253
+
254
+ function locks(rawArgs) {
255
+ const { target, passthrough } = extractTargetedArgs(rawArgs);
256
+ const repoRoot = resolveRepoRoot(target);
257
+ const [command, ...rest] = passthrough;
258
+ if (command === 'shared-enable') {
259
+ const state = sharedGitState.enable(repoRoot, parseSharedRemote(rest));
260
+ process.stdout.write(`[${TOOL_NAME}] Shared Git state enabled via ${state.remote}.\n`);
261
+ process.exitCode = 0;
262
+ return;
263
+ }
264
+ if (command === 'shared-disable') {
265
+ if (rest.length) throw new Error('shared-disable does not accept arguments');
266
+ sharedGitState.disable(repoRoot);
267
+ process.stdout.write(`[${TOOL_NAME}] Shared Git state disabled for this repository.\n`);
268
+ process.exitCode = 0;
269
+ return;
270
+ }
271
+ if (command === 'shared-status') {
272
+ if (rest.length) throw new Error('shared-status does not accept arguments');
273
+ const state = sharedGitState.settings(repoRoot);
274
+ if (!state.enabled) {
275
+ process.stdout.write(`[${TOOL_NAME}] Shared Git state is disabled.\n`);
276
+ process.exitCode = 0;
277
+ return;
278
+ }
279
+ const lockCount = sharedGitState.listLocks(repoRoot).length;
280
+ const laneCount = sharedGitState.listRemoteAgentBranches(repoRoot).length;
281
+ process.stdout.write(
282
+ `[${TOOL_NAME}] Shared Git state enabled via ${state.remote}: ${lockCount} lock(s), ${laneCount} remote agent branch(es).\n`
283
+ );
284
+ process.exitCode = 0;
285
+ return;
286
+ }
287
+
288
+ const state = sharedGitState.settings(repoRoot);
289
+ if (
290
+ !state.enabled ||
291
+ !['claim', 'allow-delete', 'release', 'validate', 'status'].includes(command)
292
+ ) {
293
+ writeCommandResult(runPackageAsset('lockTool', passthrough, { cwd: repoRoot }));
294
+ return;
295
+ }
296
+ const parsed = parseLockOperation(passthrough);
297
+ if (command === 'claim') return sharedClaim(repoRoot, passthrough, parsed);
298
+ if (command === 'allow-delete') return sharedAllowDelete(repoRoot, passthrough, parsed);
299
+ if (command === 'release') return sharedRelease(repoRoot, passthrough, parsed);
300
+ if (command === 'validate') return sharedValidate(repoRoot, passthrough, parsed);
301
+ return sharedStatus(repoRoot, passthrough, parsed);
302
+ }
303
+
304
+ module.exports = { locks };
package/src/context.js CHANGED
@@ -143,7 +143,7 @@ function toDestinationPath(relativeTemplatePath) {
143
143
 
144
144
  // scripts/ ↔ templates/scripts/ layout convention (single source of truth):
145
145
  //
146
- // 1. PAIRED files (10): tracked on both sides; scripts/<file> is a symlink
146
+ // 1. PAIRED files: tracked on both sides; scripts/<file> is a symlink
147
147
  // to ../templates/scripts/<file> per PR #548. See
148
148
  // scripts/check-script-symlinks.sh for the exact list. CI + the
149
149
  // .githooks/pre-commit shim both enforce that no symlink is ever
@@ -163,12 +163,14 @@ function toDestinationPath(relativeTemplatePath) {
163
163
  // safety block (auto-managed by syncManagedGitignoreLines below).
164
164
  const TEMPLATE_FILES = [
165
165
  'scripts/agent-preflight.sh',
166
+ 'scripts/agent-stalled-report.sh',
167
+ 'scripts/agent-autofinish-watch.sh',
168
+ 'scripts/agent-claude-stop-finish.sh',
166
169
  'scripts/guardex-docker-loader.sh',
167
170
  'scripts/guardex-env.sh',
168
171
  'github/pull.yml.example',
169
172
  'github/workflows/ci.yml',
170
173
  'github/workflows/ci-full.yml',
171
- 'github/workflows/cr.yml',
172
174
  'github/workflows/README.md',
173
175
  ];
174
176
 
@@ -351,6 +353,7 @@ const COMMAND_TYPO_ALIASES = new Map([
351
353
  const SUGGESTIBLE_COMMANDS = [
352
354
  'status',
353
355
  'setup',
356
+ 'onboard',
354
357
  'doctor',
355
358
  'branch',
356
359
  'pivot',
@@ -394,6 +397,7 @@ const CLI_COMMAND_GROUPS = [
394
397
  label: 'Setup & health',
395
398
  description: 'Install, repair, and check a repo. Run these first on a new clone.',
396
399
  commands: [
400
+ ['onboard', 'Guided first-run tour: where you are + the exact next command (alias: welcome)'],
397
401
  ['setup', 'Install, repair, and verify guardrails (flags: --repair, --install-only, --target, --current)'],
398
402
  ['doctor', 'Repair drift + verify (flags: --target, --current; auto-sandboxes on protected main)'],
399
403
  ['status', 'Show GitGuardex CLI + service health without modifying files'],
@@ -428,7 +432,7 @@ const CLI_COMMAND_GROUPS = [
428
432
  description: 'Review / cleanup bots, AI setup prompts, and safety reports.',
429
433
  commands: [
430
434
  ['agents', 'Start/stop repo-scoped review + cleanup bots'],
431
- ['pr-review', 'Run local Codex/Claude PR review and post inline GitHub comments or write an artifact'],
435
+ ['pr-review', 'Run local Codex/Claude PR review; post inline GitHub comments, write an artifact, or --fix the findings'],
432
436
  ['cockpit', 'Create or attach to a repo tmux cockpit session'],
433
437
  ['install-agent-skills', 'Install Guardex Codex/Claude skills into the user home'],
434
438
  ['speckit', 'Install Spec Kit (specify-cli) SDD slash skills (/speckit-specify, /speckit-plan, ...) into the current repo'],
@@ -474,6 +478,9 @@ const AI_SETUP_PART_ALIASES = new Map([
474
478
  ['compact-commands', 'rtk'],
475
479
  ['command-compression', 'rtk'],
476
480
  ['token-commands', 'rtk'],
481
+ ['compress', 'headroom'],
482
+ ['compression', 'headroom'],
483
+ ['headroom-mcp', 'headroom'],
477
484
  ['reviewbot', 'review-bot'],
478
485
  ['forksync', 'fork-sync'],
479
486
  ]);
@@ -537,6 +544,17 @@ const AI_SETUP_PARTS = [
537
544
  'Do not wrap machine-readable commands with RTK when code parses stdout (`--porcelain`, `--json`, NUL-delimited output, or exact stdout contracts).',
538
545
  ],
539
546
  },
547
+ {
548
+ name: 'headroom',
549
+ label: 'Headroom context compression',
550
+ promptLines: [
551
+ 'When the headroom MCP/proxy is available, compress large blobs before they enter context; it is reversible (retrieve restores the original), so prefer it over truncating. Fall back to plain text when headroom is absent.',
552
+ 'Compress noisy `gx` output, long logs, and large file/diff dumps with headroom_compress; keep PR URLs, branch names, and file paths visible so you can still act on them.',
553
+ 'Pull a dropped detail back with headroom_retrieve <hash>; audit savings with headroom_stats.',
554
+ 'Runtime hook: set GUARDEX_COMPRESS_CMD="<filter>" so gx routes its own large narrative output (e.g. `gx prompt --snippet`) through your compressor; unset leaves output byte-for-byte unchanged.',
555
+ 'Do not compress machine-readable output (`--json`, `--porcelain`, NUL-delimited, exact stdout contracts) or any value you must use verbatim.',
556
+ ],
557
+ },
540
558
  {
541
559
  name: 'integrate',
542
560
  label: 'Integrate',
@@ -6,6 +6,10 @@ const {
6
6
  PACKAGE_SCRIPT_ASSETS,
7
7
  } = require('../context');
8
8
 
9
+ // 32 MiB: comfortably above anything an asset prints in a normal run, and far
10
+ // enough below memory pressure that a runaway logger still fails loudly.
11
+ const DEFAULT_MAX_BUFFER = 32 * 1024 * 1024;
12
+
9
13
  function requireValue(rawArgs, index, flagName) {
10
14
  const value = rawArgs[index + 1];
11
15
  if (!value || value.startsWith('-')) {
@@ -24,7 +28,14 @@ function run(cmd, args, options = {}) {
24
28
  stdio: options.stdio || 'pipe',
25
29
  cwd: options.cwd,
26
30
  env: options.env ? { ...process.env, ...options.env } : process.env,
31
+ input: options.input,
27
32
  timeout: options.timeout,
33
+ // Node caps a piped spawnSync at 1 MiB and then SIGTERMs the child with
34
+ // ENOBUFS. That is survivable for a probe, but the long-running assets
35
+ // (branch-finish waiting on a merge, prune sweeps) print steadily and can
36
+ // reach it — at which point the asset dies mid-merge and the only trace is
37
+ // an unexplained non-zero status.
38
+ maxBuffer: options.maxBuffer || DEFAULT_MAX_BUFFER,
28
39
  });
29
40
  }
30
41
 
@@ -101,8 +112,28 @@ function runReviewBotCommand(repoRoot, rawArgs, options = {}) {
101
112
  });
102
113
  }
103
114
 
115
+ // Assets whose output is only ever echoed back to the operator, never parsed,
116
+ // and which can run for minutes (branch-finish waits on a PR merge). Piping
117
+ // those buffers every line until the process exits: the run looks hung, and if
118
+ // anything kills it mid-flight the entire record of what it did is lost with
119
+ // the buffer — which is exactly how a killed `branch finish --gate-review`
120
+ // leaves no trace of whether the merge ran. Stream them instead.
121
+ const STREAMED_ASSETS = new Set(['branchFinish']);
122
+
123
+ // `gx agents finish --json` scrapes an asset's output by patching
124
+ // process.stdout.write (src/agents/finish.js), which a child on 'inherit'
125
+ // bypasses entirely. It raises this while a capture is active; honour it, or
126
+ // the capture comes back empty and the JSON evidence loses its PR URL.
127
+ function assetStdio(assetKey, requested) {
128
+ if (requested) return requested;
129
+ if (!STREAMED_ASSETS.has(assetKey)) return undefined;
130
+ return process.env.GUARDEX_CAPTURE_ASSET_OUTPUT === '1' ? 'pipe' : 'inherit';
131
+ }
132
+
104
133
  function invokePackageAsset(assetKey, rawArgs, options = {}) {
105
- const result = runPackageAsset(assetKey, rawArgs, options);
134
+ const stdio = assetStdio(assetKey, options.stdio);
135
+ const result = runPackageAsset(assetKey, rawArgs, { ...options, stdio });
136
+ // Null under 'inherit' — the child already wrote straight to our streams.
106
137
  if (result.stdout) process.stdout.write(result.stdout);
107
138
  if (result.stderr) process.stderr.write(result.stderr);
108
139
  if (result.status !== 0) {
@@ -114,6 +145,7 @@ function invokePackageAsset(assetKey, rawArgs, options = {}) {
114
145
 
115
146
  module.exports = {
116
147
  run,
148
+ assetStdio,
117
149
  extractTargetedArgs,
118
150
  packageAssetEnv,
119
151
  packageAssetPath,
@@ -11,6 +11,7 @@ const {
11
11
  OMX_SCAFFOLD_FILES,
12
12
  AGENT_WORKTREE_RELATIVE_DIRS,
13
13
  defaultAgentWorktreeRelativeDir,
14
+ envFlagIsTruthy,
14
15
  } = require('../context');
15
16
  const { runPackageAsset } = require('../core/runtime');
16
17
 
@@ -50,6 +51,7 @@ const {
50
51
  const { ensureOmxScaffold, configureHooks } = require('../scaffold');
51
52
  const { detectRecoverableAutoFinishConflict, printAutoFinishSummary, isTerseMode } = require('../output');
52
53
  const { autoCommitWorktreeForFinish } = require('../finish');
54
+ const { runReviewGate } = require('../finish/review-gate');
53
55
 
54
56
  /**
55
57
  * @typedef {Object} SandboxMetadata
@@ -330,7 +332,13 @@ function doctorFinishFlowIsPending(output) {
330
332
  return (
331
333
  /\[agent-branch-finish\] PR merge not completed yet; leaving PR open\./.test(output) ||
332
334
  /\[agent-branch-finish\] PR pending review\/check policy\./.test(output) ||
333
- /\[agent-branch-finish\] PR auto-merge enabled; waiting for required checks\/reviews\./.test(output)
335
+ /\[agent-branch-finish\] PR auto-merge enabled; waiting for required checks\/reviews\./.test(output) ||
336
+ // A held merge (--no-auto-promote / guardex:merge-hold marker) exits 0
337
+ // with the PR open and the lane deliberately retained. Anything but
338
+ // 'pending' here sends the sandbox cleanup after a live held PR —
339
+ // force-deleting its worktree, local branch, and remote branch.
340
+ /^MERGE_HELD=1$/m.test(output) ||
341
+ /\[agent-branch-finish\] Merge hold active/.test(output)
334
342
  );
335
343
  }
336
344
 
@@ -863,6 +871,34 @@ function syncDoctorLockRegistryAfterMerge(repoRoot, sandboxLockContent) {
863
871
  };
864
872
  }
865
873
 
874
+ // When GUARDEX_AUTO_SHIP is on, the unattended auto-finish sweep must honor the
875
+ // same merge gate as `gx finish` (clean AI review + green CI + GitHub-mergeable)
876
+ // before merging an agent branch to base. The gate only applies to the PR path;
877
+ // the direct/local fallbacks have no PR or CI to gate, so they pass through
878
+ // unchanged. `runReviewGate` is injectable via `deps.runReviewGate` for tests.
879
+ // Returns `{ skip: true, reason }` when the gate blocks the merge.
880
+ function runAutoShipGateForBranch({ autoShip, fallbackMode, repoRoot, branch, baseBranch }, deps = {}) {
881
+ if (!autoShip || fallbackMode !== '') {
882
+ return { skip: false };
883
+ }
884
+ const gate = deps.runReviewGate || runReviewGate;
885
+ // Override the reviewer for unattended runs: if the default provider is
886
+ // unavailable in the sweep environment, GUARDEX_AUTO_SHIP_REVIEW_PROVIDER
887
+ // avoids a permanent gate-block on every branch.
888
+ const reviewProvider = process.env.GUARDEX_AUTO_SHIP_REVIEW_PROVIDER || 'codex';
889
+ try {
890
+ gate({
891
+ repoRoot,
892
+ branch,
893
+ baseBranch,
894
+ options: { reviewProvider, allowNoChecks: false },
895
+ });
896
+ return { skip: false };
897
+ } catch (error) {
898
+ return { skip: true, reason: `merge gate blocked (${error.message})` };
899
+ }
900
+ }
901
+
866
902
  function autoFinishReadyAgentBranches(repoRoot, options = {}) {
867
903
  const baseBranch = String(options.baseBranch || '').trim();
868
904
  const dryRun = Boolean(options.dryRun);
@@ -872,6 +908,7 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
872
908
  ? options.excludeBranches.map((branch) => String(branch || '').trim()).filter(Boolean)
873
909
  : [],
874
910
  );
911
+ const autoShip = envFlagIsTruthy(process.env.GUARDEX_AUTO_SHIP);
875
912
 
876
913
  const summary = {
877
914
  enabled: true,
@@ -984,6 +1021,16 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
984
1021
  continue;
985
1022
  }
986
1023
 
1024
+ const gateOutcome = runAutoShipGateForBranch(
1025
+ { autoShip, fallbackMode, repoRoot, branch, baseBranch },
1026
+ { runReviewGate: options.runReviewGate },
1027
+ );
1028
+ if (gateOutcome.skip) {
1029
+ summary.skipped += 1;
1030
+ summary.details.push(`[skip] ${branch}: ${gateOutcome.reason}`);
1031
+ continue;
1032
+ }
1033
+
987
1034
  summary.attempted += 1;
988
1035
  const finishArgs = [
989
1036
  '--branch',
@@ -1000,6 +1047,7 @@ function autoFinishReadyAgentBranches(repoRoot, options = {}) {
1000
1047
  }
1001
1048
  finishArgs.push(waitForMerge ? '--wait-for-merge' : '--no-wait-for-merge');
1002
1049
  finishArgs.push('--cleanup');
1050
+
1003
1051
  const finishResult = runPackageAsset('branchFinish', finishArgs, { cwd: repoRoot });
1004
1052
  const combinedOutput = [finishResult.stdout || '', finishResult.stderr || ''].join('\n').trim();
1005
1053
 
@@ -1098,6 +1146,13 @@ function executeDoctorSandboxLifecycle(options, blocked, metadata, integrations)
1098
1146
 
1099
1147
  execution.omxScaffoldSync = summarizeDoctorOmxScaffoldSync(blocked.repoRoot, dryRun);
1100
1148
 
1149
+ // `gx doctor` is the explicit recovery path for an invalid lock registry.
1150
+ // Publish the repaired sandbox copy before claiming changed files so the
1151
+ // fail-closed lock tool never has to ignore corrupt sibling state.
1152
+ const lockSyncState = syncDoctorLockRegistryBeforeMerge(blocked.repoRoot, metadata);
1153
+ execution.lockSync = lockSyncState.result;
1154
+ execution.sandboxLockContent = lockSyncState.sandboxLockContent;
1155
+
1101
1156
  if (!dryRun) {
1102
1157
  execution.autoCommit = autoCommitDoctorSandboxChanges(metadata);
1103
1158
  if (execution.autoCommit.status === 'committed') {
@@ -1112,10 +1167,6 @@ function executeDoctorSandboxLifecycle(options, blocked, metadata, integrations)
1112
1167
  execution.finish = createDoctorSkippedOperation('dry-run skips doctor sandbox finish flow');
1113
1168
  }
1114
1169
 
1115
- const lockSyncState = syncDoctorLockRegistryBeforeMerge(blocked.repoRoot, metadata);
1116
- execution.lockSync = lockSyncState.result;
1117
- execution.sandboxLockContent = lockSyncState.sandboxLockContent;
1118
-
1119
1170
  execution.protectedBaseRepairSync = mergeDoctorSandboxRepairsBackToProtectedBase(
1120
1171
  options,
1121
1172
  blocked,
@@ -1320,6 +1371,7 @@ function runDoctorInSandbox(options, blocked, rawIntegrations = {}) {
1320
1371
  }
1321
1372
 
1322
1373
  module.exports = {
1374
+ doctorFinishFlowIsPending,
1323
1375
  extractAgentBranchStartMetadata,
1324
1376
  resolveSandboxTarget,
1325
1377
  buildSandboxDoctorArgs,
@@ -1336,6 +1388,7 @@ module.exports = {
1336
1388
  emitDoctorSandboxJsonOutput,
1337
1389
  emitDoctorSandboxConsoleOutput,
1338
1390
  autoFinishReadyAgentBranches,
1391
+ runAutoShipGateForBranch,
1339
1392
  pruneStaleAgentWorktrees,
1340
1393
  runDoctorInSandbox,
1341
1394
  };