@imdeadpool/guardex 8.2.0 → 8.4.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 (35) hide show
  1. package/README.md +68 -10
  2. package/bin/multiagent-safety.js +18 -1
  3. package/package.json +1 -1
  4. package/skills/gitguardex/SKILL.md +26 -2
  5. package/src/agents/message.js +764 -0
  6. package/src/agents/sessions.js +23 -1
  7. package/src/cli/args.js +64 -8
  8. package/src/cli/commands/agents.js +18 -0
  9. package/src/cli/commands/branch.js +94 -2
  10. package/src/cli/commands/finish.js +44 -2
  11. package/src/cli/commands/mcp.js +4 -3
  12. package/src/cli/shared/sandbox.js +5 -53
  13. package/src/cli/shared-locks.js +4 -0
  14. package/src/doctor/index.js +26 -26
  15. package/src/finish/index.js +10 -2
  16. package/src/finish/post-branch-finish-cleanup.js +324 -0
  17. package/src/finish/review-gate.js +47 -6
  18. package/src/git/index.js +9 -4
  19. package/src/mcp/collect.js +52 -3
  20. package/src/mcp/server.js +54 -2
  21. package/src/pr-checks.js +20 -5
  22. package/src/pr.js +122 -1
  23. package/src/scaffold/index.js +13 -0
  24. package/templates/AGENTS.multiagent-safety.md +37 -9
  25. package/templates/AGENTS.multiagent-safety.min.md +10 -4
  26. package/templates/codex/skills/gitguardex/SKILL.md +26 -2
  27. package/templates/githooks/pre-commit +40 -5
  28. package/templates/githooks/pre-push +72 -25
  29. package/templates/scripts/agent-branch-finish.sh +300 -21
  30. package/templates/scripts/agent-branch-start.sh +22 -2
  31. package/templates/scripts/agent-file-locks.py +170 -3
  32. package/templates/scripts/agent-preflight.sh +30 -0
  33. package/templates/scripts/agent-reconcile-openspec-tasks.js +105 -0
  34. package/templates/scripts/agent-worktree-prune.sh +406 -31
  35. package/templates/scripts/guardex-env.sh +291 -0
package/src/pr.js CHANGED
@@ -18,6 +18,8 @@ const {
18
18
  const { repoApiPath } = require('./github-api');
19
19
  const { FAILING_CONCLUSIONS, summarizeStatusCheckRollup } = require('./pr-checks');
20
20
 
21
+ const BILLING_BLOCKED_JOB_MESSAGE = /^The job was not started because recent account payments have failed or your spending limit needs to be increased\. Please check the ['"]Billing & plans['"] section in your settings\.?$/i;
22
+
21
23
  const DEFAULT_POLL_INTERVAL_MS = 5_000;
22
24
  const DEFAULT_POLL_TIMEOUT_MS = 10 * 60 * 1000;
23
25
 
@@ -57,6 +59,114 @@ function ghJson(repoRoot, args) {
57
59
  }
58
60
  }
59
61
 
62
+ function githubActionsJobId(check) {
63
+ if (String(check?.__typename || '') !== 'CheckRun') return '';
64
+ if (!String(check?.name || '').trim()) return '';
65
+ const state = String(check?.conclusion || '').toUpperCase();
66
+ if (!FAILING_CONCLUSIONS.has(state)) return '';
67
+
68
+ try {
69
+ const url = new URL(String(check?.detailsUrl || ''));
70
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com') return '';
71
+ const match = url.pathname.match(/\/actions\/runs\/\d+\/job\/(\d+)(?:\/|$)/);
72
+ return match ? match[1] : '';
73
+ } catch (_error) {
74
+ return '';
75
+ }
76
+ }
77
+
78
+ function githubCheckRunAnnotationsPath(job, expectedCheckRunId) {
79
+ try {
80
+ const url = new URL(String(job?.check_run_url || ''));
81
+ if (url.protocol !== 'https:' || url.hostname !== 'api.github.com') return '';
82
+ const match = url.pathname.match(/^\/repos\/[^/]+\/[^/]+\/check-runs\/(\d+)\/?$/);
83
+ return match && match[1] === String(expectedCheckRunId)
84
+ ? `check-runs/${match[1]}/annotations`
85
+ : '';
86
+ } catch (_error) {
87
+ return '';
88
+ }
89
+ }
90
+
91
+ function commitCheckRuns(repoRoot, headSha, runner = run) {
92
+ const sha = String(headSha || '').trim();
93
+ if (!/^[0-9a-f]{7,64}$/i.test(sha)) return [];
94
+
95
+ const result = runner(GH_BIN, [
96
+ 'api',
97
+ repoApiPath(repoRoot, `commits/${sha}/check-runs?per_page=100`, runner),
98
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
99
+ if (result.status !== 0) return [];
100
+
101
+ try {
102
+ const payload = JSON.parse(String(result.stdout || ''));
103
+ const checkRuns = Array.isArray(payload?.check_runs) ? payload.check_runs : [];
104
+ return Number(payload?.total_count) === checkRuns.length ? checkRuns : [];
105
+ } catch (_error) {
106
+ return [];
107
+ }
108
+ }
109
+
110
+ function matchingCheckRunId(check, checkRuns) {
111
+ const matches = checkRuns.filter((candidate) => String(candidate?.app?.slug || '') === 'github-actions'
112
+ && String(candidate?.name || '') === String(check?.name || '')
113
+ && String(candidate?.details_url || '') === String(check?.detailsUrl || '')
114
+ && String(candidate?.status || '').toUpperCase() === String(check?.status || '').toUpperCase()
115
+ && String(candidate?.conclusion || '').toUpperCase() === String(check?.conclusion || '').toUpperCase());
116
+ if (matches.length !== 1) return '';
117
+ const id = String(matches[0]?.id || '');
118
+ return /^\d+$/.test(id) ? id : '';
119
+ }
120
+
121
+ function isBillingBlockedCheckRun(repoRoot, check, expectedCheckRunId, runner = run) {
122
+ const jobId = githubActionsJobId(check);
123
+ if (!jobId || !expectedCheckRunId) return false;
124
+
125
+ const jobResult = runner(GH_BIN, [
126
+ 'api',
127
+ repoApiPath(repoRoot, `actions/jobs/${jobId}`, runner),
128
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
129
+ if (jobResult.status !== 0) return false;
130
+
131
+ let job;
132
+ try {
133
+ job = JSON.parse(String(jobResult.stdout || ''));
134
+ } catch (_error) {
135
+ return false;
136
+ }
137
+ if (String(job?.status || '').toLowerCase() !== 'completed'
138
+ || String(job?.conclusion || '').toLowerCase() !== 'failure'
139
+ || job?.runner_id !== 0
140
+ || String(job?.runner_name || '') !== ''
141
+ || !Array.isArray(job?.steps)
142
+ || job.steps.length !== 0) return false;
143
+
144
+ const annotationsPath = githubCheckRunAnnotationsPath(job, expectedCheckRunId);
145
+ if (!annotationsPath) return false;
146
+
147
+ const result = runner(GH_BIN, [
148
+ 'api',
149
+ repoApiPath(repoRoot, annotationsPath, runner),
150
+ ], { cwd: repoRoot, timeout: 60_000, allowFailure: true });
151
+ if (result.status !== 0) return false;
152
+
153
+ let annotations;
154
+ try {
155
+ annotations = JSON.parse(String(result.stdout || ''));
156
+ } catch (_error) {
157
+ return false;
158
+ }
159
+ if (!Array.isArray(annotations) || annotations.length !== 1) return false;
160
+
161
+ const [annotation] = annotations;
162
+ return annotation?.path === '.github'
163
+ && Number(annotation?.start_line) === 1
164
+ && String(annotation?.annotation_level || '').toLowerCase() === 'failure'
165
+ && String(annotation?.title || '') === ''
166
+ && String(annotation?.raw_details || '') === ''
167
+ && BILLING_BLOCKED_JOB_MESSAGE.test(String(annotation?.message || '').trim());
168
+ }
169
+
60
170
  /**
61
171
  * Resolve the PR for `branch` if any exists on the origin remote.
62
172
  * Returns null when no PR is open (or any are merged / closed only).
@@ -249,7 +359,15 @@ function getPullRequestStatus(repoRoot, branch) {
249
359
  const pr = findOpenPrForBranch(repoRoot, branch);
250
360
  if (!pr) return null;
251
361
 
252
- const rollup = summarizeStatusCheckRollup(pr.statusCheckRollup);
362
+ let checkRuns;
363
+ const expectedCheckRunId = (check) => {
364
+ if (!checkRuns) checkRuns = commitCheckRuns(repoRoot, pr.headRefOid);
365
+ return matchingCheckRunId(check, checkRuns);
366
+ };
367
+
368
+ const rollup = summarizeStatusCheckRollup(pr.statusCheckRollup, {
369
+ isWaived: (check) => isBillingBlockedCheckRun(repoRoot, check, expectedCheckRunId(check)),
370
+ });
253
371
 
254
372
  return {
255
373
  number: pr.number,
@@ -268,6 +386,7 @@ function getPullRequestStatus(repoRoot, branch) {
268
386
  base: pr.baseRefName,
269
387
  checks: rollup.summary,
270
388
  failedNames: rollup.failedNames,
389
+ billingWaivedNames: rollup.waivedNames,
271
390
  supersededChecks: rollup.supersededCount,
272
391
  };
273
392
  }
@@ -491,6 +610,8 @@ module.exports = {
491
610
  pushBranch,
492
611
  openPullRequest,
493
612
  getPullRequestStatus,
613
+ githubActionsJobId,
614
+ isBillingBlockedCheckRun,
494
615
  checkOutcomes,
495
616
  baselineFailures,
496
617
  enableAutoMerge,
@@ -716,6 +716,16 @@ function buildRepoVscodeSettings(existingSettings = {}) {
716
716
  ? existingSettings[REPO_SCAN_IGNORED_FOLDERS_SETTING]
717
717
  : [];
718
718
 
719
+ // Keep normal subfolder discovery, but do not auto-register a worktree just
720
+ // because one of its files was opened in the primary workspace. Otherwise
721
+ // pruning it can leave a stale, endlessly syncing SCM provider behind.
722
+ if (existingSettings['git.autoRepositoryDetection'] !== false) {
723
+ nextSettings['git.autoRepositoryDetection'] = 'subFolders';
724
+ }
725
+ // Repository scan ignores do not affect VS Code's separate Git worktree
726
+ // detector. Disable it for the primary checkout so a removed Guardex
727
+ // worktree cannot remain registered as an endlessly syncing SCM provider.
728
+ nextSettings['git.detectWorktrees'] = false;
719
729
  nextSettings[REPO_SCAN_IGNORED_FOLDERS_SETTING] = uniqueStringList([
720
730
  ...existingIgnoredFolders,
721
731
  ...MANAGED_REPO_SCAN_IGNORED_FOLDERS,
@@ -771,6 +781,9 @@ function buildParentWorkspaceView(repoRoot) {
771
781
  })),
772
782
  ],
773
783
  settings: {
784
+ 'git.autoRepositoryDetection': 'subFolders',
785
+ 'git.detectWorktrees': true,
786
+ 'git.repositoryScanIgnoredFolders': [],
774
787
  'scm.alwaysShowRepositories': true,
775
788
  },
776
789
  },
@@ -5,31 +5,51 @@
5
5
 
6
6
  Guardex is enabled by default. Disable via repo-root `.env` with `GUARDEX_ON=0|false|no|off`. Re-enable with `GUARDEX_ON=1`.
7
7
 
8
+ Worktree policy defaults to strict `always`. Opt a repository into adaptive
9
+ routing with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` or
10
+ `git config --local multiagent.worktreeMode adaptive`.
11
+
8
12
  ### Core rules
9
13
 
10
- - Work from an `agent/*` branch + worktree. **Never** edit the protected base directly.
11
- - Claim files before editing. Confirm a path is in your claim before deleting it.
14
+ - In strict `always` mode, work from an `agent/*` branch + worktree. **Never** edit the protected base directly.
15
+ - In adaptive mode, bounded single-agent work may remain on the current checkout after the radar and ownership checks below pass.
16
+ - Claim files before editing in isolated lanes. Confirm a path is in your claim before deleting it.
12
17
  - Commit, push, and open/update a PR for completed work unless the user says keep-local.
13
18
  - Keep outputs and notes compact. Less word, same proof.
14
19
 
15
20
  ### Task-size routing
16
21
 
17
- Small tasks stay direct and caveman-only.
22
+ Small tasks stay direct and caveman-only when adaptive mode is enabled and no
23
+ other writer or overlapping change is present. Strict mode still isolates them.
18
24
 
19
25
  For typos, single-file tweaks, one-liners, version bumps, comment-only changes, or similarly bounded asks, solve directly and do not escalate into heavy orchestration just because a keyword appears.
20
26
 
21
27
  Lightweight escape prefixes: `quick:`, `simple:`, `tiny:`, `minor:`, `small:`, `just:`, `only:`.
22
28
 
23
- Promote to full Guardex / OMX orchestration only when scope grows into multi-file behavior change, API/schema work, refactor, migration, architecture, cross-cutting scope, long prompt, or multi-agent execution. Orchestration alone does not require OpenSpec.
29
+ Promote to an isolated Guardex lane when scope grows into a multi-file behavior
30
+ change, API/schema work, refactor, migration, architecture, cross-cutting or
31
+ long-lived work, or multi-agent execution. Orchestration alone does not require
32
+ OpenSpec.
24
33
 
25
34
  OpenSpec is opt-in. Do not create or update OpenSpec artifacts unless the user asks for them, the task continues an existing OpenSpec change, or an explicit T2/T3 workflow is selected.
26
35
 
36
+ ### Adaptive lane selection
37
+
38
+ Before direct edits, run `gx status`, inspect active lanes with
39
+ `gx mcp list-agents --no-prs`, and check every intended path with
40
+ `gx mcp who-owns <file>`. Also inspect the current checkout's dirty paths.
41
+
42
+ Stay direct only for bounded work when no competing writer, ownership claim, or
43
+ dirty-path overlap exists. Pivot before editing (or before expanding scope) if
44
+ another writer appears, a target is owned/dirty elsewhere, or the task becomes
45
+ substantial or long-lived.
46
+
27
47
  ### Isolation (the load-bearing rule)
28
48
 
29
- Every task = one `agent/*` branch + worktree. Start with:
49
+ Start an isolated lane with:
30
50
 
31
51
  ```bash
32
- gx branch start "<task>" "<agent-name>"
52
+ gx branch start --new --no-transfer "<task>" "<agent-name>"
33
53
  ```
34
54
 
35
55
  Then `cd` into the printed worktree path. Every subsequent git command runs from inside that worktree.
@@ -38,7 +58,8 @@ If a worktree is already open for this chat/session, **continue in it** instead
38
58
 
39
59
  ### Primary-tree lock
40
60
 
41
- On the primary checkout, do not run:
61
+ In strict mode, or after adaptive routing selects isolation, do not run these on
62
+ the primary checkout:
42
63
 
43
64
  ```bash
44
65
  git checkout <ref> git switch <ref>
@@ -46,7 +67,13 @@ git switch -c ... git checkout -b ...
46
67
  git worktree add <p> <agent-branch>
47
68
  ```
48
69
 
49
- Allowed on primary: `git fetch`, `git pull --ff-only`. Anything else needs `gx branch start` first.
70
+ In adaptive direct mode, ordinary bounded edits/commits/pushes are allowed after
71
+ the radar preflight passes. Branch switching and worktree manipulation still use
72
+ `gx branch start` rather than raw Git commands.
73
+
74
+ The protected-main shell allowlist covers `git add`/ordinary commit/push and
75
+ bounded test/lint/build commands. Custom executors, scripts, or history rewrites
76
+ require an isolated lane.
50
77
 
51
78
  If you are about to type `git checkout agent/...` from the primary checkout, **stop** — that is the mistake that flips primary onto an agent branch.
52
79
 
@@ -80,7 +107,8 @@ No long proof dumps, no stale narrative, no full logs. Bulky proof goes in PRs o
80
107
 
81
108
  ### Completion
82
109
 
83
- Finish with:
110
+ Direct adaptive work uses the repository's ordinary commit/push flow. Finish an
111
+ isolated lane with:
84
112
 
85
113
  ```bash
86
114
  gx branch finish --branch "<agent-branch>" --via-pr --wait-for-merge --cleanup
@@ -2,11 +2,17 @@
2
2
  ## Multi-Agent Safety (minimal)
3
3
 
4
4
  Guardex is enabled by default. Disable via repo-root `.env` with `GUARDEX_ON=0`.
5
+ Worktrees default to strict `always` mode. Repositories that prefer a faster
6
+ single-agent path may opt in with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` (or
7
+ `git config --local multiagent.worktreeMode adaptive`).
5
8
 
6
- - Work from an `agent/*` branch + worktree — never edit the protected base (`main`/`dev`) directly. Start with `gx branch start "<task>" "<agent-name>"`, then `cd` into the printed worktree.
7
- - Claim files before editing: `gx locks claim --branch "<agent-branch>" <file...>`.
8
- - Finish completed work via PR + cleanup: `gx branch finish --branch "<agent-branch>" --via-pr --wait-for-merge --cleanup` (or `gx finish --all`).
9
- - Default to the self-repairing gated ship — add `--gate-review --gate-autofix` so blocking findings are fixed and re-verified before the merge instead of leaving the PR open. Add `--gate-baseline` only where the base branch CI is already red. CI waits until the review is clean by default; `--no-gate-serial-ci` opts into overlap. Codex code-assist defaults to bounded `medium` effort (override with `GUARDEX_REVIEW_CODEX_EFFORT`). Posting a review is not merging: `gx pr-review` posts and exits; only `gx branch finish` merges.
9
+ - In adaptive mode, small single-agent work may stay on the current checkout only after `gx status`, `gx mcp list-agents --no-prs`, and `gx mcp who-owns <file>` show no competing writer or target-file ownership.
10
+ - Direct protected-main shell work is limited to `git add`/ordinary commit/push and bounded test/lint/build commands; custom executors or history rewrites use an isolated lane.
11
+ - Pivot to an isolated lane when the task is substantial/long-lived, another writer is active in the repo, a target path is dirty or owned elsewhere, or scope expands. Use `gx branch start --new --no-transfer "<task>" "<agent-name>"`, then `cd` into the printed worktree.
12
+ - In strict `always` mode, work from an `agent/*` branch + worktree and never edit the protected base (`main`/`dev`) directly.
13
+ - In an isolated lane, claim files before editing: `gx locks claim --branch "<agent-branch>" <file...>`.
14
+ - Finish isolated work via PR + cleanup: `gx branch finish --branch "<agent-branch>" --via-pr --wait-for-merge --cleanup` (or `gx finish --all`). Direct adaptive work uses the repository's ordinary commit/push flow.
15
+ - For isolated lanes, default to the self-repairing gated ship — add `--gate-review --gate-autofix` so blocking findings are fixed and re-verified before the merge instead of leaving the PR open. Add `--gate-baseline` only where the base branch CI is already red. CI waits until the review is clean by default; `--no-gate-serial-ci` opts into overlap. Codex code-assist defaults to bounded `medium` effort (override with `GUARDEX_REVIEW_CODEX_EFFORT`). Posting a review is not merging: `gx pr-review` posts and exits; only `gx branch finish` merges.
10
16
 
11
17
  Want the full multi-agent contract (Colony coordination, OpenSpec, token discipline, recovery)? Run `gx setup --contract`.
12
18
  <!-- multiagent-safety:END -->
@@ -10,6 +10,30 @@ Use when a GitGuardex-managed repository needs safe edits or multi-agent coordin
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
+ ## Choose the lane before editing
14
+
15
+ Worktree policy is strict `always` unless the repo opts into `adaptive` with
16
+ `GUARDEX_WORKTREE_MODE=adaptive` in `.env` or
17
+ `git config --local multiagent.worktreeMode adaptive`.
18
+
19
+ 1. Run `gx status`. In adaptive mode, also inspect `list_agents` (or
20
+ `gx mcp list-agents --no-prs`), the current dirty paths, and `who_owns` for
21
+ every intended file.
22
+ 2. Stay on the current checkout only for bounded, single-agent work with no
23
+ competing writer, claimed target, or dirty-path overlap.
24
+ 3. Pivot to a new isolated lane when the task is substantial/long-lived,
25
+ another writer is active in the repo, a target is owned or dirty elsewhere,
26
+ or the scope expands. Use
27
+ `gx branch start --new --no-transfer "<bounded task>" "<agent>"`.
28
+ 4. Re-run the radar before expanding scope. Never overwrite another lane's
29
+ changes. If direct work already has edits when a pivot becomes necessary,
30
+ transfer only those known edits deliberately; do not absorb unrelated files.
31
+
32
+ Direct adaptive work supports file edits, `git add`/ordinary commit/push, and
33
+ bounded test/lint/build commands. Custom executors, scripts, or history rewrites
34
+ pivot to an isolated lane. Isolated work uses claims and the gated
35
+ `gx branch finish` flow below.
36
+
13
37
  ## Keep the default workflow lean
14
38
 
15
39
  - Default to direct T1 work in code and tests. Do not create OpenSpec artifacts from task wording alone.
@@ -24,11 +48,11 @@ Before parallel work, inspect the field with the MCP `list_agents` tool or the C
24
48
  gx mcp list-agents --no-prs
25
49
  ```
26
50
 
27
- For every file a writer may touch, check ownership, create an isolated lane, then claim it:
51
+ For every file a parallel writer may touch, check ownership, create an isolated lane, then claim it:
28
52
 
29
53
  ```sh
30
54
  gx mcp who-owns path/to/file.ts
31
- gx branch start "<bounded task>" "<agent>"
55
+ gx branch start --new --no-transfer "<bounded task>" "<agent>"
32
56
  gx locks claim --branch "<agent-branch>" path/to/file.ts
33
57
  ```
34
58
 
@@ -63,6 +63,13 @@ if [[ -n "${CLAUDECODE:-}" || -n "${CLAUDE_CODE_SESSION_ID:-}" ]]; then
63
63
  is_agent_session=1
64
64
  fi
65
65
 
66
+ worktree_mode="always"
67
+ if declare -F guardex_repo_worktree_mode >/dev/null 2>&1; then
68
+ worktree_mode="$(guardex_repo_worktree_mode "$repo_root")"
69
+ elif [[ "${GUARDEX_WORKTREE_MODE:-}" == "adaptive" ]]; then
70
+ worktree_mode="adaptive"
71
+ fi
72
+
66
73
  is_vscode_git_context=0
67
74
  if [[ -n "${VSCODE_GIT_IPC_HANDLE:-}" || -n "${VSCODE_GIT_ASKPASS_NODE:-}" || -n "${VSCODE_IPC_HOOK_CLI:-}" ]]; then
68
75
  is_vscode_git_context=1
@@ -95,6 +102,30 @@ for protected_branch in $protected_branches_raw; do
95
102
  fi
96
103
  done
97
104
 
105
+ # Adaptive mode is an explicit repo opt-in for bounded, single-agent work on
106
+ # the protected checkout. The agent workflow performs the radar/ownership
107
+ # preflight before editing and pivots to a worktree when scope or concurrency
108
+ # grows. Strict mode remains the default.
109
+ is_adaptive_direct_commit=0
110
+ if [[ "$worktree_mode" == "adaptive" && "$is_agent_session" == "1" && "$is_protected_branch" == "1" ]]; then
111
+ if ! declare -F guardex_repo_has_competing_worktree_activity >/dev/null 2>&1 \
112
+ || guardex_repo_has_competing_worktree_activity "$repo_root" "$NODE_BIN"; then
113
+ cat >&2 <<'MSG'
114
+ [guardex-adaptive] Adaptive direct commit blocked: another agent lane has dirty files or locks.
115
+ Inspect `gx mcp list-agents --no-prs`, then isolate this work:
116
+ gx branch start --new --no-transfer "<task-or-plan>" "<agent-name>"
117
+ MSG
118
+ exit 1
119
+ fi
120
+ if ! declare -F guardex_claim_adaptive_session_lease >/dev/null 2>&1 \
121
+ || ! guardex_claim_adaptive_session_lease "$repo_root"; then
122
+ echo "[guardex-adaptive] Adaptive direct commit blocked: another agent session owns this checkout." >&2
123
+ exit 1
124
+ fi
125
+ is_adaptive_direct_commit=1
126
+ # Continue into the remaining commit validations instead of bypassing them.
127
+ fi
128
+
98
129
  codex_require_agent_branch_raw="${GUARDEX_CODEX_REQUIRE_AGENT_BRANCH:-$(git config --get multiagent.codexRequireAgentBranch || true)}"
99
130
  if [[ -z "$codex_require_agent_branch_raw" ]]; then
100
131
  codex_require_agent_branch_raw="true"
@@ -138,7 +169,7 @@ if [[ "$is_codex_session" == "1" && "$is_protected_branch" == "1" ]]; then
138
169
  fi
139
170
  fi
140
171
 
141
- if [[ "$should_require_codex_agent_branch" == "1" && "${GUARDEX_ALLOW_CODEX_ON_NON_AGENT:-0}" != "1" ]]; then
172
+ if [[ "$is_adaptive_direct_commit" != "1" && "$should_require_codex_agent_branch" == "1" && "${GUARDEX_ALLOW_CODEX_ON_NON_AGENT:-0}" != "1" ]]; then
142
173
  if [[ "$is_codex_session" == "1" && "$branch" != agent/* ]]; then
143
174
  if [[ "$is_protected_branch" == "1" ]]; then
144
175
  if [[ "$is_codex_managed_only_commit_on_protected" == "1" ]]; then
@@ -164,7 +195,7 @@ MSG
164
195
  fi
165
196
  fi
166
197
 
167
- if [[ "$is_protected_branch" == "1" ]]; then
198
+ if [[ "$is_protected_branch" == "1" && "$is_adaptive_direct_commit" != "1" ]]; then
168
199
  # Humans may commit directly on protected branches; only agent sessions
169
200
  # (Codex / Claude Code / OMX) are blocked.
170
201
  if [[ "$is_agent_session" != "1" ]]; then
@@ -208,8 +239,8 @@ MSG
208
239
  exit 1
209
240
  fi
210
241
 
211
- if [[ "$branch" == agent/* ]]; then
212
- if [[ "${GUARDEX_AUTOCLAIM_STAGED_LOCKS:-1}" == "1" ]]; then
242
+ if [[ "$branch" == agent/* || "$is_adaptive_direct_commit" == "1" ]]; then
243
+ if [[ "$branch" == agent/* && "${GUARDEX_AUTOCLAIM_STAGED_LOCKS:-1}" == "1" ]]; then
213
244
  # Auto-claim non-deletion staged paths. Deletions need an explicit
214
245
  # `--allow-delete` flag below so `locks validate --staged` doesn't
215
246
  # reject the commit on the same trip the user staged the delete.
@@ -254,7 +285,11 @@ if [[ "$branch" == agent/* ]]; then
254
285
  fi
255
286
  fi
256
287
 
257
- if ! run_guardex_cli locks validate --branch "$branch" --staged; then
288
+ _validate_args=(locks validate --branch "$branch" --staged)
289
+ if [[ "$is_adaptive_direct_commit" == "1" ]]; then
290
+ _validate_args+=(--allow-unclaimed)
291
+ fi
292
+ if ! run_guardex_cli "${_validate_args[@]}"; then
258
293
  cat >&2 <<'MSG'
259
294
  [agent-branch-guard] Agent branch commits require file ownership locks.
260
295
  Claim files first:
@@ -9,6 +9,7 @@ repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
9
9
  if [[ -z "$repo_root" ]]; then
10
10
  exit 0
11
11
  fi
12
+ NODE_BIN="${GUARDEX_NODE_BIN:-node}"
12
13
  guardex_env_helper="${repo_root}/scripts/guardex-env.sh"
13
14
  if [[ -f "$guardex_env_helper" ]]; then
14
15
  # shellcheck source=/dev/null
@@ -48,6 +49,13 @@ if [[ -n "${CLAUDECODE:-}" || -n "${CLAUDE_CODE_SESSION_ID:-}" ]]; then
48
49
  is_agent_session=1
49
50
  fi
50
51
 
52
+ worktree_mode="always"
53
+ if declare -F guardex_repo_worktree_mode >/dev/null 2>&1; then
54
+ worktree_mode="$(guardex_repo_worktree_mode "$repo_root")"
55
+ elif [[ "${GUARDEX_WORKTREE_MODE:-}" == "adaptive" ]]; then
56
+ worktree_mode="adaptive"
57
+ fi
58
+
51
59
  protected_branches_raw="${GUARDEX_PROTECTED_BRANCHES:-$(git config --get multiagent.protectedBranches || true)}"
52
60
  if [[ -z "$protected_branches_raw" ]]; then
53
61
  protected_branches_raw="dev main master"
@@ -64,51 +72,90 @@ is_protected_branch() {
64
72
  return 1
65
73
  }
66
74
 
75
+ is_null_oid() {
76
+ local oid="${1:-}"
77
+ [[ -n "$oid" && -z "${oid//0/}" ]]
78
+ }
79
+
67
80
  blocked_refs=()
81
+ adaptive_direct_push=1
68
82
  while IFS=' ' read -r local_ref local_sha remote_ref remote_sha; do
69
83
  if [[ -z "${remote_ref:-}" || "$remote_ref" != refs/heads/* ]]; then
84
+ adaptive_direct_push=0
70
85
  continue
71
86
  fi
72
87
 
73
88
  remote_branch="${remote_ref#refs/heads/}"
74
89
  if is_protected_branch "$remote_branch"; then
75
90
  blocked_refs+=("$remote_branch")
91
+ if [[ "$local_ref" != "refs/heads/$remote_branch" ]] \
92
+ || is_null_oid "$local_sha"; then
93
+ adaptive_direct_push=0
94
+ elif ! is_null_oid "$remote_sha" \
95
+ && ! git merge-base --is-ancestor "$remote_sha" "$local_sha" 2>/dev/null; then
96
+ adaptive_direct_push=0
97
+ fi
98
+ else
99
+ adaptive_direct_push=0
76
100
  fi
77
101
  done
78
102
 
79
103
  if [[ "${#blocked_refs[@]}" -gt 0 ]]; then
80
- if [[ "$is_codex_session" == "1" ]]; then
104
+ allow_adaptive_direct_push=0
105
+ if [[ "$worktree_mode" == "adaptive" && "$is_agent_session" == "1" \
106
+ && "${#blocked_refs[@]}" == "1" \
107
+ && "$adaptive_direct_push" == "1" \
108
+ && "$(git branch --show-current 2>/dev/null)" == "${blocked_refs[0]}" ]]; then
109
+ if ! declare -F guardex_repo_has_competing_worktree_activity >/dev/null 2>&1 \
110
+ || guardex_repo_has_competing_worktree_activity "$repo_root" "$NODE_BIN"; then
111
+ cat >&2 <<'MSG'
112
+ [guardex-adaptive] Adaptive direct push blocked: another agent lane has dirty files or locks.
113
+ Inspect `gx mcp list-agents --no-prs`; coordinate or finish the isolated lane first.
114
+ MSG
115
+ exit 1
116
+ fi
117
+ if ! declare -F guardex_claim_adaptive_session_lease >/dev/null 2>&1 \
118
+ || ! guardex_claim_adaptive_session_lease "$repo_root"; then
119
+ echo "[guardex-adaptive] Adaptive direct push blocked: another agent session owns this checkout." >&2
120
+ exit 1
121
+ fi
122
+ allow_adaptive_direct_push=1
123
+ fi
124
+
125
+ if [[ "$allow_adaptive_direct_push" != "1" ]]; then
126
+ if [[ "$is_codex_session" == "1" ]]; then
127
+ {
128
+ echo "[guardex-preedit-guard] Codex push detected toward protected branch."
129
+ echo "[guardex-preedit-guard] Protected target(s): ${blocked_refs[*]}"
130
+ echo "[guardex-preedit-guard] Run Codex from an agent/* branch and merge via PR."
131
+ echo
132
+ echo "Temporary bypass (not recommended):"
133
+ echo " ALLOW_PUSH_ON_PROTECTED_BRANCH=1 git push ..."
134
+ } >&2
135
+ exit 1
136
+ fi
137
+
138
+ # Humans may push directly to protected branches; only agent sessions are blocked.
139
+ if [[ "$is_agent_session" != "1" ]]; then
140
+ exit 0
141
+ fi
142
+
143
+ if [[ "$is_vscode_git_context" == "1" && "$allow_vscode_protected_branch_writes" == "1" ]]; then
144
+ exit 0
145
+ fi
146
+
81
147
  {
82
- echo "[guardex-preedit-guard] Codex push detected toward protected branch."
83
- echo "[guardex-preedit-guard] Protected target(s): ${blocked_refs[*]}"
84
- echo "[guardex-preedit-guard] Run Codex from an agent/* branch and merge via PR."
148
+ echo "[agent-branch-guard] Push to protected branch blocked."
149
+ echo "[agent-branch-guard] Protected target(s): ${blocked_refs[*]}"
150
+ echo "[agent-branch-guard] Use an agent branch and merge via PR."
151
+ echo "[agent-branch-guard] Optional repo opt-in for VS Code protected-branch push:"
152
+ echo " git config multiagent.allowVscodeProtectedBranchWrites true"
85
153
  echo
86
154
  echo "Temporary bypass (not recommended):"
87
155
  echo " ALLOW_PUSH_ON_PROTECTED_BRANCH=1 git push ..."
88
156
  } >&2
89
157
  exit 1
90
158
  fi
91
-
92
- # Humans may push directly to protected branches; only agent sessions are blocked.
93
- if [[ "$is_agent_session" != "1" ]]; then
94
- exit 0
95
- fi
96
-
97
- if [[ "$is_vscode_git_context" == "1" && "$allow_vscode_protected_branch_writes" == "1" ]]; then
98
- exit 0
99
- fi
100
-
101
- {
102
- echo "[agent-branch-guard] Push to protected branch blocked."
103
- echo "[agent-branch-guard] Protected target(s): ${blocked_refs[*]}"
104
- echo "[agent-branch-guard] Use an agent branch and merge via PR."
105
- echo "[agent-branch-guard] Optional repo opt-in for VS Code protected-branch push:"
106
- echo " git config multiagent.allowVscodeProtectedBranchWrites true"
107
- echo
108
- echo "Temporary bypass (not recommended):"
109
- echo " ALLOW_PUSH_ON_PROTECTED_BRANCH=1 git push ..."
110
- } >&2
111
- exit 1
112
159
  fi
113
160
 
114
161
  exit 0