CLI resource admission policies
/resources works in standard chat and emulated passthrough. It shows a readable policy summary with configuration paths and the source of each setting; JSON is an advanced format, not required for routine configuration. Settings are read on each launch/watch poll. Permissions and subprocess memory limits remain independent.
Admission is opt-in
With the built-in defaults (defaultClass: low, unknownShellClass: low, the rule list limited to cheap diagnostics), no command is classified high. Nothing is serialized through the exclusive activity lane, no RAM/GPU capacity probe runs, and no launch is ever blocked. This is deliberate: a command like ssh host 'mvn test' consumes resources on a remote machine, and no policy can see that cost — so admission only engages where it can be measured: commands you explicitly configure.
To enable serialization for chosen work:
/resources default high— every unmatched launch takes the lane again;/resources unknown-shell high— unparsed syntax is treated as heavy;/resources rule builds high mvn— only Maven (optionally with argument prefixes) is high; everything else stays low.
Commands running on remote machines (ssh, remote shells) are never classified by this host; configure rules on the machine that actually runs them.
The lane is the only queue
Sessions that share a machine must not serialize heavy work with a lock file and a waiter script of their own. Nothing can list such a queue, nobody is woken from it, and two waiters that each wait for the other to go quiet hold it until a timeout. The shell mandate therefore blocks, in bash and process launch calls (and in the provider hook for native shell tools):
- a lock utility run directly:
flock,lockfile,lockfile-create,dotlockfile,lckdo,setlock,with-lock-ex, also behindtimeout/nohup/envand insidebash -c '...'; - a script outside the project that takes such a lock, run as
bash FILE,source FILE, or by path. The refusal names the file and the line.
The refusal points at the lane: launch the work with process action=launch. If the lane is held, the launch is refused before anything runs, the session joins the queue in arrival order and is woken when its turn comes; edit_coordinator action=query_activities shows the holder and the queue. That only serializes commands the policy classes high, so a project that needs one lane must say which commands take it (/resources rule ...).
To hold a lane across several steps (build, then tests), take a named coordinator lock: edit_coordinator action=acquire_lock lock_name=<name>, and release_lock when done. A script takes the same lock for its own run with kompile edit-coordinator lock-hold --name <name> --pid $$ (held until the script exits), or wraps one command in kompile edit-coordinator lock-run --name <name> -- <command>. A script started by the holder runs under the holder's lock. See "Named locks" in docs/mcp/README.md.
Not blocked: scripts inside the project (the nearest directory above the working directory that holds .git or kompile.project.json) and scripts kept in any other repository or kompile project below the home directory (a session in one checkout runs the tracked wrappers of its sibling by absolute path), which may guard themselves with a lock; commands that only name a lock utility (command -v flock); and scripts the mandate cannot read (a path built from a variable, a missing file, a file over 512 KB). Only the script named in the call is read, not the scripts it runs in turn.
The rule is on by default. Turn it off with "laneEnforcerEnabled": false in ~/.kompile/harness-config.json, or for one process with KOMPILE_LANE_ENFORCER=off.
Configuration sources
Precedence, lowest to highest:
- Built-in defaults.
- User defaults:
~/.kompile/resource-policy.json. - Project overrides:
<project>/.kompile/resource-policy.json.
Fields inherit independently. An explicit rules array replaces the inherited ordered list; this preserves existing full-policy files and rule removal semantics. Editing a scalar writes only that override, not a snapshot of all defaults. Editing rules saves the effective rule list to the selected scope. /resources inherit rules returns to the inherited list. Existing saved policies are not automatically rewritten. Project discovery resolves the registered project root, falling back to the working directory when no registered project exists.
Interactive wizard
Run /resources setup to configure rules, defaults, or inheritance through numbered choices. /resources add jumps straight to adding a rule. Both standard chat and emulated passthrough reuse their existing input reader—no JSON required.
The wizard asks for project/user scope, rule name, executable, optional argument prefix, and resource class. High is the safe default. It shows a summary and requires explicit confirmation before saving (default: no). cancel, Ctrl+C, or EOF discards the operation. Invalid menu choices are re-prompted. /resources global add fixes the scope to user settings.
Commands
/resources show(or bare/resources): readable effective policy and sources./resources sources: configuration paths, precedence and setting origins./resources rules: list the ordered rules (kept out of the brief default summary)./resources check <shell command>: explain classification without executing./resources rule <id> low|high <executable> [argument prefix...]: prepend rules for bothbashandprocess launch. Tokens match literally, not as substrings. Omitting the prefix matches every invocation of that executable./resources global <command>: operate on user defaults rather than project settings. Project overrides still win on actual launches./resources inherit default|unknown-shell|rules: remove the selected scope's override./resources json: export the full effective JSON (advanced)./resources add: interactive add-rule wizard. Plain-text arguments also work likerule; legacy JSON input remains accepted for compatibility./resources remove <id>: remove a rule./resources default low|high: unmatched launch class./resources unknown-shell low|high: unsupported shell syntax class./resources set <policy JSON>: validate and atomically replace the policy./resources preview <tool> <arguments JSON>: explain classification without execution./resources help: syntax and fields.
low does not enter the exclusive high-resource lane or its RAM/GPU capacity probe. high uses existing lane/capacity checks and watches. Async crawls retain their inner capacity admission. With the defaults, everything — including builds, tests, model work, crawls and unknown scripts — launches low; explicit rules or a raised default re-enable guarding. A lightweight command followed by a build remains low unless a rule marks the build high. Invalid policy files fail conservatively high; help and explicit set repair remain usable.
For example (no JSON):
/resources check free -m
/resources rule java-version low java -version
/resources check java -version
/resources remove java-version
/resources global unknown-shell highRules created by rule have <id>-bash and <id>-process IDs; removing the base ID removes both. Duplicate IDs are rejected without changing the file. Read-only/lifecycle actions do not enter admission.
Typed rules
Policy fields: defaultClass, unknownShellClass, rules (ordered array). Each rule: id, tool, class (low/high), all (AND conditions). First matching rule wins per command. Highest class wins across a shell chain. Descriptions are never concatenated into command classification.
Conditions use path (JSON Pointer), op, and typed JSON value:
| Path | Meaning |
|---|---|
/arguments/action | Original tool arguments; any name/nested path supported |
/shell/executable | Literal executable basename, including from absolute paths |
/shell/argv | Exact argument tokens, excluding executable |
/shell/options/-Dtest | String value in a -Dtest=Name token (before --) |
/shell/environment/MAVEN_OPTS | Literal leading assignment or env NAME=value value |
Operators: eq (typed equality), contains (array membership), sequence (consecutive array tokens), prefix (initial array tokens), exists (boolean), gte/lte (numeric comparisons). Use sequence with ["-pl", "module"] for space-separated flag/value pairs. JSON Pointer escaping applies: / in keys becomes ~1, ~ becomes ~0.
Example for a known small test, not all Maven tests:
/resources add {"id":"small-test","tool":"bash","class":"low","all":[{"path":"/shell/executable","op":"eq","value":"mvn"},{"path":"/shell/argv","op":"contains","value":"test"},{"path":"/shell/argv","op":"sequence","value":["-pl",":my-module"]},{"path":"/shell/options/-Dtest","op":"eq","value":"MySmallTest"}]}
/resources preview bash {"command":"/home/agibsonccc/dev-apps/mvn/bin/mvn -pl :my-module -Dtest=MySmallTest test"}Add a separate rule with tool: "process" for background launches. Prepend high rules for flags such as -am or native build options when appropriate. Rules are user-configured cost estimates, not measured memory usage.
The parser supports literal quotes, escaping, leading environment assignments, env NAME=value, and separators (&&, ||, ;, |, &, newline). A shell that runs a script file (bash tools/build.sh cpu, also sh and zsh) is classified as that script: /shell/executable is build.sh and /shell/argv is the script's own arguments, so a rule written for the script matches however it is started. Expansions, redirects, control syntax and wrappers (bash -c, sudo, timeout, etc.; env with options other than --) use unknownShellClass; they are not partially interpreted to justify a low result. This is not a full Bash interpreter or a security sandbox.
Rules apply to guarded launch actions: bash, process launch, production crawls, model-runtime mutations, pipeline run/test, graph embedding training, code indexing, and evaluation execution. Status/output/cancel remain available during heavy work.
Process and queue behavior
Background launches publish the resolved class. State updates retain it; subsequent policy edits cannot turn an already-running low process into a blocker. Legacy process entries without a class use the current policy. Retained high reservations are not revoked by configuration changes.
Blocked tool-call watches reevaluate their tool/arguments against current policy. Reclassifying waiting work as low makes it eligible to wake, without auto-execution.
Sessions blocked on the high-resource lane wait in the order they were blocked. The line is user-wide, like the lane (~/.kompile/coordination/system/waiters), with one place per session:
- When the lane frees, only the first session in line is told. The others stay waiting instead of all waking to lose the same race.
- A launch from a session that is not first is refused while an earlier one is still in line, including a session that never waited. The refusal names who is next.
- A session's place lasts while its watch keeps checking. Once it has been told the lane is free it has 120 seconds to retry; after that, or when its process exits, the next session is served.
- An admitted launch leaves the line. Other work the same session still has waiting rejoins at the back.
edit_coordinator action=query_activities lists the lane holder and the line.
Edit locks are advisory and self-healing: a lock whose holder has expired presence or a provably dead PID is evicted by the next coordination read — no MCP release_edit round-trip is needed. kompile edit-coordinator release --all clears every lock without any agent session.
Explicit edit_coordinator checks accept action: "preflight_activity" or "watch_activity", tool_name: "bash", and tool_arguments: {"command": "..."}. The old kind-only form remains a high-resource check (it has no arguments to classify). Execution/preflight results include resourceClassification evidence.
Background-process watchdog (memory pressure, idle and orphaned commands)
This is independent of admission and the crawl subprocess RSS watchdog. It covers background commands (the process tool / process launch) of every kompile chat and MCP session on the machine; subagents, the chat/MCP JVMs and unrelated processes are never targets. It does three things:
- Memory-pressure kill — on by default at 85% host RAM. When RAM in use (
MemAvailableon Linux) stays at/above the threshold, or is projected to cross it, the largest background command tree of any session is killed (whole tree, RSS of the command and all its descendants). Trees underminKillRssMb(default 256) are never killed — they would not relieve the pressure. At most one kill box-wide percooldownMs: sessions coordinate through a lock file, so ten sessions seeing the same pressure do not each kill something. - Idle reaping —
idleTimeoutMinutes, default 60. A session's command with no output and under 1% of one core of CPU across its tree for that long is killed. Launch withkeep_alive: trueto exempt a quiet long-lived command (a dev server, a watcher); memory-pressure kills still apply to it.0disables idle reaping. Idle reaping is independent ofenabled. - Orphan reaping — always on. Every running command has a lease in
~/.kompile/run/process-leases/recording its owner JVM and both processes' OS start times. A session killed without running its shutdown hooks (SIGKILL, the kernel OOM killer) leaves its commands running; any session reaps them at startup and every minute. A reused PID is never signalled.
Every kill is reported: the owning session's agent gets the process-completion notice with Killed by the kompile process watchdog: <reason> and the chat shows it; the reason is the last line of the process log and is published to coordination state (so a chat driving an MCP server sees it on the mirrored row); the killing session's chat gets a notice for kills of processes it does not own; and every action is appended to ~/.kompile/logs/process-watchdog.log.
The sampler also reads CPU, swap, the project filesystem and, only when a GPU threshold is set, each NVIDIA GPU's memory and utilization. GPU metrics use UUIDs so a device-order change cannot transfer momentum between devices. Unsupported/missing metrics are omitted, not assumed healthy or used to justify a kill. Non-NVIDIA GPU telemetry is not yet supported.
Configure in standard chat or emulated passthrough:
/resources monitor show
/resources monitor set ram 90
/resources monitor set cpu 95
/resources monitor set gpuMemory 96
/resources monitor set gpuUtilization 98
/resources monitor set breachCount 3
/resources monitor set projectionSeconds 10
/resources monitor set idleTimeoutMinutes 60
/resources monitor set minKillRssMb 256
/resources monitor enable
/resources monitor disable
/resources global monitor set ram 92Resource names: cpu, ram, swap, disk, gpuMemory, gpuUtilization. All thresholds are percentages in [0,100]; 0 disables that resource. The default is RAM 85 only; CPU, swap, disk, GPU memory and GPU utilization are disabled because saturation can be normal productive work (a full GPU allocator pool is not a host OOM). Background commands are killable even if unrelated work caused the host pressure; /resources monitor disable turns the pressure kill off.
Settings inherit independently from ~/.kompile/resource-monitor.json to <project>/.kompile/resource-monitor.json, including individual resource thresholds. Edits take effect at the next poll. Malformed configuration disables enforcement with an observable error; it never supplies a fabricated kill threshold.
Momentum is the exponential moving average of percentage-point changes per second, using actual elapsed monotonic time (momentumAlpha, default 0.3). A resource breaches when it is at/above its limit, or when at least two consecutive rising samples exceed minMomentumPercentPerSecond (default 0.5) and its smoothed rate projects reaching the limit within projectionSeconds (default 10). Set the projection to 0 for threshold-only enforcement. A falling/flat sample cancels the momentum trigger. breachCount (default 3) consecutive breaches are required; missing/invalid telemetry, changed policy, or a long sampling gap resets history. Sampling interval is intervalMs (default 2000, minimum 1000).
The monitor kills one command tree per decision — the largest leased background command of any session — then enforces cooldownMs (default 30000) box-wide before another kill. A command this session owns goes through the existing process-kill lifecycle; another session's command is signalled by PID + OS start time after its reason is written beside its lease, and its owner reports that reason when it sees the exit. Shared mirrors, virtual watchers, restored history entries, subagents and the chat/MCP JVMs are never auto-kill targets. Crawl runtime children continue to use their existing subprocess watchdog. This is not a cgroup/job-object containment boundary: detached or newly spawned descendants outside the captured tree are not guaranteed to be stopped.
The process tool's resource_status action reports per-resource usage, smoothed momentum, projected usage, consecutive breaches, eligible candidates, kill count and last kill reason. A killed process's metadata carries terminationReason, available in process status/list. Callback errors have an explicit unknown outcome and still enforce cooldown, since signalling may already have happened. The monitor is a daemon and is closed with its owning process manager; status reads never advance enforcement.
The CLI launcher (kompile, and JVM CLI children started by CliProcessLauncher) caps the chat/MCP JVM heap at min(8 GiB, 25% of RAM). KOMPILE_CLI_MAX_HEAP=<size> overrides the cap; KOMPILE_CLI_MAX_HEAP=off keeps the JVM's ergonomic maximum.