swapaudit answers the question free cannot: which processes and /tmp
caches are holding swap and RAM, and what is safe to reclaim right now.
It is a single static Linux binary for developer workstations. The default
audit is read-only. Every cleanup is explicit, previewable with --dry-run,
and guarded by UID, path, symlink, and PID start-tick checks.
What it does:
- It attributes memory. Per-process
VmSwap,/tmpcache size and idle time, and separate categories for dormant agents, orphaned agents, untouched caches, and abandoned runs. - It reclaims safely. No implicit destructive action. Each cleanup group has its own flag, and the tool re-reads process and path evidence before it acts.
- It stays out of the way. Zero runtime dependencies, one static binary, no daemon, no account, and no telemetry.
+--------------------------------------------------------------------------------------------------+
| ◆ SWAP & IN-MEMORY CACHE AUDITOR |
+--------------------------------------------------------------------------------------------------+
Swap [#######.........] 48.5% 8.3 GB / 17.1 GB (free 8.8 GB)
RAM [######..........] 39.2% 12.2 GB / 31.2 GB (avail 19.0 GB)
/tmp [#######.........] 47.7% 7.4 GB / 15.6 GB (free 8.2 GB)
+--------------------------------------------------------------------------------------------------+
| ◆ Actionable Reclaim Candidates (Cleanable: 5.9 GB) |
+--------------------------------------------------------------------------------------------------+
PID | Target / Name | Category | Size | Idle | Action
----------+--------------------+------------------+------------+----------+-----------------------
> 2603976 | agy | dormant-agents | 338.8 MB | 20h45m | End dormant session
> - | go-build704621508 | untouched-caches | 338.7 MB | 20h46m | Prune untouched cache
> - | go-build4040953814 | untouched-caches | 324.9 MB | 20h46m | Prune untouched cache
> - | go-build2314295942 | untouched-caches | 304.2 MB | 1d9h | Prune untouched cache
... and 652 smaller candidates (1.9 GB). Run with --all to inspect full list.
Install the latest static binary:
curl -sSL https://github.com/jadmadi/swapaudit/releases/latest/download/swapaudit-linux-amd64 \
-o ~/.local/bin/swapaudit && chmod +x ~/.local/bin/swapauditRun the audit, then preview every cleanup:
swapaudit
swapaudit --clean-all --dry-runFull install options: Installation methods. Roadmap and the current feature freeze: ROADMAP.md.
Modern developer workstations run dozens of language server isolates, container runtimes, headless browsers, and local AI agent worker processes. Over time, inactive background processes accumulate anonymous memory pages that the Linux kernel pages out to disk.
Meanwhile, temporary build directories and test suites allocate gigabytes of volatile storage inside
/tmp, which mounts as a tmpfs RAM-backed filesystem. When RAM pressure rises, tmpfs pages compete
directly with process memory for physical space and swap blocks.
free, top, and vmstat report aggregate swap usage or resident set size.
They cannot answer three triage questions:
- Which dormant processes pushed hundreds of megabytes into swap hours or days ago?
- Which abandoned test workspaces in
/tmpare inflating the kernel tmpfs backing store? - What can be safely cleaned right now without disrupting running applications?
The audit answers all three in one pass. For comparisons with earlyoom, systemd-oomd, zram, smem, and vmstat, see docs/comparison/.
The audit reads kernel counters and /tmp metadata. Cleanup is a separate,
explicit step with a dry-run preview and a JSON receipt.
Kernel memory subsystems interact across physical RAM, swap space, and tmpfs mounts:
PHYSICAL RAM & KERNEL MEMORY SUBSYSTEMS
=============================================================================
+---------------------------------------------------------------------------+
| Physical RAM |
| +-----------------------+ +-------------------+ +-------------------+ |
| | Active Applications | | Inode / PageCache | | /tmp tmpfs Mount | |
| | (RSS in Memory) | | (Kernel Buffers) | | (RAM-backed disk) | |
| +-----------------------+ +-------------------+ +-------------------+ |
+---------------------------------------------------------------------------+
| |
| (Kernel Anonymous Page Out) | (Swap backed)
v v
+---------------------------------------------------------------------------+
| Linux Swap Space |
| +-----------------------+ +-------------------+ +-------------------+ |
| | Dormant Agent Workers | | Idle Shell Stacks | | Swapped tmpfs Blks| |
| | (VmSwap in /proc) | | (Aggregated) | | (Stale runs) | |
| +-----------------------+ +-------------------+ +-------------------+ |
+---------------------------------------------------------------------------+
The visual triage pipeline extracts kernel data, classifies occupants, and enforces safety guards:
flowchart TD
A["Kernel Data Extraction"] --> B["/proc/meminfo & Statfs"]
A --> C["/proc/[pid]/status (VmSwap)"]
A --> D["/proc/[pid]/sched (Idle Time)"]
A --> E["/tmp Lstat & Recursive ModTime"]
B --> F["Memory & Swap Pool Header"]
C & D --> G["Process Classification Engine"]
E --> H["Filesystem Cache Classifier"]
G --> I{"Classification"}
I -->|"Idle > Threshold"| J["Dormant Agents"]
I -->|"Parent Dead"| K["Orphaned Processes"]
I -->|"KDE / System"| L["Desktop Daemons (Protected)"]
I -->|"Active"| M["Active Apps (Protected)"]
H --> N{"Cache Status"}
N -->|"Build Cache > MaxAge"| O["Untouched Caches"]
N -->|"Test Run > MaxAge"| P["Abandoned Runs"]
N -->|"Recent Activity"| Q["Active Caches (Protected)"]
J & K & O & P --> R["Actionable Reclaim Candidates"]
R --> S["Safety Verification: UID, Symlink, PID StartTicks"]
S --> T["Surgical Cleanup: SIGTERM / os.RemoveAll"]
Attribution:
- Per-process and per-cache ranking:
VmSwapfrom/proc,/tmpcache size, and newest mtime, sorted by size, swap, RAM, or age. - Precise process classification: dormant AI coding agents, browser MCP servers, and orphaned sessions.
- Shell flood protection: aggregates dozens of idle subshells into one row.
Safe cleanup:
- Read-only default: the audit changes nothing until a cleanup flag is passed.
- Kernel start-tick verification: re-reads start ticks before
SIGTERMto avoid PID-reuse kills. - Real-UID ownership: never signals a process owned by another user.
- Fail-closed orphan evidence: systemd services and processes without a controlling terminal are not treated as orphans.
- Strict path confinement: prunes only under
/tmpor/var/tmp, owned by the active UID, and rejects symlinks at every walk boundary. - Guarded swap drain: per-device
swapoff/swaponwith feasibility math, a RAM reserve, and mandatory re-enable before the next device. - Bounded downloads: the self-updater caps binaries at 50 MB and checksum files at 1 MB.
Low overhead:
- Pure Go, standard library only, no runtime dependencies.
- Sub-second audit with no daemon or background worker.
- Terminal-aware formatting with
NO_COLORand an ASCII fallback.
- Linux only; uses
/procand Linux cgroups. - Scans
/tmp, not/var/tmp. Cleanup is confined to both. - Cache cleanup does not yet inspect open file descriptors, process working
directories, or file-backed mappings. Do not prune a cache while a build or
test is using it. The design contract is in
docs/cache-liveness.md; the checks that actually run are indocs/safety.md. - Agent detection covers a fixed runtime list plus MCP heuristics, not every agent.
- The swap drain briefly disables each device while it is re-enabled. The machine stays up, but this is not zero downtime.
- RAM used relies on
MemAvailable(Linux 3.14+).
Pre-built standalone binary:
Download the latest static binary for your architecture (amd64, arm64, armv7, riscv64):
curl -sSL https://github.com/jadmadi/swapaudit/releases/latest/download/swapaudit-linux-amd64 \
-o ~/.local/bin/swapaudit && chmod +x ~/.local/bin/swapauditIn-place self-upgrade:
If swapaudit is already installed on your system, upgrade it to the latest release with:
swapaudit upgradeBuild from source with Makefile:
git clone https://github.com/jadmadi/swapaudit.git
cd swapaudit
make build
make installVia go install:
go install github.com/jadmadi/swapaudit/cmd/swapaudit@latestRequirements: Linux with kernel 3.10 or newer (tested on Linux 6.x with systemd and glibc).
Basic audit:
Run swapaudit without arguments to view overall memory status and actionable candidates:
swapauditSorting and filtering:
Sort occupants by age instead of size to reveal long-dormant processes:
swapaudit --sort ageInspect all individual processes without shell aggregation:
swapaudit --allSet custom display row limits:
swapaudit --limit 25Surgical cleanup commands:
Simulate all cleanup actions without deleting files or killing processes:
swapaudit --clean-all --dry-runPrune stale build caches untouched for over 12 hours:
swapaudit --clean-untouchedPrune abandoned test suites and review runs in /tmp:
swapaudit --clean-abandonedEnd dormant agent sessions idle for over 2 hours:
swapaudit --clean-dormantClean all safe targets with interactive confirmation:
swapaudit --clean-allBypass interactive prompts in automated cron jobs:
swapaudit --clean-untouched -yCustomization flags:
Add custom project prefixes for /tmp test runs:
swapaudit --tmp-pattern "myproject-*" --tmp-pattern "e2e-run-*"Customize the cutoff age for stale caches (default: 12h):
swapaudit --max-age 6hCustomize the idle threshold for dormant agent sessions (default: 2h):
swapaudit --idle-threshold 45mForce plain ASCII output for minimal terminal environments:
swapaudit --asciiDisable ANSI colors:
swapaudit --no-colorPrint version information:
swapaudit --versionSwap does not require a reboot. The kernel only faults a swapped page back into
RAM when it is touched. To empty swap while keeping the machine up, the
supported mechanism is a drain cycle: swapoff <device> to fault every page
back in, then swapon <device> to re-enable the now-empty area.
swapaudit reclaim runs that cycle with a feasibility check, a RAM reserve, and
a mandatory re-enable for every device:
swapaudit reclaim --dry-run # read-only plan, no root required
sudo swapaudit reclaim --drain-swap # drain swap back into RAM
sudo swapaudit reclaim --drop-caches # release clean page cacheThe plan refuses to start unless:
MemAvailable - used swap - reserve >= 0
The default reserve is max(512 MiB, 10% of RAM). If swap is already empty,
the command performs no swapoff/swapon churn. If the full swap footprint
does not fit, the planner drains the largest safe subset and reports the bytes
that remain in swap. zram is skipped by default because draining it
decompresses pages into RAM and usually increases pressure. Use
--include-zram only when you accept that trade-off.
Every device is restored before the next device is disabled. A failed or
interrupted restore exits 3 and prints the exact sudo swapon recovery
command. --json emits a receipt with before/after swap, RAM, page cache, and
per-device outcomes. No daemon, systemd unit, pidfile, or lock file is created.
See docs/reclaim.md for the math, exit codes, zram notes, and a disposable swap-file verification protocol.
When both stdin and stdout are terminals, the report ends with a four-row action menu. Scripts, pipes, and CI have no TTY, so their output is unchanged.
ACTION PICKER
KEY | TIER | ITEMS | SIZE | RESOURCE | SAFETY
1 | untouched caches (>12h) | 5 | 367.5 MB | RAM | rebuildable
2 | abandoned runs (>12h idle) | 25 | 12.4 MB | RAM | rebuildable
3 | dormant agents (>2h idle) | 3 | 197.9 MB | swap | irreversible
4 | orphaned agents (parent gone) | 0 | — | swap | irreversible
Selecting a tier opens a review panel with the exact targets, sizes, idle times,
and what the tier frees. Nothing runs until you type the scope token: the target
count for filesystem tiers (for example 5) or the PID of the largest target for
process tiers (for example 1618347). A mismatch is refused with the expected
token; after three attempts the tier is cancelled. q, empty input, or EOF
exits without touching anything. No passcode is stored: the token confirms the
scope of the action, not your identity.
After a successful action the picker re-scans once and prints the measured swap and tmpfs before/after. Dry-run rehearsal uses the same flow:
swapaudit --dry-runThe menu is on by default only when a terminal is present. Force it with
--interactive (a non-TTY is then a usage error), disable it with
--no-interactive or SWAPAUDIT_NO_INTERACTIVE=1.
Process tiers 3 and 4 send SIGTERM and are irreversible; the cleaner still
re-verifies PID start ticks and refuses reused PIDs. Cache tiers 1 and 2 are
rebuildable. The picker performs no deletion or signalling itself: it delegates
to the same guarded cleaner used by the --clean-* flags.
swapaudit sample is a headless measurement engine for scripts, statuslines,
and CI. It samples the fast lane (system counters and per-process swap), walks
/tmp on a slower lane, and estimates how fast swap or tmpfs is filling.
swapaudit sample --once | jq .
swapaudit sample --stream --interval=1s --record=/tmp/swap-trace.ndjson--once emits the full JSON snapshot plus a window block with trends, rates,
movers, and a nullable eta_seconds. --stream emits one NDJSON line per tick
and a final stopped line. The estimator gates on sample count, window span,
fit quality, monotonicity, and direction, so a null ETA means "not enough
evidence" rather than a confident lie.
Process identity is (pid, start_ticks), so a recycled PID cannot fabricate a
mover; exited processes are reported in exited_bytes. See
docs/sampling.md for the estimator gates, attribution
caveats, trace format, and statusline/CI recipes.
swapaudit watch runs the sampler in the foreground and sends one notification
per incident when swap or tmpfs is projected to run out.
swapaudit watch
swapaudit watch --test-notify
swapaudit watch --json --duration=30sThe trigger requires danger to persist for --sustain, uses --rearm-eta and
--rearm-pressure hysteresis, enforces a per-resource --cooldown and hourly
cap, and falls back to absolute pressure when the ETA is null. The transport
chain probes notify-send, gdbus, dbus-send, kdialog, OSC 777, and finally
stderr; every invocation is argv-only with a three-second timeout. --json
emits the same events as NDJSON and sends nothing.
No daemon, pidfile, lock file, or service unit is created. See
docs/watch.md for the state diagram, payloads, transport
details, fatigue tuning, the systemd-run recipe, and the privacy note.
--json emits exactly one versioned document to stdout for scripts, statuslines,
editors, and CI. The mode is read-only and never runs the update check, prints a
banner, or truncates the item list.
swapaudit --json > snapshot.json
swapaudit --json --no-command > snapshot.json # omit command lines for logsThe document carries system counters, thresholds, per-category totals, and every
raw item. Items use a canonical order, nullable fields are explicit, and arrays
are never null. See docs/json-schema.md for the full
field table, nullability rules, exit codes, and consumer recipes.
swapaudit --json | jq -r '.totals.cleanable_bytes'Cleanup, --dry-run, --yes, and interactive flags are rejected with exit 2
when combined with --json.
Opt-in release check:
The default audit makes no network requests. Pass --check-updates or set
SWAPAUDIT_CHECK_UPDATES=1 to check GitHub once for a newer release:
swapaudit --check-updatesThe check performs one request and prints a subtle notice after the report.
In-place self-upgrade:
Run swapaudit upgrade to upgrade your installed binary in place. The updater fetches release
metadata, streams the release binary with a 50MB limit, verifies SHA256 checksums, and replaces
the executable atomically.
swapaudit upgrade| Command or flag | Default | Description |
|---|---|---|
| upgrade | - | Check GitHub releases and upgrade swapaudit in place |
| reclaim | - | Drain swap into RAM and optionally drop page cache |
| --drain-swap | true | Drain active swap devices back into RAM (reclaim default) |
| --drop-caches | false | Sync and drop clean page cache and dentries |
| --include-zram | false | Allow draining zram (usually increases RAM use) |
| --reserve | 10% RAM | RAM kept available after the drain (floor 512MiB) |
| --timeout | 5m | Per-command timeout for swapoff/swapon (10s..30m) |
| --sort <size|swap|ram|age> | size | Sort column for occupant tables: size, swap, ram, or age |
| --limit | 12 | Maximum rows to display in the main occupants table |
| --all | false | Show all individual processes without grouping |
| --clean-untouched | false | Prune stale build caches untouched beyond max-age |
| --clean-abandoned | false | Prune abandoned test suites and review runs in /tmp |
| --clean-dormant | false | Terminate dormant agent sessions idle beyond threshold |
| --clean-orphaned | false | Terminate orphaned agent sessions whose parent shell died |
| --clean-tmp | false | Prune all cleanable /tmp caches (untouched and abandoned) |
| --clean-all | false | Run safe cleanups (untouched, abandoned, dormant) |
| --dry-run | false | Simulate actions without deleting files or killing processes |
| -y, --yes | false | Automatically answer yes to confirmation prompts |
| --max-age | 12h | Age cutoff duration for stale /tmp directories |
| --idle-threshold | 2h | Idle duration threshold for classifying dormant agents |
| --tmp-pattern | (list) | Additional pattern for temporary artifacts in /tmp (repeatable) |
| --check-updates | false | Check GitHub for a newer release (one request) |
| --json | false | Emit one stable machine-readable JSON document |
| --no-command | false | Omit command lines from JSON output (requires --json) |
| --ascii | false | Use plain ASCII glyphs instead of Unicode box characters |
| --no-color | false | Disable ANSI color highlighting |
| -v, --version | false | Print swapaudit version and build metadata |
| -h, --help | false | Show CLI usage help message |
The project follows a standard modular Go architecture:
cmd/swapaudit: application entry point.internal/app: CLI execution coordinator and flag parser.internal/cache:/tmpcache scanner, pattern matcher, and mtime depth analysis.internal/cleaner: surgical pruning and process termination with verification guards.internal/live: headless sampler, bounded ring, OLS estimator, and raw trace recorder.internal/model: shared data types for memory, processes, and categories.internal/notify: probed notification transports with argv-only execution.internal/proc: kernel/procparsers for status, meminfo, swaps, PSI, sched, and cmdline.internal/reclaim: swap-drain planner, feasibility math, guarded executor, and receipt.internal/snapshot: versioned machine-readable schema and pure document builder.internal/term: terminal layout, ANSI color engine, and text width calculations.internal/watch: danger state machine, sustain/hysteresis/cooldown, and payload rendering.internal/triage: process classification and shell aggregation logic.internal/updater: release checking and atomic binary self-upgrades.internal/version: version string formatting and build metadata.
Running tests and linters:
./scripts/lint
./scripts/testFor contribution instructions, see CONTRIBUTING.md. Before proposing a new feature, read the demand-validation research and feature freeze; feature work is frozen until that research reaches a written decision. For project governance and security policies, see GOVERNANCE.md and SECURITY.md. For agent-specific operating guidance, see AGENTS.md.
swapaudit is free software dual-licensed under:
-
Waqf Digital Public License, Level 2: Binding Attribution (WaqfDPL-Mulzim 1.0) Dedicated as a perpetual digital endowment (Waqf) for the sake of Allah to benefit developers and communities worldwide. Requires reciprocal copyleft and author attribution. Consult the WaqfDPL registry at https://github.com/WaqfTech/waqf-license-draft. See WaqfDPL-1.0.md for the full legal text.
-
GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later) Guarantees reciprocal software freedom under the Free Software Foundation copyleft framework. See LICENSE-AGPL.txt and https://www.gnu.org/licenses/agpl-3.0.html for the full legal text.
Users and distributors may choose to follow the terms of either license.
Author: Jad Madi (https://github.com/jadmadi)