Bash memory rules: Node commands run in claude-cmd.slice, and runs that would starve the machine are refused

Personal Claude Code mods: plugins of function hooks that restyle the transcript, add rows around the prompt and react to tool calls. Built and used on Claude Code 2.1.287+, Linux.
| Mod | What it does | Commands | Needs | |||
|---|---|---|---|---|---|---|
| quiet-bash | One-line tool rows (✓ <description>, red ✗ exit N on failure, +N −M on edits, duration for calls ≥10 s). Hides every tool's result block (Bash output, Edit diffs, WebFetch, MCP and Agent results; interactive tools, SendUserFile and image Reads keep theirs), finished read-only rows (Read/Grep/Glob, and calls the engine ran read-only like ls or git status, and every Claude in Chrome step but navigate), collapsed tool groups unless one failed, and timed-out GitLab pipeline-wait notices. Inline PNG thumbnails under rows that read, sent or wrote a PNG (at most 3 written ones per call), relative paths included; a group holding a thumbnail stays open, even under /quiet | /quiet brings it all back; /thumb [big] <path> shows a PNG (relative to the session's directory) as thumb #N: <path> | ImageMagick (magick) for thumbnails; a terminal with kitty graphics (see herdr) | |||
| quiet-spinner | Plain spinner words (thinking, writing, running, waiting, preparing) and Took 1m 4s instead of the whimsical ones | – | – | |||
| usage-percent | Row under the prompt: `ctx ▰▱▱▱ 34% \ | 5h ▰▰▱▱ 41% \ | wk ▰▰▰▱ 86% \ | fable ▰▰▱▱ 28% (four-cell bars; the fourth is the plan's model-scoped week, from the usage endpoint with the session's login) and resets 1d5h a gap after them for the weekly reset, yellow from 80 %, red from 95 %. Memory (claude.slice usage as a ten-cell bar of its limit + app.slice pressure, yellow from 20 %, red from 50 %) is sampled every 10 s and drawn by TamaGoxtix's band. In Nx repos also, on the right, the session's own nx serve projects (▶ admin api; a bare nx serve or run-many -t serve shows ▶ serve) and the branch's pipeline (ci ⏳ test, ⏸` when it waits on a manual job or an approval; none for Azure remotes) | – | gh / glab logged in for the pipeline; systemd claude.slice for memory |
| reminder-log | Tallies the reminders Claude Code injects for the model, per session; drops the token counter and repeated commit attribution blocks (sent again after a compaction) | /reminders prints the tally of the last 30 days | – | |||
| mr-banner | Colored card with a link under each MR/PR created, merged, approved or reviewed | – | GitLab MCP server named gitlab, or glab / gh | |||
| coderabbit-band | Band above the prompt with the open CodeRabbit threads (by severity) and nitpicks of the current branch's GitLab MR, with a link. Shows only when something is open | /coderabbit hides it until the counts change | glab logged in; GitLab remote | |||
| redact | Secrets in prompts and tool output reach the model as ‹secret:…› tokens; only Write/Edit turn them back into the real value. See redact | – | betterleaks on PATH | |||
| mem-guard | Bash commands that run Node tools go into a memory-capped claude-cmd.slice scope. Refused, with the fix in the message: nx affected/run-many without --parallel=1, a pnpm script that has a :lite twin, jest without a worker cap (--maxWorkers=N, -w N or --runInBand; a percentage doesn't count), pkill -f/pgrep -f with an unbracketed pattern, ci:local, heavy runs and dev-server starts while the slice is above 75 % or under pressure, a third heavy command or a third dev server at once, and writes by a check-runner subagent. See mem-guard | – | Linux with systemd: a user claude-cmd.slice, ps; see mem-guard | |||
| handover | Skill plus mod: the handover skill writes a one-sentence handover for a cold session to ~/.claude/handover.md; the mod files it per session under ~/.claude/handovers/<session id>.md, so parallel sessions in one repo never overwrite each other. A band above the prompt shows it; after /clear that session's sentence waits in the prompt (Tab takes it) and the next prompt spends it. A new terminal suggests nothing but lists the open sentences of the repo it started in (newest first, 14 days); a sentence belongs to the repo of the file its session wrote last, else to the folder the session started in | /handover-copy copies it and hides the band; /handover lists, /handover N puts one in the prompt, /handover drop N removes it; a sentence pasted by hand leaves the list too | – | |||
| herdr-notify | GNOME popup when Claude waits for a permission, an answer or a new prompt (a Notification hook, not a plugin). Skipped while that pane is the focused one in herdr. Clicking it raises Ghostty and focuses that session's herdr pane. Hook: `"Notification": [{"matcher": "permission_prompt\ | idle_prompt\ | elicitation_dialog", "hooks": [{"type": "command", "command": "bash \"$HOME/.claude/skills/herdr-notify/notify.sh\""}]}]` | – | herdr, Ghostty, notify-send, jq | |
| stack-down | On /clear and exit (also logout, a finished -p run, SIGINT/SIGTERM/SIGHUP), stops what the session left running in its repo: the nx processes it started (with their workers), and the repo's Docker Compose projects (compose down, volumes kept) unless another Claude session works in the same repo. Only for a session at a repo's top level (git rev-parse --show-toplevel); one started above the repos, such as ~/Dev, stops nothing | – | docker compose, git | |||
| review-walk | Skill plus mod: /review-walk takes the findings of the reviews already run in the conversation (/code-review, a repo's own review skill, CodeRabbit threads, MR comments), merges and ranks them, and asks fix / issue / skip one finding at a time; fixes wait until every finding is decided. The mod puts Finding N/M, a progress bar and the decisions so far over each question, and a band above the prompt between them. Decisions you authorised up front ("apply every Fix") are recorded through its ReviewWalkDecide tool instead of a question. The walk starts only after the skill runs, so a review on its own draws no band | /review-walk | A review run first: it walks findings, it never reviews. Any review skill or source works | |||
| tamagoxtix | Third line beside the monster, idle and while Claude works: usage-percent's memory bar. A fork of fabandrade88/tamagoxtix (MIT): a pixel monster in place of the spinner that acts out what Claude does, a band above the prompt between turns, cheer scenes while you type, twelve palettes, an optional powerline status line. The fork drops the band's usage column and repo column (repo-line shows repo and branch), the spinner's token line (usage-percent has the limits), pads the effects column so the text beside the monster stays put, adds /tamagoxtix animate off for still scenes, and puts the other mods' bands under the monster's caption instead of replacing them. With quiet-spinner the monster's line shows the plain word when quiet-spinner sits outer in the chain, else the whimsical one. The herdr half is herdr-tamagoxtix (sidebar faces, a usage popup, a tab-bar status area) | /tamagoxtix help, `… pet on\ | off hides the band, … palette <name>, … statusline on\ | off (writes statusLine into settings.json, backup kept), … theme on\ | off, … reroll` | Node.js 18+, a Nerd Font (or /tamagoxtix icons plain); git for the status line |
| task-meter | Band above the prompt with one row per running task: background shells, foreground shells after 5 s, subagents (their shells as └ child rows, tool count ⚒ N), workflows, monitors. Per row a ten-cell bar (filled where the output shows [N/M], a percentage or an nx task count, else one cell walking), the process tree's memory (yellow from 2 GB, red from 4 GB) and the running time, in aligned columns. Rows end with the task | – | Linux: ps, /proc/<pid>/fd, tail | |||
| repo-line | A line right above the prompt: the repository's name as a badge on the repository's own colour (a golden-angle hue per new repository, kept in the store), the branch (@abc1234 when detached) and (wt: name) in a linked worktree, so a prompt does not go to the wrong session. `/repo-line color <hue | #rrggbb> overrides, color reset` drops it | /repo-line | git | ||
| needs-you | Asks that wait on you stand out. Adds a system-prompt section: yes/no approvals and choices go through AskUserQuestion; anything else Claude waits on you for goes on its own line ⏸ Needs you: …. Those lines are drawn bold in the theme's warning colour (as plain text: links and code spans inside them are not formatted), pinned in a band above the prompt until your next message (or Clear), and in herdr shown as a ⏸ in the session's sidebar row; a ? there while an AskUserQuestion picker is open. See herdr for the sidebar row | – | herdr ≥ 0.9.5 for the sidebar icons, with { token = "$ask" } and { token = "$pick" } in ui.sidebar.agents.rows | |||
| ask-guard | When a reply asks a yes/no question in prose (shall I…?, want me to…?, ok to push…?, should I…? and similar), a Stop hook sends Claude back to ask it with AskUserQuestion, once per reply. Skips code blocks, > quotes, quoted text and ⏸ Needs you lines; a hook that fails lets the reply through | – | – | |||
| pii-guard | Asks before a tool call would send your personal data off the machine: WebFetch, WebSearch, every MCP tool (Claude in Chrome form fills included) and network Bash commands (curl, wget, urllib, requests, gh, git push …) whose input holds one of your identifiers, plain or URL-encoded, case-insensitive. Calls only to localhost pass. Born from a session that put the user's email into a third-party API's User-Agent because the API's policy asked for contact details. Does not see inside script files a command runs | – | pluginConfigs.pii-guard.options.identifiers in ~/.claude/settings.json: comma-separated emails and names (empty = off) |
The model sees exactly what it would without them: the mods change what is drawn, except reminder-log, which drops two kinds of injected reminders, redact, which hides secrets, mem-guard, which runs Node commands inside a systemd scope and refuses some with a mem-guard: … error, and stack-down, which stops the session's own servers and, when no other session is in the repo, its Compose stacks when the session ends.
Four mods call out on their own:
get_merge_request on the gitlab MCP server for the link and title. gh/glab commands cost nothing extra.glab for GitLab origin remotes: a 60 s timer checks the branch, and a fetch (glab mr view plus all pages of the MR's discussions) runs every minute for 15 min after a git push, every 5 min while the band shows something, every 15 min otherwise, and once 5 s after a thread is resolved.node on its usage script at session start and after each turn, and contacts no host. The mod's own README lists every call.ps and pwdx for nx serve processes, and docker inspect once per container a server runs in, to read its compose project directory. The pipeline (gh run list / glab ci get) is fetched when HEAD moves, 15 s after a git push, every minute while it runs and every 5 min otherwise.From the marketplace (gets updates; herdr-notify and herdr-link-toast are not in it):
claude plugin marketplace add schreibse/claude-code-mods
claude plugin install quiet-bash@schreibse-mods # per mod
Then turn on updates: /plugin → Marketplaces → schreibse-mods → Enable auto-update. See Updates.
From a clone, to adapt a mod or work on it. Claude Code loads every plugin folder under ~/.claude/skills/ at session start. Don't install the same mod from the marketplace too: the installed copy silently replaces the folder.
~/.claude/skills: clone straight into it: ``sh git clone https://github.com/schreibse/claude-code-mods ~/.claude/skills ``sh git clone https://github.com/schreibse/claude-code-mods ~/src/claude-code-mods ln -s ~/src/claude-code-mods/quiet-bash ~/.claude/skills/quiet-bash # per mod ``New sessions pick them up; a running one needs /exit and claude --continue.
Leave a mod out: claude plugin uninstall <mod>@schreibse-mods, or delete or unlink its folder. Try one for a single session: claude --plugin-dir ~/src/claude-code-mods/<mod>.
Where they run. Built and used only in the terminal CLI on Fedora (Linux, systemd, cgroup v2). The engine also loads user-scope mods in the local session the desktop app starts for its Code tab, and draws them there (desktop surface); untested here. See Setting up for what each mod needs.
This repo is the skills folder itself, so .gitignore ignores everything and re-includes each mod: a new mod needs a !/<name>/ line or git won't see it. .claude-plugin/types/ is generated by the engine and stays untracked.
Each mod has its own version (plugin.json) and a CHANGELOG.md in its folder; each release is a git tag <mod>--v<version>.
Plugin updated: <mod> · Run /reload-plugins to apply. Without it nothing tells you; check by hand: ``sh claude plugin marketplace update schreibse-mods claude plugin update quiet-bash@schreibse-mods # per mod; "already at the latest version" if none ``CHANGELOG.md. Read every version you skipped: a major version means you have to act (a new hook in settings.json, a new dependency, a removed command).git -C ~/.claude/skills pull --ff-only, then read the changelogs of the mods whose version moved (git -C ~/.claude/skills diff ORIG_HEAD -- '*/.claude-plugin/plugin.json').betterleaks scans every prompt and tool result before it reaches the model. Each value it flags becomes ‹secret:xxxxxxxx› and stays hidden wherever it appears later, even where the scanner would not recognise it again.
| The model's call | What happens |
|---|---|
| Write, Edit, NotebookEdit with a token | the real value is written to the file |
| Write that would drop a secret the file holds | refused: use Edit |
| Agent, SendMessage, TodoWrite with a token | passed on as the token |
| Any other tool with a token (Bash, WebFetch, MCP …) | refused, so the value never leaves |
| A token the mod no longer knows (after a restart) | refused, never restored wrongly |
Cut-short output. Before Bash or any tool with a file_path/path (Read, Grep, Edit …) runs, every file the call names (Bash: the first 10 words that could be paths, files up to 1 MB) is scanned whole, so cut -c1-60 .env, cut -d= -f2 or a Read of a few lines from a PEM key still come back as tokens. Multi-line secrets are hidden line by line. Bash words resolve against the directory each segment runs in (cd sub && cut -c1-40 .env), and ~/, $HOME/ and ${HOME}/ expand to the home directory.
Rules. betterleaks' defaults plus redact/betterleaks.toml: Sentry DSN keys, and client secrets too short for the generic rules. A client secret containing dev, local, test, example, changeme or placeholder stays visible, so local dev clients keep working in commands.
Not covered:
git show HEAD:.env | cut …, printenv | cut …); the transcript file's structured tool records, which keep real values (the model does not read them).cut -c1-40 *.env), quoted paths with spaces and a cd inside a subshell ((cd sub && cut -c1-40 .env)).client-secret rule needs some entropy (≥ 3.0), so short, repetitive client secrets stay visible.base64, rev, xxd) or sent (curl -T file). redact keeps secrets out of the model's context by accident; it is not a sandbox against a model trying to get them.‹secret:…› token is refused like any other tool call carrying one.The vault lives in session memory: /exit forgets it.
The status line shows redacted N once a value is hidden: N counts vault entries, so a PEM key counts once per line. A toast per call names the rules that hid new values. Without betterleaks the status line says off (no betterleaks) and nothing is hidden. A betterleaks run that fails leaves that call unredacted (values already in the vault stay hidden): one toast per failure streak, the status says off (betterleaks), and the next call scans again.
Every Bash command that names a Node tool (node, npx, pnpm, npm, npm exec, yarn, nx, jest, vitest, playwright, tsc, ngc) runs as systemd-run --user --scope --slice=claude-cmd.slice -p MemoryMax=30% -p MemorySwapMax=4% -- bash -c '…', so an overrun dies with exit 137 instead of taking the desktop down. Leading cd … && stay outside the wrapper, so the shell's directory still moves.
The rules read what each part of a command runs (after &&, |, ;, &, $( ), inside bash -c '…', following cd), never words it only mentions, so a commit message saying pkill -f passes. Not looked into: xargs, make, eval, scripts.
At once, counted per scope or service anywhere in claude.slice from one ps scan (skipped when ps fails):
node script that imports Playwright, tsc, ngc, an nx task), a running dev server included; the nx daemon doesn't count;nx serve, nx run x:serve, a serve* script): the API and one app.A command counts as heavy for these checks when it runs one of those tools, docker compose up, or a test, build, lint, typecheck, e2e or serve* script.
check-runner subagents (an agent type of the owner's) only run checks: git commands that change the tree or history, sed -i, --write/--fix, starting or stopping servers or processes, and writes outside /tmp are refused with "Report the failure instead of fixing it".
Assumes this setup; the messages name it:
claude-cmd.slice user unit. Without it systemd makes the slice with no limit of its own: each command is still capped at 30 % of RAM, but the headroom check has nothing to measure and stays off: ``ini # ~/.config/systemd/user/claude-cmd.slice [Slice] MemoryMax=30% MemorySwapMax=4% ` A full slice can livelock without ever reaching the OOM killer, so let systemd-oomd kill a scope in it under sustained pressure: systemctl --user set-property claude-cmd.slice ManagedOOMMemoryPressure=kill ManagedOOMMemoryPressureLimit=50%. systemd turns a percentage into bytes of the machine's RAM (on 27 GiB: 8.2G and 1.1G), so the same unit fits any machine. Check what a machine gets: systemd-run --user --scope -q -p MemoryMax=30% -- sh -c 'cat /sys/fs/cgroup$(cut -d: -f3 /proc/self/cgroup)/memory.max'`fuser -k 4700/tcp.:lite twin (lint:affected:lite, typecheck:lite, test:affected:lite) and a slow ci:local script.git@work:org/repo) reads as ci no login (work) though you are logged in.Under herdr (here inside Ghostty), quiet-bash's thumbnails draw only their alt text, and links in mr-banner, coderabbit-band and Claude's own output aren't clickable.
Cause: Claude Code turns on kitty graphics only for terminals whose XTVERSION answer is kitty (≥ 0.28) or starts with ghostty, and hyperlinks only for terminals it recognises. herdr forwards both, but answers with its own name, so Claude Code turns both off.
Fix: force both on, inside herdr only, before Claude Code starts (it reads them at startup):
# ~/.bashrc.d/herdr-terminal.sh
if [ -n "$HERDR_ENV" ]; then
export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
export FORCE_HYPERLINK=1
fi
The herdr client forks its server into the client's own cgroup, so a server started inside a Ghostty window dies with that window and takes every pane with it. A wrapper in ~/.bashrc.d starts the first server in its own scope under app.slice instead; every other call, herdr plugin … included, goes straight through:
# ~/.bashrc.d/herdr-scope.sh
herdr() {
if [ $# -eq 0 ] && [ -z "$HERDR_ENV" ] && ! command herdr status server 2>/dev/null | grep -q '^status: running'; then
systemd-run --user --scope -q --slice=app.slice --unit="herdr-$(date +%s)" "$HOME/.local/bin/herdr"
else
command herdr "$@"
fi
}
Also turn on herdr's kitty graphics passthrough (off by default) in ~/.config/herdr/config.toml:
[experimental]
kitty_graphics = true
Then herdr server reload-config, open a new herdr pane (old panes keep the old environment) and start Claude Code there. Check it: /thumb /path/to/some.png should draw the picture.
herdr opens a ctrl+clicked link in the background with no feedback, and ignores file:// links altogether. herdr-link-toast opens http(s) links with xdg-open and shows a toast. It also opens the path in quiet-bash's thumbnail captions, which link to http://localhost/open-file/<path> because file:// isn't clickable in herdr. Such a link opens only when the path ends in .png; any other gets a "Could not open link" toast. Needs python3 ≥ 3.9. Install:
herdr plugin link ~/.claude/skills/herdr-link-toast
needs-you reports two tokens on its own pane (herdr pane report-metadata): $ask (⏸) while a ⏸ Needs you line is open, $pick (?) while an AskUserQuestion picker is open. herdr draws them only where the agent row names them, in ~/.config/herdr/config.toml:
[ui.sidebar.agents]
rows = [["state_icon", { token = "$ask", fg = "#f5a623", bold = true }, { token = "$pick", fg = "#f5a623", bold = true }, "machine", "workspace", "tab"], ["agent"]]
fg takes hex only. The row layout is the client's: after editing, choose reload config in herdr's menu (herdr server reload-config does not reload it).
The herdr half of tamagoxtix, unchanged from upstream: the monster's face in the sidebar, a usage popup (herdr plugin action invoke tamagoxtix.stats) and, on request, a status area right of the tabs and herdr colors f
hooks/register.ts 103 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { checkRunnerRefusal, crowdedRefusal, drivesPlaywright, escapeRefusal, invocations, isHeavy, isServe, nodeScripts, parsePressure, refusal, runningRefusal, scoped, withServeElsewhere } from './rules'
4import type { Invocation, Pressure, ScriptsByDir } from './rules'
5
6const sliceDirs = new Map<string, string>()
7let home = ''
8
9const CMD_SLICE = 'claude-cmd.slice'
10const SESSIONS_SLICE = 'claude.slice'
11
12// Not cached while the slice is inactive, so it is looked up again on the next call.
13async function resolveSlice($: EngineInterface, name: string): Promise<string> {
14 if (!sliceDirs.has(name)) {
15 const group = await $.process.run(['systemctl', '--user', 'show', name, '-p', 'ControlGroup', '--value']).catch(() => null)
16 const path = group?.exitCode === 0 ? group.stdout.trim() : ''
17 if (path !== '') {
18 sliceDirs.set(name, `/sys/fs/cgroup${path}`)
19 }
20 }
21 return sliceDirs.get(name) ?? ''
22}
23
24// The sessions' slice is measured against MemoryHigh, where throttling starts; the command slice against its MemoryMax.
25async function readPressure($: EngineInterface, name: string): Promise<Pressure | null> {
26 const slice = await resolveSlice($, name)
27 if (slice === '') {
28 return null
29 }
30 const read = (file: string) => $.fs.read(`${slice}/${file}`)
31 const limitFile = name === SESSIONS_SLICE ? 'memory.high' : 'memory.max'
32 const [current, max, pressure] = await Promise.all([read('memory.current'), read(limitFile), read('memory.pressure')]).catch(() => ['', '', ''])
33 return parsePressure(current ?? '', max ?? '', pressure ?? '')
34}
35
36async function crowdedSlice($: EngineInterface): Promise<string | null> {
37 for (const name of [CMD_SLICE, SESSIONS_SLICE]) {
38 const pressure = await readPressure($, name)
39 const crowded = pressure === null ? null : crowdedRefusal(pressure, name)
40 if (crowded !== null) {
41 return crowded
42 }
43 }
44 return null
45}
46
47async function scriptsIn($: EngineInterface, dir: string): Promise<Record<string, string>> {
48 const manifest = await $.fs.read(`${dir}/package.json`).catch(() => '{}')
49 try {
50 return (JSON.parse(manifest) as { scripts?: Record<string, string> }).scripts ?? {}
51 } catch {
52 return {}
53 }
54}
55
56async function scriptsOf($: EngineInterface, calls: readonly Invocation[]): Promise<ScriptsByDir> {
57 const dirs = [...new Set(calls.map(call => call.dir))]
58 const scripts = await Promise.all(dirs.map(dir => scriptsIn($, dir)))
59 return Object.fromEntries(dirs.map((dir, i) => [dir, scripts[i] ?? {}]))
60}
61
62async function runsPlaywrightScript($: EngineInterface, calls: readonly Invocation[]): Promise<boolean> {
63 const sources = await Promise.all(nodeScripts(calls, home).map(file => $.fs.read(file).catch(() => '')))
64 return sources.some(source => drivesPlaywright(source ?? ''))
65}
66
67export const register: Register = on => {
68 on('session.start', async ($, e, next) => {
69 await resolveSlice($, CMD_SLICE)
70 home = (await $.env.get('HOME')) ?? ''
71 return next(e)
72 })
73
74 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
75 if (e.agentId !== undefined) {
76 const agents = await $.agent.list().catch(() => [])
77 if (agents.find(agent => agent.id === e.agentId)?.type === 'check-runner') {
78 const writeRefusal = checkRunnerRefusal(e.command)
79 if (writeRefusal !== null) {
80 return { deny: `mem-guard: ${writeRefusal}` }
81 }
82 }
83 }
84 const calls = invocations(e.command, { cwd: await $.session.cwd(), home })
85 const refused = escapeRefusal(e.command) ?? refusal(calls, await scriptsOf($, calls))
86 if (refused !== null) {
87 return { deny: `mem-guard: ${refused}` }
88 }
89 if (isHeavy(calls) || isServe(calls) || (await runsPlaywrightScript($, calls))) {
90 const crowded = await crowdedSlice($)
91 if (crowded !== null) {
92 return { deny: `mem-guard: ${withServeElsewhere(calls, crowded)}` }
93 }
94 const ps = await $.process.run(['ps', '-eo', 'cgroup:250=,args=', '--cols', '600']).catch(() => null)
95 const busyRefusal = ps?.exitCode === 0 ? runningRefusal(calls, ps.stdout) : null
96 if (busyRefusal !== null) {
97 return { deny: `mem-guard: ${withServeElsewhere(calls, busyRefusal)}` }
98 }
99 }
100 return next({ ...e, command: scoped(e.command) })
101 })
102}
103hooks/rules.ts 342 lines1export type Pressure = { usedBytes: number; maxBytes: number; psiAvg10: number }
2export type Shell = { cwd: string; home: string }
3export type ScriptsByDir = Record<string, Record<string, string>>
4export type Invocation = { line: string; tool: string; call: string; script: string | null; dir: string }
5
6const GIB = 1024 ** 3
7const FULL_SHARE = 0.75
8// Every session shares claude.slice; past its MemoryHigh the kernel throttles them all.
9const SESSIONS_FULL_SHARE = 0.85
10const PSI_LIMIT = 20
11
12const HEAVY_TOOLS = ['nx', 'jest', 'vitest', 'playwright', 'tsc', 'ngc']
13const NODE_TOOLS = ['node', 'npx', 'pnpm', 'npm', 'yarn', ...HEAVY_TOOLS]
14const PREFIX = /^(?:(?:sudo|time|nice|env|exec|command|then|do|else|if|while|until|\{|!)\s+|timeout\s+\S+\s+|\w+=\S*\s+)*/
15const PNPM_FLAGS = String.raw`(?:(?:--filter|-F|-C|--dir)\s+\S+\s+|-[\w-]+(?:=\S+)?\s+)*`
16const RUNNER = new RegExp(String.raw`^(?:npx\s+(?:-\S+\s+)*|npm\s+(?:exec|x)\s+(?:-\S+\s+)*|pnpm\s+${PNPM_FLAGS}(?:exec\s+|dlx\s+|run\s+)?|yarn\s+(?:run\s+)?|node\s+(?=\S*node_modules\/\.bin\/)|)(?:\S*node_modules\/\.bin\/)?`)
17const SCRIPT = new RegExp(String.raw`^(?:pnpm\s+${PNPM_FLAGS}(?:run\s+)?|npm\s+run\s+|yarn\s+(?:run\s+)?)([\w:-]+)`)
18const SHELL_C = /^(?:ba)?sh\s+(?:-\w+\s+)*-c\s+(?:'([^']*)'|"((?:[^"\\]|\\.)*)")/
19const CD = /^cd(?:\s+(\S+))?$/
20const NX_LIGHT = /^nx\s+(show|graph|reset|daemon|report|list|--version)\b/
21const NX_TEST = /^nx\s+(?:test\b|run\s+\S+:test(?::\S+)?(?=\s|$))|\s(?:-t|--targets?)[= ]\s*(?:\S*,)?test(?=[,\s]|$)/
22const PARALLEL_ONE = /--parallel[= ]1([^0-9]|$)/
23const WORKER_CAP = /\s(?:--runInBand|-i)(?=\s|$)|\s(?:--maxWorkers|--max-workers|-w)(?:=|\s+)(?![^\s%]*%)\S/
24const JEST_NO_RUN = /\s(?:--listTests|--showConfig|--clearCache|--version|-v|--help|-h)(?=\s|$)/
25const KILL_BY_NAME = /\s(?:-[a-zA-Z]*f[a-zA-Z]*|--full)(?=\s|$)/
26const KILL_VALUE_FLAG = /^(?:-[GgPstuU]|--(?:signal|euid|uid|group|pgroup|parent|session|terminal|ns|nslist))$/
27const WORD = /(?:'[^']*'|"[^"]*"|[^\s'"])+/g
28
29// Splits on control operators and command substitutions outside quotes; a heredoc body is no command.
30export function segments(command: string): string[] {
31 const parts: string[] = []
32 const heredocs: string[] = []
33 let part = ''
34 let quote: '' | "'" | '"' = ''
35 const opened: Array<'' | '"'> = []
36 const cut = () => {
37 parts.push(part.trim())
38 part = ''
39 }
40 for (let i = 0; i < command.length; i++) {
41 const c = command[i] ?? ''
42 const two = command.slice(i, i + 2)
43 if (quote === "'") {
44 quote = c === "'" ? '' : quote
45 part += c
46 } else if (c === '\\') {
47 part += two
48 i++
49 } else if (two === '$(') {
50 cut()
51 opened.push(quote)
52 quote = ''
53 i++
54 } else if (c === '`') {
55 cut()
56 } else if (quote === '"') {
57 quote = c === '"' ? '' : quote
58 part += c
59 } else if (c === "'" || c === '"') {
60 quote = c
61 part += c
62 } else if (two === '<<') {
63 const tag = /^<<-?\s*(['"]?)(\w+)\1/.exec(command.slice(i))?.[2]
64 if (tag !== undefined) {
65 heredocs.push(tag)
66 }
67 part += two
68 i++
69 } else if (c === '\n' && heredocs.length > 0) {
70 cut()
71 for (const tag of heredocs.splice(0)) {
72 const end = new RegExp(String.raw`\n\t*${tag}(?=\n|$)`).exec(command.slice(i))
73 i = end === null ? command.length : i + end.index + end[0].length - 1
74 }
75 } else if (two === '&&' || two === '||') {
76 cut()
77 i++
78 } else if (c === '(') {
79 cut()
80 opened.push('')
81 } else if (c === ')') {
82 cut()
83 quote = opened.pop() ?? ''
84 } else if (';|&\n'.includes(c)) {
85 cut()
86 } else {
87 part += c
88 }
89 }
90 cut()
91 return parts.filter(p => p.length > 0)
92}
93
94function resolvePath(dir: string, home: string, target = '~'): string {
95 const raw = target.replace(/^(['"])(.*)\1$/, '$2')
96 if (raw === '-') {
97 return dir
98 }
99 const path = raw.startsWith('~') ? home + raw.slice(1) : raw.startsWith('/') ? raw : `${dir}/${raw}`
100 const parts: string[] = []
101 for (const part of path.split('/')) {
102 if (part === '..') {
103 parts.pop()
104 } else if (part !== '' && part !== '.') {
105 parts.push(part)
106 }
107 }
108 return `/${parts.join('/')}`
109}
110
111// `FOO=1 timeout 60 pnpm exec jest x` → line `pnpm exec jest x`, tool `jest`, call `jest x`; a `bash -c '…'` is opened up.
112export function invocations(command: string, shell: Shell): Invocation[] {
113 let dir = shell.cwd
114 return segments(command).flatMap(part => {
115 const line = part.replace(PREFIX, '').replace(/[\s}]+$/, '')
116 const cd = CD.exec(line)
117 if (cd !== null) {
118 dir = resolvePath(dir, shell.home, cd[1])
119 }
120 const inner = SHELL_C.exec(line)
121 const nested = inner === null ? [] : invocations(inner[1] ?? (inner[2] ?? '').replace(/\\(.)/g, '$1'), { ...shell, cwd: dir })
122 const call = line.replace(RUNNER, '')
123 return [{ line, tool: call.split(/\s/)[0] ?? '', call, script: SCRIPT.exec(line)?.[1] ?? null, dir }, ...nested]
124 })
125}
126
127function liteSibling(script: string, scripts: Record<string, string>): string | null {
128 if (script.endsWith(':lite')) {
129 return null
130 }
131 return scripts[`${script}:lite`] === undefined ? null : script
132}
133
134function words(line: string): string[] {
135 return line.match(WORD) ?? []
136}
137
138// The first operand that is neither a flag nor a flag's value.
139function killPattern(line: string): string {
140 const args = words(line).slice(1)
141 for (let i = 0; i < args.length; i++) {
142 const arg = args[i] ?? ''
143 if (KILL_VALUE_FLAG.test(arg)) {
144 i++
145 } else if (!arg.startsWith('-')) {
146 return arg
147 }
148 }
149 return ''
150}
151
152function invocationRefusal({ line, tool, call, script }: Invocation, scripts: Record<string, string>): string | null {
153 if (tool === 'nx' && /^nx\s+(affected|run-many)\b/.test(call) && !PARALLEL_ONE.test(call)) {
154 return "nx affected/run-many must run with --parallel=1. Prefer the repo's :lite script (pnpm run lint:affected:lite, typecheck:lite, test:affected:lite)."
155 }
156 const base = script === null ? null : liteSibling(script, scripts)
157 if (base !== null) {
158 return `use 'pnpm run ${base}:lite' instead of '${script}'.`
159 }
160 if (script === 'ci:local') {
161 return 'ci:local runs everything in sequence (~45 min here). Push and let the pipeline be the gate.'
162 }
163 if (/^(?:\S*\/)?p(kill|grep)\s/.test(line) && KILL_BY_NAME.test(line) && !killPattern(line).includes('[')) {
164 return "pkill -f / pgrep -f with a plain pattern matches its own wrapper and kills it (exit 143). Stop it by port (fuser -k 4700/tcp), by saved PID, or bracket the pattern: pkill -f '[n]x serve'."
165 }
166 const isJest = (tool === 'jest' && !JEST_NO_RUN.test(call)) || (tool === 'nx' && NX_TEST.test(call))
167 if (isJest && !WORKER_CAP.test(call)) {
168 return 'jest runs need --maxWorkers=2 (or --runInBand): its pool otherwise sizes itself off the CPU count, per task.'
169 }
170 return null
171}
172
173export function refusal(calls: readonly Invocation[], scripts: ScriptsByDir): string | null {
174 for (const call of calls) {
175 const refused = invocationRefusal(call, scripts[call.dir] ?? {})
176 if (refused !== null) {
177 return refused
178 }
179 }
180 return null
181}
182
183export function isHeavy(calls: readonly Invocation[]): boolean {
184 return calls.some(
185 ({ line, tool, call, script }) =>
186 (HEAVY_TOOLS.includes(tool) && !NX_LIGHT.test(call)) ||
187 (script !== null && /^(test|build|lint|typecheck|e2e|serve)/.test(script)) ||
188 /^docker(-compose|\s+compose)\b.*\sup\b/.test(line),
189 )
190}
191
192const SCRIPT_RUNNERS = ['node', 'tsx', 'ts-node']
193const PLAYWRIGHT_IMPORT = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)['"](?:playwright(?:-core)?|@playwright\/test)(?:\/[^'"]*)?['"]/
194
195/** Script files run by `node`, `tsx` or `ts-node`; the caller reads them to see whether they drive a browser. */
196export function nodeScripts(calls: readonly Invocation[], home: string): string[] {
197 return calls.flatMap(({ call, dir }) => {
198 const [program = '', ...args] = words(call)
199 const file = SCRIPT_RUNNERS.includes(program.replace(/^.*\//, '')) ? args.find(arg => !arg.startsWith('-')) : undefined
200 return file !== undefined && /\.[cm]?[jt]s['"]?$/.test(file) ? [resolvePath(dir, home, file)] : []
201 })
202}
203
204export function drivesPlaywright(source: string): boolean {
205 return PLAYWRIGHT_IMPORT.test(source)
206}
207
208export function crowdedRefusal(pressure: Pressure, slice = 'claude-cmd.slice'): string | null {
209 const used = pressure.usedBytes / GIB
210 const max = pressure.maxBytes / GIB
211 const share = slice === 'claude-cmd.slice' ? FULL_SHARE : SESSIONS_FULL_SHARE
212 if (pressure.usedBytes <= pressure.maxBytes * share && pressure.psiAvg10 <= PSI_LIMIT) {
213 return null
214 }
215 return `${slice} is at ${used.toFixed(1)}/${Number(max.toFixed(1))}G, pressure ${pressure.psiAvg10.toFixed(0)}%. Wait for a running build or test to finish, stop a dev server you are not using, or push and let CI run it.`
216}
217
218const BUDGET_SLICE = /\s--slice[= ]claude(?:-cmd)?\.slice(?=\s|$)/
219const NODE_TOOL_WORD = new RegExp(String.raw`(?:^|[\s'"/])(?:${NODE_TOOLS.join('|')})(?=[\s'"]|$)`)
220
221/** A unit started without a claude slice lands in app.slice, outside the budget every session shares. */
222export function escapeRefusal(command: string): string | null {
223 const escapes = segments(command).some(part => {
224 const line = part.replace(PREFIX, '')
225 return /^systemd-run\b/.test(line) && !BUDGET_SLICE.test(line) && NODE_TOOL_WORD.test(line.replace(/^systemd-run\b/, ''))
226 })
227 return escapes
228 ? 'systemd-run without --slice=claude.slice puts a Node tool outside the memory budget every session shares. Run it plainly (mem-guard scopes it), or give a long-lived server --slice=claude.slice.'
229 : null
230}
231
232function runsNode({ line, tool }: Invocation): boolean {
233 const program = (line.split(/\s/)[0] ?? '').replace(/^.*\//, '')
234 return NODE_TOOLS.includes(program) || NODE_TOOLS.includes(tool)
235}
236
237// Leading `cd`s stay outside the wrapper so the shell's working directory still moves.
238export function scoped(command: string): string {
239 const cds = /^(?:\s*cd(?:\s+(?:'[^']*'|"[^"]*"|[^\s;&|'"]+))?\s*(?:&&|;))*/.exec(command)?.[0] ?? ''
240 const rest = command.slice(cds.length).trimStart()
241 if (/^systemd-run/.test(rest) || !invocations(rest, { cwd: '/', home: '' }).some(runsNode)) {
242 return command
243 }
244 const quoted = `'${rest.replace(/'/g, `'\\''`)}'`
245 const wrapped = `systemd-run --user --scope -q --slice=claude-cmd.slice --expand-environment=no -p MemoryMax=30% -p MemorySwapMax=4% -- bash -c ${quoted}`
246 return cds === '' ? wrapped : `${cds.trim()} ${wrapped}`
247}
248
249export function parsePressure(current: string, max: string, pressure: string): Pressure | null {
250 const usedBytes = Number(current.trim())
251 const maxBytes = Number(max.trim())
252 const psiAvg10 = Number(/^some avg10=([\d.]+)/m.exec(pressure)?.[1] ?? NaN)
253 return [usedBytes, maxBytes, psiAvg10].every(Number.isFinite) ? { usedBytes, maxBytes, psiAvg10 } : null
254}
255
256const MAX_HEAVY_AT_ONCE = 2
257// A test runner, a build, an nx task or a browser Playwright launched; the nx daemon stays out, and a dev server is counted on its own.
258const HEAVY_PROCESS =
259 /\/jest(?:-cli)?\/bin\/|jest-worker\/build\/workers|\/vitest\/|playwright\/(?:cli\.js|lib\/common\/process)|\/ms-playwright\/|playwright_\w+dev_profile-|\/typescript\/(?:bin|lib)\/tsc\b|\/compiler-cli\/bundles\/src\/bin\/ngc|nx\/dist\/bin\/run-executor\.js/
260const SERVE = /\bnx(?:\.js)?\s+serve\b|:serve(?::\S+)?(?:\s|$)/
261
262/** Each scope or service in claude.slice, claude-cmd.slice included, with its processes' args, from `ps -eo cgroup=,args=`. */
263function scopesOf(ps: string): string[][] {
264 const scopes = new Map<string, string[]>()
265 for (const row of ps.split('\n')) {
266 const match = /\/claude\.slice\/(?:claude-cmd\.slice\/)?([^\s/]+\.(?:scope|service))\S*\s+(.*)$/.exec(row)
267 if (match) {
268 scopes.set(match[1], [...(scopes.get(match[1]) ?? []), match[2]])
269 }
270 }
271 return [...scopes.values()]
272}
273
274/** Heavy commands running in claude.slice, one per scope; a dev server is not one of them. */
275export function heavyScopes(ps: string): number {
276 return scopesOf(ps).filter(args => !args.some(arg => SERVE.test(arg)) && args.some(arg => HEAVY_PROCESS.test(arg))).length
277}
278
279/** Dev servers running in claude.slice, one per scope or service. */
280export function serveScopes(ps: string): number {
281 return scopesOf(ps).filter(args => args.some(arg => SERVE.test(arg))).length
282}
283
284export function isServe(calls: readonly Invocation[]): boolean {
285 return calls.some(({ call, script }) => SERVE.test(call) || (script !== null && /^serve\b/.test(script)))
286}
287
288// The API and one app.
289const MAX_SERVES_AT_ONCE = 2
290
291export function serveRefusal(running: number): string | null {
292 return running < MAX_SERVES_AT_ONCE
293 ? null
294 : `${running} dev servers are already running (at most ${MAX_SERVES_AT_ONCE}: the API and one app). Stop one by its port first (fuser -k 4700/tcp).`
295}
296
297export function concurrencyRefusal(running: number): string | null {
298 return running < MAX_HEAVY_AT_ONCE
299 ? null
300 : `${running} heavy commands are already running, dev servers included (at most ${MAX_HEAVY_AT_ONCE} at once). Wait for one to finish or stop a dev server.`
301}
302
303/** A refused dev server can still run in the user's own terminal, outside the shared budget, if they agree. */
304export function withServeElsewhere(calls: readonly Invocation[], refused: string): string {
305 return isServe(calls) ? `${refused} Or ask the user to serve the app in their own terminal (app.slice, outside this budget).` : refused
306}
307
308/** A dev server counts as a heavy command, and a dev server start also against the dev servers. */
309export function runningRefusal(calls: readonly Invocation[], ps: string): string | null {
310 const serves = serveScopes(ps)
311 return (isServe(calls) ? serveRefusal(serves) : null) ?? concurrencyRefusal(heavyScopes(ps) + serves)
312}
313
314const RUNNER_WRITES: ReadonlyArray<readonly [RegExp, string]> = [
315 [/(?:^|[\s;&|(])git\s+(?:-[Cc]\s+\S+\s+|-\S+\s+)*(?:checkout|restore|reset|stash|clean|commit|push|rebase|revert|apply|cherry-pick|merge|switch|rm|mv|add)\b/, 'changes the working tree or git history'],
316 [/(?:^|[\s;&|(])sed\s+(?:\S+\s+)*?(?:-[a-zA-Z]*i|--in-place)\b/, 'edits a file in place'],
317 [/\s--(?:write|fix)(?:[=\s]|$)/, 'rewrites files'],
318 [/(?:^|[\s;&|(])(?:systemctl\s+(?:--user\s+)?(?:start|stop|restart|kill|reset-failed)|systemd-run\s.*--unit|docker(?:\s+compose)?\s+(?:start|stop|restart|kill|rm|down|up)|pkill|killall|kill|fuser\s+-k)\b/, 'starts or stops a server or process'],
319 [/(?:^|[^<>&\d])>>?(?!>)\s*(?!\/tmp\/|\/dev\/)[^\s&]/, 'writes a file outside /tmp'],
320]
321const FILE_WRITERS = ['tee', 'rm', 'touch', 'cp', 'mv']
322
323/** Whether a tee, rm, touch, cp or mv names a path outside /tmp and /dev; a cp's source is only read. */
324function writesOutsideTmp(command: string): boolean {
325 return segments(command).some(part => {
326 const [path = '', ...args] = words(part.replace(PREFIX, ''))
327 const program = path.replace(/^.*\//, '')
328 if (!FILE_WRITERS.includes(program)) {
329 return false
330 }
331 const operands = args.filter((arg, i) => !/^-|^\d*[<>]/.test(arg) && !/^\d*[<>]+&?$/.test(args[i - 1] ?? ''))
332 return operands.slice(program === 'cp' ? 1 : 0).some(arg => !/^['"]?\/(?:tmp|dev)\//.test(arg))
333 })
334}
335
336/** A check-runner runs checks and reports; anything that changes files, git or servers is refused. */
337export function checkRunnerRefusal(command: string): string | null {
338 const reason = RUNNER_WRITES.find(([pattern]) => pattern.test(command))?.[1] ?? (writesOutsideTmp(command) ? 'writes a file outside /tmp' : null)
339 return reason === null ? null : `a check-runner only runs checks: this command ${reason}. Report the failure instead of fixing it.`
340}
341
342