@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
package/src/cli/args.js CHANGED
@@ -2,6 +2,7 @@ const {
2
2
  path,
3
3
  DEFAULT_SHADOW_CLEANUP_IDLE_MINUTES,
4
4
  TARGETED_FORCEABLE_MANAGED_PATHS,
5
+ envFlagIsTruthy,
5
6
  } = require('../context');
6
7
  const { DEFAULT_NESTED_REPO_MAX_DEPTH } = require('../git');
7
8
 
@@ -293,6 +294,9 @@ function parsePrReviewArgs(rawArgs) {
293
294
  post: false,
294
295
  artifact: '',
295
296
  timeoutMs: 10 * 60 * 1000,
297
+ // Apply the findings as commits on the current agent branch instead of only
298
+ // reporting them. Off by default: this writes to the working tree.
299
+ fix: false,
296
300
  };
297
301
 
298
302
  for (let index = 0; index < parsed.args.length; index += 1) {
@@ -319,6 +323,14 @@ function parsePrReviewArgs(rawArgs) {
319
323
  options.post = false;
320
324
  continue;
321
325
  }
326
+ if (arg === '--fix') {
327
+ options.fix = true;
328
+ continue;
329
+ }
330
+ if (arg === '--no-fix') {
331
+ options.fix = false;
332
+ continue;
333
+ }
322
334
  if (arg === '--artifact' || arg === '--output') {
323
335
  options.artifact = requireValue(parsed.args, index, arg);
324
336
  index += 1;
@@ -373,6 +385,12 @@ function parseAgentsArgs(rawArgs) {
373
385
  sessionId: '',
374
386
  finishArgs: [],
375
387
  metadata: {},
388
+ activity: '',
389
+ worktree: '',
390
+ backend: '',
391
+ waiting: false,
392
+ done: false,
393
+ print: false,
376
394
  };
377
395
  let terminalProvided = false;
378
396
 
@@ -421,6 +439,54 @@ function parseAgentsArgs(rawArgs) {
421
439
  index += 1;
422
440
  continue;
423
441
  }
442
+ if (arg === '--session') {
443
+ const next = rest[index + 1];
444
+ if (!next) {
445
+ throw new Error('--session requires an agent session id');
446
+ }
447
+ options.sessionId = next;
448
+ index += 1;
449
+ continue;
450
+ }
451
+ if (arg === '--activity' || arg === '--status') {
452
+ const next = rest[index + 1];
453
+ if (!next || next.startsWith('-')) {
454
+ throw new Error('--activity requires a state (working, waiting, done, idle)');
455
+ }
456
+ options.activity = next;
457
+ index += 1;
458
+ continue;
459
+ }
460
+ if (arg === '--worktree') {
461
+ const next = rest[index + 1];
462
+ if (!next) {
463
+ throw new Error('--worktree requires a path');
464
+ }
465
+ options.worktree = next;
466
+ index += 1;
467
+ continue;
468
+ }
469
+ if (arg === '--backend') {
470
+ const next = rest[index + 1];
471
+ if (!next || next.startsWith('-')) {
472
+ throw new Error('--backend requires auto, kitty, or tmux');
473
+ }
474
+ options.backend = next;
475
+ index += 1;
476
+ continue;
477
+ }
478
+ if (arg === '--waiting') {
479
+ options.waiting = true;
480
+ continue;
481
+ }
482
+ if (arg === '--done') {
483
+ options.done = true;
484
+ continue;
485
+ }
486
+ if (arg === '--print') {
487
+ options.print = true;
488
+ continue;
489
+ }
424
490
  if (arg === '--json') {
425
491
  options.json = true;
426
492
  continue;
@@ -592,7 +658,7 @@ function parseAgentsArgs(rawArgs) {
592
658
  throw new Error(`Unknown option: ${arg}`);
593
659
  }
594
660
 
595
- if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions'].includes(options.subcommand)) {
661
+ if (!['start', 'stop', 'status', 'files', 'diff', 'locks', 'finish', 'cleanup-sessions', 'set-status', 'jump'].includes(options.subcommand)) {
596
662
  throw new Error(`Unknown agents subcommand: ${options.subcommand}`);
597
663
  }
598
664
  if (options.pid !== null && options.subcommand !== 'stop') {
@@ -638,8 +704,17 @@ function parseAgentsArgs(rawArgs) {
638
704
  throw new Error('agents finish accepts only one of --session or --branch');
639
705
  }
640
706
  }
641
- if (options.branch && !['files', 'diff', 'locks', 'finish'].includes(options.subcommand)) {
642
- throw new Error('--branch is only supported with `gx agents files|diff|locks|finish`');
707
+ if (options.branch && !['files', 'diff', 'locks', 'finish', 'set-status', 'jump'].includes(options.subcommand)) {
708
+ throw new Error('--branch is only supported with `gx agents files|diff|locks|finish|set-status|jump`');
709
+ }
710
+ if ((options.activity || options.worktree) && !['set-status'].includes(options.subcommand)) {
711
+ throw new Error('--activity and --worktree are only supported with `gx agents set-status`');
712
+ }
713
+ if ((options.waiting || options.done || options.print) && !['jump'].includes(options.subcommand)) {
714
+ throw new Error('--waiting, --done, and --print are only supported with `gx agents jump`');
715
+ }
716
+ if (options.subcommand === 'set-status' && !options.activity) {
717
+ throw new Error('gx agents set-status requires --activity <working|waiting|done|idle>');
643
718
  }
644
719
  if (
645
720
  options.json &&
@@ -1077,6 +1152,14 @@ function parseMergeArgs(rawArgs) {
1077
1152
  }
1078
1153
 
1079
1154
  function parseFinishArgs(rawArgs, defaults = {}) {
1155
+ // `GUARDEX_AUTO_SHIP=1` (opt-in) makes a bare `gx finish` / `gx branch finish`
1156
+ // behave like `gx ship`: open a PR from the worktree, wait for merge, clean up,
1157
+ // and enforce the merge gate (clean AI review + green CI) before merging to base.
1158
+ // via-pr / wait-for-merge / cleanup are already the defaults, so the only delta
1159
+ // is flipping the gate-review default on. Explicit flags (e.g. --no-gate-review)
1160
+ // still override below.
1161
+ const autoShip = envFlagIsTruthy(process.env.GUARDEX_AUTO_SHIP);
1162
+ const fastMode = rawArgs.includes('--fast');
1080
1163
  const options = {
1081
1164
  target: process.cwd(),
1082
1165
  base: '',
@@ -1091,11 +1174,33 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1091
1174
  advanceSubmodules: false,
1092
1175
  failFast: false,
1093
1176
  commitMessage: '',
1094
- mergeMode: defaults.mergeMode || 'pr',
1095
- skipPreflight: false,
1096
- gateReview: defaults.gateReview ?? false,
1177
+ mergeMode: fastMode ? 'pr' : (defaults.mergeMode || 'pr'),
1178
+ fastMode,
1179
+ skipPreflight: fastMode,
1180
+ // Precedence: explicit flag (set in the loop below) > defaults (caller) >
1181
+ // GUARDEX_AUTO_SHIP env > hardcoded off. Note `defaults.gateReview === false`
1182
+ // (not undefined) also wins over the env toggle, since `??` only falls
1183
+ // through on null/undefined.
1184
+ gateReview: fastMode ? false : (defaults.gateReview ?? autoShip),
1097
1185
  reviewProvider: defaults.reviewProvider || 'codex',
1186
+ // Empty = the provider's own default model.
1187
+ reviewModel: defaults.reviewModel || '',
1188
+ reviewTimeoutMs: defaults.reviewTimeoutMs,
1189
+ // Keep the PR draft until the review passes so GitHub cannot merge it while
1190
+ // the verdict is pending. `--no-gate-serial-ci` explicitly opts into overlap.
1191
+ gateSerialCi: defaults.gateSerialCi ?? true,
1098
1192
  allowNoChecks: false,
1193
+ // Gate on "no NEW failing checks vs the base branch" instead of absolute
1194
+ // green, so a repo whose base is already red can still ship unattended.
1195
+ gateBaseline: false,
1196
+ // Let the gate repair its own blocking findings instead of only reporting
1197
+ // them. Off by default: this writes commits to the branch.
1198
+ gateAutofix: false,
1199
+ gateAutofixRounds: 1,
1200
+ // After a bulk `--all` finish, sweep merged-but-stranded worktree dirs whose
1201
+ // branch was merged out-of-band and never reaped (the post-merge "retained"
1202
+ // gap). Only fires for `--all`; opt out with --no-sweep-orphans.
1203
+ sweepOrphans: defaults.sweepOrphans ?? true,
1099
1204
  };
1100
1205
 
1101
1206
  for (let index = 0; index < rawArgs.length; index += 1) {
@@ -1140,10 +1245,21 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1140
1245
  options.all = true;
1141
1246
  continue;
1142
1247
  }
1248
+ if (arg === '--no-sweep-orphans') {
1249
+ options.sweepOrphans = false;
1250
+ continue;
1251
+ }
1252
+ if (arg === '--sweep-orphans') {
1253
+ options.sweepOrphans = true;
1254
+ continue;
1255
+ }
1143
1256
  if (arg === '--dry-run') {
1144
1257
  options.dryRun = true;
1145
1258
  continue;
1146
1259
  }
1260
+ if (arg === '--fast') {
1261
+ continue;
1262
+ }
1147
1263
  if (arg === '--wait-for-merge') {
1148
1264
  options.waitForMerge = true;
1149
1265
  continue;
@@ -1224,6 +1340,33 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1224
1340
  options.allowNoChecks = true;
1225
1341
  continue;
1226
1342
  }
1343
+ if (arg === '--gate-baseline') {
1344
+ options.gateBaseline = true;
1345
+ continue;
1346
+ }
1347
+ if (arg === '--no-gate-baseline') {
1348
+ options.gateBaseline = false;
1349
+ continue;
1350
+ }
1351
+ if (arg === '--gate-autofix') {
1352
+ options.gateAutofix = true;
1353
+ continue;
1354
+ }
1355
+ if (arg === '--no-gate-autofix') {
1356
+ options.gateAutofix = false;
1357
+ continue;
1358
+ }
1359
+ if (arg === '--gate-autofix-rounds') {
1360
+ const raw = rawArgs[index + 1];
1361
+ const rounds = Number.parseInt(String(raw ?? ''), 10);
1362
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > 5) {
1363
+ throw new Error('--gate-autofix-rounds requires an integer between 1 and 5');
1364
+ }
1365
+ options.gateAutofixRounds = rounds;
1366
+ options.gateAutofix = true;
1367
+ index += 1;
1368
+ continue;
1369
+ }
1227
1370
  if (arg === '--review-provider') {
1228
1371
  const next = rawArgs[index + 1];
1229
1372
  if (!next || !['codex', 'claude'].includes(next)) {
@@ -1233,9 +1376,63 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1233
1376
  index += 1;
1234
1377
  continue;
1235
1378
  }
1379
+ if (arg === '--review-model') {
1380
+ const next = String(rawArgs[index + 1] ?? '').trim();
1381
+ if (!next || next.startsWith('-')) {
1382
+ throw new Error('--review-model requires a model name (e.g. sonnet)');
1383
+ }
1384
+ options.reviewModel = next;
1385
+ index += 1;
1386
+ continue;
1387
+ }
1388
+ if (arg === '--review-timeout-ms') {
1389
+ const raw = rawArgs[index + 1];
1390
+ const timeoutMs = Number.parseInt(String(raw ?? ''), 10);
1391
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
1392
+ throw new Error('--review-timeout-ms requires a positive integer');
1393
+ }
1394
+ options.reviewTimeoutMs = timeoutMs;
1395
+ index += 1;
1396
+ continue;
1397
+ }
1398
+ if (arg === '--gate-serial-ci') {
1399
+ options.gateSerialCi = true;
1400
+ continue;
1401
+ }
1402
+ if (arg === '--no-gate-serial-ci') {
1403
+ options.gateSerialCi = false;
1404
+ continue;
1405
+ }
1236
1406
  throw new Error(`Unknown option: ${arg}`);
1237
1407
  }
1238
1408
 
1409
+ if (fastMode) {
1410
+ const incompatibleFlag = rawArgs.find((arg) => [
1411
+ '--gate-review',
1412
+ '--gate-autofix',
1413
+ '--gate-autofix-rounds',
1414
+ '--preflight',
1415
+ '--direct-only',
1416
+ ].includes(arg));
1417
+ const modeIndex = rawArgs.indexOf('--mode');
1418
+ const modeValue = modeIndex >= 0 ? rawArgs[modeIndex + 1] : '';
1419
+ const incompatibleMode = modeIndex >= 0 && modeValue !== 'pr'
1420
+ ? `--mode ${modeValue || '<missing>'}`
1421
+ : '';
1422
+ const conflict = incompatibleFlag || incompatibleMode;
1423
+ if (conflict) {
1424
+ throw new Error(`--fast cannot be combined with ${conflict}`);
1425
+ }
1426
+
1427
+ // Fast mode is an explicit per-run profile: PR/squash path, no local
1428
+ // preflight, and no AI review/autofix. GitHub branch protection and its
1429
+ // required checks remain authoritative at merge time.
1430
+ options.mergeMode = 'pr';
1431
+ options.skipPreflight = true;
1432
+ options.gateReview = false;
1433
+ options.gateAutofix = false;
1434
+ }
1435
+
1239
1436
  if (options.branch && !options.branch.startsWith('agent/')) {
1240
1437
  throw new Error(`--branch must reference an agent/* branch (received: ${options.branch})`);
1241
1438
  }
@@ -11,6 +11,7 @@ const { resolveRepoRoot } = require('../../git');
11
11
  const { run } = require('../../core/runtime');
12
12
  const agentInspect = require('../../agents/inspect');
13
13
  const agentStatus = require('../../agents/status');
14
+ const agentActivity = require('../../agents/activity');
14
15
  const agentCleanupSessions = require('../../agents/cleanup-sessions');
15
16
  const agentsFinishModule = require('../../agents/finish');
16
17
  const agentsStart = require('../../agents/start');
@@ -171,6 +172,22 @@ function agents(rawArgs) {
171
172
  const repoRoot = resolveRepoRoot(options.target);
172
173
  const statePath = agentsStatePathForRepo(repoRoot);
173
174
 
175
+ if (options.subcommand === 'set-status') {
176
+ const result = agentActivity.runSetStatusCommand(repoRoot, options);
177
+ if (result.stdout) process.stdout.write(result.stdout);
178
+ if (result.stderr) process.stderr.write(result.stderr);
179
+ process.exitCode = result.status;
180
+ return;
181
+ }
182
+
183
+ if (options.subcommand === 'jump') {
184
+ const result = agentActivity.runJumpCommand(repoRoot, options);
185
+ if (result.stdout) process.stdout.write(result.stdout);
186
+ if (result.stderr) process.stderr.write(result.stderr);
187
+ process.exitCode = result.status;
188
+ return;
189
+ }
190
+
174
191
  if (options.subcommand === 'finish') {
175
192
  const result = finishAgentSession(repoRoot, options);
176
193
  if (options.json) {
@@ -1,14 +1,197 @@
1
1
  // `gx branch`, `gx pivot`, `gx ship`, `gx locks`, `gx worktree` — branch
2
2
  // workflow surface. Pure code-motion from src/cli/main.js.
3
- const { TOOL_NAME, SHORT_TOOL_NAME } = require('../../context');
4
- const { resolveRepoRoot } = require('../../git');
3
+ const {
4
+ TOOL_NAME,
5
+ SHORT_TOOL_NAME,
6
+ path,
7
+ fs,
8
+ } = require('../../context');
9
+ const {
10
+ resolveRepoRoot,
11
+ resolveFinishBaseBranch,
12
+ currentBranchName,
13
+ listAgentWorktrees,
14
+ } = require('../../git');
5
15
  const {
6
16
  run,
7
17
  extractTargetedArgs,
8
18
  runPackageAsset,
9
19
  invokePackageAsset,
10
20
  } = require('../../core/runtime');
21
+ const { runReviewGate } = require('../../finish/review-gate');
22
+ const { createFinishProgress } = require('../../finish/progress');
23
+ const { autoCommitWorktreeForFinish } = require('../../finish');
11
24
  const { finish, merge } = require('./finish');
25
+ const { locks } = require('../shared-locks');
26
+
27
+ const REVIEW_PROVIDERS = ['codex', 'claude'];
28
+
29
+ // Review-gate and auto-commit options are gx-level flags.
30
+ // agent-branch-finish.sh does not parse them (it exits 1 on the unknown
31
+ // argument), and its --via-pr path merges the moment the PR opens, so the shell
32
+ // cannot enforce the gate itself. Pull the flags out of the script's argv and
33
+ // honor them here.
34
+ function splitGateReviewFlags(args) {
35
+ const scriptArgs = [];
36
+ let fastMode = false;
37
+ let gateReview = false;
38
+ let reviewProvider;
39
+ let gateAutofix = false;
40
+ let gateAutofixRounds = 1;
41
+ let gateBaseline = false;
42
+ let gateSerialCi = true;
43
+ let reviewModel;
44
+ let reviewTimeoutMs;
45
+ let noAutoCommit = false;
46
+ let commitMessage = '';
47
+ for (let index = 0; index < args.length; index += 1) {
48
+ const arg = args[index];
49
+ if (arg === '--fast') {
50
+ fastMode = true;
51
+ } else if (arg === '--no-auto-commit') {
52
+ noAutoCommit = true;
53
+ } else if (arg === '--commit-message') {
54
+ commitMessage = String(args[index + 1] ?? '').trim();
55
+ if (!commitMessage || commitMessage.startsWith('-')) {
56
+ throw new Error('--commit-message requires a value');
57
+ }
58
+ index += 1;
59
+ } else if (arg === '--gate-review') {
60
+ gateReview = true;
61
+ } else if (arg === '--no-gate-review' || arg === '--skip-review-gate') {
62
+ gateReview = false;
63
+ } else if (arg === '--gate-serial-ci') {
64
+ gateSerialCi = true;
65
+ } else if (arg === '--no-gate-serial-ci') {
66
+ gateSerialCi = false;
67
+ } else if (arg === '--review-model') {
68
+ // Consume the value for the same reason as --review-provider: a bare
69
+ // model name left behind becomes a positional the shell script rejects.
70
+ reviewModel = args[index + 1] ?? '';
71
+ index += 1;
72
+ } else if (arg.startsWith('--review-model=')) {
73
+ reviewModel = arg.slice('--review-model='.length);
74
+ } else if (arg === '--review-timeout-ms' || arg.startsWith('--review-timeout-ms=')) {
75
+ // The shell script does not know this gx-level gate flag either.
76
+ reviewTimeoutMs = arg.includes('=') ? arg.slice('--review-timeout-ms='.length) : (args[index + 1] ?? '');
77
+ if (!arg.includes('=')) index += 1;
78
+ } else if (arg === '--gate-baseline') {
79
+ gateBaseline = true;
80
+ } else if (arg === '--no-gate-baseline') {
81
+ gateBaseline = false;
82
+ } else if (arg === '--gate-autofix') {
83
+ gateAutofix = true;
84
+ } else if (arg === '--no-gate-autofix') {
85
+ gateAutofix = false;
86
+ } else if (arg === '--gate-autofix-rounds' || arg.startsWith('--gate-autofix-rounds=')) {
87
+ // Consume the value too, for the same reason as --review-provider: a bare
88
+ // number left behind becomes a positional the shell script rejects.
89
+ let raw;
90
+ if (arg.includes('=')) {
91
+ raw = arg.slice('--gate-autofix-rounds='.length);
92
+ } else {
93
+ raw = args[index + 1];
94
+ index += 1;
95
+ }
96
+ const rounds = Number.parseInt(String(raw ?? ''), 10);
97
+ if (!Number.isInteger(rounds) || rounds < 1 || rounds > 5) {
98
+ throw new Error('--gate-autofix-rounds requires an integer between 1 and 5');
99
+ }
100
+ gateAutofixRounds = rounds;
101
+ gateAutofix = true;
102
+ } else if (arg === '--review-provider') {
103
+ // Consume the value too — leaving it behind would hand the script a bare
104
+ // "claude" positional and it would exit 1. A missing value becomes "" so
105
+ // the check below rejects it, matching args.js: falling back to the
106
+ // default here would gate with codex a caller who asked for claude.
107
+ reviewProvider = args[index + 1] ?? '';
108
+ index += 1;
109
+ } else if (arg.startsWith('--review-provider=')) {
110
+ reviewProvider = arg.slice('--review-provider='.length);
111
+ } else {
112
+ scriptArgs.push(arg);
113
+ }
114
+ }
115
+
116
+ if (fastMode) {
117
+ const incompatibleFlag = args.find((arg) => [
118
+ '--gate-review',
119
+ '--gate-autofix',
120
+ '--gate-autofix-rounds',
121
+ '--preflight',
122
+ '--direct-only',
123
+ ].includes(arg));
124
+ const modeIndex = args.indexOf('--mode');
125
+ const modeValue = modeIndex >= 0 ? args[modeIndex + 1] : '';
126
+ const incompatibleMode = modeIndex >= 0 && modeValue !== 'pr'
127
+ ? `--mode ${modeValue || '<missing>'}`
128
+ : '';
129
+ const conflict = incompatibleFlag || incompatibleMode;
130
+ if (conflict) {
131
+ throw new Error(`--fast cannot be combined with ${conflict}`);
132
+ }
133
+
134
+ gateReview = false;
135
+ gateAutofix = false;
136
+ if (!scriptArgs.includes('--via-pr')) scriptArgs.push('--via-pr');
137
+ if (!scriptArgs.includes('--no-preflight')) scriptArgs.push('--no-preflight');
138
+ }
139
+
140
+ if (reviewProvider !== undefined) {
141
+ reviewProvider = String(reviewProvider).trim().toLowerCase();
142
+ // Fail closed on a typo rather than silently falling back to the default: a
143
+ // caller who named a provider must not quietly get a different one.
144
+ if (!REVIEW_PROVIDERS.includes(reviewProvider)) {
145
+ throw new Error(`--review-provider requires a value of ${REVIEW_PROVIDERS.join('|')}`);
146
+ }
147
+ }
148
+
149
+ if (reviewModel !== undefined) {
150
+ reviewModel = String(reviewModel).trim();
151
+ // Same fail-closed reasoning as --review-provider: a caller who named a
152
+ // model must not silently get the provider's default one instead.
153
+ if (!reviewModel || reviewModel.startsWith('-')) {
154
+ throw new Error('--review-model requires a model name (e.g. sonnet)');
155
+ }
156
+ }
157
+
158
+ if (reviewTimeoutMs !== undefined) {
159
+ reviewTimeoutMs = Number.parseInt(String(reviewTimeoutMs ?? ''), 10);
160
+ if (!Number.isInteger(reviewTimeoutMs) || reviewTimeoutMs <= 0) {
161
+ throw new Error('--review-timeout-ms requires a positive integer');
162
+ }
163
+ }
164
+
165
+ return {
166
+ gateReview,
167
+ reviewProvider,
168
+ reviewModel,
169
+ reviewTimeoutMs,
170
+ gateAutofix,
171
+ gateAutofixRounds,
172
+ gateBaseline,
173
+ gateSerialCi,
174
+ noAutoCommit,
175
+ commitMessage,
176
+ scriptArgs,
177
+ };
178
+ }
179
+
180
+ // Read `--flag value` or `--flag=value` out of an argv array.
181
+ function readFlagValue(args, flag) {
182
+ const index = args.indexOf(flag);
183
+ if (index >= 0 && index + 1 < args.length) return args[index + 1];
184
+ const inline = args.find((arg) => arg.startsWith(`${flag}=`));
185
+ return inline ? inline.slice(flag.length + 1) : undefined;
186
+ }
187
+
188
+ function isLinkedAgentWorktree(worktreePath) {
189
+ try {
190
+ return fs.statSync(path.join(worktreePath, '.git')).isFile();
191
+ } catch {
192
+ return false;
193
+ }
194
+ }
12
195
 
13
196
  function branch(rawArgs) {
14
197
  const activeCwd = process.cwd();
@@ -20,9 +203,83 @@ function branch(rawArgs) {
20
203
  }
21
204
  if (subcommand === 'finish') {
22
205
  const { target, passthrough } = extractTargetedArgs(rest);
23
- invokePackageAsset('branchFinish', passthrough, {
24
- cwd: resolveRepoRoot(target),
25
- env: { GUARDEX_FINISH_ACTIVE_CWD: activeCwd },
206
+ const repoRoot = resolveRepoRoot(target);
207
+ const {
208
+ gateReview,
209
+ reviewProvider,
210
+ reviewModel,
211
+ reviewTimeoutMs,
212
+ gateAutofix,
213
+ gateAutofixRounds,
214
+ gateBaseline,
215
+ gateSerialCi,
216
+ noAutoCommit,
217
+ commitMessage,
218
+ scriptArgs,
219
+ } = splitGateReviewFlags(passthrough);
220
+ const finishBranch = readFlagValue(scriptArgs, '--branch') || currentBranchName(repoRoot);
221
+ const finishBase = resolveFinishBaseBranch(repoRoot, finishBranch, readFlagValue(scriptArgs, '--base'));
222
+ const finishWorktree = listAgentWorktrees(repoRoot)
223
+ .find((entry) => entry.branch === finishBranch)?.worktreePath || '';
224
+ // Keep the legacy behavior for agent branches checked out directly in the
225
+ // primary repository. Guardex-managed lanes are linked worktrees; limiting
226
+ // auto-commit to those avoids scooping primary-checkout runtime artifacts
227
+ // into an otherwise already-committed branch.
228
+ const autoCommitWorktree = finishWorktree && isLinkedAgentWorktree(finishWorktree)
229
+ ? finishWorktree
230
+ : '';
231
+ const progress = createFinishProgress({ repoRoot, branch: finishBranch, baseBranch: finishBase });
232
+ progress.start(
233
+ 'prepare',
234
+ autoCommitWorktree ? 'checking worktree and pending changes' : 'resolving branch and finish policy',
235
+ );
236
+ const commitState = autoCommitWorktree
237
+ ? autoCommitWorktreeForFinish(repoRoot, autoCommitWorktree, finishBranch, { noAutoCommit, commitMessage })
238
+ : { changed: false, committed: false };
239
+ if (commitState.committed) {
240
+ console.log(`[${TOOL_NAME}] Auto-committed '${finishBranch}' before finish.`);
241
+ }
242
+ progress.complete(
243
+ 'prepare',
244
+ commitState.committed ? 'pending changes auto-committed' : 'branch and base resolved',
245
+ );
246
+ // Fail-closed: runReviewGate throws on a dirty review, red CI, or a PR
247
+ // GitHub will not merge. Throwing here means the script never runs, so
248
+ // the merge never happens.
249
+ if (gateReview) {
250
+ runReviewGate({
251
+ repoRoot,
252
+ branch: finishBranch,
253
+ // Must match how the shell resolves --base when it is omitted, which
254
+ // honors branch.<name>.guardexBase. Resolving differently would gate one
255
+ // base and merge into another.
256
+ baseBranch: finishBase,
257
+ // review-gate.js falls back to its own default when this is undefined,
258
+ // which keeps a bare --gate-review behaving exactly as before.
259
+ options: {
260
+ reviewProvider,
261
+ reviewModel,
262
+ reviewTimeoutMs,
263
+ gateAutofix,
264
+ gateAutofixRounds,
265
+ gateBaseline,
266
+ gateSerialCi,
267
+ },
268
+ progress,
269
+ });
270
+ } else {
271
+ progress.skip('review', 'review gate disabled');
272
+ progress.skip('autofix', 'review gate disabled');
273
+ progress.skip('ci', 'review gate disabled; repository policy controls merge readiness');
274
+ }
275
+ invokePackageAsset('branchFinish', scriptArgs, {
276
+ cwd: repoRoot,
277
+ env: {
278
+ GUARDEX_FINISH_ACTIVE_CWD: activeCwd,
279
+ GUARDEX_FINISH_CHECKLIST: '1',
280
+ GUARDEX_FINISH_GATE_DONE: gateReview ? '1' : '0',
281
+ ...progress.eventEnv,
282
+ },
26
283
  });
27
284
  return;
28
285
  }
@@ -90,20 +347,16 @@ function ship(rawArgs) {
90
347
  ensureFlag('--cleanup');
91
348
  // `gx ship` enforces the merge gate (clean review + green CI) by default;
92
349
  // an explicit --no-gate-review / --skip-review-gate opts back out.
93
- if (!args.includes('--no-gate-review') && !args.includes('--skip-review-gate')) {
350
+ if (
351
+ !args.includes('--fast')
352
+ && !args.includes('--no-gate-review')
353
+ && !args.includes('--skip-review-gate')
354
+ ) {
94
355
  ensureFlag('--gate-review');
95
356
  }
96
357
  return finish(args);
97
358
  }
98
359
 
99
- function locks(rawArgs) {
100
- const { target, passthrough } = extractTargetedArgs(rawArgs);
101
- const result = runPackageAsset('lockTool', passthrough, { cwd: resolveRepoRoot(target) });
102
- if (result.stdout) process.stdout.write(result.stdout);
103
- if (result.stderr) process.stderr.write(result.stderr);
104
- process.exitCode = result.status;
105
- }
106
-
107
360
  function worktree(rawArgs) {
108
361
  const activeCwd = process.cwd();
109
362
  const [subcommand, ...rest] = rawArgs;
@@ -31,6 +31,10 @@ const MANAGED_HOOK_FILES = [
31
31
  'agent_branch_advisor.py',
32
32
  'post_edit_tracker.py',
33
33
  'skill_tracker.py',
34
+ // Shared module imported by agent_branch_advisor.py + post_edit_tracker.py
35
+ // for live-session presence. Must ship with them or those hooks fail their
36
+ // import (fail-open, but then presence is silently absent on target repos).
37
+ '_session_presence.py',
34
38
  ];
35
39
 
36
40
  const MANAGED_SLASH_COMMANDS = [
@@ -48,6 +52,7 @@ const EXPECTED_HOOK_MATCHERS = {
48
52
  UserPromptSubmit: ['skill_activation.py', 'agent_branch_advisor.py'],
49
53
  PreToolUse: ['skill_guard.py'],
50
54
  PostToolUse: ['post_edit_tracker.py', 'skill_tracker.py'],
55
+ Stop: ['agent-claude-stop-finish.sh'],
51
56
  };
52
57
 
53
58
  const TEMPLATE_DEFAULT_SETTINGS = {
@@ -111,6 +116,16 @@ const TEMPLATE_DEFAULT_SETTINGS = {
111
116
  ],
112
117
  },
113
118
  ],
119
+ Stop: [
120
+ {
121
+ hooks: [
122
+ {
123
+ type: 'command',
124
+ command: 'bash "${CLAUDE_PROJECT_DIR:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}/scripts/agent-claude-stop-finish.sh"',
125
+ },
126
+ ],
127
+ },
128
+ ],
114
129
  },
115
130
  };
116
131