heavy-gate
Health Uyari
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 8 GitHub stars
Code Basarisiz
- rm -rf — Recursive force deletion command in tests/test_queue.sh
- rm -rf — Recursive force deletion command in uninstall.sh
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
Run many AI coding agents in parallel on one laptop without running out of memory: machine-wide queue for heavy commands, Claude Code hook and memory guard.
heavy-gate
Run many AI coding agents in parallel on one laptop without running out of memory.
Leer en español · The story behind it (postmortem, ES)
When several agents (Claude Code, Codex, Cursor…) work in parallel, each in its own git worktree, nobody runs out of memory while editing. A single agent takes about 300–400 MB. What kills the machine is when they all start their tests and builds at the same moment:
jestdefaults to cores − 1 workers;lerna/nxfan out builds;- each
ts-jestworker can take 2 GB.
On a 16 GB MacBook, three agents running jest at once peaked at 27 GB of node, exhausted compressed memory and swap, and froze the machine until the kernel watchdog rebooted it.
heavy-gate fixes this without limiting the number of agents. It limits how many heavy commands run at the same time:
| Piece | What it does |
|---|---|
heavy |
Machine-wide FIFO queue for heavy commands. N slots (flock, released by the OS if a process dies), plus a free-memory check before starting. Cancelling a job kills its whole process group, so no orphaned workers are left. |
heavy-hook |
Claude Code PreToolUse hook. It rewrites any jest/vitest/tsc/lerna/nx/eslint/stryker/npm test|build|lint command to run through heavy, so agents can't forget. Quote-aware: grep 'jest' x is left alone. |
heavy-guard |
Memory watchdog (launchd on macOS, systemd on Linux). If free memory drops below 10%, it kills the largest test/build process, and never your browser, Docker, editor or agents. Worst case: one test run fails. Not a kernel panic. heavy then tells the agent that it was the guard that cut the run. |
agent 1 ─┐ ┌─ slot 0: jest (agent 3)
agent 2 ─┤ npx jest … ──hook──▶ │ slot 1: tsc (agent 1) heavy-guard
agent 3 ─┤ npm run build ──────▶ │ slot 2: free watches memory,
agent N ─┘ (editing: no limit) └─ queue: [agent 2: build] ... kills the biggest
starts only if free mem ≥ 25% test process < 10%
Pure Python 3.8+ standard library. No dependencies. macOS and Linux.
Step by step
1. Requirements
- macOS or Linux.
python33.8 or newer. On macOS:brew install python, or the one fromxcode-select --install.- Optional: Claude Code, for the automatic hook.
2. Clone
git clone https://github.com/LautaroAcosta/heavy-gate.git
cd heavy-gate
3. Install
./install.sh --claude-hook
This:
- copies the scripts to
~/.local/share/heavy-gateand linksheavy,heavy-hookandheavy-guardinto~/.local/bin. Make sure that directory is in yourPATH. - creates
~/.heavy/config.json. - starts
heavy-guardas a user service: LaunchAgentdev.heavy-gate.guardon macOS,heavy-guard.serviceon Linux. - with
--claude-hook, merges the hook into~/.claude/settings.json. Existing hooks are kept and a backup is written next to the file.
Using an orchestrator that runs agents with their own CLAUDE_CONFIG_DIR? Some tools do, for example Orca profiles. Add those directories too:
./install.sh --claude-hook --claude-config-dir "/path/to/profile/home"
Not using Claude Code? Skip --claude-hook and see Other agents and manual use.
4. Verify
heavy status # slots, queue and free memory
heavy-guard --once # current memory level and what the guard would kill first
In a Claude Code session, ask it to run npx tsc --version. Then:
tail -1 ~/.heavy/log.jsonl # should show a "start" event for that command
If nothing shows up, open /hooks in Claude Code once, or restart the session, so it reloads the settings.
5. Tune it
Edit ~/.heavy/config.json. It is re-read on every check, so no restart is needed.
| Key | Default | Meaning |
|---|---|---|
slots |
3 | Heavy commands allowed at the same time. |
min_free |
25 | A new job waits until at least this % of memory is available. If nothing is running, it starts anyway. |
poll_s |
1 | How often a queued job re-checks. |
kill_below |
10 | The guard kills the largest test/build process below this % free. |
warn_below |
18 | The guard logs a warning below this %. |
guard_poll_s |
2 | How often the guard checks. |
guard_dry_run |
false | Log what would be killed, without killing it. |
Rule of thumb:
slots ≈ (RAM − what you normally use for browser, Docker and IDE) / peak memory of one heavy job
Measure the peak with heavy-guard --once while a job runs. Do step 6 first: making each job lighter lets you raise slots.
6. Make each heavy job lighter (biggest win)
The queue caps how many jobs run. These settings cap how big each one is. See docs/jest-and-tsc-tuning.md. In short:
// jest.config.js
module.exports = {
maxWorkers: 2, // default is cores - 1
workerIdleMemoryLimit: '1GB', // recycle leaky workers (jest >= 29)
transform: { '^.+\\.ts$': ['ts-jest', { isolatedModules: true }] }, // no type-check per worker
// or: transform: { '^.+\\.(t|j)s$': '@swc/jest' }
};
Also:
lerna run build --concurrency 2, ornx run-many --parallel=2.- Run type-checking once, with
tsc --noEmit, instead of inside every jest worker. - While iterating, agents should run only related tests:
jest --findRelatedTests <changed files>.
7. Other agents and manual use
The hook is specific to Claude Code. For anything else, prefix the command yourself:
heavy npx jest
heavy npm run build
Or make your shell do it, in ~/.zshrc or ~/.bashrc:
jest() { heavy npx jest "$@"; }
tsc() { heavy npx tsc "$@"; }
Tell your agents about it in your AGENTS.md / CLAUDE.md. Example:
Heavy commands (jest, tsc, builds) go through
heavy, a machine-wide queue. If one takes a while to start, it is waiting for a slot or free memory: don't cancel or retry it (heavy statusshows the queue). While iterating, run only related tests with--maxWorkers=2; run the full suite once before finishing. A[heavy] heavy-guard killedline (exit code 75 when the command failed) means the memory guard cut the run: don't treat it as a test failure; retry when memory is free before changing code or tests. If it fails again with no such line, it is a real failure.
8. Logs and metrics
# time spent waiting in the queue
jq -s '[.[]|select(.event=="start")|.waited_s]|{jobs:length,avg:(add/length),max:max}' ~/.heavy/log.jsonl
# lowest free memory and highest total node memory seen (one sample per minute)
jq -s '{min_free:(map(.level)|min), max_node_mb:(map(.node_mb)|max)}' ~/.heavy/mem.jsonl
# guard interventions
cat ~/.heavy/guard.jsonl
9. Troubleshooting
| Problem | Fix |
|---|---|
| A command "hangs" | Probably queued: run heavy status. |
Exit code 75, or a [heavy] heavy-guard killed line |
Don't treat it as a test failure: memory ran low and the guard killed a process of that job. Before changing anything, retry when more memory is free, run it on its own, or use fewer workers (--maxWorkers=2). If it fails again with no such line, it is a real failure: treat it as one. If the command exits 0 anyway (a pipe, ||, or the runner retried), the 0 is kept and only the notice appears: check that the output is complete. |
| Bypass the queue once | Put HEAVY_BYPASS=1 in the command. For a whole Claude session, start it with HEAVY_DISABLE=1. |
| Guard not running on macOS | launchctl print gui/$(id -u)/dev.heavy-gate.guard, and check ~/.heavy/guard.err. Scripts must not live in ~/Documents or ~/Desktop: launchd can't read those without a privacy grant and hangs on open(). That is why the installer copies them to ~/.local/share. |
| macOS asks for "python wants to access Documents" | You ran the guard from a protected folder. Reinstall with ./install.sh. |
| A light command got queued | Open an issue with the command. The classifier errs on the side of queueing. |
10. Uninstall
./uninstall.sh # scripts, guard and the hook in ~/.claude
./uninstall.sh --claude-config-dir "/path/..." # also other config dirs
./uninstall.sh --purge # also delete ~/.heavy (config + logs)
How it works (details)
- Slots are
flocked files in~/.heavy/slots. The kernel releases the lock when the holder exits, even withkill -9, so slots never leak. - FIFO. Every caller writes
~/.heavy/waiting/<pid>on arrival. Only the oldest live waiter may take a slot, and dead waiters are cleaned up automatically. - Memory check. On macOS it uses
sysctl kern.memorystatus_level, the % of memory the kernel considers available. On Linux,MemAvailable / MemTotal. - Process groups. The job runs with
start_new_session. Signals toheavyare forwarded to the whole group, and the group is reaped when the job ends. - Nested calls. Inside a job,
HEAVY_HELD=1is set and any nestedheavyruns directly, so there are no deadlocks. - Guard kills.
heavy-guardrecords the process group of what it kills in~/.heavy/guard.jsonl. When a job ends,heavyreads the new entries (the whole file if it shrank) and, if one hit that job, says so on stderr and turns a failed exit code into 75 (EX_TEMPFAIL). An exit code of 0 stays 0. - The hook splits the command with
shlex(quote-aware) and checks the first word of each simple command, unwrappingnpx,npm exec,env,VAR=xand so on. It returnsupdatedInputwithheavy /bin/zsh -c '<original>'and preserves the other tool-input fields.
Limitations
- macOS has no cgroups, so there is no hard per-process memory cap. The guard is a safety net, not a guarantee. For hard caps, run tests in a container (
docker run --memory=4g) or on a remote Linux box. - The queue limits concurrency, not job size. One badly configured
jest(7 workers × 2 GB) can still be huge on its own: do step 6. - The hook only covers Claude Code's Bash tool. Other tools need the manual prefix or shell functions.
- Guard kills are only reported for commands that run through
heavy(not withHEAVY_BYPASSorHEAVY_DISABLE) and for processes still in the job's process group: one that callssetsid(or is started detached) leaves it, so killing it is not reported. The hook isPreToolUse, so it can only warn the agent in advance; covering the rest with aPostToolUsehook is a next step.
Tests
python3 -m unittest discover tests # hook classifier, guard kill reporting
sh tests/test_queue.sh # queue: ordering, exit codes, nesting, orphan cleanup
License
MIT
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi