@imdeadpool/guardex 8.4.13 → 8.4.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,454 +1,130 @@
1
1
  <p align="center">
2
- <img alt="GitGuardex logo" src="./logo.png" width="240">
2
+ <img alt="GitGuardex logo" src="./logo.png" width="180">
3
3
  </p>
4
4
 
5
- <h1 align="center">GitGuardex</h1>
5
+ # GitGuardex
6
6
 
7
- <p align="center">
8
- <strong>Safe parallel work for Codex, Claude, and humans.</strong><br>
9
- One task → one worktree → one PR → one clean merge.
10
- </p>
11
-
12
- <p align="center">
13
- <a href="https://www.npmjs.com/package/@imdeadpool/guardex"><img alt="npm version" src="https://img.shields.io/npm/v/%40imdeadpool%2Fguardex?label=npm&style=flat-square&color=cb3837&logo=npm&logoColor=white"></a>
14
- <a href="https://github.com/recodeee/gitguardex/actions/workflows/ci.yml"><img alt="CI status" src="https://img.shields.io/github/actions/workflow/status/recodeee/gitguardex/ci.yml?branch=main&label=CI&style=flat-square"></a>
15
- <a href="https://scorecard.dev/viewer/?uri=github.com/recodeee/gitguardex"><img alt="OpenSSF Scorecard" src="https://img.shields.io/ossf-scorecard/github.com/recodeee/gitguardex?label=OpenSSF%20Scorecard&style=flat-square"></a>
16
- <a href="https://github.com/recodeee/gitguardex/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/recodeee/gitguardex?label=stars&style=flat-square&color=d4ac0d"></a>
17
- <a href="./LICENSE"><img alt="license" src="https://img.shields.io/npm/l/%40imdeadpool%2Fguardex?label=license&style=flat-square&color=97ca00"></a>
18
- </p>
7
+ **Run Codex, Claude, and human contributors in parallel without sharing a checkout.** GitGuardex adds file claims, PR review gates, and safe cleanup to Git worktrees. One task → one worktree → one PR.
19
8
 
20
- <p align="center">
21
- <a href="#install">Install</a> ·
22
- <a href="#the-problem">Why</a> ·
23
- <a href="#what-gitguardex-can-do">Capabilities</a> ·
24
- <a href="#see-every-lane-in-vs-code">VS Code view</a> ·
25
- <a href="#daily-workflow">Workflow</a> ·
26
- <a href="#code-assist-review-gate">Code assist</a> ·
27
- <a href="#essential-commands">Commands</a>
28
- </p>
9
+ [![npm](https://img.shields.io/npm/v/%40imdeadpool%2Fguardex)](https://www.npmjs.com/package/@imdeadpool/guardex)
10
+ [![CI](https://github.com/opencue/gitguardex/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/opencue/gitguardex/actions/workflows/ci.yml)
11
+ [License](./LICENSE)
29
12
 
30
- ---
13
+ [Quick start](#install) · [AI code review](#code-assist-review-gate) · [Impact Assist](#impact-assist) · [How it compares](#how-it-compares)
31
14
 
32
15
  ## Install
33
16
 
34
- <p align="center">
35
- <img alt="Install GitGuardex" src="https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/install-hero.svg" width="680">
36
- </p>
17
+ Requires Node.js 18+, Git, and an authenticated GitHub CLI (`gh`) for the PR flow. Use Linux or macOS; on Windows, use WSL.
37
18
 
38
- ```bash
39
- npm i -g @imdeadpool/guardex
40
- cd /path/to/your-repo
19
+ ```sh
20
+ npm install -g @imdeadpool/guardex
21
+ cd /path/to/repo
41
22
  gx setup
42
- gx onboard # optional 2-minute tour
23
+ gx branch start "Add checkout validation" "codex" --no-transfer
43
24
  ```
44
25
 
45
- Requires **Node.js 18+**, Git, and GitHub CLI (`gh`). Recommended on macOS or
46
- Linux; use WSL on Windows.
47
-
48
- > [!WARNING]
49
- > GitGuardex is an independent project. It is not affiliated with OpenAI,
50
- > Anthropic, or Codex.
26
+ Enter the worktree printed by `gx branch start`. Claim the files you intend to edit:
51
27
 
52
- ---
53
-
54
- ## The problem
55
-
56
- ![Parallel agents colliding in the same files](https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/problem-agent-collision.svg)
57
-
58
- Parallel agents can edit the same files, overwrite tests, or commit directly to
59
- `main`. More agents can create more conflicts instead of more progress.
60
-
61
- ### What GitGuardex can do
62
-
63
- <p align="center">
64
- <img alt="GitGuardex capability map: isolated lanes, evidence-driven shipping, and safe cleanup" src="https://raw.githubusercontent.com/opencue/gitguardex/main/docs/images/capabilities-dark.svg" width="900">
65
- </p>
66
-
67
- | Isolate and coordinate | Ship with evidence | Recover without loss |
68
- | --- | --- | --- |
69
- | One `agent/*` branch and worktree per task. | Preflight, CI, and optional AI review block risky merges. | Dirty, locked, blocked, and uncertain lanes are preserved. |
70
- | Shared file claims prevent silent overwrites. | The recorded base keeps unattended finishes on the correct target. | Successful lanes are merged, then their temporary branch and worktree are removed. |
71
- | Protected branches stay behind a PR boundary. | Billing-aware fallbacks waive only explicitly named checks. | Cleanup fails closed instead of deleting work it cannot prove safe. |
72
-
73
- <details>
74
- <summary><strong>Implementation evidence and shipped hardening</strong></summary>
75
-
76
- - **Correct base targeting** — persist and validate each lane's base so an
77
- unattended finish cannot use another checkout's target. When
78
- `branch.<b>.guardexBase` is absent (e.g., a worktree created with raw
79
- `git worktree add`), the finish and stop hooks infer the base from git
80
- history: the oldest reflog "Created from &lt;name&gt;" entry wins; if absent,
81
- ancestry distance (commits ahead of each candidate's merge-base) selects the
82
- closest; ties prefer `multiagent.baseBranch`, then protected branches, then
83
- lexical order; and the result is persisted as `branch.<b>.guardexBase` for
84
- every subsequent gate. ([#745](https://github.com/opencue/gitguardex/pull/745), [#750](https://github.com/opencue/gitguardex/pull/750), [#751](https://github.com/opencue/gitguardex/pull/751))
85
- - **Billing-aware CI fallback** — waive only named checks that GitHub could not
86
- start because of billing, while keeping repository preflight mandatory.
87
- ([#743](https://github.com/opencue/gitguardex/pull/743))
88
- - **OpenSpec progress reconciliation** — merge conflicting `tasks.md` progress
89
- deterministically and validate it before continuing. ([#753](https://github.com/opencue/gitguardex/pull/753))
90
- - **Reusable successful preflight** — reuse proof only while the source HEAD,
91
- base commit, command, and script stay unchanged; billing-waiver preflights
92
- are never cached. ([#757](https://github.com/opencue/gitguardex/pull/757))
93
- - **Fail-closed cleanup** — preserve dirty, locked, open-PR, blocked, or
94
- uncertain lanes; close idle clean worktrees without deleting their branches.
95
- ([#741](https://github.com/opencue/gitguardex/pull/741), [#744](https://github.com/opencue/gitguardex/pull/744), [#746](https://github.com/opencue/gitguardex/pull/746), [#752](https://github.com/opencue/gitguardex/pull/752))
96
- - **Workspace hygiene** — safely remove successful detached lanes, avoid stale
97
- VS Code worktree providers, and keep `gx branch finish --help` free of
98
- repository side effects. ([#742](https://github.com/opencue/gitguardex/pull/742), [#747](https://github.com/opencue/gitguardex/pull/747), [#748](https://github.com/opencue/gitguardex/pull/748), [#754](https://github.com/opencue/gitguardex/pull/754))
99
-
100
- </details>
101
-
102
- ### See every lane in VS Code
103
-
104
- Create an explicit multi-root workspace when you want every managed worktree to
105
- appear as its own Source Control repository:
106
-
107
- ```bash
108
- gx setup --vscode-worktree-view
109
- code ../<repo>-branches.code-workspace
28
+ ```sh
29
+ gx locks claim --branch "$(git branch --show-current)" src/checkout.ts
110
30
  ```
111
31
 
112
- <p align="center">
113
- <img alt="VS Code Explorer showing separate Codex and Claude worktree groups" src="https://raw.githubusercontent.com/opencue/gitguardex/main/docs/images/vscode-worktrees-overview.png" width="668">
114
- </p>
115
-
116
- The generated workspace enables Git subfolder discovery, worktree detection,
117
- and an empty repository-scan exclusion list. This is opt-in: GitGuardex does not
118
- rewrite your repository's `.gitignore` or loosen the default single-repository
119
- workspace. Disable future generation with `--no-vscode-worktree-view`.
120
-
121
- ---
122
-
123
- ## Daily workflow
124
-
125
- ```bash
126
- # 1. Start an isolated lane
127
- gx branch start "fix-auth" "codex"
128
-
129
- # 2. Inside the printed worktree, claim what you will edit
130
- gx locks claim --branch "$(git branch --show-current)" src/auth.ts test/auth.test.ts
32
+ Make the change and run your project's tests. Then ship the PR:
131
33
 
132
- # 3. Implement and verify
133
- npm test
134
-
135
- # 4. Commit, open a PR, merge, and clean up
34
+ ```sh
136
35
  gx branch finish --via-pr --wait-for-merge --cleanup
137
36
  ```
138
37
 
139
- ### Agent token usage
140
-
141
- `gx usage` delegates to [ccusage](https://github.com/ccusage/ccusage), reading the
142
- token usage already recorded by supported coding-agent CLIs. Install ccusage
143
- once with `npm install -g ccusage`; GX never silently downloads it.
38
+ Finish can commit and open the PR, run the selected gates, then squash-merge and clean up the finished lane. It does not override GitHub branch protection.
144
39
 
145
- ```bash
146
- gx usage # daily totals across detected agents
147
- gx usage codex session --json --offline # Codex sessions, machine-readable
148
- gx usage claude daily --since 20260921 # Claude Code date filter
149
- gx usage codex session --help # ccusage's report-specific options
150
- ```
151
-
152
- Reports cover ccusage's configured local log roots, **not just the current GX
153
- repository**. `CODEX_HOME` and other ccusage environment/config settings pass
154
- through unchanged. Use `GUARDEX_CCUSAGE_BIN` to select an executable or JS entry
155
- point. GX preserves the backend output and exit status, without recounting
156
- tokens or treating missing ccusage as a successful empty report.
40
+ ## Code-assist review gate
157
41
 
158
- Costs are API-equivalent estimates, not invoices or subscription balances.
159
- Pricing may require network access; `--offline` uses ccusage's offline pricing.
160
- Missing logs cannot be measured, and Codex log support is experimental.
161
- For A/B comparisons, use separate sessions with the same tasks/model and check
162
- task success before comparing input, output, cached tokens and elapsed time.
163
- This command reports usage; it does not itself run an A/B experiment.
42
+ For AI code review, install and authenticate the Codex or Claude Code CLI.
164
43
 
165
- ### One-call agent context
44
+ ```sh
45
+ gx pr-review --pr 123 --post
46
+ ```
166
47
 
167
- `gx context` exposes the existing MCP context collector as compact JSON, scoped
168
- to the current repository. Read the current lane, peer agents, and ownership of
169
- multiple files without separate per-file calls:
48
+ Review an existing PR using your local Codex CLI. GitGuardex falls back to Claude Code if Codex cannot launch; pin either with `--provider` (or `--review-provider` when finishing). The review posts severity, file and line, and the reason a finding matters. **Posting a review does not merge the PR.**
170
49
 
171
- ```bash
172
- gx context src/auth.ts test/auth.test.ts
173
- gx context --target /path/to/worktree --max-bytes 20000 --json
174
- ```
50
+ With `--gate-review`, high and critical findings block the finish. Add `--gate-autofix` to attempt fixes and review the new head before merging. A green CI run is not a substitute for a clean review, or vice versa.
175
51
 
176
- PR lookup is opt-in with `--include-prs`. The default limit is 20,000 UTF-8 bytes
177
- of JSON, excluding the trailing newline; this is a byte budget, not a token
178
- count. Up to 200 file paths are accepted. Use `--` before dash-prefixed filenames.
179
- Only optional peer summaries may be omitted, with `complete: false` and an
180
- omission count. Required safety data, including ownership conflicts, is never
181
- truncated: an insufficient budget fails. Raise `--max-bytes` (up to 1 MiB) or
182
- split the file batch. This read-only snapshot does not claim files or grant edit
183
- permission; existing locks, approvals and merge gates still apply.
184
-
185
- Run `node scripts/benchmark-context-cli.js` for a repeated local comparison of
186
- separate MCP requests, the already-available batched MCP call, and this CLI.
187
- It checks equivalent safety facts and reports timings and output bytes, not
188
- provider-token counts or universal performance savings.
189
-
190
- For a small change that you already verified locally, use the explicit fast
191
- profile:
192
-
193
- ```bash
194
- gx branch finish --fast
52
+ ```sh
53
+ gx branch finish --via-pr --wait-for-merge --cleanup --gate-review --gate-autofix
195
54
  ```
196
55
 
197
- `--fast` still opens a PR and uses squash merge, but skips the local preflight,
198
- AI review, and review autofix. Repository branch protection and required CI
199
- checks still control whether GitHub accepts the merge. Do not use fast mode for
200
- security-sensitive, migration, dependency, or broad refactor changes.
201
-
202
- <p align="center">
203
- <img alt="Guarded VS Code Source Control example" src="https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/workflow-source-control-grouped.png" width="760">
204
- </p>
56
+ If a diff exceeds the review size limit, split the PR to continue. A standalone review may report partial findings, but cannot pass the gate. See [preflight setup](./docs/preflight.md) for local checks.
205
57
 
206
- ---
58
+ <details>
59
+ <summary>See a real review on GitHub</summary>
207
60
 
208
- ## Worktree provisioning
61
+ ![A GitGuardex review showing severity, file locations, and findings](https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/code-assist-review-gate.png)
209
62
 
210
- Opt into isolated dependency copies in `.guardex.json` (JSONC is supported):
63
+ [Open the example PR](https://github.com/projects-kssk/Wireless_KFB_Project/pull/165) · [Full-size screenshot](https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/code-assist-review-gate.png)
211
64
 
212
- ```json
213
- {
214
- "provision": {
215
- "files": { "copy": ["node_modules", ".env"], "symlink": [] },
216
- "postCreate": ["npm run build"]
217
- }
218
- }
219
- ```
65
+ </details>
220
66
 
221
- New `gx branch start` worktrees apply this configuration. `copy` supports files
222
- and directories, attempts native copy-on-write, and falls back to regular copying.
223
- Unlike shared symlinks, modifying a copied dependency does not modify the source.
224
- Existing targets are left untouched. Internal symlinks are relocated inside the
225
- copy; dangling links, links outside the selected directory, and special files
226
- fail the directory copy without installing a partial target. An explicit copy
227
- never falls back to a shared symlink. Without an explicit copy policy, legacy
228
- dependency sharing remains available; choose copies for writable dependencies.
229
-
230
- **Migration:** `postCreate` now skips commands until their exact ordered list has
231
- been approved locally for that repository. In a human terminal, run:
232
-
233
- ```bash
234
- gx worktree approve-hooks --target /path/to/source-repo
235
- gx worktree provision --source /path/to/source-repo --target /path/to/agent-worktree
236
- # Revoke approval without running hooks:
237
- gx worktree approve-hooks --target /path/to/source-repo --revoke
238
- ```
67
+ ---
239
68
 
240
- Approval is stored outside the repo under the Guardex user's
241
- `.config/gitguardex/provision-approvals/`. Changed command lists require fresh
242
- consent; noninteractive runs and `--yes` cannot grant it. Approved hooks can run
243
- arbitrary shell code, including subsequently changed scripts: approval is not a
244
- sandbox or a review of those scripts. `GUARDEX_PROVISION_HOOKS=0` disables even
245
- approved hooks. `provision --with-defaults` also applies legacy dependency links
246
- where they do not overlap an explicit copy policy (used by branch creation).
247
-
248
- `gx agents status` prints its header before Git probes and then each completed
249
- session row on a terminal. Redirected text and `--json` retain their prior format.
250
- This is progressive display, not a claim that Git collection is faster.
251
-
252
- These adaptations were inspired by [Worktrunk](https://github.com/max-sixty/worktrunk),
253
- not implemented by adding a second worktree manager. Reproduce the local copy
254
- comparison with `node scripts/benchmark-provision.js`; it reports repeated-run
255
- timings and allocation accounting, not universal performance or storage savings.
256
-
257
- ### Native worktree navigation
258
-
259
- ```bash
260
- eval "$(gx shell-init bash)" # zsh supported too; fish: gx shell-init fish | source
261
- gx switch agent/bot/my-task # registered branch, worktree path, or "-" for previous
262
- gx switch pr:123 --create # GitHub PR (requires gh); creation uses GX safety gates
263
- gx switch # terminal picker with diff-stat and PR preview
264
- gx switch agent/bot/my-task --json
265
- ```
69
+ ## Impact Assist
266
70
 
267
- Without shell integration, `gx switch` prints the destination; it cannot change
268
- the parent shell's directory. `--print` is path-only and `--json` is structured
269
- output. Navigation does not change the primary checkout. `--create` provisions
270
- a GX agent lane from an existing branch or PR head, retaining quotas and claims,
271
- not a second worktree manager. PR URLs must match this repository; fork PR heads
272
- are fetched through the origin repository's numbered PR ref and verified by SHA.
273
-
274
- ### Approved lifecycle hooks
275
-
276
- Alongside the existing `provision.postCreate`, configure named lifecycle events:
277
-
278
- ```json
279
- {
280
- "hooks": {
281
- "pre-start": ["npm ci", { "build": "npm run build", "lint": "npm run lint" }],
282
- "pre-merge": "npm test",
283
- "post-start": "echo Ready"
284
- },
285
- "hookTimeoutMs": 600000
286
- }
287
- ```
71
+ **Code review asks what could break. Impact Assist asks what the repository gains or gives up by merging.** The review renders this as a **PR impact** section: benefits, trade-offs, links to supporting diff lines, and suggested next steps when available.
288
72
 
289
- An array is an ordered pipeline; commands in a named object run concurrently,
290
- and the next stage waits for all of them to succeed. Pre hooks block; post hooks
291
- run in the background with per-run output and status files.
292
-
293
- ```bash
294
- gx worktree hook approve pre-start --source /path/to/repo
295
- gx worktree hook approve pre-merge --source /path/to/repo
296
- gx worktree hook approve post-start --source /path/to/repo
297
- gx worktree hook pre-start --source /path/to/repo --worktree /path/to/lane --dry-run
298
- gx worktree hook logs --source /path/to/repo --json
299
- gx worktree hook approve pre-start --source /path/to/repo --revoke
300
- ```
73
+ For example, a material benefit (**+25**) and a notable trade-off (**−10**) yield **65/100** from a neutral baseline of **50**. That is a diff-based estimate, not a benchmark or a merge verdict. If the diff is incomplete or the estimate has no valid supporting evidence, the section reports it as unavailable.
301
74
 
302
- Consent is interactive and local, bound to the repository, event, exact ordered
303
- commands and timeout. Changes require approval again. These approvals are separate
304
- from legacy `postCreate`; `--yes` cannot approve shell execution. State lives under
305
- the Guardex user's `.config/gitguardex/lifecycle-hooks/`, outside the repository.
306
- Approved commands are arbitrary shell code, not sandboxed; invoked scripts can
307
- change independently of the approved command text.
308
-
309
- Events are `pre-*` and `post-*` for `start`, `switch`, `commit`, `merge`,
310
- and `remove`. Start hooks run after provisioning but before readiness, then
311
- after successful initialization; reduced provisioning modes skip them. Switch
312
- hooks surround destination selection, before the shell consumes its path.
313
- Commit hooks surround GX finish's auto-commit (not unrelated manual Git commits).
314
- Merge hooks supplement, never replace, existing PR/merge gates: a pre-merge hook
315
- that changes the source revision or leaves changes aborts the merge.
316
- Removal hooks apply to guarded prune and deferred finish cleanup, not internal
317
- temporary integration/probe trees. A failed pre-remove preserves the worktree;
318
- post-remove runs from the surviving repository, with `GUARDEX_WORKTREE` retaining
319
- the removed path. Hooks also receive `GUARDEX_REPO_ROOT`, `GUARDEX_BRANCH` and
320
- `GUARDEX_HOOK_EVENT`. `GUARDEX_PROVISION_HOOKS=0` disables hooks explicitly.
321
-
322
- ### Explicit ignored-file copy
323
-
324
- ```bash
325
- gx worktree copy-ignored --source /path/to/repo --target /path/to/lane --dry-run --json
326
- gx worktree copy-ignored --source /path/to/repo --target /path/to/lane
327
- ```
75
+ [See Impact Assist on a real GitGuardex PR](https://github.com/opencue/gitguardex/pull/897#pullrequestreview-6070455129).
328
76
 
329
- Only ignored files are eligible. Optional source `.worktreeinclude` narrows the
330
- selection using Git's ignore-pattern syntax, for example `node_modules/**`
331
- followed by `!node_modules/private/`. Existing or tracked target files are never
332
- overwritten, and symlink escapes and nested repositories are rejected. This
333
- explicit command does not broaden the normal branch-start copy policy.
334
- GX runtime/ownership directories are excluded, including aliases pointing into
335
- them. Foreign file claims and malformed lock registries block copying. Shared
336
- remote-lock mode currently refuses this command rather than bypassing remote
337
- ownership or fetching state during a read-only dry-run.
338
- See [third-party attribution](THIRD-PARTY-NOTICES.md).
77
+ ## How it compares
339
78
 
340
- ## Code-assist review gate
79
+ | If you use… | It handles… | What GitGuardex adds |
80
+ | --- | --- | --- |
81
+ | Plain `git worktree` | Separate checkouts | Task identity, shared file claims, and cleanup that preserves work it cannot safely remove |
82
+ | A standalone AI reviewer | Findings on a diff | Optional blocking review and autofix tied to the PR finish, plus a separate impact estimate |
83
+ | GitHub Actions and branch protection | Required checks and merge rules | Local preflight, worktree ownership, and a single workflow from task start to cleanup |
341
84
 
342
- Add `--gate-review` to review the PR before merge. Add `--gate-autofix` to let
343
- the agent repair blocking findings and run the review again.
85
+ GitGuardex works with Git, GitHub, and your existing agent CLI. It does not replace them.
344
86
 
345
- ```bash
346
- gx branch finish --via-pr --wait-for-merge --cleanup \
347
- --gate-review --gate-autofix
348
- ```
87
+ <details>
88
+ <summary>See the problem and capability diagrams</summary>
349
89
 
350
- High and critical findings block the merge. The review is posted directly on
351
- the PR as a readable severity, location, and finding table.
352
- If the PR diff exceeds the review size limit, the merge gate stops before
353
- launching the reviewer. Split the PR into smaller changes and rerun the gate.
354
- A standalone `gx pr-review` can still produce an advisory report marked partial.
355
- Both `gx pr-review` and the finish gate use Codex first. If the Codex CLI cannot
356
- launch, they try Claude. Timeouts, failed or invalid reviews, and findings do not
357
- trigger a switch. Use `--provider` or `--review-provider` to pin one provider.
358
-
359
- After a clean review, normal gated finishes run the repository preflight while
360
- GitHub CI runs. The final publish still requires both and checks the exact head
361
- and base. After an interruption, rerun the same finish command: an unchanged
362
- review policy and revision can reuse a recent Codex verdict if it is still the
363
- latest, unchanged review on GitHub. A mandatory trusted-base CI fallback
364
- preflight is never replaced by the regular preflight receipt.
365
-
366
- Set `GUARDEX_REVIEW_COMPACT_DIFF=1` to try a smaller review prompt for large npm
367
- lockfile patches. Only unchanged generated context is compacted; changed lines
368
- and their coordinates are kept. The original diff is still used for coverage,
369
- anchors and Abide. This opt-in does not apply to PR Lens.
370
-
371
- For a repository that intentionally disables its GitHub Actions workflows,
372
- enable the local CI fallback from that checkout:
373
-
374
- ```bash
375
- git config --local multiagent.ciFallbackWhenDisabled true
376
- ```
90
+ ## The problem
377
91
 
378
- After the normal CI registration grace period, the gate accepts zero check
379
- runs only if GitHub confirms a nonempty workflow list with every workflow
380
- manually disabled and reports the reviewed PR as mergeable. A clean review
381
- and a successful target-aware preflight from the trusted base are still
382
- required. Missing or unverified workflow state, pending or failed checks,
383
- and GitHub branch protection are not bypassed.
92
+ ![Parallel agents colliding in the same files](https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/problem-agent-collision.svg)
384
93
 
385
- <p align="center">
386
- <a href="https://github.com/projects-kssk/Wireless_KFB_Project/pull/165">
387
- <img alt="GitGuardex code-assist blocking a PR with review findings" src="https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/code-assist-review-gate.png" width="920">
388
- </a>
389
- </p>
94
+ ### What GitGuardex can do
390
95
 
391
96
  <p align="center">
392
- <sub>
393
- Real example: <a href="https://github.com/projects-kssk/Wireless_KFB_Project/pull/165">Wireless_KFB_Project PR #165</a>
394
- · <a href="https://raw.githubusercontent.com/recodeee/gitguardex/main/docs/images/code-assist-review-gate.png">open the full-size screenshot</a>
395
- </sub>
97
+ <img alt="GitGuardex capability map: isolated lanes, evidence-driven shipping, and safe cleanup" src="https://raw.githubusercontent.com/opencue/gitguardex/main/docs/images/capabilities-dark.svg" width="900">
396
98
  </p>
397
99
 
398
- ---
100
+ </details>
399
101
 
400
- ## Essential commands
401
-
402
- | Command | Purpose |
403
- | --- | --- |
404
- | `gx` / `gx status` | Show repo safety and the next action. |
405
- | `gx setup` | Install or refresh Guardex in a repo. |
406
- | `gx doctor` | Repair Guardex drift. |
407
- | `gx branch start "task" "agent"` | Create an isolated task lane. |
408
- | `gx locks claim --branch <branch> <files...>` | Claim files before editing. |
409
- | `gx branch finish --via-pr --wait-for-merge --cleanup` | Ship safely through a PR. |
410
- | `gx branch finish --fast` | Squash-merge a locally verified small change without local preflight or AI review. |
411
- | `gx agents status` | Show active agent lanes. |
412
- | `gx agents send --session <id> --message <text>` | Deliver safely to an idle agent or queue for its next turn. |
413
- | `gx agents inbox [--ack <message-id>]` | Read or acknowledge the authenticated standalone message queue. |
414
- | `gx cleanup` | Prune merged or stale worktrees. |
415
-
416
- Need the terminal cockpit? Run `gx cockpit`; see the
417
- [cockpit guide](./docs/agents-cockpit.md). Run `gx --help` for every command.
102
+ ## More workflows
418
103
 
419
- ---
104
+ - **See what other agents own:** `gx status`, `gx context path/to/file`, or the [agent cockpit](./docs/agents-cockpit.md).
105
+ - **Inspect local agent usage:** `gx usage` reads local logs through [ccusage](https://github.com/ccusage/ccusage); it does not install the backend.
106
+ - **Preview cleanup and storage:** `gx cleanup --dry-run` and the [worktree storage guide](./docs/worktree-storage.md).
107
+ - **Configure verification:** [local preflight](./docs/preflight.md), [OpenSpec (opt-in)](./docs/openspec-getting-started.md), or `gx --help`.
108
+ - **Advanced worktrees:** [provisioning, navigation, and lifecycle hooks](https://github.com/opencue/gitguardex/blob/f748d7e02c853b29826bb1e1005127468de407e8/README.md#worktree-provisioning) and [VS Code setup](https://github.com/opencue/gitguardex/blob/f748d7e02c853b29826bb1e1005127468de407e8/README.md#see-every-lane-in-vs-code).
109
+ - **Launch with a Cue profile:** [preview, start, and resume GitGuardex tasks](https://github.com/opencue/cuecards/blob/main/docs/gitguardex-workflows.md).
420
110
 
421
111
  <details>
422
- <summary><strong>Advanced setup and maintainer notes</strong></summary>
423
-
424
- ### AGENTS.md safety block
425
-
426
- GitGuardex preserves your instructions. It only manages content between:
427
-
428
- ```text
429
- <!-- multiagent-safety:START -->
430
- <!-- multiagent-safety:END -->
431
- ```
112
+ <summary>Agent skills and maintainer releases</summary>
432
113
 
433
- ### Agent skills
434
-
435
- ```bash
114
+ ```sh
436
115
  npx skills add recodee/gitguardex
437
- npx skills add recodee/ # browse the namespace
116
+ gx release # create/update the current GitHub release from README notes
438
117
  ```
439
118
 
440
119
  `gx setup` does not auto-run `npx skills add ...`. If the picker does not show a separate `guardex` skill, that is expected; use the `gitguardex` skill.
441
120
 
442
- ### Package releases
121
+ `gx release` is the maintainer path for package releases. It reads `README.md`, finds the last published GitHub release, and writes one grouped GitHub release body.
443
122
 
444
- ```bash
445
- gx release # create/update the current GitHub release from README notes
446
- ```
123
+ </details>
447
124
 
448
- `gx release` is the maintainer path for package releases. It reads `README.md`,
449
- finds the last published GitHub release, and writes one grouped GitHub release body.
125
+ [Contributing](./CONTRIBUTING.md) · [Security](./SECURITY.md) · [Issues](https://github.com/opencue/gitguardex/issues) · [Third-party notices](./THIRD-PARTY-NOTICES.md)
450
126
 
451
- </details>
127
+ GitGuardex is independent and is not affiliated with OpenAI or Anthropic.
452
128
 
453
129
  ## Release notes
454
130
 
@@ -506,11 +182,3 @@ finds the last published GitHub release, and writes one grouped GitHub release b
506
182
  the committed metadata so packed and signed assets stay aligned.
507
183
 
508
184
  </details>
509
-
510
- ---
511
-
512
- <p align="center">
513
- <a href="https://github.com/recodeee/gitguardex/issues">Issues</a> ·
514
- <a href="./CONTRIBUTING.md">Contributing</a> ·
515
- <a href="./SECURITY.md">Security</a>
516
- </p>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imdeadpool/guardex",
3
- "version": "8.4.13",
3
+ "version": "8.4.15",
4
4
  "description": "Guardian T-Rex for your multi-agent repo. Isolated worktrees, file locks, and PR-only merges stop parallel Codex & Claude agents from overwriting each other's work. Auto-wires Oh My Codex, Oh My Claude, OpenSpec, and Caveman.",
5
5
  "license": "MIT",
6
6
  "preferGlobal": true,
@@ -20,6 +20,7 @@
20
20
  "package:check": "node --check bin/multiagent-safety.js && bash scripts/check-script-symlinks.sh && npm pack --dry-run",
21
21
  "verify": "npm run format:check:changed && npm run lint && npm test && npm run package:check",
22
22
  "prepublishOnly": "node scripts/prepublish-bump-version.js",
23
+ "postinstall": "node -e \"require('./src/heavy').installReport()\"",
23
24
  "agent:codex": "bash ./scripts/codex-agent.sh",
24
25
  "agent:branch:start": "bash ./scripts/agent-branch-start.sh",
25
26
  "agent:branch:finish": "bash ./scripts/agent-branch-finish.sh",
@@ -97,5 +98,5 @@
97
98
  "jsonc-parser": "3.3.1",
98
99
  "semver": "7.7.4"
99
100
  },
100
- "gitHead": "a7f1bda2a3c02d75fb2b75fcafed7812c425d4b7"
101
+ "gitHead": "39adfb07abdaae8c2bfa267603355d60382d5d65"
101
102
  }
@@ -10,6 +10,11 @@ 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
+ On Linux, use `gx run-heavy -- <command> [args...]` for foreground builds,
14
+ typechecks and full test suites. Codex and Claude share the same local RAM-based
15
+ queue; `gx mem-doctor` explains why a job would wait. Leave lightweight reads
16
+ and edits unwrapped.
17
+
13
18
  ## Choose the lane before editing
14
19
 
15
20
  Worktree policy is strict `always` unless the repo opts into `adaptive` with
package/src/cli/main.js CHANGED
@@ -167,7 +167,8 @@ function hasRenderableHelp(command) {
167
167
  function helpFlagIsTopLevel(rest) {
168
168
  if (!rest.length) return false;
169
169
  if (!String(rest[0]).startsWith('-')) return false;
170
- return rest.some((arg) => HELP_FLAGS.has(arg));
170
+ const separator = rest.indexOf('--');
171
+ return (separator === -1 ? rest : rest.slice(0, separator)).some((arg) => HELP_FLAGS.has(arg));
171
172
  }
172
173
 
173
174
  function printCommandHelp(command) {
@@ -349,6 +350,8 @@ async function main() {
349
350
  if (command === 'release') return require('./commands/release').release(rest);
350
351
  if (command === 'watch') return require('./commands/watch').watch(rest);
351
352
  if (command === 'budget') return require('../budget').runBudgetCommand(rest);
353
+ if (command === 'mem-doctor') return require('../heavy').memDoctor(rest);
354
+ if (command === 'run-heavy') return require('../heavy').runHeavy(rest);
352
355
  if (command === 'ci-init') return require('../ci-init').runCiInitCommand(rest);
353
356
  if (command === 'speckit') return require('../speckit').runSpeckitCommand(rest);
354
357
 
package/src/context.js CHANGED
@@ -386,6 +386,8 @@ const SUGGESTIBLE_COMMANDS = [
386
386
  'print-agents-snippet',
387
387
  'release',
388
388
  'budget',
389
+ 'mem-doctor',
390
+ 'run-heavy',
389
391
  'ci-init',
390
392
  'speckit',
391
393
  ];
@@ -403,6 +405,8 @@ const CLI_COMMAND_GROUPS = [
403
405
  ['setup', 'Install, repair, and verify guardrails (flags: --repair, --install-only, --target, --current)'],
404
406
  ['doctor', 'Repair drift + verify (flags: --target, --current; auto-sandboxes on protected main)'],
405
407
  ['status', 'Show GitGuardex CLI + service health without modifying files'],
408
+ ['mem-doctor', 'Show live RAM, swap, and heavy-job queue capacity'],
409
+ ['run-heavy', 'Run a local build or test through the adaptive memory queue'],
406
410
  ['migrate', 'Convert legacy repo-local installs to the zero-copy CLI-owned surface'],
407
411
  ],
408
412
  },
@@ -488,6 +492,18 @@ const CLI_COMMAND_HELP = {
488
492
  speckit: { nativeHelp: true },
489
493
  prompt: { nativeHelp: true },
490
494
 
495
+ 'mem-doctor': {
496
+ usage: 'gx mem-doctor [--json]',
497
+ summary: 'Read RAM, swap, memory pressure, and local heavy-job capacity without making changes.',
498
+ flags: [['--json', 'Machine-readable report']],
499
+ examples: ['gx mem-doctor', 'gx mem-doctor --json'],
500
+ },
501
+ 'run-heavy': {
502
+ usage: 'gx run-heavy -- <command> [args...]',
503
+ summary: 'Wait for local RAM and a shared foreground job slot before running a command.',
504
+ examples: ['gx run-heavy -- npm run build', 'gx run-heavy -- pnpm test'],
505
+ },
506
+
491
507
  setup: {
492
508
  usage: 'gx setup [options]',
493
509
  summary: 'Install, repair, and verify the guardrails in a repo. Idempotent — safe to re-run.',
@@ -13,8 +13,10 @@ const fs = require('fs');
13
13
  const path = require('path');
14
14
  const { spawnSync } = require('child_process');
15
15
  const { run, runPackageAsset } = require('../core/runtime');
16
+ const { heavyInvocation, needsPythonFallback } = require('../heavy');
16
17
 
17
18
  const PREFLIGHT_SCRIPTS = ['typecheck', 'lint'];
19
+ const PREFLIGHT_SECONDS = 5 * 60;
18
20
 
19
21
  function readJson(file) {
20
22
  try {
@@ -128,11 +130,18 @@ function runPreflight(repoRoot, worktreePath, branch, baseBranch, options = {})
128
130
  if (options.verbose) {
129
131
  process.stdout.write(`[preflight] running ${label}…\n`);
130
132
  }
131
- const result = spawnSync(cmd, args, {
133
+ const directOptions = {
132
134
  cwd: repoRoot,
133
135
  stdio: ['ignore', 'pipe', 'pipe'],
134
- timeout: 5 * 60_000,
136
+ timeout: PREFLIGHT_SECONDS * 1000,
137
+ };
138
+ const invocation = heavyInvocation(cmd, args, PREFLIGHT_SECONDS);
139
+ // The Linux runner starts its own execution clock only after admission.
140
+ let result = spawnSync(invocation.command, invocation.args, {
141
+ ...directOptions,
142
+ timeout: invocation.queued ? undefined : directOptions.timeout,
135
143
  });
144
+ if (needsPythonFallback(result, invocation)) result = spawnSync(cmd, args, directOptions);
136
145
  const stdout = (result.stdout || '').toString();
137
146
  const stderr = (result.stderr || '').toString();
138
147
  const ok = !result.error && result.status === 0;
@@ -0,0 +1,113 @@
1
+ const { spawn, spawnSync } = require('node:child_process');
2
+ const { totalmem, freemem, constants } = require('node:os');
3
+ const path = require('node:path');
4
+
5
+ const runner = path.join(__dirname, 'run.py');
6
+ const GiB = 1024 ** 3;
7
+ const gib = (bytes) => `${(bytes / GiB).toFixed(1)} GiB`;
8
+
9
+ function inspect(profileOnly = false) {
10
+ if (process.platform === 'linux') {
11
+ const result = spawnSync('python3', [runner, profileOnly ? 'profile' : 'diagnose'], {
12
+ encoding: 'utf8',
13
+ timeout: profileOnly ? 1500 : 3500
14
+ });
15
+ if (result.status === 0) return JSON.parse(result.stdout);
16
+ if (!profileOnly && result.error?.code !== 'ENOENT') {
17
+ throw new Error(
18
+ result.stderr?.trim() || result.error?.message || 'Memory diagnostics failed'
19
+ );
20
+ }
21
+ }
22
+ return {
23
+ supported: false,
24
+ hostTotalBytes: totalmem(),
25
+ availableBytes: freemem(),
26
+ reason: process.platform === 'linux' ? 'Linux queue needs python3' : 'Local queue is Linux-only'
27
+ };
28
+ }
29
+
30
+ function installReport() {
31
+ const report = inspect(true);
32
+ const ram = gib(report.hostTotalBytes);
33
+ console.log(
34
+ report.supported
35
+ ? `[gx] Detected ${ram} RAM; adaptive queue: up to ${report.maxJobs} heavy jobs (${gib(report.totalBytes)} effective RAM).`
36
+ : `[gx] Detected ${ram} RAM; ${report.reason}.`
37
+ );
38
+ }
39
+
40
+ function memDoctor(args) {
41
+ if (args.length && (args.length !== 1 || args[0] !== '--json')) {
42
+ throw new Error('Usage: gx mem-doctor [--json]');
43
+ }
44
+ const report = inspect();
45
+ if (args[0] === '--json') {
46
+ console.log(JSON.stringify(report, null, 2));
47
+ return;
48
+ }
49
+ console.log(
50
+ `RAM: ${gib(report.availableBytes)} ${report.supported ? 'available' : 'free'} / ${gib(report.totalBytes ?? report.hostTotalBytes)} total`
51
+ );
52
+ if (!report.supported) {
53
+ console.log(report.reason);
54
+ return;
55
+ }
56
+ console.log(`Swap: ${gib(report.swapFreeBytes)} free / ${gib(report.swapTotalBytes)} total`);
57
+ console.log(
58
+ report.enabled
59
+ ? `Heavy jobs: ${report.activeJobs}/${report.maxJobs} busy, ${report.admissibleJobs} can start now; ${gib(report.reserveBytes)} RAM reserved`
60
+ : 'Heavy-job queue disabled'
61
+ );
62
+ console.log(
63
+ `Memory pressure (10s): some ${report.pressureAvg10.some ?? 'n/a'}%, full ${report.pressureAvg10.full ?? 'n/a'}%`
64
+ );
65
+ console.log(
66
+ `systemd worker scope: ${report.scopeAvailable ? `available, MemoryHigh ${gib(report.memoryHighBytes)}/job` : 'unavailable'}`
67
+ );
68
+ }
69
+
70
+ function heavyInvocation(command, args, executionSeconds) {
71
+ if (process.platform === 'linux' && process.env.GUARDEX_HEAVY_QUEUE !== '0') {
72
+ const budget = executionSeconds ? ['--run-timeout', String(executionSeconds)] : [];
73
+ return { command: 'python3', args: [runner, ...budget, '--', command, ...args], queued: true };
74
+ }
75
+ return { command, args };
76
+ }
77
+
78
+ function needsPythonFallback(result, invocation) {
79
+ return (
80
+ invocation.command === 'python3' &&
81
+ invocation.args[0] === runner &&
82
+ result.error?.code === 'ENOENT' &&
83
+ result.error.path === 'python3'
84
+ );
85
+ }
86
+
87
+ async function runHeavy(args) {
88
+ if (args[0] !== '--' || !args[1]) throw new Error('Usage: gx run-heavy -- <command> [args...]');
89
+ const [, command, ...commandArgs] = args;
90
+ const invocation = heavyInvocation(command, commandArgs);
91
+ function launch({ command, args }) {
92
+ return new Promise((resolve, reject) => {
93
+ const child = spawn(command, args, { stdio: 'inherit' });
94
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'];
95
+ const forward = (signal) => child.kill(signal);
96
+ for (const signal of signals) process.on(signal, forward);
97
+ child.once('error', reject);
98
+ child.once('close', (code, signal) => {
99
+ for (const name of signals) process.off(name, forward);
100
+ resolve(code ?? (signal ? 128 + constants.signals[signal] : 1));
101
+ });
102
+ });
103
+ }
104
+ try {
105
+ process.exitCode = await launch(invocation);
106
+ } catch (error) {
107
+ if (!needsPythonFallback({ error }, invocation)) throw error;
108
+ console.error('[gx] python3 unavailable; running without the local memory queue.');
109
+ process.exitCode = await launch({ command, args: commandArgs });
110
+ }
111
+ }
112
+
113
+ module.exports = { installReport, memDoctor, runHeavy, heavyInvocation, needsPythonFallback };
@@ -0,0 +1,394 @@
1
+ """Per-user Linux admission control for foreground build and test commands."""
2
+ import contextlib
3
+ import fcntl
4
+ import json
5
+ import os
6
+ from pathlib import Path
7
+ import pwd
8
+ import re
9
+ import shutil
10
+ import signal
11
+ import stat
12
+ import subprocess
13
+ import sys
14
+ import time
15
+
16
+ MIB = 1024 ** 2
17
+ GIB = 1024 * MIB
18
+ MAX_SLOTS = 4
19
+ CGROUP = Path("/sys/fs/cgroup")
20
+
21
+
22
+ def read(path):
23
+ try:
24
+ return Path(path).read_text()
25
+ except OSError:
26
+ return ""
27
+
28
+
29
+ def counters(path):
30
+ return {key.rstrip(":"): int(value) for key, value, *_ in
31
+ (line.split() for line in read(path).splitlines() if line.strip())
32
+ if value.isdecimal()}
33
+
34
+
35
+ def number(path):
36
+ value = read(path).strip()
37
+ return int(value) if value.isdecimal() else None
38
+
39
+
40
+ def current_group():
41
+ for line in read("/proc/self/cgroup").splitlines():
42
+ if line.startswith("0::/"):
43
+ group = (CGROUP / line[4:]).resolve()
44
+ if group == CGROUP or CGROUP in group.parents:
45
+ return group
46
+ return None
47
+
48
+
49
+ def v1_memory_group():
50
+ for line in read("/proc/self/cgroup").splitlines():
51
+ _, controllers, group = line.split(":", 2)
52
+ if "memory" in controllers.split(","):
53
+ break
54
+ else:
55
+ return None
56
+ for line in read("/proc/self/mountinfo").splitlines():
57
+ left, separator, right = line.partition(" - ")
58
+ if not separator:
59
+ continue
60
+ fs, _, options = right.split()
61
+ if fs != "cgroup" or "memory" not in options.split(","):
62
+ continue
63
+ root, mount = (Path(re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), field))
64
+ for field in left.split()[3:5])
65
+ try:
66
+ directory = (mount / Path(group).relative_to(root)).resolve()
67
+ except ValueError:
68
+ continue
69
+ if (directory == mount or mount in directory.parents) and (directory / "memory.limit_in_bytes").is_file():
70
+ return mount, directory
71
+ return None
72
+
73
+
74
+ def cgroup_headroom(total, available):
75
+ v1 = v1_memory_group()
76
+ root, group = v1 or (CGROUP, current_group())
77
+ if group is None:
78
+ return total, available
79
+ limit_file, usage_file = ("memory.limit_in_bytes", "memory.usage_in_bytes") if v1 else ("memory.max", "memory.current")
80
+ for parent in (group, *group.parents):
81
+ if not v1 or parent == group or read(parent / "memory.use_hierarchy").strip() != "0":
82
+ limit = number(parent / limit_file)
83
+ used = number(parent / usage_file)
84
+ if limit is not None:
85
+ total = min(total, limit)
86
+ available = min(available, max(0, limit - (used or 0)))
87
+ if parent == root:
88
+ break
89
+ return total, available
90
+
91
+
92
+ def policy(total, available, active):
93
+ # ponytail: one conservative estimate per job; add job-specific weights only
94
+ # if measured workloads consistently need different admission thresholds.
95
+ max_jobs = min(MAX_SLOTS, max(1, total // (8 * GIB))) if total else 0
96
+ reserve = max(total // 8, min(512 * MIB, total // 4))
97
+ job = min(2 * GIB, total // 4)
98
+ additional = min(max_jobs - active, (available - reserve) // max(1, job) - active)
99
+ return {
100
+ "maxJobs": max_jobs,
101
+ "activeJobs": active,
102
+ "admissibleJobs": max(0, additional),
103
+ "reserveBytes": reserve,
104
+ "estimatedJobBytes": job,
105
+ "memoryHighBytes": min(4 * GIB, total // 2),
106
+ }
107
+
108
+
109
+ def snapshot(active):
110
+ mem = counters("/proc/meminfo")
111
+ host_total = mem.get("MemTotal", 0) * 1024
112
+ host_available = mem.get("MemAvailable", 0) * 1024
113
+ total, available = cgroup_headroom(host_total, host_available)
114
+ return {
115
+ "supported": True,
116
+ "enabled": os.environ.get("GUARDEX_HEAVY_QUEUE") != "0",
117
+ "hostTotalBytes": host_total,
118
+ "hostAvailableBytes": host_available,
119
+ "totalBytes": total,
120
+ "availableBytes": available,
121
+ "swapTotalBytes": mem.get("SwapTotal", 0) * 1024,
122
+ "swapFreeBytes": mem.get("SwapFree", 0) * 1024,
123
+ **policy(total, available, active),
124
+ }
125
+
126
+
127
+ def queue_dir():
128
+ uid = os.getuid()
129
+ runtime = Path(f"/run/user/{uid}")
130
+ if check_directory(runtime):
131
+ return runtime / "gitguardex-heavy"
132
+ # Use the account's home, not the caller's HOME. Prefer it over shared /tmp.
133
+ try:
134
+ home = Path(pwd.getpwuid(uid).pw_dir)
135
+ if home.is_absolute():
136
+ info = home.stat()
137
+ if stat.S_ISDIR(info.st_mode) and info.st_uid == uid and not info.st_mode & 0o022:
138
+ return home / ".cache" / "gitguardex-heavy"
139
+ except (KeyError, OSError):
140
+ pass
141
+ # Unmapped UIDs still share a queue; creation rejects foreign-owned paths.
142
+ return Path(f"/tmp/gitguardex-heavy-{uid}")
143
+
144
+
145
+ def check_directory(directory, create=False):
146
+ if create:
147
+ directory.mkdir(parents=True, exist_ok=True, mode=0o700)
148
+ try:
149
+ info = directory.lstat()
150
+ except FileNotFoundError:
151
+ return False
152
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
153
+ raise RuntimeError(f"unsafe queue directory: {directory}")
154
+ return True
155
+
156
+
157
+ def try_lock(path, create=False):
158
+ flags = (os.O_RDWR | os.O_CREAT) if create else os.O_RDONLY
159
+ try:
160
+ fd = os.open(path, flags | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
161
+ except FileNotFoundError:
162
+ if not create:
163
+ return None, False
164
+ raise
165
+ try:
166
+ info = os.fstat(fd)
167
+ if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid():
168
+ raise RuntimeError(f"unsafe queue lock: {path}")
169
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
170
+ return fd, False
171
+ except BlockingIOError:
172
+ os.close(fd)
173
+ return None, True
174
+ except BaseException:
175
+ os.close(fd)
176
+ raise
177
+
178
+
179
+ @contextlib.contextmanager
180
+ def inspect_slots(directory, create=False):
181
+ with contextlib.ExitStack() as stack:
182
+ slots = []
183
+ for index in range(MAX_SLOTS):
184
+ fd, busy = try_lock(directory / f"slot-{index}", create)
185
+ if fd is not None:
186
+ if create:
187
+ stack.callback(os.close, fd)
188
+ else:
189
+ os.close(fd)
190
+ fd = None
191
+ slots.append((fd, busy))
192
+ yield slots
193
+
194
+
195
+ def admit(directory):
196
+ guard, _ = try_lock(directory / "admission", create=True)
197
+ if guard is None:
198
+ return None
199
+ try:
200
+ with inspect_slots(directory, create=True) as slots:
201
+ plan = snapshot(sum(busy for _, busy in slots))
202
+ if plan["admissibleJobs"]:
203
+ # dup keeps the same kernel lock after the probe releases its fd.
204
+ fd = next(fd for fd, _ in slots if fd is not None)
205
+ return os.dup(fd), plan["memoryHighBytes"]
206
+ finally:
207
+ os.close(guard)
208
+ return None
209
+
210
+
211
+ def user_manager_group():
212
+ uid = os.getuid()
213
+ return CGROUP / f"user.slice/user-{uid}.slice/user@{uid}.service"
214
+
215
+
216
+ def worker_slice():
217
+ if os.environ.get("GUARDEX_HEAVY_SCOPE") == "0" or not (CGROUP / "cgroup.controllers").is_file():
218
+ return None
219
+ # Only move out of ordinary user scopes. Stay under the same parent slice
220
+ # and don't escape memory limits on the caller's scope itself.
221
+ group = current_group()
222
+ if group is None or not group.name.endswith(".scope"):
223
+ return None
224
+ parent = group.parent
225
+ if parent.parent != user_manager_group() or parent.name not in ("app.slice", "session.slice"):
226
+ return None
227
+ if any(read(group / f"memory.{field}").strip() != "max" for field in ("max", "high")):
228
+ return None
229
+ if not shutil.which("systemd-run") or not shutil.which("systemctl"):
230
+ return None
231
+ try:
232
+ ready = subprocess.run(
233
+ ["systemctl", "--user", "show", "--property=Version", "--value"], stdin=subprocess.DEVNULL,
234
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2,
235
+ ).returncode == 0
236
+ return parent / parent.name.replace(".slice", "-gxheavy.slice") if ready else None
237
+ except (OSError, subprocess.TimeoutExpired):
238
+ return None
239
+
240
+
241
+ def supervise(command, seconds, pass_fds, *, new_session):
242
+ interrupted = False
243
+ with subprocess.Popen(command, start_new_session=new_session, pass_fds=pass_fds) as child:
244
+ def send(signum):
245
+ with contextlib.suppress(ProcessLookupError):
246
+ (os.killpg if new_session else os.kill)(child.pid, signum)
247
+
248
+ def forward(signum, _frame):
249
+ nonlocal interrupted
250
+ interrupted = True
251
+ send(signum)
252
+
253
+ previous = {signum: signal.signal(signum, forward)
254
+ for signum in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)}
255
+ try:
256
+ status = child.wait(timeout=seconds)
257
+ return status, interrupted
258
+ except subprocess.TimeoutExpired:
259
+ send(signal.SIGKILL)
260
+ print(f"[gx] Heavy job timed out after {seconds}s of execution.", file=sys.stderr)
261
+ return 124, interrupted
262
+ finally:
263
+ for signum, handler in previous.items():
264
+ signal.signal(signum, handler)
265
+
266
+
267
+ def exit_status(status):
268
+ return status if status >= 0 else 128 - status
269
+
270
+
271
+ def run_scope(command, seconds, scope, high, slot_fd):
272
+ # Scope setup and the command can fail with the same exit code. Only the
273
+ # in-scope wrapper can attest that it has taken responsibility for the job.
274
+ reader, writer = os.pipe2(os.O_CLOEXEC | os.O_NONBLOCK)
275
+ try:
276
+ scoped = ["systemd-run", "--user", "--scope", "--quiet", f"--slice={scope.name}",
277
+ "--description=GitGuardex heavy job", "-p", f"MemoryHigh={high}", "--",
278
+ sys.executable, os.path.abspath(__file__), "scoped", str(writer),
279
+ "" if seconds is None else str(seconds), str(slot_fd), *command]
280
+ try:
281
+ status, interrupted = supervise(scoped, None, (slot_fd, writer), new_session=False)
282
+ except (FileNotFoundError, PermissionError):
283
+ return None
284
+ if interrupted or status < 0:
285
+ return exit_status(status)
286
+ with contextlib.suppress(BlockingIOError):
287
+ if os.read(reader, 1):
288
+ return exit_status(status)
289
+ return None
290
+ finally:
291
+ os.close(reader)
292
+ os.close(writer)
293
+
294
+
295
+ def execute(command, seconds, scope=None, high=None, slot_fd=None):
296
+ if scope:
297
+ status = run_scope(command, seconds, scope, high, slot_fd)
298
+ if status is not None:
299
+ return status
300
+ if seconds is not None:
301
+ # Keep the slot locked if the supervisor dies while the child is running.
302
+ pass_fds = () if slot_fd is None else (slot_fd,)
303
+ status, _ = supervise(command, seconds, pass_fds, new_session=True)
304
+ return exit_status(status)
305
+ signal.signal(signal.SIGPIPE, signal.SIG_DFL)
306
+ os.execvp(command[0], command)
307
+
308
+
309
+ def run(command, seconds=None):
310
+ if os.environ.get("GUARDEX_HEAVY_QUEUE") == "0" or os.environ.get("GUARDEX_HEAVY_ACTIVE") == "1":
311
+ return execute(command, seconds)
312
+ directory = queue_dir()
313
+ check_directory(directory, create=True)
314
+ timeout = int(os.environ.get("GUARDEX_HEAVY_WAIT_SECONDS", "120"))
315
+ if timeout < 0:
316
+ raise ValueError("GUARDEX_HEAVY_WAIT_SECONDS must be a non-negative integer")
317
+ deadline = time.monotonic() + timeout
318
+ warned = False
319
+ while True:
320
+ admission = admit(directory)
321
+ if admission is not None:
322
+ fd, high = admission
323
+ os.set_inheritable(fd, True)
324
+ os.environ["GUARDEX_HEAVY_ACTIVE"] = "1"
325
+ return execute(command, seconds, worker_slice(), high, fd)
326
+ remaining = deadline - time.monotonic()
327
+ if remaining <= 0:
328
+ with inspect_slots(directory) as slots:
329
+ plan = snapshot(sum(busy for _, busy in slots))
330
+ active = plan["activeJobs"]
331
+ needed = max(0, plan["reserveBytes"] + plan["estimatedJobBytes"] * (active + 1)
332
+ - plan["availableBytes"])
333
+ detail = f"{active}/{plan['maxJobs']} slots occupied"
334
+ if needed:
335
+ detail += f"; needs {needed / GIB:.1f} GiB more available RAM"
336
+ print(f"[gx] Heavy job not started before timeout ({detail}). Run gx mem-doctor.", file=sys.stderr)
337
+ return 75
338
+ if not warned:
339
+ print("[gx] Waiting for a heavy-job slot and available RAM…", file=sys.stderr)
340
+ warned = True
341
+ time.sleep(min(1, remaining))
342
+
343
+
344
+ def diagnose():
345
+ directory = queue_dir()
346
+ with inspect_slots(directory) if check_directory(directory) else contextlib.nullcontext([]) as slots:
347
+ report = snapshot(sum(busy for _, busy in slots))
348
+ pressure = read("/proc/pressure/memory")
349
+ group = worker_slice()
350
+ report.update(
351
+ pressureAvg10={line.split()[0]: float(line.split()[1].split("=")[1])
352
+ for line in pressure.splitlines()},
353
+ scopeAvailable=group is not None,
354
+ scopeSlice=group.name if group else None,
355
+ scopeMemoryCurrentBytes=number(group / "memory.current") if group else None,
356
+ scopeMemoryPeakBytes=number(group / "memory.peak") if group else None,
357
+ scopeMemoryEvents=counters(group / "memory.events") if group else {},
358
+ )
359
+ print(json.dumps(report))
360
+
361
+
362
+ def main(args):
363
+ if args == ["diagnose"]:
364
+ diagnose()
365
+ elif args == ["profile"]:
366
+ print(json.dumps(snapshot(0)))
367
+ elif len(args) >= 4 and args[0] == "--run-timeout" and args[2] == "--":
368
+ return run(args[3:], int(args[1]))
369
+ elif len(args) >= 5 and args[0] == "scoped":
370
+ ready, seconds, slot_fd = args[1:4]
371
+ os.write(int(ready), b"1")
372
+ os.close(int(ready))
373
+ return execute(args[4:], int(seconds) if seconds else None, slot_fd=int(slot_fd))
374
+ elif len(args) >= 2 and args[0] == "--":
375
+ return run(args[1:])
376
+ else:
377
+ raise ValueError("expected diagnose, profile or -- <command>")
378
+ return 0
379
+
380
+
381
+ if __name__ == "__main__":
382
+ try:
383
+ sys.exit(main(sys.argv[1:]))
384
+ except KeyboardInterrupt:
385
+ sys.exit(130)
386
+ except FileNotFoundError as error:
387
+ print(f"[gx] {error}", file=sys.stderr)
388
+ sys.exit(127)
389
+ except PermissionError as error:
390
+ print(f"[gx] {error}", file=sys.stderr)
391
+ sys.exit(126)
392
+ except (OSError, RuntimeError, ValueError) as error:
393
+ print(f"[gx] {error}", file=sys.stderr)
394
+ sys.exit(1)
@@ -16,6 +16,7 @@ routing with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` or
16
16
  - Claim files before editing in isolated lanes. Confirm a path is in your claim before deleting it.
17
17
  - Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
18
18
  - Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
19
+ - On Linux, run foreground builds, typechecks and full test suites with `gx run-heavy -- <command>`; inspect local capacity with `gx mem-doctor`.
19
20
  - Commit, push, and open/update a PR for completed work unless the user says keep-local.
20
21
  - Keep outputs and notes compact. Less word, same proof.
21
22
 
@@ -13,6 +13,7 @@ single-agent path may opt in with `GUARDEX_WORKTREE_MODE=adaptive` in `.env` (or
13
13
  - In an isolated lane, claim files before editing: `gx locks claim --branch "<agent-branch>" <file...>`.
14
14
  - Use CodeGraph first for repository symbol, relationship, architecture, and impact lookup. If the project is not initialized, run `codegraph init -i` once and retry.
15
15
  - Use `opensrc path <package-or-owner/repo[@ref|#ref]>` before generic clone/download when inspecting dependency or external repository source.
16
+ - On Linux, run foreground builds, typechecks and full test suites with `gx run-heavy -- <command>`; inspect local capacity with `gx mem-doctor`.
16
17
  - 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.
17
18
  - 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. Never ask the user whether to run the review or to merge: review automatically and merge when the gate is clean; stop only when it blocks or the user said keep-local.
18
19
 
@@ -10,6 +10,11 @@ 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
+ On Linux, use `gx run-heavy -- <command> [args...]` for foreground builds,
14
+ typechecks and full test suites. Codex and Claude share the same local RAM-based
15
+ queue; `gx mem-doctor` explains why a job would wait. Leave lightweight reads
16
+ and edits unwrapped.
17
+
13
18
  ## Choose the lane before editing
14
19
 
15
20
  Worktree policy is strict `always` unless the repo opts into `adaptive` with
@@ -332,10 +332,14 @@ run_preflight() {
332
332
  finish_progress running preflight "final verification before publish"
333
333
  echo "[agent-branch-finish] Running pre-flight: ${script_path}" >&2
334
334
  local preflight_status=0
335
+ local runner=()
336
+ if [[ -n "$CLI_ENTRY" ]]; then
337
+ runner=(run_guardex_cli run-heavy --)
338
+ fi
335
339
  if [[ -n "$trusted_tree" ]]; then
336
- ( cd "$preflight_cwd" && "$script_path" --guardex-target-worktree "$worktree" ) || preflight_status=$?
340
+ ( cd "$preflight_cwd" && "${runner[@]}" "$script_path" --guardex-target-worktree "$worktree" ) || preflight_status=$?
337
341
  else
338
- ( cd "$preflight_cwd" && GUARDEX_PREFLIGHT_TARGET_WORKTREE="$worktree" "$script_path" ) || preflight_status=$?
342
+ ( cd "$preflight_cwd" && GUARDEX_PREFLIGHT_TARGET_WORKTREE="$worktree" "${runner[@]}" "$script_path" ) || preflight_status=$?
339
343
  fi
340
344
  if [[ -n "$trusted_tree" ]]; then
341
345
  rm -rf -- "$trusted_tree"