@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.
Files changed (50) hide show
  1. package/README.md +115 -324
  2. package/package.json +23 -5
  3. package/skills/gitguardex/SKILL.md +83 -3
  4. package/src/agents/finish.js +15 -0
  5. package/src/ci-init/index.js +0 -1
  6. package/src/cli/args.js +137 -3
  7. package/src/cli/commands/branch.js +267 -14
  8. package/src/cli/commands/claude.js +15 -0
  9. package/src/cli/commands/doctor.js +26 -0
  10. package/src/cli/commands/onboard.js +293 -0
  11. package/src/cli/commands/prompt.js +15 -3
  12. package/src/cli/commands/review.js +18 -0
  13. package/src/cli/commands/setup.js +8 -6
  14. package/src/cli/commands/status.js +12 -0
  15. package/src/cli/main.js +2 -0
  16. package/src/cli/shared-locks.js +304 -0
  17. package/src/context.js +21 -3
  18. package/src/core/runtime.js +33 -1
  19. package/src/doctor/index.js +58 -5
  20. package/src/finish/heartbeat.js +169 -0
  21. package/src/finish/index.js +106 -4
  22. package/src/finish/progress.js +262 -0
  23. package/src/finish/review-gate.js +453 -32
  24. package/src/github-api.js +59 -0
  25. package/src/mcp/collect.js +87 -12
  26. package/src/output/index.js +210 -0
  27. package/src/pr-checks.js +121 -0
  28. package/src/pr-review.js +581 -51
  29. package/src/pr.js +143 -21
  30. package/src/provider-binary.js +101 -0
  31. package/src/review-diff.js +116 -0
  32. package/src/review-fix.js +229 -0
  33. package/src/sandbox/index.js +11 -5
  34. package/src/scaffold/index.js +4 -16
  35. package/src/shared-git-state.js +566 -0
  36. package/templates/AGENTS.multiagent-safety.md +63 -11
  37. package/templates/AGENTS.multiagent-safety.min.md +1 -0
  38. package/templates/codex/skills/gitguardex/SKILL.md +83 -3
  39. package/templates/githooks/post-checkout +4 -9
  40. package/templates/githooks/pre-commit +17 -1
  41. package/templates/github/workflows/README.md +30 -23
  42. package/templates/scripts/agent-autofinish-watch.sh +280 -0
  43. package/templates/scripts/agent-branch-finish.sh +354 -23
  44. package/templates/scripts/agent-branch-start.sh +49 -22
  45. package/templates/scripts/agent-claude-stop-finish.sh +194 -0
  46. package/templates/scripts/agent-file-locks.py +167 -24
  47. package/templates/scripts/agent-preflight.sh +14 -2
  48. package/templates/scripts/agent-stalled-report.sh +40 -0
  49. package/templates/scripts/codex-agent.sh +10 -63
  50. package/templates/github/workflows/cr.yml +0 -46
@@ -1,13 +1,93 @@
1
1
  ---
2
2
  name: gitguardex
3
- description: "Repo guardrail check and repair."
3
+ description: "Use for GitGuardex branch/worktree safety, agent or subagent collision avoidance, file ownership, and gated PR finishing. Not for code-quality review."
4
4
  ---
5
5
 
6
- Use when repo safety may be broken.
6
+ Use when a GitGuardex-managed repository needs safe edits or multi-agent coordination.
7
7
 
8
8
  `gx status` -> `gx doctor` -> `gx status --strict`
9
9
 
10
10
  Bootstrap: `gx setup`
11
11
  Ops: `gx branch start "<task>" "<agent>"`, `gx locks claim --branch "<agent-branch>" <file...>`, `gx branch finish --branch "<agent-branch>" --base <base> --via-pr --wait-for-merge --cleanup`, `gx finish --all`, `gx cleanup`
12
12
 
13
- When inspecting or verifying, prefer `rtk` compact wrappers if available (`rtk git status`, `rtk grep`, `rtk test <cmd>`). Do not wrap commands whose stdout is parsed by scripts.
13
+ ## Keep the default workflow lean
14
+
15
+ - Default to direct T1 work in code and tests. Do not create OpenSpec artifacts from task wording alone.
16
+ - OpenSpec is explicit opt-in: use `--tier T2` for a change workspace or `--tier T3` for change plus plan only when the user requests OpenSpec or the caller explicitly selects T2/T3.
17
+ - Treat the commit, targeted test output, and compact final handoff as the routine task record.
18
+
19
+ ## Agent and subagent collaboration
20
+
21
+ Before parallel work, inspect the field with the MCP `list_agents` tool or the CLI fallback:
22
+
23
+ ```sh
24
+ gx mcp list-agents --no-prs
25
+ ```
26
+
27
+ For every file a writer may touch, check ownership, create an isolated lane, then claim it:
28
+
29
+ ```sh
30
+ gx mcp who-owns path/to/file.ts
31
+ gx branch start "<bounded task>" "<agent>"
32
+ gx locks claim --branch "<agent-branch>" path/to/file.ts
33
+ ```
34
+
35
+ - **One owner per file.** Split writer subagents by non-overlapping files or modules. Read-only scouts may share a surface; writers may not.
36
+ - Give each subagent one bounded objective and a verification command. Do not ask one subagent to explore, redesign, implement, and review the same slice.
37
+ - Re-check `list_agents` before expanding scope. If another lane owns or is already editing a file, coordinate a handoff or choose a different slice.
38
+ - Return a compact handoff: conclusion, `file:line`, changed files, verification result, and blocker or next action. Do not relay full logs.
39
+ - Finish each writing lane through its own PR once. Never run duplicate finish commands for the same branch.
40
+
41
+ ## Optional cross-machine Git lock and radar state
42
+
43
+ Local worktree locks remain the default. When agents on multiple machines use the same writable Git remote, opt into shared state per repository:
44
+
45
+ ```sh
46
+ gx locks shared-enable --remote origin
47
+ gx locks shared-status
48
+ ```
49
+
50
+ After enablement, ordinary `claim`, `allow-delete`, `validate`, `release`, and `status` commands also use atomic remote refs under `refs/gitguardex/locks/*`. `gx mcp list-agents` combines local worktrees with remote `agent/*` branches and shared lock owners; `gx mcp who-owns` resolves the same shared owner data.
51
+
52
+ - Shared mode is explicit and fail-closed: if the remote is unreachable, rejects custom refs, or returns invalid metadata, do not keep a local-only claim or approve a commit.
53
+ - The remote must allow authenticated custom-ref creation, compare-and-swap updates, and deletion. GitGuardex stores validated JSON metadata in commits; it never executes remote metadata, and publishes only a hashed machine identifier.
54
+ - Push the agent branch when full remote-lane visibility matters. A lock still makes an unpushed branch visible as a lock-owning remote lane.
55
+ - Release locks before disabling shared state or abandoning a lane. Cross-machine locks are not automatically reaped because one host cannot safely prove that another host's process is dead.
56
+ - `gx locks shared-disable` stops shared reads and writes for this repository; it does not delete remote refs owned by any machine.
57
+
58
+ ## Finish checklist in Codex
59
+
60
+ Before starting a long `gx finish`, `gx ship`, or `gx branch finish`, show this compact Markdown checklist in commentary and update it from the CLI's `[gx:finish]` transition lines:
61
+
62
+ - [ ] Prepare branch
63
+ - [ ] Local preflight
64
+ - [ ] Push and open PR
65
+ - [ ] AI review
66
+ - [ ] Review autofix
67
+ - [ ] CI checks
68
+ - [ ] Merge
69
+ - [ ] Cleanup
70
+
71
+ Render each state-change update as a compact card, not as a raw log dump:
72
+
73
+ ### 🚀 GX Finish · `3/8`
74
+ `agent/...` → `main` · 🔄 **AI review** · `00:44`
75
+
76
+ - ✅ Prepare branch
77
+ - ✅ Local preflight
78
+ - ✅ Push and open PR · `#123`
79
+ - 🔄 AI review
80
+ - ⬜ Review autofix
81
+ - ⬜ CI checks
82
+ - ⬜ Merge
83
+ - ⬜ Cleanup
84
+
85
+ Start the command with a short initial yield, then poll the background process every 15-30 seconds. Between polls, post an updated checklist when the active stage changes; during a quiet long stage, name the active stage and elapsed time at most every 30 seconds. Never leave the user with only Codex's generic **Working** or **Waiting for background terminal** label. Do not launch a duplicate finish while the first process is still alive, and do not mark a checkbox complete until a matching `✓` line or equivalent terminal evidence arrives.
86
+
87
+ Treat `🏁 Cleanup` as finished-but-best-effort, not as unconditional success: surface any cleanup warnings beside it instead of converting it to `✅`.
88
+
89
+ Structured phase events are persisted privately under `.omx/state/finish-runs/*.jsonl` (`0700` directory, `0600` files). Prefer that JSONL stream over parsing narrative logs when exact state is needed; the visual output prints the active event-file path.
90
+
91
+ When inspecting or verifying, prefer `rtk` compact wrappers if available (`rtk git status`, `rtk grep`, `rtk test <cmd>`, and noisy gx reads like `rtk gx status` / `rtk gx doctor`). Do not wrap commands whose stdout is parsed by scripts (`--json`, `--porcelain`, exact stdout contracts) or shell-ready output (`gx prompt --exec`).
92
+
93
+ To shrink gx's own large narrative output (e.g. `gx prompt`, `gx prompt --snippet`) before it lands in your context, set `GUARDEX_COMPRESS_CMD="<stdin->stdout filter>"`; gx routes that output through the filter (terse/non-TTY mode, fail-open, JSON skipped). Unset = byte-for-byte unchanged. Confirm it is wired with `gx status` or `gx doctor` — both print a `Token compression` line and flag a configured-but-missing binary (doctor's warning is advisory and never changes its safe/unsafe exit code).
@@ -85,9 +85,19 @@ function buildFinishEvidence(session, finishArgs, status, result, captured = {})
85
85
  };
86
86
  }
87
87
 
88
+ // Patching process.stdout.write only catches what THIS process writes. A child
89
+ // spawned on 'inherit' writes straight to fd 1 and sails past the patch, so an
90
+ // asset that streams has to be told to pipe while a capture is in flight —
91
+ // otherwise the merged-PR line never reaches buildFinishEvidence and the
92
+ // session records MERGED with an empty prUrl. Read by src/core/runtime.js and
93
+ // src/finish/index.js when they pick an asset's stdio.
94
+ const CAPTURE_ENV = 'GUARDEX_CAPTURE_ASSET_OUTPUT';
95
+
88
96
  function captureProcessOutput(fn) {
89
97
  let stdout = '';
90
98
  let stderr = '';
99
+ const previousCapture = process.env[CAPTURE_ENV];
100
+ process.env[CAPTURE_ENV] = '1';
91
101
  const originalStdoutWrite = process.stdout.write;
92
102
  const originalStderrWrite = process.stderr.write;
93
103
  process.stdout.write = function captureStdout(chunk, encoding, callback) {
@@ -107,6 +117,11 @@ function captureProcessOutput(fn) {
107
117
  } finally {
108
118
  process.stdout.write = originalStdoutWrite;
109
119
  process.stderr.write = originalStderrWrite;
120
+ if (previousCapture === undefined) {
121
+ delete process.env[CAPTURE_ENV];
122
+ } else {
123
+ process.env[CAPTURE_ENV] = previousCapture;
124
+ }
110
125
  }
111
126
  }
112
127
 
@@ -197,7 +197,6 @@ function renderCiInitHelp() {
197
197
  'Files copied (from gitguardex templates/github/workflows/):',
198
198
  ` - ci.yml PR-time CI with draft-skip + concurrency-cancel.`,
199
199
  ` - ci-full.yml Weekly cross-runtime matrix + label opt-in.`,
200
- ` - cr.yml AI code review with agent/* + draft skip.`,
201
200
  ` - README.md Documents the budget posture and customization knobs.`,
202
201
  '',
203
202
  'The command stages copied files with git add when the target is a git repo;',
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;
@@ -1140,6 +1152,14 @@ function parseMergeArgs(rawArgs) {
1140
1152
  }
1141
1153
 
1142
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');
1143
1163
  const options = {
1144
1164
  target: process.cwd(),
1145
1165
  base: '',
@@ -1154,11 +1174,33 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1154
1174
  advanceSubmodules: false,
1155
1175
  failFast: false,
1156
1176
  commitMessage: '',
1157
- mergeMode: defaults.mergeMode || 'pr',
1158
- skipPreflight: false,
1159
- 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),
1160
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,
1161
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,
1162
1204
  };
1163
1205
 
1164
1206
  for (let index = 0; index < rawArgs.length; index += 1) {
@@ -1203,10 +1245,21 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1203
1245
  options.all = true;
1204
1246
  continue;
1205
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
+ }
1206
1256
  if (arg === '--dry-run') {
1207
1257
  options.dryRun = true;
1208
1258
  continue;
1209
1259
  }
1260
+ if (arg === '--fast') {
1261
+ continue;
1262
+ }
1210
1263
  if (arg === '--wait-for-merge') {
1211
1264
  options.waitForMerge = true;
1212
1265
  continue;
@@ -1287,6 +1340,33 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1287
1340
  options.allowNoChecks = true;
1288
1341
  continue;
1289
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
+ }
1290
1370
  if (arg === '--review-provider') {
1291
1371
  const next = rawArgs[index + 1];
1292
1372
  if (!next || !['codex', 'claude'].includes(next)) {
@@ -1296,9 +1376,63 @@ function parseFinishArgs(rawArgs, defaults = {}) {
1296
1376
  index += 1;
1297
1377
  continue;
1298
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
+ }
1299
1406
  throw new Error(`Unknown option: ${arg}`);
1300
1407
  }
1301
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
+
1302
1436
  if (options.branch && !options.branch.startsWith('agent/')) {
1303
1437
  throw new Error(`--branch must reference an agent/* branch (received: ${options.branch})`);
1304
1438
  }
@@ -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;