Dicklesworthstone/storage_ballast_helper
Acerca de
Cross-platform Rust daemon that prevents disk-full incidents for AI coding workloads using predictive pressure control, safe artifact cleanup, and multi-volume ballast pools.
IA y aprendizaje automáticoWhat you can do
- Predictive pressure control - EWMA + PID reacts before disks hit critical levels
- Multi-volume ballast pools - Frees space on the exact filesystem under pressure
- Safe artifact cleanup - Deterministic scoring + hard vetoes (.git, protected paths, too-recent files, open files)
- Emergency recovery - Reclaim space on critically full disks without a database or config prerequisite
Crecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- +6
- in 15 days
- +9
- in 1 month
- Recopilando historial
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
Originalstorage_ballast_helper (sbh)
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/storage_ballast_helper/main/scripts/install.sh | bash
macOS users: jump straight to the macOS quick start for the launchd, Homebrew, manual install, and Full Disk Access checklist. For the incident that drove the Mac port, see the 2026-05-03 macOS case study.
Cross-platform disk-pressure defense for AI coding workloads: predictive monitoring, safe cleanup, ballast release, and explainable policy decisions.
TL;DR
The problem: agent swarms and build systems can fill disks faster than humans can react, causing failed builds, stuck daemons, and crashed workflows.
The solution: sbh continuously monitors storage pressure, predicts exhaustion, and safely reclaims space using layered controls: ballast pools, deterministic artifact scoring, hard safety vetoes, and conservative fallback modes.
Why Use sbh?
| Capability | What it gives you |
|---|---|
| Predictive pressure control | EWMA + PID reacts before disks hit critical levels |
| Multi-volume ballast pools | Frees space on the exact filesystem under pressure |
| Safe artifact cleanup | Deterministic scoring + hard vetoes (.git, protected paths, too-recent files, open files) |
| Emergency recovery | Reclaim space on critically full disks without a database or config prerequisite |
| Project protection | .sbh-protect markers and config globs prevent accidental cleanup in critical repos |
| Explainable decisions | Evidence ledger + sbh explain shows why each action happened |
| Strong observability | status, dashboard, stats, blame, structured logs, and decision traces |
| Production rollout safety | Shadow -> canary -> enforce modes with automatic fallback and guardrails |
Quick Example
# 1) Install and bootstrap service
sbh install --systemd
# 2) Provision per-volume ballast pools
sbh ballast provision
# 3) Protect critical projects from cleanup
sbh protect /data/projects/critical-app
# 4) Inspect pressure and forecast
sbh check --target-free 15
sbh status --json
# 5) Run cleanup scan and review candidates
sbh scan /data/projects --top 20 --min-score 0.70
# 6) Execute safe cleanup with confirmation
sbh clean --target-free 20
# 7) Investigate decisions and trends
sbh explain --id <decision-id>
sbh stats --window 24h
sbh blame --json
# 8) Emergency recovery
sbh emergency /data --target-free 10 --yes
Design Principles
- Safety before aggressiveness: hard vetoes always win over reclaim pressure.
- Predict, then act: pressure trends and controller outputs drive timing and scope.
- Deterministic decisions: identical inputs produce identical ranking and policy outcomes.
- Explainability is mandatory: every action has traceable evidence and rationale.
- Fail conservative: policy/guard failures force fallback-safe behavior.
Implementation Constraints
sbh enforces several hard constraints that shape the codebase:
#![forbid(unsafe_code)]in bothlib.rsandmain.rs. No unsafe blocks, no raw pointer arithmetic, no manual memory management. All platform-specific behavior goes through safe abstractions (nix,libcbindings,signal-hook).- No async runtime. Concurrency uses OS threads with
crossbeam-channelfor bounded message passing andparking_lotfor synchronization. This avoids the complexity and debugging opacity of async runtimes while providing predictable scheduling behavior for a daemon that needs to respond to pressure signals in bounded time. - Pedantic + nursery Clippy lints are enabled project-wide. The code is held to strict Rust idiom standards beyond the default warning set.
- Deterministic builds. The release profile uses
opt-level = 3(speed optimization),lto = true(link-time optimization),codegen-units = 1,panic = "abort", andstrip = truefor a lean, predictable binary.
The Problem in Depth
AI coding agents (Claude Code, Codex, Gemini CLI, etc.) spawn parallel build processes, download dependencies, generate intermediate artifacts, and write logs continuously. A single agent can produce gigabytes of build artifacts per hour. Run a dozen agents across multiple projects on the same machine, and disk consumption becomes unpredictable and bursty in ways that traditional monitoring tools were never designed for.
The failure mode is severe: when a disk hits 100%, everything breaks simultaneously. Builds fail mid-compilation, SQLite databases corrupt, daemon state files can't be written, and even basic shell operations stop working. Recovery from a completely full disk is painful because most cleanup tools themselves need to write temporary files.
Existing solutions fall short in specific ways:
- Cron + rm scripts are fragile, have no pressure awareness, and can't distinguish a 2-hour-old build artifact from a 2-hour-old source file. They run on fixed schedules regardless of whether the disk is at 10% or 99%.
- Generic temp cleaners (tmpreaper, systemd-tmpfiles) only handle
/tmpand similar well-known paths. They don't understand build artifact structures, can't score candidates by reclaimability, and have no concept of project protection. - Filesystem quotas prevent individual users from consuming too much space but don't help when the problem is aggregate consumption across legitimate workloads on the same volume.
- Manual cleanup doesn't scale and can't react faster than a human can type
du -shand decide what to delete.
sbh targets this environment directly: multiple concurrent agents, bursty disk consumption, safety-critical deletion decisions, and the need to react in seconds rather than minutes.
How sbh Compares
| Capability | sbh |
Cron + rm scripts |
Generic temp cleaners | Manual cleanup |
|---|---|---|---|---|
| Predictive pressure response | ✅ EWMA + PID | ❌ | ❌ | ❌ |
| Multi-volume awareness | ✅ | ⚠️ usually custom | ⚠️ partial | ⚠️ manual |
| Hard safety vetoes | ✅ built-in | ⚠️ fragile scripts | ⚠️ limited | ✅ human judgment |
| Explainability and traces | ✅ | ❌ | ❌ | ❌ |
| Emergency recovery | ✅ | ❌ | ❌ | ⚠️ slow |
| Service-grade observability | ✅ | ❌ | ⚠️ minimal | ❌ |
Real-World Operator Perspective
This table comes from an operator who had been managing disk pressure across a fleet of AI coding VMs using hand-rolled cron scripts:
| Problem | Cron script | sbh |
|---|---|---|
Agents use unpredictable target dir names (rch*, pi_agent_rust_*, etc.) |
Script misses them | Multi-factor scoring finds ANY stale build artifact by structure, not name |
| Disk fills in < 10 min between cron runs | Machine is stuck until next run | Continuous monitoring (1s polls), predicts exhaustion 30 min ahead |
| Cleaning active build dirs breaks agents | Age-based heuristic (fragile) | Checks for open file handles; hard veto on in-use dirs |
/dev/shm keeps getting filled |
Emergency kill at 90% | Continuous special location monitoring with configurable free buffer target |
| No audit trail | fleet-maintenance.log with one-liners |
Full evidence ledger; sbh explain shows exactly why something was/wasn't deleted |
| Disk hits 100% before anything reacts | Dead until next cron | Ballast files: pre-allocated sacrificial space, released instantly under pressure |
Ballast files address the worst case: a completely full disk where nothing works. Pre-allocate 10+ GiB of sacrificial space per volume; when pressure spikes, release it instantly to buy time while the scanner identifies and removes actual artifacts.
Installation
Option 0: Unix One-Liner Installer
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/storage_ballast_helper/main/scripts/install.sh | bash
The one-liner detects Linux versus macOS, downloads the matching release
artifact, installs the sbh binary, and updates an existing systemd or launchd
service binary when one is already registered. Register a daemon that can
reclaim build artifacts with sudo sbh install --auto: it chooses systemd on
Linux or launchd on macOS and installs a system service when running as root.
Without root, sbh install --auto installs a user service and warns that its
scanner cannot inspect other users' open or mapped files. It therefore refuses
deletion candidates; ballast release still works. Explicit --user or
--scope user|system overrides the automatic scope. sbh status and
sbh doctor --system report the running daemon's process visibility.
Pin a specific version:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/storage_ballast_helper/main/scripts/install.sh | bash -s -- --version v0.1.0
macOS Quick Start
For a system LaunchDaemon that can reclaim build artifacts:
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/storage_ballast_helper/main/scripts/install.sh | bash
sudo sbh install --auto
sudo sbh doctor --pal
sbh status
sudo sbh install --auto detects macOS, chooses launchd system scope, uses
the system configuration and data paths, and provisions the default ballast
preset. To request a user LaunchAgent explicitly:
sbh install --launchd --scope user --auto
A non-root LaunchAgent cannot see other users' processes (macOS hides them),
so its open-file check is never complete and the scanner refuses deletion
candidates. Ballast release still works. The installer explains this limit
before service registration; sbh status and sbh doctor --system also report it.
When enabled, scanner.include_user_temp_dir adds the service user's temporary
directory. Under root this is root's directory: list your $TMPDIR in
scanner.root_paths explicitly if you want the system service to watch it.
Homebrew is supported by the packaged formula skeleton and the
Dicklesworthstone/homebrew-sbh tap. Every release runs
scripts/dsr_release.sh tap VERSION, which renders
packaging/homebrew/Formula/sbh.rb with the version and the per-architecture
SHA-256s of the published darwin archives (refusing if the published checksums
differ from the local build) and pushes it to the tap with the releasing
operator's gh login. sbh doctor --release fails when the tap lags the latest
release. With the tap current, the operator path is:
brew tap Dicklesworthstone/sbh
brew install sbh
sbh install --launchd --scope user --auto
sbh doctor --pal
Manual macOS install from source is the same Cargo path as Linux, followed by launchd setup:
cargo install --git https://github.com/Dicklesworthstone/storage_ballast_helper --bin sbh
sbh install --launchd --scope user --auto
sbh doctor --pal
Grant Full Disk Access before relying on cleanup scans that need protected
locations under ~/Library; sbh doctor --pal reports the exact FDA status and
links to docs/macos-full-disk-access.md.
Option 1: From Git (Cargo)
cargo install --git https://github.com/Dicklesworthstone/storage_ballast_helper --bin sbh
Option 2: From Source
git clone https://github.com/Dicklesworthstone/storage_ballast_helper.git
cd storage_ballast_helper
cargo build --release
./target/release/sbh --help
Option 3: GitHub Release Artifact
gh release download --repo Dicklesworthstone/storage_ballast_helper --pattern "sbh-*.tar.xz"
Verify a Release
Each release ships a manifest, storage_ballast_helper-vX.Y.Z-manifest.json,
that lists every archive's SHA-256, and a minisign signature for it
(.minisig). The raw sbh_<os>_<arch> binaries are not all listed under
their published names, so verify the archive for your platform; the sbh
inside it is the same file as the raw binary. Check the signature, then
check the archive against the manifest:
V=0.7.4
A="sbh-v$V-x86_64-unknown-linux-gnu.tar.xz" # or the archive for your platform
gh release download "v$V" --repo Dicklesworthstone/storage_ballast_helper \
--pattern "storage_ballast_helper-v$V-manifest.json*" --pattern "$A"
minisign -Vm "storage_ballast_helper-v$V-manifest.json" \
-P RWTQGPeLsnm9G7VFdFWkkcRi3wJK/PqsYxWC+oLNN74W9IjBxRU1Xu70
jq -r --arg a "$A" '.artifacts[] | select(.name == $a) | .sha256' \
"storage_ballast_helper-v$V-manifest.json"
sha256sum "$A" # must print the same hash (macOS: shasum -a 256 "$A")
The release signing public key (minisign key id 1BBD79B28BF718D0):
RWTQGPeLsnm9G7VFdFWkkcRi3wJK/PqsYxWC+oLNN74W9IjBxRU1Xu70
SHA256SUMS lists the same hashes but is not signed; the signed manifest is
what ties a binary to the release. The macOS binaries are also signed with a
Developer ID and notarized: codesign --verify --strict sbh.
Environment Health and Migration
The bootstrap system detects and repairs common installation problems, from stale PATH entries to misconfigured service files. It runs automatically during sbh install and can be invoked manually with sbh bootstrap.
Environment Health States
| State | Meaning |
|---|---|
| Healthy | All checks pass |
| Degraded | Minor issues detected, sbh remains functional |
| Broken | Significant issues preventing correct operation |
| NotInstalled | No installation footprint detected |
Migration Reasons
The bootstrap scanner checks for 16 migration conditions:
| Reason | Description |
|---|---|
binary-not-on-path |
Binary exists but shell PATH does not include its directory |
stale-path-entry |
Shell profile references a binary location that no longer exists |
duplicate-path-entries |
Multiple sbh PATH entries in the same shell profile |
systemd-unit-stale-binary |
systemd ExecStart points to a missing binary |
systemd-unit-stale-paths |
systemd ReadWritePaths= does not cover the configured scan roots, ballast or data directories (the daemon could not delete or write there under ProtectSystem=strict); repaired by rewriting the line and daemon-reload |
launchd-plist-stale-binary |
launchd ProgramArguments references a missing binary |
deprecated-config-key |
Config uses renamed keys (scan_interval_secs, max_ballast_mb, log_level) |
legacy-config-path |
Config exists in an older Linux/XDG, manual, or Homebrew path and should be copied to the canonical platform path |
legacy-data-path |
State/log files exist in an older Linux/XDG, manual, or Homebrew data path and should be copied to the canonical platform data directory |
missing-state-file |
Data directory exists but state.json is absent |
orphaned-completion |
Shell completion script installed for an unavailable shell |
stale-completion |
Completion script out of date |
empty-ballast-pool |
Ballast directory is undersized or empty |
binary-permissions |
Binary is not executable |
stale-backup-file |
Old backup from a previous install past the cleanup threshold |
interrupted-install |
Marker file indicates an incomplete prior installation |
Repair Actions
Each detected issue maps to one of 10 action types: RemoveProfileLine, DeduplicateProfile, FixPermissions, UpdateServicePath, CopyLegacyConfig, CopyLegacyState, RemoveOrphanedFile, CleanupBackup, CreateDirectory, InitStateFile.
All mutations create timestamped backups before writing. Legacy config/state migration is copy-only and never overwrites an existing canonical file, so older XDG/manual/Homebrew sources remain in place until the operator removes them deliberately. A 7-day default threshold governs automatic cleanup of old backup files.
# Run bootstrap scan and repair
sbh bootstrap
# Dry-run to see what would change
sbh bootstrap --dry-run
# Machine-readable report (reasons use the kebab-case codes above)
sbh bootstrap --dry-run --json
# Read-only scan as part of doctor
sbh doctor --env
# Skip the automatic install-time repairs
sbh install --no-bootstrap
During sbh install only the actions that fix the install being produced run automatically: RemoveProfileLine, DeduplicateProfile, FixPermissions, UpdateServicePath, CreateDirectory, InitStateFile. Legacy config/state copies, orphaned-file removal, and backup cleanup are planned and reported but left for an explicit sbh bootstrap. A non-dry-run sbh bootstrap exits non-zero when the environment is still Broken afterwards or any action failed.
Source: src/cli/bootstrap.rs
Quick Start
- Check your config path:
sbh config path
- Validate config:
sbh config validate
- Install service:
sbh install --systemd # Linux
sbh install --launchd # macOS
- Start monitoring:
sbh daemon
- Open live dashboard:
sbh dashboard
Config and State Paths
sbh uses platform-native defaults unless you explicitly override them:
| Platform | Config | State, logs, ballast, update cache |
|---|---|---|
| Linux | ~/.config/sbh/config.toml |
~/.local/share/sbh/ |
| Linux system service | /etc/sbh/config.toml |
/var/lib/sbh/ |
| macOS user service | ~/Library/Application Support/sbh/config.toml |
~/Library/Application Support/sbh/ |
| macOS system service | /Library/Application Support/sbh/config.toml |
/private/var/sbh/ |
The default ballast pool is ~/.local/share/sbh/ballast for Linux user installs, /var/lib/sbh/ballast for Linux system services, ~/Library/Application Support/sbh/ballast.bin for macOS LaunchAgents, and /private/var/sbh/ballast.bin for macOS LaunchDaemons. Override [paths].ballast_dir in the config file when the ballast pool must live on a specific volume.
Precedence is: --config, then SBH_CONFIG, then the platform default. On macOS, setting SBH_USE_XDG_PATHS=1, setting XDG_CONFIG_HOME/XDG_DATA_HOME, or already having ~/.config/sbh/config.toml without a native App Support config opts into the XDG layout.
Install Wizard
Running sbh install --wizard launches guided setup:
- Service manager -- systemd (Linux default), launchd (macOS default), or none (manual start).
- Service scope -- system-wide when running as root, user service otherwise. The wizard explains the scanner limitations of non-root services. Explicit service and scope flags are retained without asking those questions again.
- Watched paths -- suggests existing platform temporary directories, resolving and deduplicating aliases. Home directories, their ancestors, and filesystem-root aliases are excluded from automatic selection. Add project or other custom paths interactively when you want them watched.
- Ballast sizing -- choose a preset or enter custom file counts:
| Preset | Files | Per-File Size | Total |
|---|---|---|---|
| Small | 5 | 1 GiB | 5 GiB |
| Medium (default) | 10 | 1 GiB | 10 GiB |
| Large | 20 | 1 GiB | 20 GiB |
| Custom | user-specified | 1 GiB | varies |
For a first-time non-interactive install (CI, automation), sbh install --auto
applies the platform-native service manager, temporary-directory watched paths,
and Medium ballast preset. If no safe temporary directory is available, setup
asks for explicit paths through the wizard or a configuration file. New wizard
configurations record the selected roots and disable implicit per-user temp
expansion. When the selected configuration already exists, --auto
retains its settings, including watched and protected paths, policy mode, and
ballast.auto_provision. Without an interactive wizard or explicit ballast
options, an existing configuration is kept byte for byte, including comments
and unknown keys. The interactive wizard merges the answers you choose into
that configuration while retaining settings it does not ask about.
Explicit --ballast-count, --ballast-size, and --ballast-path arguments
override the existing settings or wizard choices and are saved for the daemon.
Counts and sizes must be positive; zero is rejected. To install without creating
ballast, set ballast.auto_provision = false in the selected configuration.
Dry-run reports and real installs use the same effective configuration, and
invalid or unreadable existing configurations are refused before writing a
replacement.
Service scope follows effective privileges: system under root or sudo, user
otherwise. Explicit scope flags always take precedence, and --config or
SBH_CONFIG retains its configuration destination. A non-root user service's
reclamation warning is included in both human and JSON install summaries,
including --auto --dry-run --json.
macOS Configure Checklist
- LaunchAgent vs LaunchDaemon:
--autoselects user scope without root and writes under~/Library/Application Support/sbh/. Undersudoit selects a system LaunchDaemon, writes data under/private/var/sbh/, and has the privileges needed to inspect other users' process activity. - Full Disk Access: run
sbh doctor --palafter install. If themacos.full_disk_accesscheck warns or fails, followdocs/macos-full-disk-access.md, then restart the launchd service. - Service control: use
sbh service --launchd --scope user statusandsbh service --launchd --scope user restartfor user installs; replace--scope userwith--scope systemfor LaunchDaemons. - Per-user temp dir:
$TMPDIR(/var/folders/<x>/<y>/T) is separate from/tmpand/var/tmp, which resolve to/private/.... The wizard selects existing temporary directories explicitly. Existing configurations withscanner.include_user_temp_dir = truealso add the service user's temp directory at load unless a configured root already covers it. - Homebrew paths: Apple Silicon installs normally live under
/opt/homebrew, Intel installs under/usr/local. When run from a Homebrew keg,sbh installverifies the current binary and registers launchd against the matching stablePREFIX/opt/sbh/bin/sbhlink. A missing or retargeted link is refused with repair instructions. This also appears in dry-run JSON; an explicitly supplied offline bundle retains precedence. Usebrew upgrade sbhto update a reused Homebrew installation.
Command Reference
Core
| Command | Purpose |
|---|---|
sbh daemon |
Run monitoring loop and policy engine |
sbh status |
Real-time health, pressure, and controller state |
sbh check |
Pre-flight space check and recommendations |
sbh check --agent-scratch [PATH] |
Read-only inventory of Claude session scratch, sizes, process references, and tree/transcript inactivity |
sbh scan |
Manual candidate discovery and scoring report |
sbh clean |
Manual cleanup with confirmation, dry run, and per-filesystem byte or inode recovery targets |
sbh undo |
Restore quarantined entries (<decision-id>, --path, --all-since, --list) |
sbh relocate |
Report dormant protected scratch, apply verified backup relocation, or restore a relocated tree (guide) |
sbh emergency |
Immediate recovery on critically full disks; optional --target-free-inodes PERCENT for inode exhaustion |
Ballast and Protection
| Command | Purpose |
|---|---|
sbh ballast status |
Show per-volume ballast inventory |
sbh ballast provision |
Create ballast pools/files idempotently |
sbh ballast release N [--mount MOUNT] |
Release N files from the configured pool, or ask the running daemon to release them on one mount |
sbh ballast release N --directory DIR |
Release verified reserve from an explicit pool even when configuration is unreadable |
sbh ballast replenish [--mount MOUNT] |
Rebuild the configured pool, or ask the running daemon to run a replenishment step on one mount |
sbh ballast verify |
Verify ballast integrity |
sbh protect <path> |
Add .sbh-protect marker |
sbh protect --list |
List all protected paths |
sbh unprotect <path> |
Remove protection marker |
sbh lease run --target PATH --max-bytes SIZE -- COMMAND... |
Run a command with a process-bound active-target lease |
sbh lease status [--target PATH] |
Inspect active lease state and machine-readable bounds |
sbh lease renew [--target PATH] [--extend DURATION] |
Authenticated soft-deadline renewal from inside the leased process tree |
sbh protect is permanent operator policy; sbh lease is ephemeral process
lifetime protection for fresh build/test output. On Linux and macOS, lease run
locks a stable sidecar before creating the target, places the command in its own
process group, injects CARGO_TARGET_DIR, and replaces sbh with the command.
The kernel releases protection when that process tree exits or crashes. A
separate watchdog terminates that process group if its renewable deadline,
declared byte budget, hard eight-hour lifetime, or the 10 GiB emergency reserve
is crossed. It never deletes the target.
The target must be absent, absolute, and an immediate child of one configured
scanner.root_paths entry. A root admits at most four concurrent leases, 64 GiB
per lease, and 128 GiB in aggregate. Renewal uses a 256-bit token inherited in
SBH_ACTIVE_LEASE_TOKEN; durable metadata stores only its SHA-256 digest. Use
--json with status or renew for automation. The command's stdout remains
its own; lease lifecycle diagnostics go to stderr.
lease_target=/data/tmp/mtdt-check-$$
sbh lease run --target "$lease_target" --max-bytes 32G --ttl 2h -- \
cargo check --workspace --all-targets
# From the leased command or one of its descendants:
sbh --json lease status
sbh --json lease renew --extend 30m
Observability and Explainability
| Command | Purpose |
|---|---|
sbh stats |
Time-window activity/deletion statistics |
sbh blame |
Attribute artifact pressure by process/agent |
sbh blame --deleted-open [--top N] [--timeout-secs N] |
Report allocated space held by deleted, still-open files and their process holders (Linux, read-only) |
sbh dashboard |
Real-time TUI dashboard |
sbh doctor --pal |
Validate platform integration and macOS runtime prerequisites |
sbh doctor --system |
Check host kernel tuning (writeback / dirty-page limits), whether each ballast pool covers the reserve its observed write bursts require, and that the daemon's own files do not live on a volume it reclaims |
sbh doctor --service [--user] |
Compare the installed systemd unit (or launchd plist) with what sbh generates: FAIL on missing hardening, a different Type=/binary, a drop-in overriding hardening, or a Condition*= gate that keeps the unit from starting; WARN on foreign drop-ins and cosmetic differences |
sbh service --systemd reinstall-unit [--purge-dropins] |
Rewrite the unit from the generator with a timestamped backup beside it and daemon-reload; drop-ins stay in effect unless --purge-dropins moves them into the backup directory |
sbh explain (--id ID | --last N | --path P | --since W) [--level 0-3] |
Explain recorded cleanup decisions: the daemon records one per evaluated candidate, sbh clean records its plan; ids are stable per artifact version and appear in scan --json and artifact_delete events |
On macOS, sbh doctor --pal adds PASS/WARN/FAIL checks for the binary signature,
Gatekeeper assessment, launchd service state, Full Disk Access, APFS inventory,
and free space on the state volume. Each warning or failure includes the
remediation command or system setting to check before installing the daemon.
Configuration and Lifecycle
| Command | Purpose |
|---|---|
| `sbh config show | set |
sbh update [flags] |
Check/apply updates with rollback, cache control, and backup management |
sbh install / sbh uninstall |
Install/remove service integration |
Dashboard
The sbh dashboard command opens a real-time TUI cockpit for monitoring disk pressure, reviewing scan candidates, inspecting policy decisions, and managing ballast pools. It replaces the legacy single-screen status display with a seven-screen navigation model, overlay system, and incident workflow shortcuts.
Launching
# Open the dashboard (requires a running daemon for live data)
sbh dashboard
# Start with a specific screen
sbh dashboard --start-screen ballast
# Use legacy single-screen mode (fallback)
sbh dashboard --legacy-dashboard
# Force new cockpit even if kill switch is set
sbh dashboard --new-dashboard
# Replay a captured activity log for a postmortem (no daemon needed):
# Space pauses/resumes, , and . step one event, Home/End seek; 10x log time
sbh dashboard --replay /var/lib/sbh/activity.jsonl --speed 10x --from 2026-08-30T10:00:00Z
Rollout controls (in config.toml):
[dashboard]
mode = "new" # "legacy" | "new" (default: "new")
kill_switch = false # Emergency fallback to legacy
Environment overrides: SBH_DASHBOARD_MODE, SBH_DASHBOARD_KILL_SWITCH.
Screens
| Key | Screen | Purpose |
|---|---|---|
1 |
Overview | Dense cockpit grid: pressure matrix, forecasts, decision pulse, hotlist, ballast, special-locations watch, counters |
2 |
Timeline | Event stream with severity filtering and detail drill-down |
3 |
Explainability | Decision evidence, posterior traces, factor contributions |
4 |
Candidates | Ranked scan results with score breakdown and veto visibility |
5 |
Ballast | Per-volume ballast inventory, release, and replenish controls |
6 |
LogSearch | JSONL/SQLite log viewing with search and filter |
7 |
Diagnostics | Daemon health, frame performance, thread status, RSS |
Keybindings
The tables are generated from the dashboard's keymap (sbh docs --section dashboard-keymap); a test resolves every global and overlay binding.
Navigation:
| Key | Where | Action |
|---|---|---|
1-7 |
Global | Jump directly to screen |
[ / ] |
Global | Previous / next screen |
Tab / Shift-Tab |
Overview | Cycle focused pane on Overview |
Enter / Space |
Overview | Open focused pane target screen |
b |
Global | Jump to Ballast screen |
Esc |
Global | Close overlay, then close open detail pane, then back, then quit |
q |
Global | Quit dashboard |
Ctrl-C |
Global | Immediate quit |
Overlays:
| Key | Where | Action |
|---|---|---|
? |
Global | Toggle help overlay (contextual keybinding reference) |
Ctrl-P or : |
Global | Open command palette (fuzzy search over every palette action) |
v |
Global | Toggle VOI scheduler overlay |
r |
Global | Force data refresh |
type, Backspace, Up/Down, Enter |
Command palette overlay | Filter, move through, and run the selected palette action |
j/k or arrows, Enter |
Incident playbook overlay | Move through the playbook and jump to the entry's screen |
Enter / Esc |
Confirmation overlay | Confirm or cancel the ballast action |
Incident shortcuts:
| Key | Where | Action |
|---|---|---|
! |
Global | Open incident triage playbook overlay |
x |
Global | Quick-release ballast (jumps to Ballast, selects a volume with files, opens the release confirmation) |
Screen-specific:
| Key | Where | Action |
|---|---|---|
j / k or arrows |
Timeline, Candidates, Explainability, Ballast | Cursor navigation |
Enter or Space |
Candidates, Explainability, Ballast | Toggle detail view |
Enter |
Timeline | Open the linked decision on Explainability |
d |
Candidates, Explainability, Ballast | Close detail panel |
f |
Timeline | Cycle severity filter |
Shift-F |
Timeline | Toggle follow mode (auto-scroll to latest) |
s |
Candidates | Cycle sort order (Score, Size, Age, Path) |
Shift-X |
Ballast | Release every available ballast file on the selected volume (confirmation) |
p |
Ballast | Replenish the released ballast files on the selected volume (confirmation) |
Shift-V |
Diagnostics | Toggle verbose frame metrics |
/ |
Log Search | Edit the search query inline (Enter runs it, Esc cancels); words match path/event/message, tokens type:, level:, path:, id:, since: |
n / p |
Log Search | Next / previous page of results |
c |
Log Search | Clear the query (newest entries again) |
Enter |
Log Search | Open the selected entry on the Timeline |
Replay scrubber:
| Key | Where | Action |
|---|---|---|
Space |
Replay (--replay) |
Pause / resume the replay |
, / . |
Replay (--replay) |
Step one event back / forward (pauses) |
Home / End |
Replay (--replay) |
Jump to the first / last event (pauses) |
To operate on a specific volume from the CLI, copy its exact absolute mount point from sbh ballast status. With the daemon running, sbh ballast release 2 --mount /data and sbh ballast replenish --mount /data use its control socket. With the daemon stopped, scoped release discovers the selected pool from the current configuration and releases its verified reserve directly, including when ballast.auto_provision is disabled. It checks the requested mount and daemon lock throughout the release. The JSON receipt for a direct release carries result.offline: true. Both routes report the number of files released and bytes freed, and a partially fulfilled request exits nonzero. Without --mount, these commands operate directly on the configured local pool.
For the configured pool, sbh ballast provision and sbh ballast replenish
exit 0 only when the reserve is complete, including when every file already
exists. A headroom floor that prevents growth exits 1 if no file was created;
creation failures exit 2 if no file was created. Either condition after some
files were created exits 4. JSON reports include the same exit_code and
error, alongside the actual creation and skipped counts.
If configuration is broken or unavailable, select the reserve directory explicitly:
sbh ballast release 2 --directory /data/.sbh/ballast
On Linux and macOS, this release-only route does not load configuration or
create a directory, lock, or ballast file. It uses the pool's existing
nonblocking lock and verifies every file's ballast header, index, original
size, full allocation, and identity. Damaged, sparse, hardlinked, symlinked,
and unrecognized files are retained; a ballast-looking filename alone grants
no permission. Directory aliases are supported and rechecked before each
removal. --directory cannot be combined with --mount or used to replenish.
Add --json for mode: "verified_directory", the actual released paths,
counts, errors, and an allocated-byte estimate. A partially completed request
exits 4; an empty verified reserve exits 1, and a refused or failed release
with no removals exits 2. A missing or busy pool lock never causes the
command to initialize or wait for another writer. Reported bytes remain an
estimate because filesystem snapshots can retain blocks after unlink.
To use that reserve before removing artifacts or quarantine recovery copies, pass its directory to emergency recovery:
sbh emergency /data/tmp --ballast-dir /data/.sbh/ballast --yes
--ballast-dir is repeatable and does not load configuration. Each explicit
pool must be on a filesystem selected by the recovery paths, although it may
sit outside their subtrees. The command verifies its original directory
identity and the selected root again after confirmation and before each
verified release. A missing or busy lock never blocks recovery or initializes
a pool. Other cleanup safety checks remain unchanged.
Reserve release stops as soon as that filesystem meets the requested byte and optional inode goals. When all selected paths have recovered, emergency exits before inspecting quarantine or scanning artifacts; already-recovered invocations retain all reserve and do not inspect the selected pool paths. Otherwise the normal quarantine and artifact stages continue. This option also requires the final recovery goals to be verified: an empty reserve and unmet goals return a nonzero exit status, and failures after successful releases retain those successes in the report and exit with partial success.
JSON reports reserve operations separately in ballast_release; artifact
counts remain separate. Each successful verified unlink also writes a
best-effort emergency_ballast_release completion receipt before the next
slot is considered. sbh log --type deletion and sbh explain can read those
receipts, and receipt_coverage reports their durability. Reserve bytes are
allocated-byte estimates, never a promise of observed filesystem free space.
When you confirm a ballast action (x, Shift-X, or p followed by Enter), the dashboard sends it to the running daemon for the selected mount. With the daemon stopped, the dashboard rereads the configuration and checks which reserve directory currently serves that mount. If it still matches the displayed directory, the dashboard applies the volume's configured reserve size and free-space floor. The dashboard shows the outcome in a notification.
Mouse support:
| Input | Action |
|---|---|
| Move | Hover-highlight Overview panes |
| Left click | Focus + open Overview pane target screen |
| Wheel on hotlist | Scroll candidate hotlist selection |
Command Palette
Press : or Ctrl-P to open the command palette. Type to fuzzy-search through 36 available actions including navigation, preference changes, overview pane controls, and incident commands. Press Enter to execute, Esc to cancel. Palette actions include:
All 36 actions, by family (id — title, shortcut where one exists):
action.*(3):action.refresh— Force refresh (r)action.jump_ballast— Jump to ballast quick-actions (b)action.quit— Quit dashboard (q)
action.overview.*(3):action.overview.focus-next— Overview pane focus next (Tab)action.overview.focus-prev— Overview pane focus previous (Shift-Tab)action.overview.open-focused— Open focused overview pane (Enter)
incident.*(3):incident.playbook— Show incident triage playbook (!)incident.quick-release— Quick-release ballast (incident) (x)incident.triage— Start incident triage (overview) (!)
nav.*(9):nav.overview— Go to Overview (1)nav.timeline— Go to Timeline (2)nav.explainability— Go to Explainability (3)nav.candidates— Go to Candidates (4)nav.ballast— Go to Ballast (5)nav.logs— Go to Log Search (6)nav.diagnostics— Go to Diagnostics (7)nav.prev— Previous screen ([)nav.next— Next screen (])
overlay.*(3):overlay.help— Open help overlay (?)overlay.voi— Open VOI overlay (v)overlay.palette— Open command palette (Ctrl-P / :)
pref.density.*(2):pref.density.compact— Set density: Compact (prefs)pref.density.comfortable— Set density: Comfortable (prefs)
pref.hints.*(3):pref.hints.full— Set hints: Full (prefs)pref.hints.minimal— Set hints: Minimal (prefs)pref.hints.off— Set hints: Off (prefs)
pref.reset.*(2):pref.reset.persisted— Reset session to persisted preferences (prefs)pref.reset.defaults— Revert preferences to defaults (prefs)
pref.start.*(8):pref.start.overview— Set default start screen: Overview (prefs)pref.start.timeline— Set default start screen: Timeline (prefs)pref.start.explainability— Set default start screen: Explainability (prefs)pref.start.candidates— Set default start screen: Candidates (prefs)pref.start.ballast— Set default start screen: Ballast (prefs)pref.start.logs— Set default start screen: Log Search (prefs)pref.start.diagnostics— Set default start screen: Diagnostics (prefs)pref.start.remember— Set default start screen: Remember Last (prefs)
Incident Workflows
During disk pressure events, the dashboard provides guided triage shortcuts. The incident system classifies pressure into four severity levels based on the daemon's pressure state:
| Severity | Trigger | Dashboard behavior |
|---|---|---|
| Normal | Green pressure | Standard operation, no hints |
| Elevated | Yellow/warning | Context-aware hints appear on relevant screens |
| High | Orange pressure | Alert banner + all triage hints visible |
| Critical | Red/emergency | Urgent alert banner + maximum triage guidance |
Triage playbook (! key): Opens a 7-entry guided playbook ordered by triage priority (entries marked High appear from Orange pressure on, the rest from Yellow; the list is generated from the code and a test keeps it so):
- Release ballast (Ballast screen, High)
- Check pressure overview (Overview screen)
- Review critical events (Timeline screen)
- Inspect deletion decisions (Explainability screen, High)
- Review pending candidates (Candidates screen, High)
- Check daemon health (Diagnostics screen)
- Search logs for errors (Log Search screen)
Use j/k to navigate entries and Enter to jump to the target screen.
Explainability reads the decision ledger. The Explainability screen lists the daemon's recent decisions from the SQLite decision_log (every keep, delete, review and veto with its factor breakdown, veto reason, policy mode and the ledger id sbh explain --id takes; a keep, review or veto that repeats the last verdict for the same artifact is recorded once a day, every delete each time); a database from before the ledger falls back to the deletions in the activity log and is marked PARTIAL with the reason. On the Timeline, an artifact_delete row names the decision that approved it (→ decision <id>, joined from the ledger for SQLite rows or carried by the JSONL line), and Enter on it opens that decision on the Explainability screen with its detail pane expanded.
Repeated-verdict suppression starts only after a successful SQLite decision write. Failed writes remain eligible for retry, and an intervening delete or changed verdict clears the older cached verdict. JSONL-only operation retains every observation so evidence and database recovery continue while SQLite is unavailable.
Quick-release (x key): One-keystroke shortcut that navigates to the Ballast screen and opens a release confirmation dialog. Reduces the typical pressure-triage path from 8 steps (legacy) to 1 keystroke.
Degraded Mode
When the daemon is unreachable (not running, state file missing, or permissions issue), the dashboard enters degraded mode:
- A
DEGRADEDindicator appears on the Overview screen. - Mount pressure data falls back to direct filesystem probes via
statvfs. - Telemetry screens (Timeline, Candidates, Explainability, Ballast) show stale or empty data.
- All navigation and overlay features remain functional.
Check Diagnostics (key 7) for daemon connection details and error counts.
Preferences
Dashboard preferences persist across sessions in ~/.config/sbh/preferences.json (--start-screen <screen> overrides the start screen for one session without touching the file):
- Start screen: Which screen to show on launch (
overview,timeline, etc.) - Density: Visual density mode (
compact,comfortable) - Hint verbosity: How much context to show (
off,minimal,full) - Contrast: High-contrast mode (respects
NO_COLORenvironment variable) - Motion: Reduced-motion mode (respects
REDUCE_MOTIONenvironment variable) - Startup help modal:
show_help_on_startdefaults tofalse(open help with?)
Configure via command palette (: then type pref) or directly in the preferences file.
Operator Docs
- Installer/update parity contract and security policy:
docs/installer-dx-parity-matrix.md - macOS Full Disk Access grant guide and screenshot refresh manifest:
docs/macos-full-disk-access.md,docs/images/macos/README.md - macOS operations guide:
docs/macos.md - macOS incident case study with the 264 GB trash staging dir, 9.8 GB Claude
cache, and active build-target footprint:
docs/macos-incident-case-study.md - Migrating from CleanMyMac, OmniDiskSweeper, DaisyDisk, or GrandPerspective:
docs/migrating-from-other-tools.md - Sample Mac configs for developer, creative, and shared LaunchDaemon machines:
docs/configs/ - macOS launchd troubleshooting guide:
docs/launchd-troubleshooting.md - Sacred path catalog and per-pattern safety reasoning:
docs/sacred-paths.md - Agent-session scratch inventory and its uncertainty/size semantics:
docs/agent-scratch.md - Dashboard/status baseline contract (pre-overhaul):
docs/dashboard-status-contract-baseline.md - Dashboard IA + navigation map (overhaul design baseline):
docs/dashboard-information-architecture.md - TUI acceptance gates + performance/error budgets:
docs/tui-acceptance-gates-and-budgets.md - Testing + log registration guide:
docs/testing-and-logging.md
For installer/update changes, use the parity matrix as the source of truth for flag semantics, integrity policy, rollback expectations, and release-gate tests.
Update Cache and Notice Controls
sbh update supports local metadata caching and explicit refresh controls:
update.metadata_cache_ttl_seconds: cache TTL for update metadata.update.metadata_cache_file: on-disk cache path (default in~/.local/share/sbh/).update.notices_enabled: enable/disable human follow-up prompts in update output.sbh update --refresh-cache: bypass cached metadata and fetch fresh release metadata.
Environment overrides are available for operator automation:
SBH_UPDATE_METADATA_CACHE_TTL_SECONDSSBH_UPDATE_METADATA_CACHE_FILESBH_UPDATE_NOTICES_ENABLEDSBH_UPDATE_ENABLEDSBH_UPDATE_OPT_OUT(turns bothupdate.enabledandupdate.notices_enabledoff)
Update Command Flags
| Flag | Description |
|---|---|
--check |
Check for updates without applying |
--version V |
Pin to a specific version tag (e.g. v0.2.1) |
--force |
Re-download even if already at the target version |
--rollback [ID] |
Roll back to the most recent backup, or a specific backup by ID |
--list-backups |
List available backup snapshots |
--prune N |
Remove old backups, keeping only the N most recent |
--max-backups N |
Maximum backups to retain (default: 5) |
--refresh-cache |
Bypass local metadata cache and fetch fresh release metadata |
--offline PATH |
Use an offline bundle manifest for airgapped updates |
--system |
Install to system-wide location (requires root) |
--user |
Install to user-local location (~/.local/bin) |
--dry-run |
Print what would be done without making changes |
--no-verify |
Skip artifact verification, including macOS trust checks (unsafe; debugging only) |
Useful operator checks:
# Inspect effective update policy/config
sbh config show --json | jq '.update'
# Force fresh metadata fetch for diagnostics
sbh update --check --refresh-cache --json
# Roll back to the previous version
sbh update --rollback
# List and prune old backups
sbh update --list-backups
sbh update --prune 3
Configuration Example
[scanner]
quarantine_enabled = true # Layer 7: Green and `sbh clean` candidates go to <root>/.sbh/quarantine (`sbh undo`)
quarantine_ttl_hours = 24
quarantine_max_bytes_pct = 5
engine = "v2" # default since v0.4.32; set "v1" to opt back into the legacy full-descent walker
event_source = "auto"
event_watch_budget = 8192
root_paths = ["/data/projects", "/tmp", "/dev/shm"]
include_user_temp_dir = true # macOS: also scan $TMPDIR (/var/folders/<x>/<y>/T); no-op elsewhere
cross_devices = false
protected_paths = ["/data/projects/production-*", "/home/*/critical-builds"]
[core]
strict_config = false # true: refuse to start when the file has keys no section declares
control_socket_enabled = true # serve control.sock beside state.json for `sbh daemon ping|scan-now|reload|shutdown`, `sbh policy`, live `sbh status`
[pressure]
green_min_free_pct = 35.0
yellow_min_free_pct = 20.0
orange_min_free_pct = 10.0
red_min_free_pct = 5.0
poll_interval_ms = 2000
[pressure.inodes]
enabled = true # finite inode capacity is independent of free bytes
green_min_free_pct = 10.0
yellow_min_free_pct = 5.0
orange_min_free_pct = 2.0
red_min_free_pct = 1.0
hysteresis_pct = 0.5
[ballast]
auto_provision = true # false: the daemon never builds the pool; use `sbh ballast provision`
file_count = 5
file_size_bytes = 1073741824 # 1 GiB per file
[ballast.overrides."/data"]
file_count = 10
file_size_bytes = 2147483648
[ballast.overrides."/tmp"]
enabled = false
[scoring]
location_weight = 0.25
name_weight = 0.25
age_weight = 0.20
size_weight = 0.15
structure_weight = 0.15
calibration_floor = 0.75
[policy]
initial_mode = "observe" # observe | canary | enforce
max_canary_deletes_per_hour = 5
kill_switch = false # true holds the daemon in fallback-safe (no deletions)
# What each fallback trigger does. Unset calibration_breach_action means
# "demote" unless initial_mode is "enforce" (then "advisory"); unset
# emergency_escalation means on for enforce fleets, off otherwise.
# calibration_breach_action = "demote" # demote | advisory
# canary_budget_action = "keep" # keep | demote
# serialization_failure_action = "demote" # demote | advisory
# auto_recover_to = "canary" # none | canary | previous
# emergency_escalation = false
[paths]
sqlite_db = "/var/lib/sbh/activity.sqlite3"
jsonl_log = "/var/lib/sbh/activity.jsonl"
[pressure.prediction]
enabled = true
action_horizon_minutes = 30.0
warning_horizon_minutes = 60.0
min_confidence = 0.7
min_samples = 5
imminent_danger_minutes = 5.0
critical_danger_minutes = 2.0
[pressure.controller]
# Per-mount PID gains (see "PID Pressure Controller"); the setpoint is green_min_free_pct.
kp = 0.25
ki = 0.08
kd = 0.02
kf = 0.8 # forecast feedforward gain
integral_cap = 100.0
hysteresis_pct = 1.0
reference_total_bytes = 1099511627776 # 1 TiB: kp applies unscaled here
kp_scale_min = 0.5
kp_scale_max = 2.0
[scheduler]
enabled = true
scan_budget_per_interval = 5
io_cost_weight = 0.1
forecast_error_threshold = 0.5
fallback_trigger_windows = 3
recovery_trigger_windows = 5
[notifications]
enabled = true
channels = ["journal", "file"] # macOS default adds "desktop"
min_notify_interval_secs = 60
urgent_notify_interval_secs = 300
[notifications.desktop]
enabled = false # macOS default: true
min_level = "orange" # macOS default: "critical"
[notifications.webhook]
enabled = false
url = ""
min_level = "red"
template = '{"text": "sbh: ${SUMMARY}"}'
[notifications.file]
path = "~/.local/share/sbh/notifications.jsonl"
[notifications.journal]
min_level = "warning"
[dashboard]
mode = "new" # "legacy" | "new"
kill_switch = false
[system_tuning]
# Kernel writeback (dirty-page) tuning. Linux-only; macOS treats it as not-applicable.
writeback_enabled = true
writeback_auto_apply_on_install = true # apply + persist during `sbh install` when run as root
writeback_target_drain_secs = 1.0 # size dirty_background_bytes to drain in ~1s
writeback_hard_ratio = 4 # dirty_bytes = 4 × dirty_background_bytes
writeback_min_background_bytes = 268435456 # 256 MiB floor
writeback_max_background_bytes = 2147483648 # 2 GiB ceiling
writeback_benchmark_enabled = true # measure device bandwidth on --apply
writeback_benchmark_bytes = 100663296 # 96 MiB micro-benchmark budget
writeback_pool_warn_bytes = 4294967296 # doctor WARN above ~4 GiB effective dirty pool
writeback_sysctl_path = "/etc/sysctl.d/99-sbh-writeback.conf"
Every section rejects keys it does not declare. sbh config validate lists unknown keys with a did-you-mean (legacy names such as [monitor], [scoring.weights], per_volume_file_size_mb or policy.mode get their replacement spelled out), the daemon warns about them at startup, and sbh config validate --strict or [core] strict_config = true turns them into errors. Path-typed values expand a leading ~ or $HOME. This example is parsed by the test suite, so it cannot drift from the code.
Environment Variable Overrides
Operator automation can override configuration via environment variables. These take precedence over config file values. The table is generated from the binary's own registry (sbh docs --section env-vars; a test keeps the registry equal to the variables the code reads); a config override names the config.toml key it sets.
| Variable | Area | Controls |
|---|---|---|
SBH_CONFIG |
paths | Config file path when --config is not given |
SBH_CONFIG_PATH |
service | Config file path the launchd plist hands the daemon |
SBH_USE_XDG_PATHS |
paths | Use XDG user paths (~/.config/sbh, ~/.local/share/sbh) instead of the system paths |
SBH_OUTPUT_FORMAT |
output | human or json when neither --json nor a terminal decides |
SBH_PREFERENCES_FILE |
dashboard | Dashboard preferences file (default ~/.config/sbh/preferences.json) |
SBH_DASHBOARD_MODE |
config override | dashboard.mode (legacy or new) |
SBH_DASHBOARD_KILL_SWITCH |
config override | dashboard.kill_switch (force the live status view) |
SBH_LAUNCHD_LABEL |
service | launchd job label override for the macOS service |
SBH_SYSTEMD_UNIT_DIR |
service | Directory the systemd unit is written to and read from |
SBH_ACTIVE_LEASE_TOKEN |
service | Renewal token sbh lease run hands the leased command (lease renew reads it) |
SBH_ACTIVE_LEASE_TARGET |
service | Leased target sbh lease run hands the leased command (default for lease status/renew) |
SBH_MACOS_QUERY_FOUNDATION_PURGEABLE |
platform | 0/false/no/off stops the macOS purgeable-space query to Foundation; the estimate then comes from the APFS container inventory |
SBH_BEHAVIOR_PRESET |
config override | pressure.behavior_preset |
SBH_POLICY_KILL_SWITCH |
config override | policy.kill_switch |
SBH_PREDICTION_ENABLED |
config override | prediction.enabled |
SBH_PREDICTION_MIN_SAMPLES |
config override | prediction.min_samples |
SBH_PREDICTION_MIN_CONFIDENCE |
config override | prediction.min_confidence |
SBH_PREDICTION_WARNING_HORIZON_MINUTES |
config override | prediction.warning_horizon_minutes |
SBH_PREDICTION_ACTION_HORIZON_MINUTES |
config override | prediction.action_horizon_minutes |
SBH_PREDICTION_IMMINENT_DANGER_MINUTES |
config override | prediction.imminent_danger_minutes |
SBH_PREDICTION_CRITICAL_DANGER_MINUTES |
config override | prediction.critical_danger_minutes |
SBH_PRESSURE_POLL_INTERVAL_MS |
config override | pressure.poll_interval_ms |
SBH_PRESSURE_GREEN_MIN_FREE_PCT |
config override | pressure.green_min_free_pct |
SBH_PRESSURE_YELLOW_MIN_FREE_PCT |
config override | pressure.yellow_min_free_pct |
SBH_PRESSURE_ORANGE_MIN_FREE_PCT |
config override | pressure.orange_min_free_pct |
SBH_PRESSURE_RED_MIN_FREE_PCT |
config override | pressure.red_min_free_pct |
SBH_PRESSURE_BEHAVIOR_HYSTERESIS_SECS |
config override | pressure.behavior_hysteresis_secs |
SBH_SCANNER_ALLOW_SOURCE_TREE_ROOTS |
config override | scanner.allow_source_tree_roots (opt in to scan roots that contain Git work trees) |
SBH_SCANNER_ENGINE |
config override | scanner.engine |
SBH_SCANNER_EVENT_SOURCE |
config override | scanner.event_source |
SBH_SCANNER_EVENT_WATCH_BUDGET |
config override | scanner.event_watch_budget |
SBH_SCANNER_DRY_RUN |
config override | scanner.dry_run |
SBH_SCANNER_CROSS_DEVICES |
config override | scanner.cross_devices |
SBH_SCANNER_FOLLOW_SYMLINKS |
config override | scanner.follow_symlinks |
SBH_SCANNER_MAX_DEPTH |
config override | scanner.max_depth |
SBH_SCANNER_PARALLELISM |
config override | scanner.parallelism |
SBH_SCANNER_PRESCAN_TIME_BUDGET_SECS |
config override | scanner.prescan_time_budget_secs |
SBH_SCANNER_MAX_DELETE_BATCH |
config override | scanner.max_delete_batch |
SBH_SCANNER_MIN_FILE_AGE_MINUTES |
config override | scanner.min_file_age_minutes |
SBH_SCANNER_MIN_RESCAN_INTERVAL_SECS |
config override | scanner.min_rescan_interval_secs |
SBH_SCANNER_MAX_SCAN_DUTY_CYCLE_PCT |
config override | scanner.max_scan_duty_cycle_pct |
SBH_SCANNER_ACTIVE_REFERENCE_CACHE_TTL_SECS |
config override | scanner.active_reference_cache_ttl_secs |
SBH_SCANNER_ACTIVE_REFERENCE_MIN_SIZE_BYTES |
config override | scanner.active_reference_min_size_bytes |
SBH_SCANNER_REPEAT_DELETION_BASE_COOLDOWN_SECS |
config override | scanner.repeat_deletion_base_cooldown_secs |
SBH_SCANNER_REPEAT_DELETION_MAX_COOLDOWN_SECS |
config override | scanner.repeat_deletion_max_cooldown_secs |
SBH_SCORING_LOCATION_WEIGHT |
config override | scoring.location_weight |
SBH_SCORING_NAME_WEIGHT |
config override | scoring.name_weight |
SBH_SCORING_AGE_WEIGHT |
config override | scoring.age_weight |
SBH_SCORING_SIZE_WEIGHT |
config override | scoring.size_weight |
SBH_SCORING_STRUCTURE_WEIGHT |
config override | scoring.structure_weight |
SBH_SCORING_MIN_SCORE |
config override | scoring.min_score |
SBH_SCORING_CALIBRATION_FLOOR |
config override | scoring.calibration_floor |
SBH_SCORING_POSTERIOR_FLOOR_DEFINITE |
config override | scoring.posterior_floor_definite |
SBH_SCORING_DEFINITE_FLOOR_MAINTENANCE_IDLE_HOURS |
config override | scoring.definite_floor_maintenance_idle_hours |
SBH_SCORING_FALSE_POSITIVE_LOSS |
config override | scoring.false_positive_loss |
SBH_SCORING_FALSE_NEGATIVE_LOSS |
config override | scoring.false_negative_loss |
SBH_SYSTEM_TUNING_WRITEBACK_ENABLED |
config override | system_tuning.writeback.enabled |
SBH_SYSTEM_TUNING_WRITEBACK_AUTO_APPLY_ON_INSTALL |
config override | system_tuning.writeback.auto_apply_on_install |
SBH_SYSTEM_TUNING_WRITEBACK_TARGET_DRAIN_SECS |
config override | system_tuning.writeback.target_drain_secs |
SBH_SYSTEM_TUNING_WRITEBACK_HARD_RATIO |
config override | system_tuning.writeback.hard_ratio |
SBH_SYSTEM_TUNING_WRITEBACK_MIN_BACKGROUND_BYTES |
config override | system_tuning.writeback.min_background_bytes |
SBH_SYSTEM_TUNING_WRITEBACK_MAX_BACKGROUND_BYTES |
config override | system_tuning.writeback.max_background_bytes |
SBH_SYSTEM_TUNING_WRITEBACK_BENCHMARK_ENABLED |
config override | system_tuning.writeback.benchmark_enabled |
SBH_SYSTEM_TUNING_WRITEBACK_BENCHMARK_BYTES |
config override | system_tuning.writeback.benchmark_bytes |
SBH_SYSTEM_TUNING_WRITEBACK_POOL_WARN_BYTES |
config override | system_tuning.writeback.pool_warn_bytes |
SBH_TELEMETRY_CPU_BUDGET_PCT |
config override | telemetry.cpu_budget_pct |
SBH_TELEMETRY_CPU_BUDGET_BURST_SECS |
config override | telemetry.cpu_budget_burst_secs |
SBH_TELEMETRY_FS_CACHE_TTL_MS |
config override | telemetry.fs_cache_ttl_ms |
SBH_TELEMETRY_EWMA_BASE_ALPHA |
config override | telemetry.ewma_base_alpha |
SBH_TELEMETRY_EWMA_MIN_ALPHA |
config override | telemetry.ewma_min_alpha |
SBH_TELEMETRY_EWMA_MAX_ALPHA |
config override | telemetry.ewma_max_alpha |
SBH_TELEMETRY_EWMA_MIN_SAMPLES |
config override | telemetry.ewma_min_samples |
SBH_TELEMETRY_DAEMON_RSS_WARNING_BYTES |
config override | telemetry.daemon_rss_warning_bytes |
SBH_TELEMETRY_DAEMON_RSS_HARD_LIMIT_BYTES |
config override | telemetry.daemon_rss_hard_limit_bytes |
SBH_UPDATE_ENABLED |
config override | update.enabled |
SBH_UPDATE_OPT_OUT |
release | A true value turns update.enabled and update.notices_enabled off |
SBH_UPDATE_METADATA_CACHE_TTL_SECONDS |
config override | update.metadata_cache_ttl_seconds |
SBH_UPDATE_METADATA_CACHE_FILE |
config override | update.metadata_cache_file |
SBH_UPDATE_NOTICES_ENABLED |
config override | update.notices_enabled |
SBH_RELEASE_API_BASE |
release | Point the release API at another server (honored only under SBH_TEST_MODE=1) |
SBH_RELEASE_DOWNLOAD_BASE |
release | Point release downloads at another server (honored only under SBH_TEST_MODE=1) |
SBH_TEST_MODE |
test | 1 enables the test overlays (injected filesystem stats, release server overrides); the daemon refuses to start under a service manager in this mode |
SBH_TEST_FS_STATS |
test | Injected per-mount filesystem statistics table (test mode) |
SBH_ARTIFACT_DIR |
test | Where the dashboard e2e artifact bundles are written |
SBH_TUI_ARTIFACT_DIR |
test | Where the TUI test artifacts are written |
SBH_EXECUTABLE_REPLACEMENT_PROBE |
test | Binary the Linux self-replacement test rewrites in place to check the service restart path (#35) |
SBH_UPDATE_HANDOFF_CONTEXT_PROBE |
test | Mode (update or another value) the update-handoff test runs its child process in, to check that a command's install-path intent is captured once (#35) |
SBH_TUI_ARTIFACT_FRAMES |
test | Include rendered frame text in the TUI test artifacts |
SBH_TEST_AGENT_SCRATCH_FIFO_CHILD |
test | Set in the child process the agent-scratch FIFO-marker test re-runs itself in, so a marker read that blocks cannot hang the suite |
SBH_TEST_GUIDED_CONFIG_DESTINATION |
test | Fixture directory for the isolated installer test that checks relative config destinations and CLI-over-environment precedence |
SBH_TEST_EXPLICIT_INSTALL_CONFIG |
test | Fixture directory for the isolated systemd test that publishes a unit with an explicit config path |
SBH_TEST_SYSTEMCTL_CALLS |
test | Fixture log where the isolated systemd installer test records its stub systemctl calls |
Architecture
Pressure Inputs
fs stats + special location probes
|
v
EWMA Forecaster --> PID Controller --> Action Planner
| |
| v
| Scan Scheduler (VOI-aware)
| |
v v
Parallel Walker -> Pattern Registry
-> Deterministic Scoring
-> Policy Engine (shadow/canary/enforce)
-> Guardrails (conformal/e-process)
-> Ranked Deletion + Ballast Release
|
v
Dual Logging (SQLite + JSONL)
Evidence Ledger + Explain API
How It Works
What follows covers the algorithms, control theory, safety mechanisms, and design rationale behind each component.
The Daemon Loop
The daemon runs four primary threads connected by bounded channels:
- Monitor thread polls filesystem stats at a configurable interval, feeds them to the EWMA forecaster and PID controller, and emits a
ScanRequestwhen pressure warrants action. - Scanner thread receives scan requests, selects
scanner.engine = "v2"(the default since v0.4.32) or"v1", scores discovered artifacts, and produces a rankedDeletionBatch. v2 adds opaque-tree pruning, a persistent candidate index, filesystem event invalidation where available, and pressure-gated reconciliation; v1 is the legacy full-descent directory walker kept as an opt-out. - Executor thread receives deletion batches and executes them through the circuit breaker and pre-flight safety checks.
- Logger thread receives activity events and writes them to both SQLite and JSONL backends.
Channels use bounded capacities (scanner: 2, executor: 64, logger: 1024) to provide natural backpressure.
Filesystem pressure observations run on bounded background workers. Capacity, inode
availability, mount ownership, and RAM-backed classification arrive together,
with the original probe-start time and mount identity. The monitor reads fresh
completed observations without waiting for native filesystem calls. The
16-worker budget reserves one slot for /; mount inventory and optional APFS
metadata refresh use independent jobs. Catalog discovery has a separate
four-worker budget, so reading user homes or cache directories cannot block
pressure-response dispatch. A blocked worker keeps its slot across reloads;
reloading cannot create an unbounded succession of replacement threads.
RAM log-fallback eligibility also runs on a bounded worker. Pending or expired
guard evidence keeps mirroring disabled, and the logger retains its separate
safety checks before writing.
macOS Full Disk Access diagnostics use one retained background worker at startup
and on five-minute refreshes. A stalled home or Mail directory cannot delay
pressure checks; diagnostic results older than ten minutes are discarded.
Missing or expired observations provide no authority for automatic maintenance,
predictive scans, or cross-device fallback roots. Healthy observed roots can
still be dispatched while a peer is unavailable. An explicit SIGUSR1 scan
keeps its complete configured scope pending until every root is observed.
Uncovered-volume alerts retry
pending samples before their freshness window expires. On macOS, pressure
sampling uses native statfs and memory-cached APFS geometry; optional metadata
refresh cannot hold up the sample, and cached free space cannot exceed current
native headroom. These bounds cover pressure observations and automatic scan
planning.
Startup and reload discovery run as a separate, read-only background job.
Readiness waits for a healthy pressure observation and the control workers,
without waiting for optional mount inventories or ballast scans. A complete
plan is adopted only for the current configuration, within its freshness
deadline, and only if no intervening release or refill changed the active pool
inventory. An unavailable volume can keep the whole optional plan pending;
it cannot stall monitoring of healthy roots. state.json.discovery reports
pending discovery, reload progress and errors. Saved release history survives
this pending window, but its old file and byte counts remain unknown until new
inventory is verified.
During startup, one additional retained worker can open an existing configured ballast directory independently of the complete layout plan. It checks the directory, native filesystem owner and current inventory, restores only matching physical release history, and makes that reserve available for pressure relief. It creates no directories or files and performs no legacy-reserve or orphan discovery. A fresh native observation can route a bind mount of the same block device to that reserve. The complete plan later preserves its release credit, cooldowns and effectiveness measurements; it cannot treat the released files as a new initial-provisioning allowance. Missing, disabled, RAM-backed, network or read-only configured pools do not gain this early release path.
Configuration loading has its own retained worker, so a blocked discovery job cannot prevent a newer policy from being read and applied. While a new policy or pool plan is pending, new ballast allocations are deferred. Previously verified pools remain available for release unless the new configuration disables or redirects them. Blocked jobs keep their slots across reloads. Rediscovery also waits for occupied allocation and release workers to exit, including cancelled workers, so late native work cannot invalidate a replacement inventory after it was captured.
Automatic ballast release runs on at most two retained workers, with one worker per physical pool. A blocked filesystem keeps its slot; the monitor can still sample other filesystems and admit release on another pool. Ordinary pressure, imminent forecasts and write recovery use the same path. Each unlink renews permission against the original filesystem evidence, current policy, dry-run and shutdown state. A weaker pressure request cancels an older release-all attempt. Read-only mount aliases can reach their writable same-device pool, and Observe mode still permits release of sacrificial ballast.
An active release gets up to two seconds before new scans on its own pool; renewal and retries do not extend that first chance. Queued requests do not hold scans. Refill waits for that pool's release worker to exit. Only confirmed removals update release totals, and only complete, current receipts replace native inventory. Confirmed removals retain their graduated release credit even if a post-release inventory read fails. A receipt superseded by reload or a filesystem change remains audit evidence without replacing newer state. If post-release inventory I/O stalls, its receipt remains pending. Manual daemon ballast controls report a busy pool while an automatic worker finishes.
Required configuration, liveness and persisted-state access during initialization, state-file writes, standalone emergency commands and explicit filesystem mutations still include synchronous operations.
Write-recovery probes use at most four retained workers. Pending results keep only the affected mounts in Recovery. Each new probe write requires a fresh native mount and cleanup-scope binding plus a live permission deadline; expiry, reload, missing samples and newer failure incidents discard earlier success.
An ENOSPC state-write failure gets a separate bounded inode diagnostic started
after the failure. Only fresh evidence from the actual destination can preserve
inode-relief policy; a stalled diagnostic records an unknown result by its
deadline, and reloads cannot reuse a late result from the previous policy.
When the scanner queue fills, automatic observations can refresh a matching scope or replace weaker automatic work. Accepted operator and configuration requests stay queued, and distinct emergencies of equal severity retain their turns. Refreshes preserve queue position without merging cleanup paths or byte, inode and swap allowances. Among equally pressured mounts, a mount that could not obtain a queue slot runs ahead of repeatedly admitted peers. A rejected catalog request remains due for retry instead of consuming its scan epoch.
An empty scan's idle backoff belongs to the resource it examined. If a mount switches between byte, inode, and swap pressure, its next actionable observation wakes cleanup even when the reported pressure level stays the same. A delayed empty result from an earlier resource episode cannot park the mount again. Repeated empty scans for the same resource still use the normal backoff.
If the logger falls behind, a dropped-event counter is incremented and reported periodically rather than blocking the monitor loop.
Each worker thread has panic recovery: up to 3 respawns within a 5-minute window before the daemon shuts down. Thread health is tracked by the self-monitor, which also watches RSS memory usage and state-file write success.
The Control Loop: EWMA Forecasting + PID Controller
The pressure response system has two parts: an EWMA forecaster that predicts when the disk will run out, and a PID controller that determines how aggressively to respond.
EWMA Rate Estimation
The EWMA (Exponentially Weighted Moving Average) estimator tracks the rate of free-space change in bytes per second, with an adaptive smoothing factor that responds to burstiness:
burstiness = |instantaneous_rate - ewma_rate| / (|ewma_rate| + 1.0)
damping = 1.0 / (1.0 + 2.0 * burstiness)
alpha = clamp(base_alpha * damping, 0.10, 0.75)
When disk consumption is steady, burstiness is low, damping is near 1.0, and alpha stays near the base value (0.3), producing smooth rate estimates. When a sudden burst hits (e.g., a large cargo build starts), burstiness spikes, damping decreases alpha toward its floor (0.10), and the estimator becomes stickier so transient spikes do not cause wild overreactions.
The estimator also tracks acceleration for trend classification. Runway uses a linear projection; a brief change in rate is not extrapolated as acceleration over the entire forecast:
time_to_exhaustion = available_bytes / forecast_rate
time_to_red = max(available_bytes - red_threshold_bytes, 0) / forecast_rate
red_threshold_bytes is the effective orange_min_free_pct /
orange_min_free_bytes boundary where the filesystem enters Red. The
red_min_* settings define the later boundary into Critical. Forecasts,
controller feedforward, and crossing calibration all use the Red-entry boundary.
For distant projections, a bounded history measures signed net consumption over five to fifteen minutes of elapsed time. Space released by a build offsets its allocations, and faster polling does not shorten that observation window. A new writer, recovery, or stopped writer replaces the old rate after three consecutive twenty-second windows agree. During warmup, after a collection gap, or when the immediate estimate puts a pressure boundary within five minutes, the projection keeps at least the immediate EWMA response. When that rate agrees with the measured windows, a confirmed writer retains its corroboration as the boundary approaches, so an older, slower burst median cannot cancel cleanup or ballast rescue. A spike outside their agreement bound keeps the existing predictive burst checks. These projections retain the normal confidence and sample gates; the measured evidence applies at any free-space percentage.
state.json keeps the immediate rate in bytes_per_sec and publishes the
corroborated projection rate separately as forecast_rate_bytes_per_sec when
that history is in use. Human status names both rates, and forecast log lines include
forecast_rate. A nonpositive projection rate means no finite exhaustion forecast.
A confidence metric combines sample count adequacy (50% weight), residual tracking (20% weight), and prediction stability (30% weight). When confidence drops below 0.2 or fewer than 3 samples exist, the estimator enters fallback mode and reports uncertainty rather than potentially misleading predictions.
Trend classification uses fixed thresholds: recovering (rate < -1.0 bytes/sec), accelerating (accel > 64.0 bytes/sec^2), decelerating (accel < -64.0 bytes/sec^2), or stable.
PID Pressure Controller
The PID controller converts the gap between target free space and actual free space into an urgency signal (0.0 to 1.0) that drives scan frequency, deletion batch sizes, and ballast release counts.
There is one controller per mount. Default gains ([pressure.controller]): Kp=0.25, Ki=0.08, Kd=0.02, Kf=0.8, integral cap 100, hysteresis 1 point. The setpoint is green_min_free_pct (20% by default). The block below is monitor::pid::FORMULAS, and a test keeps this copy identical to the code:
error = target_free_pct - current_free_pct
kp_m = Kp * clamp(sqrt(total_bytes / reference_total_bytes), kp_scale_min, kp_scale_max)
integral = clamp(integral + error * dt, -integral_cap, integral_cap) # frozen while the mount cannot act
derivative = 0.3 * (error - last_error) / dt + 0.7 * last_derivative
feedforward = Kf * clamp(1 - seconds_to_red / action_horizon_secs, 0, 1) # 0 without a forecast
raw = kp_m * error + Ki * integral + Kd * derivative + feedforward
urgency = 1 - exp(-max(0, raw))
Three things make this a controller that cannot wind up while it has no actuator:
- Capacity gain scheduling. Errors are in percent, and one point is 55 GiB on a 5.5 TB pool but 1 GiB on a small root.
Kpis scaled bysqrt(total / reference_total_bytes)(reference 1 TiB), clamped to [0.5, 2] xKp, so large volumes answer a one-point error harder and tiny ones softer. - Forecast feedforward. The EWMA forecast enters as a smooth term that grows from 0 at the action horizon (
pressure.prediction.action_horizon_minutes, 30 by default) toKfat zero seconds-to-red, instead of stepped urgency boosts. Urgency is monotone in the forecast: a nearer red never lowers it. - Anti-windup on actionability. The integral is frozen while the mount's controller is observe-only (no root path on the device), idle after an empty pass, or recovering from a read-only or full filesystem. A mount sbh cannot act on no longer accumulates a Red urgency it could do nothing with; the integral also resets on every level change.
The 1 - exp(-x) transform maps the raw output to a 0-1 range with a natural saturation curve: small errors produce proportionally small urgency, while large errors quickly approach 1.0 without overshooting.
Pressure levels are defined by free-space thresholds; the table is generated from PressureConfig::default() and the controller's RESPONSE_TABLE by sbh docs --render README.md:
| Level | Default free % | Scan interval | Ballast release | Max delete batch |
|---|---|---|---|---|
| Green | > 20% | base interval | 0 files | 2, 5 above urgency 0.5, 10 above urgency 0.8 |
| Yellow | 14-20% | base/2 (at least 500 ms) | 0-1 files (urgency > 0.55) | 5 |
| Orange | 10-14% | base/4 (at least 250 ms) | 1-3 files (urgency > 0.75) | 10 |
| Red | 6-10% | base/8 (at least 125 ms) | 3-5 files (urgency > 0.85) | 20 + 60 x max(urgency - 0.5, 0) |
| Critical | < 6% | 100 ms | 10 files | 40 + 120 x max(urgency - 0.5, 0) |
Critical is any free space below the Red threshold (red_min_free_pct). At Red and Critical levels, delete batch sizes scale dynamically with PID urgency output, allowing the system to be more aggressive when pressure is rising rapidly versus slowly. At Critical, the controller issues maximum-urgency responses regardless of PID output. Whether a level's response actually runs also depends on the memory-state behavior matrix in src/daemon/policy.rs.
When predictive forecasting is enabled, the time-to-red estimate feeds the controller's feedforward term: a forecast inside the action horizon (default 30 minutes) raises urgency smoothly, up to Kf at zero seconds, even while current pressure is only Yellow. This lets the system start scanning and releasing ballast before pressure actually reaches dangerous levels.
Artifact Scoring: Decision-Theoretic Ranking
Every file and directory discovered during a scan receives a composite score from five weighted factors, then passes through a Bayesian decision-theoretic framework that explicitly models the costs of wrong decisions.
The Five Scoring Factors
Location (default weight 0.25) rates directories by how likely they are to contain safely deletable artifacts:
| Path pattern | Score |
|---|---|
/tmp, /private/tmp, /var/tmp, /data/tmp, /dev/shm |
0.95 |
/data/projects/*/.tmp_* patterns |
0.90 |
/Library/Developer/Xcode/DerivedData/* |
0.90 |
/data/projects/*/.target (hidden build dirs) |
0.85 |
macOS Application Support caches (/Library/Application Support/.../Cache*) |
0.82 |
/data/projects/*/target (Rust/Java build dirs) |
0.80 |
*/.cache/* |
0.60 |
Generic */projects/* |
0.40 |
| Default unknown | 0.30 |
*/documents/* |
0.10 |
System paths (/, /bin, /lib, /usr) |
0.00 |
Name (default weight 0.25) matches against a pattern registry of known artifact types: .o files, node_modules, __pycache__, .class files, .wasm intermediates, and hundreds of others. Each pattern carries a confidence score.
Age (default weight 0.2) uses an effective age timestamp that differs by entry type. For files, the modification time (mtime) is used because content change is what matters. For directories, the creation (birth) time is preferred when available, because directory mtime updates whenever any direct child is added or removed — making active build caches like target/ appear perpetually young when mtime is used alone. Birth time reflects when the directory was actually created and is stable across rebuilds. If birth time is unavailable, mtime is used as a fallback.
The age-to-score curve is monotonic, capping at 1.0 (older artifacts are always at least as likely to be abandoned as younger ones):
| Age | Score | Rationale |
|---|---|---|
| < 30 min | 0.00 | Likely in active use |
| 30 min - 2 hours | 0.20 | Possibly still needed |
| 2 - 4 hours | 0.70 | Probably stale |
| >= 4 hours | 1.00 | Peak staleness; older artifacts remain fully eligible |
Size (default weight 0.15) favors larger artifacts (more space reclaimed per deletion) with diminishing returns at extremes:
| Size | Score |
|---|---|
| < 1 MiB | 0.05 |
| 1 - 10 MiB | 0.20 |
| 10 - 100 MiB | 0.40 |
| 100 MiB - 1 GiB | 0.70 |
| 1 - 10 GiB | 1.00 |
| 10 - 50 GiB | 0.90 |
| > 50 GiB | 0.75 |
Structure (default weight 0.15) examines directory contents for signals: presence of .git/ (score 0.0, never delete), Cargo fingerprint/incremental directories (0.95), deps + build directories together (0.85), or mostly object files (0.90).
Pressure Multiplier
The composite score is scaled by current urgency to make the system more aggressive under pressure:
urgency <= 0.3: multiplier = 1.0 + urgency (range: 1.0 - 1.3)
urgency <= 0.5: multiplier = 1.3 + (urgency - 0.3) (range: 1.3 - 1.5)
urgency <= 0.8: multiplier = 1.5 + (urgency - 0.5) * 1.67 (range: 1.5 - 2.0)
urgency > 0.8: multiplier = 2.0 + (urgency - 0.8) * 5.0 (range: 2.0 - 3.0)
At Green-level pressure (urgency ~0.1), scores are barely inflated. At Critical (urgency ~1.0), scores are tripled, causing marginal candidates to cross the deletion threshold.
Bayesian Decision Framework
The scoring engine does not use the composite score directly as a delete/keep threshold. Instead, it models the decision as a Bayesian expected-loss problem.
First, the composite score is converted to a posterior probability that the artifact is abandoned (no longer needed by any running process):
scaled = min(total_score / 1.5, 1.0)
logit = 3.5 * (scaled - 0.5) + 2.0 * (confidence - 0.5)
posterior_abandoned = sigmoid(logit)
Then the expected loss of each action is computed:
- Loss of keeping an abandoned artifact:
posterior * false_negative_loss(default: 30) - Loss of deleting a useful artifact:
(1 - posterior) * false_positive_loss(default: 50)
The asymmetric defaults (50 vs. 30) encode the design principle that wrongly deleting something useful is costlier than failing to clean up something stale, while remaining aggressive enough to actually reclaim space under pressure.
These base losses are then adjusted by epistemic uncertainty, which combines entropy of the posterior with calibration confidence:
entropy = -(p * ln(p) + (1-p) * ln(1-p)) / ln(2)
uncertainty = 0.65 * entropy + 0.35 * (1 - calibration)
High uncertainty inflates the deletion loss more than the keep loss, making the system conservative when it isn't confident. The final decision follows a threshold policy: delete only when the keep-loss significantly exceeds the delete-loss and the posterior exceeds a minimum threshold that scales with uncertainty.
When uncertainty is too high to decide, the artifact is placed in a Review category rather than being silently kept or deleted. Review items are surfaced in sbh scan output and dashboard displays.
Batch Planning
When a byte target is known (sbh clean --target-free N, or the bytes a pressured mount needs to return to Green), the executor no longer takes the top-N candidates by composite score. The batch planner (src/scanner/planner.rs) orders the approved candidates by expected reclaim per unit of expected loss ((1 - posterior) * false_positive_loss) and takes them while the level's batch size, the risk budget and the target allow, stopping as soon as the target is met: a 40 GiB candidate at posterior 0.85 comes before a 200 MiB one at 0.95. The risk budget is scoring.batch_risk_budget_by_level times one false-positive loss (Green 1x, Yellow 2x, Orange 5x, Red 10x, Critical unbounded). Review candidates are never planned outside sbh emergency, ties break on bytes then path so identical inputs plan identically, and every batch logs [SBH-PLANNER] level=.. target_bytes=.. planned_bytes=.. risk_budget=.. risk_used=.. chosen=n skipped_for_budget=m top_n_risk=.. plus a planner activity event carrying the plan. sbh clean --json and sbh scan --json carry the plan as a plan block, and sbh explain --id quotes it: "chosen 1st: 40.0 GiB at posterior 0.85 (loss 7.5 of budget 250.0) because it reaches the target with 50% of the risk the top-scored set would use".
Manual cleanup plans each physical filesystem independently. Free space on a
healthy filesystem cannot satisfy another filesystem's target or consume its
risk budget. Mount aliases share a target and budget, and --max-items remains
a limit for the whole command, with pressured filesystems considered first.
The JSON plans_by_mount array provides these individual plans beside the
aggregate plan. Unknown or changed filesystem ownership refuses planning;
if capacity becomes unavailable during target-driven execution, the affected
candidate is held with pressure_unavailable until a later invocation can
confirm its headroom.
After sbh clean --target-free N, the human report and JSON recovery_goals
show measured available space at each requested root. A cross-device plan also
checks the mount points it included. The planner's byte estimate and the
filesystem's final reading can differ, particularly when cleanup moves an
artifact into quarantine on the same disk.
For scripts, sbh clean /path --target-free 15 --require-target --yes --json
requires a fresh observation that every target was reached. Exit 1 means a
target remained unmet with no completed cleanup. Exit 2 means a target could
not be verified before any cleanup completed. Exit 4 reports partial completion
when work completed and a target is unmet or unverified. The ordinary
quarantine setting still applies. Use --no-quarantine only when permanent
removal is intended. Omitting --require-target keeps a best-effort cleanup's
usual exit status and still reports the measurements.
Use sbh clean /data/tmp --target-free-inodes 10 --no-quarantine --dry-run --json to preview inode recovery on a filesystem with finite inode accounting. A live inode-targeted cleanup verifies the available inode count on each selected filesystem. Combine --target-free-inodes with --target-free when both resources are scarce. The planner admits eligible artifacts within the configured risk and item budgets and checks the live counters before each action. In quarantine mode, an inode-targeted run reports the shortage and leaves the files in place. When the selected roots cover the relevant mounts, it reports this directly without walking the artifact tree or opening the decision ledger. A same-filesystem move retains their inodes and can consume more for quarantine metadata. Use --no-quarantine on a live run to authorize permanent removal. If one filesystem cannot supply usable inode counters, its plan includes an inode_issue. Cleanup holds that volume and any enclosing candidate, continues on independently verified filesystems, and reports the final outcome for each target.
macOS Xcode DerivedData
On macOS, sbh recognizes immediate children of ~/Library/Developer/Xcode/DerivedData/ as xcode-derived-data cleanup candidates. The DerivedData root itself is not deleted as one broad target; per-project subdirectories are ranked independently and still pass through age, active-file, parent, and sacred-overlap checks.
DerivedData cleanup is classified as definite because Xcode regenerates indexes and intermediate build data on the next build. The tradeoff is latency: the first Xcode build after cleanup can be slower while those caches and indexes are rebuilt.
macOS Time Machine Local Snapshots
On macOS, sbh status estimates bytes retained by local Time Machine snapshots when APFS inventory data exposes a retained-snapshot estimate. The status output includes the exact reclaim command for the affected mount:
sudo tmutil thinlocalsnapshots / 9999999999999999 4
sbh clean --thin-local-snapshots --dry-run prints the same command, the selected mount, and the current estimated reclaimable bytes when available. sudo sbh clean --thin-local-snapshots --yes runs the macOS tmutil thinlocalsnapshots wrapper for / by default; pass --local-snapshot-mount <MOUNT> to target another APFS mount.
Thinning can take 30 seconds or longer. It asks macOS to free up to the estimated retained snapshot bytes, but the exact amount released is controlled by Time Machine and APFS. System-wide thinning requires sudo/root.
This matters for ballast release. If a local Time Machine snapshot references the ballast files, sbh ballast release can unlink those files immediately but df may not show the recovered space until the snapshots that still reference those blocks are thinned or expire. On default Time Machine settings that retention window is commonly about 24 hours. When sbh reports retained local snapshots, run the thin command above before relying on ballast release as visible free space.
macOS Electron App Caches
On macOS, sbh recognizes Electron application cache directories under ~/Library/Application Support/<app>/. This covers common regenerated cache shapes used by Cursor, Claude Desktop, VS Code, Slack, Discord, and similar apps:
Cache/Service Worker/CacheStorage/Code Cache/GPUCache/IndexedDB/vm_bundles/
These are classified as likely cleanup candidates, not sacred app data. The cache directory still passes through age, active-file, parent, and sacred-overlap checks before deletion, so a running app with open files can keep its active cache out of the deletion plan.
macOS Release Work Buildroots
On macOS, sbh recognizes stale staging directories that match ~/release-work/*[-_]buildroot as release-work-buildroot candidates after they are at least seven days old. These are operator-created release build roots that are easy to forget after a release or verification run; the 2026-05-03 ~/release-work/mcp_agent_mail_rust_buildroot incident left a 39 GB buildroot idle for 11 days.
The detector treats the exact release-work/*[-_]buildroot shape as a staging artifact even when the directory contains a copied Cargo.toml, but it still passes through active-reference, parent, bundle-extension, and sacred-overlap checks before deletion. Newer buildroots are kept until they cross the seven-day age threshold.
macOS User-Named Trash Directories
In volatile temporary roots such as /tmp and /private/tmp, sbh recognizes immediate children named trash, trashed, or *-trash-* as user-named-trash candidates. These names are ambiguous by design, so they are never auto-promoted straight to deletion; high-pressure scoring can only place them in Review unless another hard veto applies.
Before any review recommendation is surfaced, sbh scans three levels inside the candidate for stowaway state markers such as .git/, .beads/, beads.db, *.db, *.sqlite, and *.sqlite3. If one is found, the candidate is kept with an explicit sacred-overlap explanation instead of being treated as disposable trash.
Progressive Delivery: The Policy Engine
The policy engine controls whether scored deletion decisions are actually executed, using a progressive delivery model borrowed from feature-flag rollout practice.
Four Modes
| Mode | Deletions Executed | Purpose |
|---|---|---|
| Observe | No (shadow only) | Validate scoring and decisions without risk. Up to 25 hypothetical decisions logged per cycle. |
| Canary | Yes, capped at 10/hour | Limited real deletions to detect scoring errors before full rollout. |
| Enforce | Yes, normal pipeline | Full production mode. All scored deletions above threshold are executed. |
| FallbackSafe | No (emergency only) | Automatic safety mode when guardrails detect problems. Only ballast release allowed. |
Promotion and Demotion
Promotion between modes (observe -> canary -> enforce) is explicit. The system never auto-promotes; an operator or automation must call promote() after validating that the current mode is performing correctly.
Demotion to FallbackSafe is automatic and triggered by any of:
- Calibration breach: 3 consecutive observation windows where the guardrail status is Fail (prediction accuracy has degraded), when
calibration_breach_action = "demote"(the default below Enforce). - Guardrail drift: The e-process alarm fires at Orange or worse, under the same
calibration_breach_actionrule. - Canary budget exhaustion: More than 10 deletions in a single hour while in Canary mode, when
canary_budget_action = "demote". - Serialization failure: The daemon cannot write its state file and
serialization_failure_actionisdemote. At Red or Critical byte pressure, it records the failure and preserves the current mode so cleanup can recover. A finalENOSPCwith fresh Red or Critical inode pressure on the state file's own filesystem receives the same treatment; unrelated pressure and other write errors do not gain that inode exception. - Kill switch: An environment variable or config flag forces immediate fallback.
Recovery with Mandatory Canary Gate
Recovery from FallbackSafe requires the guardrails to report 3 consecutive clean observation windows (configurable via recovery_clean_windows). With the default auto_recover_to = "canary", an Enforce fleet does not return directly to Enforce: it recovers to Canary and re-proves itself there. The canary gate is temporary: an automatically entered Canary that runs 30 minutes without a new fallback returns to the operator's intended mode (the initial_mode or the last sbh policy promote/demote), and a later fallback remembers that intended mode rather than the waypoint Canary. A Canary the operator chose stays Canary. auto_recover_to = "previous" skips the gate; "none" leaves recovery to sbh policy promote.
The drift alarm (e-process) and the calibration breach are both statements about the forecaster, so both follow calibration_breach_action, which defaults to advisory for Enforce fleets: forecast drift is logged, and deletion keeps running on the scoring, veto and regret evidence that actually governs it. The canary hourly budget counts deletions the executor performed, not approvals it later dropped.
Guard Penalty
When guardrails report a non-Pass status, a penalty (default 50.0) is added to the expected-loss-of-deletion for high-impact candidates. This raises the bar for deletion decisions during periods of reduced confidence without completely halting cleanup.
Behavior Matrix
What actually runs at a given pressure is the behavior matrix: memory pressure (rows) crossed with disk pressure (columns) selects a scanner posture, a cleanup posture, a ballast action and a notification severity. [behavior] preset (or SBH_BEHAVIOR_PRESET) picks v0.6 (the default: reclaim before the cliff), v0.5 (the matrix shipped through v0.5.x, for rollback) or custom (v0.6 plus [behavior.cells.<memory>_<disk>] overrides, which go through the never-reduce rule in src/daemon/policy.rs). The tables are generated from the code by sbh docs --render README.md.
The scan posture sets the CPU pace: aggressive paces the scanner at twice telemetry.cpu_budget_pct (at most one core), light and definite_only at half, and normal at the configured value. Automatic scanner passes, including Critical passes, use the measured CPU allowance; Critical pressure exempts the monitor from yielding so ballast release and monitoring stay responsive.
definite_only also limits automatic discovery to candidate-index replay, the existing shallow artifact pre-scan and catalog probes. It defers broad recursive walks; a live switch to definite_only or skip stops an ongoing general walk at its next checkpoint. Unfinished roots remain pending so ordinary scans can reconcile them when memory pressure eases. skip starts no new automatic scans. Cleanup and ballast authority still follow their behavior-matrix cells, while explicit scan-now and SIGUSR1 requests retain their requested reconciliation scope and existing pacing rules.
Preset v0.6 (default) (cell = scan / cleanup / ballast / notify):
| Memory \ Disk | green | yellow | orange | red | critical |
|---|---|---|---|---|---|
| normal | normal / high_confidence_candidates / none / none | aggressive / high_confidence_candidates / none / low | aggressive / definite_candidates / release / normal | aggressive / any_definite_candidate / release_first / high | aggressive / any_definite_candidate / release_first / emergency |
| warn | light / high_confidence_candidates / none / low | light / high_confidence_candidates / none / normal | light / definite_candidates / release / normal | definite_only / any_definite_candidate / release_first / high | definite_only / any_definite_candidate / release_first / emergency |
| critical | skip / high_confidence_candidates / none / normal | definite_only / high_confidence_candidates / none / high | definite_only / definite_candidates / release / high | definite_only / any_definite_candidate / release_first / emergency | definite_only / any_definite_candidate / release_first / emergency |
Preset v0.5 (cell = scan / cleanup / ballast / notify):
| Memory \ Disk | green | yellow | orange | red | critical |
|---|---|---|---|---|---|
| normal | normal / none / none / none | aggressive / identify_only / none / low | aggressive / identify_only / none / low | aggressive / definite_candidates / release / high | aggressive / definite_candidates / release / high |
| warn | light / none / none / low | light / high_confidence_candidates / release / normal | light / high_confidence_candidates / release / normal | definite_only / definite_candidates / release_first / high | definite_only / definite_candidates / release_first / high |
| critical | skip / none / none / normal | definite_only / most_promising_candidates / release / high | definite_only / most_promising_candidates / release / high | definite_only / any_definite_candidate / release_first / emergency | definite_only / any_definite_candidate / release_first / emergency |
Safety Layers
sbh uses layered safety: six independent mechanisms, any one of which can veto a deletion regardless of what the others decide.
Layer 1: Protection Registry
Two protection mechanisms prevent cleanup of important directories:
- Marker files: Place a
.sbh-protectfile in any directory. That directory and all descendants are permanently excluded from scanning and deletion.sbh protect <path>creates this marker and records the path insacred.tomlnext to the active config file so future scan/clean/daemon runs also load it throughscanner.protected_paths. An empty marker file is valid; optional TOML metadata can record why it exists:reason = "year-end backup" added_by = "jemanuel" protected_at = "2026-05-07T03:50:00Z" - Config globs: Shell-style patterns in
scanner.protected_paths(e.g.,/data/projects/production-*). Evaluated at scan time against every candidate path. - Target-only roots: a root in
scanner.target_only_roots(macOS default/private/tmp/claude-*, the coding-agent scratch root) stays protected as a whole except for pure, idle cargo target dirs. Such a dir hasCACHEDIR.TAGor.rustc_info.jsonat its top, and its top level holds only what cargo writes there (debug,release,release-*profiles holding a build,doc, an emptytmp,package, target triples such aswasm32-wasip1, cargo's lock and report files, plus.DS_Storeand.metadata_never_index; benchmark baselines such ascriterion/keep it). No.sbh-protector.gitis in it, inside it or between it and the root, and it is not at or below anexcluded_pathsentry other than the root itself (operators exclude the scratch root so the main scanner skips it); it was not created or modified, and nothing in it was modified, withinscanner.target_only_idle_hours(24 by default); and no process holds a file open in it or works in it. While the root's mount is at Yellow or above, the daemon checks the roots every 10 minutes and sends what passes through the usual policy, planner and executor checks, pinned to the directories it surveyed; the executor drops anything outside the root. Only theprotected_pathspatterns that protect the root as a whole (the root, a parent, or everything in it) are not applied; a pattern naming something inside the root, such as**/target, still is. A marker always wins. A root may not be/or contain... A user-scoped macOS daemon cannot see other users' processes, so it keeps every candidate; use the system-scope service. - rch staging bases: an rch worker keeps a copy of each project it builds under its staging base (
transfer.remote_base), one tree per<base>/<project>/<tree>. sbh keeps project source, so these trees are pruned only through rch's ownrch cache clean, which keeps any tree modified within its--olderwindow and validates every path. While the mount of a base inscanner.rch_staging_bases(Linux default/data/tmp/rch;[]turns this off) is at Orange or worse, the daemon in Enforce mode, and never underscanner.dry_run, passes over it at most every 30 minutes. It asks rch which trees have been idle for 72 hours at Orange, 48 at Red and 24 at Critical. Then, one project directory at a time, it re-asks and checks every tree rch would prune, or could within the hour: no.sbh-protectat it, above it or anywhere inside it, no overlap withprotected_paths, not at or belowexcluded_pathsor a source tree, and no process holding a file open in it or working in it. Only when all of them pass does it runrch cache clean --project=<name> --execute; otherwise the whole project stays. Therchit runs isscanner.rch_binary, or else the first of/usr/local/bin/rch,/usr/bin/rch,/root/.local/bin/rchand/root/.cargo/bin/rch. That file and every directory above it must belong to root or the daemon's user and be writable by no one else. It runs with a cleared environment, and a run that hangs is killed. - Sacred status:
sbh status --sacredlists active marker/config protections, the sacred catalog size, and how many current scan candidates overlap sacred paths.
sbh protect reports marker creation separately from persistent registration.
If a marker is created or already present but the active sacred.toml cannot be
updated (for example, a non-root caller using system configuration), the marker
remains active and the command returns exit status 4 (partial success) with the
registration error. Full success remains 0 (ok); user and runtime failures retain
their existing exit codes. JSON includes status, exit_code, marker_created,
marker_present, sacred_config_registered, and sacred_config_error, alongside
the existing fields. Repeated requests preserve existing marker contents and
retry registration. Marker protection needs no daemon reload and lasts while
the marker is present. See Protection command outcomes
for the complete result contract and a release-automation example.
For target-only batches, the executor renews the exception immediately before each real deletion. A trace directory or session log added while earlier batch entries are being removed revokes eligibility even if the target's inode stays the same. An unreadable or truncated purity listing retains the target. Live policy and compression checks follow that filesystem probe.
Target-only nominations also carry revocable permission from the scanner configuration that selected them. Changing the opted-in roots, idle window, exclusions, or protection rules invalidates old work; removing and re-adding the same root requires a fresh selection. The executor renews that permission after the purity probe and before mutation, so a long batch cannot keep using a protection exception that the operator has withdrawn.
Target-only discovery advances across bounded passes, including through a directory listing that is too large to read in one pass. Up to four roots keep their own traversal positions and bounded pages of candidate names; waiting roots still receive a bounded fresh pass and take retained slots as sweeps finish. Unfinished surveys receive a full turn before discovery advances. A target too large for one full survey yields to later targets. These positions are volatile scheduling hints: resumed work renews directory identities, ancestry, protection and Cargo structure, and every nomination needs fresh purity, idleness and active-reference checks. Replacing a root or changing its configured scope discards the old positions. Live revocation retires saved directory readers on the retained worker, including when the tier is disabled. After reaching the end, discovery starts a new cycle to find entries added behind an earlier reader.
An in-flight rch staging pass is also revocable. Reloading its scanner, pressure, or policy settings cancels the old pass, as does leaving Enforce mode or recovering enough space to require an older idle cutoff. The worker checks cancellation after its process and marker checks and before starting each rch command. Restoring the earlier settings or pressure cannot revive that pass; a blocked worker keeps its slot until it exits.
Staging admission also runs off the monitor: one worker probes the configured bases and resolves the trusted rch executable. The monitor admits its result only while the same configuration remains active and the bases' mounts still need cleanup. Evidence expires after 60 seconds, including the wait for the monitor to receive it. A blocked admission worker holds its slot without delaying monitoring or starting additional workers.
Target-only root expansion, filesystem probes, and surveys run on one retained worker, so a slow or stuck scratch filesystem does not block the monitor. Reloading the target policy revokes the old worker without starting overlapping replacements. Before submitting a batch, it checks the root's identity and mount again, requires pressure evidence younger than 60 seconds, and defers candidates if pressure has fallen since they were scored. A worker stuck in a native filesystem call holds its slot until that call returns.
Layer 2: Pre-Flight Safety Checks
Before any deletion is executed, an eight-point pre-flight check must pass:
- Path still exists: Uses
symlink_metadata()(doesn't follow symlinks) to verify the target hasn't been removed by another process since scoring. - Not a symlink: Symlinks are rejected because
remove_dir_allfollows symlinks into the target, which could destroy data outside watched directories. - Parent is writable: Checks effective write permission via
access(W_OK)to catch read-only mounts and permission changes since scan time. - No Git metadata or tracked source: Candidates containing a Git repository or tracked files are retained, including deep subtrees of linked worktrees. Ordinary untracked build artifacts remain eligible. If a repository marker exists but Git cannot verify its index, the candidate is retained. Lean source files also veto deletion when no repository metadata is available.
- Not a Cargo source root: A direct
Cargo.tomlwithout Cargo build-output markers vetoes deletion, even when a directory name matchestarget,target_*,*_target, or*-target. Broad target-like names outside temporary storage also require Cargo build-output markers before they can become deletion candidates;/private/tmptarget caches still require open-file checks. - No stowaway sacred state: Depth-limited scans reject cleanup candidates that contain protected marker directories or database state such as
.git/,.beads/,*.db,*.sqlite, or*.sqlite3. - Not open by any process: The deletion executor checks platform open-file evidence before reclaiming a target tree. Linux scans
/proc/*/fdsymlinks; macOS uses the PAL/libproc open-file collector. If that pre-flight evidence is incomplete, the batch fails conservative instead of deleting an in-use directory. - No active-target lease: The executor probes the stable kernel lock derived from the candidate and its ancestors, both during pre-flight and immediately before mutation. A locked target is skipped even when its metadata is expired, over quota, unreadable, or tampered; the watchdog cancels the owner and deletion waits for the kernel to release the lock. This closes the gap where open-file evidence can miss build outputs between compiler phases.
Any single check failure causes the candidate to be skipped (not failed), so it doesn't trip the circuit breaker.
Layer 3: Circuit Breaker
The deletion executor tracks consecutive failures. After 5 consecutive deletion errors (not skips), the circuit breaker trips and halts that batch.
The daemon also tracks failed cleanup attempts separately for each observed filesystem. Five errors without a successful cleanup on that filesystem start its retry cooldown, using a 30 second base that doubles on each trip (60 seconds for the first trip, capped at 5 minutes). Candidates on a cooling filesystem are held before policy accounting; healthy filesystems in the same queued batch remain eligible. A successful cleanup resets only its own filesystem's retry debt, and safety refusals or dry-run previews do not count as failures. Failure-rate alarms use the same filesystem-specific streams, so successes on a healthy volume cannot hide failures elsewhere. If a candidate has no observed filesystem identity, its failure history applies only to that exact path.
Layer 4: Policy Engine Gates
As described above, the progressive delivery system (observe/canary/enforce) ensures deletions are validated at each stage before reaching full production. The canary mode caps deletions at 10 per hour, limiting blast radius during initial rollout.
Layer 5: Guardrails and Drift Detection
The guardrail system continuously validates that the forecasting and scoring pipeline is well-calibrated. If predictions drift from reality, the system automatically falls back to safe mode. See the Guardrails section below for details.
rch Build Pools
rch's remote CARGO_TARGET_DIRs (.rch-target-<worker>-{pool,job,pid}-<key>) are warm caches shared by later builds, so their age is the newest write anywhere in the tree, never the directory's birth time. Normally sbh honors rch's own floors: a pooled dir must be idle for 168 hours and a per-job dir for 12. Pools in daily use never go that long without a write and grew without bound on the fleet, so once the controller's urgency reaches 0.7 (from roughly mid-Orange, always at Red) the floors drop to 60 minutes for pools and 30 for per-job dirs, and the idle probe may walk up to 2000000 entries. A pool written inside the floor is vetoed at every pressure, and the open-file and active-lease rails still apply at deletion time.
Repeated removals of the same warm-cache path raise its idle floor, including rch's Go caches and structurally recognized shared Go caches. This history survives a daemon restart as soon as the successful unlink receipt reaches SQLite; it does not wait for the later regret observation to finish. Receipts retain the structural category and mutation completion time, so logger delay does not extend the history window. Matching receipts and regret outcomes count the deletion once; older outcome-only history remains usable. Failed attempts, quarantine moves and planned DELETE decisions do not count. Restart recovery restores the cache's backoff, without inventing a clean or regret label for an observation interrupted by shutdown. Logging failures can still leave a removal without recoverable history.
Layer 6: Repeat-Deletion Dampening
When an artifact path is deleted and then recreated (common with build directories in active projects), the dampening tracker applies exponential-backoff cooldowns to prevent deletion loops:
cooldown = base_cooldown * 2^(cycle_count - 1), capped at max_cooldown
The first deletion of a given path has no cooldown. After the second deletion, cooldown starts at the base value and doubles with each subsequent cycle.
| Parameter | Config Key | Default |
|---|---|---|
| Base cooldown | scanner.repeat_deletion_base_cooldown_secs |
300s (5 min) |
| Maximum cooldown | scanner.repeat_deletion_max_cooldown_secs |
3600s (1 hour) |
Red and Critical pressure bypasses all dampening. Disk safety takes priority over anti-churn protection.
Layer 8: Regret Labels and Per-Category Calibration
A deletion was a mistake when the same directory entry (parent device and inode plus name) is recreated within scoring.regret_window_minutes (30) of the deletion while a process has its working directory or an open file under the parent: something still used it. The daemon watches every removal for good, labels each one regret, clean (the window passed) or unknown (recreated with no live user), stores the label in SQLite decision_outcome and as a decision_outcome JSONL line, and sbh explain --id <decision-id> shows it as an Outcome: line.
Labels calibrate the fast lane per artifact category. Each category keeps a Beta posterior on its regret rate under a prior pooled across categories, and a Clopper-Pearson upper bound (95%) on that rate. The bound's excess over the tolerated rate (scoring.regret_alpha_definite 0.02 for Definite-dominated categories, scoring.regret_alpha_likely 0.005 otherwise) lowers the category's calibration factor, which the decision layer turns into a higher required posterior for Delete; explain shows it as Regret calibration:. Zero regrets never tighten anything, and a regret in one category never touches another. A per-category e-process against "regret rate <= alpha" suspends only that category's deletions (Delete verdicts become Review, fallback_reason: category suspended after regrets) for scoring.regret_suspend_minutes (60) when it alarms. The calibrator is rebuilt from the last 30 days of stored outcomes at daemon start.
Layer 7: Quarantine-First Deletion and sbh undo
Hard vetoes make the known mis-scorings impossible; they cannot make the next one recoverable. At Green there is time to keep the bytes around, so the daemon does: a Green batch (and every sbh clean unless --no-quarantine) does not unlink a candidate, it renames it into <root>/.sbh/quarantine/<decision-id>/<basename> on the same filesystem, next to a <decision-id>.json record naming the original path. The quarantine root carries a .sbh-protect marker so no scan ever scores it. The event is still artifact_delete with "quarantined": true and no bytes freed.
Quarantined space is reclaimable on demand:
| Condition | What happens |
|---|---|
| Green or Yellow | Background sweeps are due once a minute. They remove entries older than scanner.quarantine_ttl_hours and cap the store at scanner.quarantine_max_bytes_pct of the volume (oldest first). |
| Orange, Red, Critical | A bounded background sweep gives existing quarantine the first opportunity to reclaim space on its filesystem. Fresh cleanup resumes when that opportunity ends; new candidates are removed for good (Unlink). |
sbh emergency |
Drains selected quarantined artifacts before scanning, including matching entries in same-filesystem ancestor stores. |
Daemon quarantine sweeps respect the live policy and dry-run setting. Canary, Observe, FallbackSafe, and dry-run retain quarantined payloads while still reporting their held bytes. Normal TTL/cap and pressure-driven purges require Enforce mode.
Automatic inventory and purge use one retained worker. Only its admitted
filesystem receives a cleanup hold; queued sweeps cannot hold other disks.
The hold expires after QUARANTINE_FIRST_CHANCE_SECS (see
sbh docs --section constants), revoking the worker before fresh cleanup
proceeds. Reload, failed pressure sampling, policy revocation, recovery and
shutdown can cancel it sooner. A blocked native operation keeps its worker
slot without blocking pressure monitoring or creating replacement threads.
Completed observations update held inventory; unavailable observations retain
the last measured value. See quarantine recovery
for the cancellation and shared resource-allowance rules.
Queued deletion batches also recheck policy and dry-run before each candidate mutation. Enforce-to-Canary transitions defer the remaining candidates for fresh quota evaluation. A pause, fallback, or kill-switch transition revokes the batch's existing approvals even if Enforce resumes before native preflight returns; later work requires a fresh policy evaluation. Temporary policy refusals do not create per-path backoff, and batches already planned as dry-runs retain their preview counts.
If quarantine removal encounters filesystem-level EROFS or ENOSPC, the
sweep stops and immediately holds candidate and quarantine deletion for the
observed filesystem, or for the affected path while its filesystem is unresolved.
The daemon then uses its recovery and write-probe path. These incidents do not
give the artifact a one-hour stuck-entry cooldown, so a successful recovery
probe permits a fresh attempt. Ordinary per-entry permission failures still
allow eligible peers to proceed; read-only namespace restrictions remain
distinct from a read-only filesystem.
RAM- and inode-only pressure apply their narrower artifact rules to held
payloads too. A record needs a known structural category and a stored
Definite decision; current exclusions for its original path and live
category suspensions are checked again before removal. Ineligible records
are retained while the bounded sweep considers later entries. Legacy records
without that evidence remain available for restore or normal TTL/cap cleanup.
RAM relief requires a positive byte estimate; inode relief can also remove a
verified directory whose byte estimate is zero.
Restore with sbh undo <decision-id> (the id is on the [SBH-QUARANTINE]
line, in sbh explain, and in sbh undo --list), sbh undo --path <original>,
or sbh undo --all-since 2h. Restore renames the remaining payload back. It
refuses when the original path exists again unless --force-suffix, which
restores beside it as <name>.restored-<decision-id>.
Bulk undo restores selected parent directories before their separately held
children, while undo --list keeps its chronological order. If a selected
parent cannot return to its original destination, or is restored beside a
replacement with --force-suffix, its dependent children stay quarantined.
Children are restored only beneath the original restored parent identity;
path aliases and rebuilt symlinks cannot redirect them into another tree.
Competing versions of one destination keep their chronological order, and
ambiguous parent generations require selecting a specific decision to restore.
Undo also checks quarantine stores along the original path's ancestors, so
an entry held at its filesystem's fallback store remains discoverable after
its entire scan root was moved. --root limits recovered entries to original
paths in that scope; it never includes siblings just because they share a
store. Aliases of a store are deduplicated. For a manual clean outside the
configured roots, --path <original> supplies an exact search scope, and a
requested decision ID can use its existing read-only decision ledger as a
location hint. Explicit --root constraints always take precedence. The
manifest is checked again under the store lock before restoration, so a
changed origin or reused decision ID must be reviewed again.
If configuration is missing, unreadable, or invalid, recovery remains available
with sbh undo <decision-id> --root <original-scope> or
sbh undo --path <original>. undo --list --root <original-scope> can inspect
that scope first. Only the explicit scope is searched; a failed configuration
load never substitutes default roots. Recovery warns that the decision ledger
cannot be updated in this mode. Without --root or --path, fix the configuration
before using an ID, --list, or --all-since. Legacy IDs retain their exact case;
uppercase input for a generated hexadecimal ID is accepted only if there is no
exact matching held entry.
Recovery completeness survives daemon restarts. New entries start with a
durable intact witness; before a purge may unlink anything, the store records
that purging has started. A bounded or interrupted purge can therefore leave
a useful remainder without allowing undo to call it a complete artifact.
undo --list identifies each entry as intact, purge_started, or unknown.
Older entries without the witness protocol remain unknown, even when their
remaining contents can be returned.
Undo JSON reports recovery_state for held entries and completeness for
returned payloads. original_estimated_size_bytes preserves the estimate made
when the artifact entered quarantine. estimated_size_bytes is null unless
the entry is intact; intact_estimated_bytes totals only those intact estimates,
and uncertain_entries counts the others. These figures are estimates, not a
new measurement of recovered bytes. Existing size_bytes, held_bytes, and
restored_bytes fields keep those estimates for intact entries or wholly intact
totals and become null when completeness is uncertain. A requested restore that returns any
uncertain payload exits 4 (partial success), including a mixed batch with
intact entries. Listing alone remains read-only and exits 0.
The ledger records restored_intact, restored_partial, or restored_unknown
without rewriting the original decision evidence. sbh explain displays this
recovery information separately. Historical restored labels are shown with
unknown completeness because they predate this proof. Recovery annotations
apply to the newest record for that stable decision ID; a later intact restore
does not overwrite an older partial annotation.
A candidate that cannot be quarantined (different filesystem from the root,
unusable store) is retained, and quarantine_unavailable records the reason.
That refusal does not authorize permanent deletion. status shows the bytes
held per mount in the Reserve column; stats reports quarantined_count and
quarantined_bytes and excludes held bytes from total_bytes_freed.
| Parameter | Config Key | Default |
|---|---|---|
| Quarantine on/off | scanner.quarantine_enabled |
true |
| Time an entry is held | scanner.quarantine_ttl_hours |
24 |
| Size cap per volume | scanner.quarantine_max_bytes_pct |
5 |
The tracker periodically prunes entries whose last deletion is older than max_cooldown, preventing unbounded memory growth in long-running daemon sessions.
Source: src/daemon/loop_main.rs
Finite Inode Capacity
A filesystem can have free bytes and still be unable to create a file because
it has run out of inodes. On Linux, sbh reads finite inode accounting
separately from byte capacity. The available count excludes reserved inodes;
zero available inodes is Critical even when many bytes remain free.
Unsupported, missing, sentinel, or inconsistent counters remain unavailable
and cannot authorize inode-driven cleanup. Platforms without finite inode
accounting continue using the existing byte and memory pressure paths.
[pressure.inodes] enables this monitor by default. Its available-inode
thresholds are 10%,
Yellow, Orange, and Red respectively; lower values are Critical. Escalation is immediate. Recovery requires an additional
0.5 percentage pointsand steps down one level per sample. Byte floors, byte forecasts, and byte PID gains do not change these thresholds.
sbh check PATH --json includes a live inodes object with status, raw
stats, and independent pressure. Orange or worse inode pressure exits
1 with reason: "inode_pressure", including when --target-free 0 permits
the byte capacity. Unavailable accounting is explicit, with no inferred
healthy pressure; disabling the inode monitor preserves valid raw counters.
sbh status shows inode availability separately, and its JSON includes
pressure.inode_mounts for writable disk and RAM-backed mounts. Each mount's
main level and pressure.overall use the strongest observed byte, inode,
or user-quota pressure. Pressured tmpfs mounts appear in the main table even
when their user quota is healthy; healthy RAM-backed mounts stay omitted.
The JSON filesystem_level preserves the byte-only level when inode or
quota pressure is present, and free / free_pct remain byte measurements.
The daemon also publishes independent tmpfs_quotas evidence in state.json.
Its sampled_at records when the native probe began; publishing a result does
not renew that timestamp. The dashboard places a separate quota badge first
in the pressure pane, including when a fresh quota result arrives during a long
filesystem-monitor sleep. Quota pressure never changes physical free-space
measurements or authorizes cleanup. Incomplete coverage stays explicit as
partial, and observations at least 30 seconds old are stale.
The daemon and sbh status --watch start refreshes every 15 seconds while
retaining the previous observation until its original 30-second freshness
deadline. A blocked refresh never extends that deadline or starts a second
reader. A failed status refresh preserves an unexpired warning and reports the
refresh failure as partial coverage.
Quota collection stops admitting new inventory and quota reads after a 10-second budget, preserving already verified counters and naming the mounts or users left unobserved. Process inventory uses only the first third of that window so known users can still be checked on hosts with many processes. The limit is cooperative: a native call already in progress and the final mount-identity check can run longer; the original freshness deadline still applies.
Prometheus exports sbh_tmpfs_quota_observation_status, observation availability
and completeness, and sbh_tmpfs_quota_observed_timestamp_seconds. Fresh finite
user limits have separate byte and inode usage, limits, and pressure series,
with mount, device, and UID labels. Unavailable or expired observations omit
their usage series; missing users and unlimited resources are never reported
as zero usage. Alert rules should check the observation timestamp as well as
availability, because a stopped textfile writer cannot refresh its export.
Inode relief uses existing definite artifact candidates on the sampled device and within configured scanner roots. Every pass has a shared limit on successful artifact removals, and every mutation rechecks current inode availability. Cleanup stops when available inodes reach the Green threshold plus its recovery margin. A changed mount, unavailable counters, revoked scope, or changed inode policy defers queued work. No estimate of an artifact's inode yield is used to claim success.
These passes unlink eligible artifacts because quarantine renames retain their inodes. They retain protection markers, age checks, active-reference checks, policy mode, and dry-run. A zero-byte estimate is eligible only for a verified directory, whose own inode can be reclaimed. Inode pressure does not start compression, log truncation, unrelated-device cleanup, or a broader emergency policy. Byte counters and bytes-freed reports keep their original meaning.
If the state file still cannot be written after the existing in-place
fallback, a returned ENOSPC together with fresh severe inode pressure on its
parent filesystem preserves the current policy mode. This lets already
authorized cleanup recover capacity. It does not promote Observe or
FallbackSafe, reset Canary limits, or excuse unrelated write errors.
RAM-Backed Scratch Preflight
On Linux, sbh check /tmp --need 5G also checks current host RAM-scratch
pressure when the path is on tmpfs or ramfs. A positive explicit --need
additionally compares the requested bytes with host MemAvailable and every
finite memory.high or memory.max boundary in the caller's visible cgroup-v2
ancestry. Each boundary uses its own scope's current charge. A large tmpfs size
limit or healthy host cannot hide a smaller process allowance.
On a quota-enabled tmpfs mount, every ordinary sbh check /tmp also checks
the effective user's byte and inode quotas. At 97% or more of either finite
limit, a check without a positive --need exits 1, even when the filesystem
has plenty of free blocks and inodes. JSON names the affected resource as
tmpfs_user_block_quota_pressure or tmpfs_user_inode_quota_pressure and
includes the user's counters under tmpfs_user_quota.
A positive --need compares the requested bytes with the remaining user byte
budget exactly: a small write can pass near the byte limit if it still fits.
An insufficient byte budget exits 1 with tmpfs_user_quota_headroom when
that budget is the limiting factor. Inode quota pressure independently blocks
the request. Both checks reuse one observation, use the smaller finite soft
or hard limit, and treat a soft limit as an early warning even while the kernel
may allow writes during its grace period. An unreadable quota or a probe that
takes more than 500 ms leaves the check incomplete (exit 4). Explicit byte
requests also retain the counters under ram_write_admission.user_quota.
The byte comparison adds no percentage reserve and does not count swap as RAM.
It distinguishes throttling boundaries from hard limits. A known shortfall
exits 1 (user error, or a pressure condition); incomplete evidence exits 4 (partial success) (Exit Codes). JSON includes
the fresh ram_scratch report and a separate ram_write_admission with the
requested bytes, observed headroom, and limiting scope. A successful check is a
current observation, not a memory reservation. Disk-backed checks skip the RAM
collection, and the check does not authorize cleanup or relocation.
Use sbh check --ram-scratch for the fuller report and top-entry attribution.
See RAM-scratch headroom for the warning rules and limits.
Agent-Session Scratch Inventory
sbh check --agent-scratch [PATH] reports Claude session directories even when
their contents are not regenerable artifacts. It recognizes
<tmp>/claude-<uid>/<project>/<session-uuid>, correlates each session with its
transcript, and checks live process references. Both the complete tree and its
transcript must have been unchanged for --min-idle-days (7 by default), with
complete process evidence, before the report labels a session idle. Active,
recent, and unknown sessions remain visible, largest observed allocations first.
sbh check --agent-scratch /data/tmp --min-idle-days 9
sbh --json check --agent-scratch /tmp --agent-scratch-top 50
This command only reports evidence for manual review. It preserves protection markers and never emits cleanup candidates. Logical bytes and allocated blocks are reported separately; hardlinks are deduplicated within each session, but reflinks/shared blocks prevent a reclaimable-space promise. Missing transcripts, limited process visibility, changed trees, and exhausted scan budgets remain explicit uncertainty. See the inventory guide for roots, limits, JSON fields, and exit statuses.
Moving and Restoring Protected Scratch
On Linux, sbh relocate --apply copies dormant eligible scratch through an
opened source directory and verifies the backup before removal. It renews the
source and parent identities, every descendant's identity and change stamps,
relocation permission, and process-use evidence at the relevant mutation
boundaries. Replaced sources, changed children, moved parents, and occupied
recovery paths refuse the move while retaining the available recovery data.
The restore stub is built privately and published without overwriting a new
occupant of the original path.
On Linux, sbh relocate --restore /absolute/path/to/stub copies the backup into
a private directory unique to the attempt, verifies it, and installs it at the
original path. The opened payload directory pins rsync's destination even if a
parent or staging pathname moves. Concurrent restores of the same stub refuse
immediately; changed records, replaced stubs, and newly occupied original paths
stop the swap while preserving the available recovery trees.
The backup and previous stub are retained after success. Human and JSON output name the saved stub, including files written there since relocation. Refused or interrupted transfers retain their staging for recovery. See relocation and restore for recovery locations and evidence limits.
Lossless Reclaim Before Cleanup
When the optional compression tier starts a pass on a supported btrfs mount at Yellow or Orange pressure, that filesystem gets one bounded opportunity to reclaim space losslessly before cleanup. The daemon publishes the hold before dispatching its pressure scans, and checks it again before executing already queued deletions or draining quarantine. Unrelated filesystems continue working. The compression tier remains off by default.
compress.roots may live on volumes outside scanner.root_paths. When no
scanner controller monitors a compression root's mount, the tier samples that
root's current free space and applies the configured pressure percentages and
absolute floors to decide whether compress.start_level is reached. Existing
controllers retain their hysteresis and predictive levels. This sampling only
admits compression; it does not add deletion roots, change the daemon's global
pressure level, or grant a cleanup hold through an unmonitored mount alias.
Read-only filesystems, failed samples, and unknown capacity cannot start a pass.
Root filesystem and device probes run on one bounded background worker; the monitor never waits for them. Completed roots can start a pass while a later probe is blocked. Admission evidence expires after 60 seconds, and a root awaiting fresh evidence cannot hold cleanup. A stuck native probe retains its worker slot rather than spawning more threads, so it can delay compression without blocking monitoring, ballast release, or emergency cleanup.
Reloading compression settings, protected paths, or control-file locations revokes the active pass and pending root evidence. Cancellation remains set until the old worker exits, and old discovery progress cannot skip work under the new settings. Unrelated UI and notification settings preserve active work.
The hold ends when the pass finishes or its wall-clock allowance expires:
the 60-second discovery budget plus compress.policy.timeout_secs, measured
from the scheduling tick. A cancellation asks the worker to stop and retains
the hold until it exits or the original deadline expires. Repeated passes
cannot renew the hold within the same eligible pressure episode.
Red and Critical pressure bypass the hold, including older batches scored before a known alias of their device escalated. Emergency quarantine cleanup and scan requests run before the daemon probes roots for a new compression pass; configured Red/Critical compression start thresholds remain supported. Ballast release retains its priority. Temporarily deferred candidates stay eligible for retry without per-path failure backoff.
Source: src/daemon/compress_tier.rs, src/daemon/loop_main.rs
The Ballast System in Depth
Ballast files are pre-allocated sacrificial space that can be released instantly when disk pressure spikes, buying time for the scanner to find and delete actual artifacts.
Provisioning
Each watched volume gets its own ballast pool. Files are named SBH_BALLAST_FILE_00001.dat through SBH_BALLAST_FILE_NNNNN.dat, with a 4096-byte JSON header containing the magic string SBH_BALLAST_v1, file index, creation timestamp, and size metadata.
On macOS, service scope controls the default pool path: user LaunchAgents use ~/Library/Application Support/sbh/ballast.bin; system LaunchDaemons use /private/var/sbh/ballast.bin. This path is still a ballast pool directory in the current multi-file implementation, and [paths].ballast_dir remains the override for custom placement.
The data payload is written differently depending on the filesystem:
- ext4/xfs: Uses
fallocate()for near-instant allocation without writing actual data. - btrfs/zfs: Writes 4 MiB chunks of random data to defeat copy-on-write deduplication, which would otherwise make the ballast files share physical blocks and release nothing when deleted.
All writes are fsynced every 64 MiB to ensure durability. Provisioning stops before a file that would take free space below the provisioning floor (15% with the default thresholds), so it never fills the disk while reserving space against future fills. The floor keeps every new file out of the first pressure level at which the behavior matrix releases ballast, with pressure.controller.hysteresis_pct to spare: the default matrix releases from Orange, so the floor is yellow_min_free_pct + hysteresis_pct. It is never lower than max(orange_min_free_pct, red_min_free_pct + 2). A lower floor let a refill on a Yellow volume end in Orange, and the daemon released the files it had just written.
Per-volume configuration overrides allow different file counts and sizes for different mount points. A 2 TiB data volume might use 10 x 2 GiB ballast files (20 GiB total), while a 100 GiB root volume uses 5 x 512 MiB files (2.5 GiB).
Release Strategy
The PID controller's pressure response directly determines how many ballast files to release:
- Low urgency (< 0.3): No ballast release. The scanner handles cleanup.
- Moderate urgency (0.3 - 0.6): Release 1 file. Provides a buffer while scanning continues.
- High urgency (0.6 - 0.9): Release 3 files. Significant immediate space recovery.
- Emergency (> 0.9): Release all remaining files. Maximum immediate relief.
Release is instant (just unlink()), providing space recovery in milliseconds rather than the seconds-to-minutes required for scanning and deletion.
Graduated release targets count observed depletion of the physical reserve,
rather than configured slots that might never have been provisioned. The daemon
carries that observation in each pool's existing state.json record, bound to
the directory's device, inode and creation time when the filesystem supplies it.
A restart over the same pool keeps prior release credit; recreated reserve
retires the credit, and a replaced pool begins a new window. Config reload keeps
the observed window while updating the replenish cooldown. Missing, unreadable
or non-matching history leaves the actual partial reserve usable. Critical
pressure still releases the available reserve. State persistence retains the
existing write cadence; emergency release adds no history-file writes or waits.
On macOS/APFS, local Time Machine snapshots can retain the released ballast blocks. In that case the release operation succeeds, but apparent free space in df, Finder, and some system APIs may not increase until one of these happens:
- The relevant local snapshots are thinned with
sudo tmutil thinlocalsnapshots <mount> 9999999999999999 4. - The snapshot retention window expires, commonly about 24 hours with default Time Machine behavior.
When local snapshots are present, sbh ballast release emits a warning for the affected mount. Treat that warning as part of the incident workflow: thin snapshots, then re-run sbh status or df -h to confirm that APFS made the released blocks visible as free space.
Replenishment
When a mount has been Green for the full ballast.replenish_cooldown_minutes, the replenishment controller rebuilds its missing ballast files one per cycle, at most one every five minutes, while the volume stays above the headroom floor. The cooldown is observed on every daemon tick, whatever the mount is doing: a Yellow or Orange excursion of more than three ticks (a compilation burst is forgiven, a real pressure episode is not) restarts it, and any release resets it. The controller also counts the files it released on each mount since the last completed Green cooldown, so the reserve being rebuilt is visible; a reserve that is short for any other reason (an operator deleted files, a floor-limited provision) is rebuilt the same way, up to the configured count.
ballast.auto_provision = false disables both startup provisioning and periodic
automatic refill. Status and reserve alerts report auto_provision_disabled
instead of promising an automatic rebuild. Existing reserve remains available
for pressure relief, and explicit sbh ballast provision or dashboard refill
commands can still rebuild it. Re-enabling the setting resumes automatic
refill through the ordinary pressure and cooldown checks.
Automatic refill runs on one background worker across all pools, so writing and syncing a reserve file does not stall the pressure monitor. Each allocation boundary renews permission, file identity and the headroom needed for the remaining bytes. Renewed pressure, missing monitor evidence, a config reload or shutdown cancels the attempt; a cancelled worker keeps its slot until native I/O returns. Emergency release never waits for its pool lock and retries after the writer stops. Only completed files receive replenishment credit, and a late worker result cannot overwrite inventory from a newer release or reload.
When ballast.auto_provision is enabled, initial provisioning uses that same
guarded worker after a complete current discovery plan arrives. It builds each
pool without waiting for the ordinary Green replenishment cooldown, subject to
fresh pressure evidence, the allocation floor, and the forecast, RAM, inode,
recovery and policy guards. Monitoring and service readiness continue during
the writes. A completed, floor-limited, failed or cancelled initial attempt
returns that pool to the ordinary paced replenishment policy.
All ballast operations (provision, release, replenish, verify) are serialized per-volume via flock() on a lockfile, preventing races between the daemon and CLI commands. sbh ballast status opens the configured directory read-only and reports files outside the configured index range as orphans. On Unix, explicit provision and replenish prune a surplus slot only after verifying its original header, index, allocation, and file identity under the pool lock. Foreign files and unverified entries remain available for inspection. Background growth retains surplus reserve for emergency release.
The daemon manages one pool per eligible mount, not just the configured ballast_dir: every mount that hosts a scan root, a special location, the state dir or the ballast dir gets <mount>/.sbh/ballast (RAM-backed, network, read-only and override-disabled mounts are skipped with a reason). sbh ballast status lists every such volume with its health, file counts, releasable bytes and skip reason, and --json carries them under volumes, so a pool the daemon built on another volume is never invisible to the operator.
Pools are planned per filesystem, not per mount entry. The mount holding a path is the one the kernel reports (statfs), so a macOS ballast dir under /Users lands on /System/Volumes/Data rather than the sealed, read-only /, and mount entries with the same source device (the bind mounts a ProtectSystem=strict unit sees for each ReadWritePaths= entry) fold into one pool on a writable entry, listed as "same filesystem as ..." and served by that pool. sbh ballast files left in a default <mount>/.sbh/ballast the daemon no longer manages (the pool moved to a configured ballast_dir, or its mount was folded) count as that filesystem's reserve and are released after the pool's own files; only files with the sbh ballast header are ever touched, and they are not replenished.
Reserve availability in status and notifications
A successful release can leave a volume at Yellow with no ballast left for the
next pressure spike. sbh status reports reserve availability separately from
disk pressure, with a prominent warning and one record per physical pool. The
pressure level, release strategy, hysteresis and refill safety floor keep their
existing meaning.
| Reserve state | Meaning |
|---|---|
healthy |
Observed releasable bytes meet or exceed the configured pool size. |
depleted |
More than 25% of the configured reserve remains, but the pool is below its configured size. |
critical |
Some reserve remains, at most 25% of configured bytes, including exactly 25%. |
exhausted |
A reserve is configured and authoritative inventory found zero releasable bytes. |
unknown |
Inventory has not completed, could not be inspected reliably, or is too old to establish current protection. |
unconfigured |
No reserve bytes are configured for this pool. Existing surplus files can still be reported. |
The report includes file counts, releasable and configured bytes, observation time, and the current reasons automatic refill cannot proceed. These can include pressure policy, the refill cooldown, dry-run mode, an occupied worker, unreadable inventory, or the safety floor. Floor evidence describes free space after allocating another whole configured file. For example:
| Free before allocation | Free after the next whole file | Safety floor | Admission |
|---|---|---|---|
| 15.1% | 14.9% | 15.0% | Refused |
Existing policy can permit refill on a Yellow mount that is idle with nothing left to reclaim; this report describes that decision without authorizing any additional writes. Improved pressure alone does not mean the reserve has recovered.
sbh status --json exposes this view under ballast.reserves, and each daemon
state.json pool record carries it as ballast_pools[].reserve. Skipped mounts
retain their exact discovery reasons in ballast.reserves.skipped_pools and
ordinary status; aliases and deliberately unmanaged filesystems do not add
reserve depletion warnings. Fresh evidence
from the running daemon takes precedence over what a less restricted status
process can see. A stalled observation becomes unknown after 90 seconds;
it never leaves a saved positive reserve claim indefinitely. Without a current
daemon report, status uses read-only inventory and explicitly marks daemon
release access and automatic refill eligibility as unknown. Releasable bytes
are allocation estimates; filesystem snapshots may retain blocks after unlink.
The cockpit's overview and Ballast screen use the same reserve observations.
They show EXHAUSTED for confirmed zero and UNKNOWN for missing, unreadable or
expired evidence; unknown quantities are displayed as unknown, never as zero
or cached positive counts. The overview retains the most urgent per-volume
condition, so a full pool on another filesystem cannot hide an exhausted pool.
While discovery or a configuration reload is pending, aggregate quantities are
unknown; independently verified pools still show their observed condition.
The detail view lists the current refill blockers. Live cockpit reads reject a
state document marked stopped or at least 90 seconds old, using both its
recorded update time and file modification time. Copying or touching an old
document cannot make it live. An unmarked crash can remain visible within that
freshness window. Incident replay keeps its historical clock and continues to
disable ballast actions.
Reserve-band changes produce ballast_reserve_changed notification records,
including the remaining reserve and refill explanation. Exhaustion has Red
notification severity, critical depletion Orange, partial depletion or unknown
inventory Warning, and recovery to healthy Info, subject to each channel's
configured level filter. Unchanged evaluations do not produce periodic repeats,
even after the ordinary notification cooldown expires. Recovery and a new
depletion episode remain visible within that cooldown, and different volumes
cannot suppress one another. On restart, the daemon inspects its pools again
and announces an unhealthy initial observation once; it never restores reserve
availability from a saved healthy state. Re-enabling notifications or changing
their destination makes the current condition eligible for delivery again.
If every accepting notification queue is full, the latest transition remains
eligible and retries at most once every five seconds while its reserve band
stays unchanged. A changed band can attempt delivery immediately. This paces
queue-loss notices as well as retries; actual channel delivery remains best
effort.
VOI Scan Scheduling
Fixed-interval full scans waste IO bandwidth when most directories haven't changed. For v1, the Value-of-Information (VOI) scheduler allocates a limited scan budget (default: 5 paths per cycle) to the paths most likely to yield reclaimable space. For v2, the same pressure signal decides when to use the persistent candidate index, event-dirty roots, or bounded reconciliation instead of recursively walking every configured root.
A missing, replaced, or read-only filesystem cannot keep other roots' pending changes waiting behind its refused event scan. Its own changes remain queued until fresh monitor evidence admits that filesystem again. A root waiting out its own empty-pass cooldown also gives ready roots a turn; the daemon-wide CPU and scan duty-cycle limits still apply.
Per-Path Statistics
The scheduler maintains EWMA-smoothed statistics for each watched path:
- Expected reclaim: Bytes recovered per scan of this path (smoothed with alpha 0.3).
- IO cost: Estimated filesystem reads per scan (initialized at 1000, updated from actuals).
- False positive rate: Fraction of scanned candidates that were later skipped or failed pre-flight checks.
Utility Scoring
Each path's utility combines exploitation (scan paths with known high yield) and exploration (periodically re-scan paths that haven't been visited recently):
utility = expected_reclaim * uncertainty_discount
- io_cost * 0.1
- fp_rate * expected_reclaim * 0.15
+ exploration_bonus
The uncertainty discount ranges from 0.5 (fewer than 3 scans, high uncertainty) to 1.0 (well-established statistics). The exploration bonus is proportional to hours since last scan (capped at 24) and inversely proportional to total scan count, ensuring every path gets periodic attention even if its historical yield is low.
The scan budget is split: 80% exploitation (highest-utility paths) and 20% exploration (least-recently-scanned paths). This balance prevents the scheduler from permanently ignoring paths where a new project has started generating artifacts.
Full-scan age, forecasts, and calibration advance only after a recursive walk exhausts its scope with a complete coverage receipt. A timed-out pass or an index/pre-scan-only result does not prove that a root is empty. Positive partial findings can still prioritize work, but that evidence expires at the revisit interval and is cleared by a completed scan. An incomplete empty result cannot park its mount's pressure controller as though the whole scope was searched.
Automatic Orange, Red, and Critical recursive walks with a finite CPU allowance alternate the normal leading-root preference with the least recently led root in the admitted scope. A turn is consumed only when the recursive walker starts: dropped requests, pacing deferrals, replay-only work, and failed starts do not spend it. This keeps other roots eligible across bounded passes while Critical scans retain their finite CPU allowance.
Fallback Mode
If the VOI scheduler's forecast error (MAPE) exceeds 50% for 3 consecutive windows, it falls back to simple round-robin scheduling. It recovers after 5 consecutive windows with acceptable MAPE. This prevents the scheduler from making poor allocation decisions when its model of the environment is wrong.
Special Location Monitoring
RAM-backed filesystems (/dev/shm, tmpfs, ramfs) require tighter monitoring than disk-backed volumes because they directly compete with application memory. The special location monitor runs independent scan loops with per-location parameters:
| Location Type | Free Buffer Target | Scan Interval | Priority |
|---|---|---|---|
/dev/shm |
20% | 3s | 255 |
| ramfs | 18% | 4s | 220 |
| tmpfs | 15% | 5s | 200 |
User-defined (/tmp, /data/tmp) |
15% | 5s | 155-160 |
| Custom paths | 15% | 5s | 140 |
Priority determines scan order when multiple locations need attention in the same cycle. Higher-priority locations are checked first.
Each location learns its own capacity-consumption rate, including mounts outside
scanner.root_paths. A fresh observation from the main mount monitor supplies a
prior while the local estimator warms up. Cached readings retain their original
timestamps and never count as new samples. A changed filesystem, resized volume,
failed read, or gap longer than three nominal polling intervals restarts local
learning. Stable or increasing available space clears the consumption signal.
The horizon can therefore warn about a rapidly filling tmpfs before its fullness
threshold is crossed, without adding cleanup roots or releasing disk ballast.
The registry asks the active Platform Abstraction Layer (PAL) for mount inventory. Linux reads /proc/mounts; macOS uses its PAL mount inventory from statfs/getmntinfo and APFS metadata. Fallback entries for /tmp and /data/tmp are added when they are not already covered. Operator-provided custom paths can override auto-discovered defaults. Duplicate paths are deduplicated, with later entries taking precedence.
Swap-Thrash Detection
The daemon monitors swap usage relative to available RAM. When swap utilization exceeds 70% while available RAM drops below 8 GiB, the system flags a swap-thrash risk. If available RAM remains ample, high swap usage is treated as normal cold-page offloading rather than thrashing.
Swap-thrash warnings are rate-limited to one per 15-minute window to avoid log noise during sustained pressure.
On Linux, less than 10% free swap also supplies an independent pressure signal
for occupied tmpfs mounts covered by scanner roots. A mount can therefore
reclaim eligible artifacts while its own filesystem free percentage is still
Green. Each relief pass has a finite byte target, accepts only structurally
definite artifacts on the same tmpfs device, and rechecks swap headroom before
each removal. Existing protection, active-use and policy checks remain in
force. sbh status shows the swap backing separately from real filesystem
free space. See RAM-scratch relief
for its scope and accounting limits.
# View swap status in the status report
sbh status --json | jq '.memory'
Source: src/monitor/special_locations.rs, src/daemon/loop_main.rs
Temp Artifact Fast-Track
Under Orange or Red pressure, recognized temporary artifacts in /tmp, /var/tmp, /data/tmp, and /private/tmp receive an adjusted age that allows them to cross the deletion threshold sooner. This accelerates cleanup of build debris in temp directories during pressure spikes without bypassing the scoring system entirely.
Constraints:
- A 2-minute minimum observed age safety floor prevents deletion of very recently created files, even under pressure.
NodeModulesandPythonCacheartifact categories are excluded from fast-tracking because they may contain active dependency trees.- Only artifacts with high-confidence pattern matches (>= 0.85 name confidence or specific known patterns like
cargo-target-prefix,agent-ft-suffix,tmp-codex) qualify.
Green and Yellow pressure levels do not trigger fast-tracking.
Source: src/daemon/loop_main.rs
Active Log Truncation
Some agent workloads hold long-lived write handles (O_WRONLY) on log files (such as codex-tui.log) that grow without bound. The standard deletion path is prevented by open-file safety vetoes, and unlinking an open file would orphan the inode without releasing disk blocks until the process exits.
Under [scanner.log_truncation], sbh reclaims this space in place via ftruncate(2) (Rust File::set_len(0)):
- Inode size drops to zero immediately, returning blocks to the filesystem.
- The inode and file descriptor remain valid, so active writers continue appending without disruption.
Configuration:
[scanner.log_truncation]
enabled = true
min_size_bytes = 104857600 # 100 MiB threshold before truncation
paths = ["/data/projects/*/*.log", "~/.local/share/*/logs/*.log"]
Manual operator truncation is available via sbh truncate-logs [--dry-run] [--yes].
Automatic log truncation requires Enforce mode. Observe, Canary, FallbackSafe
(including the kill switch), and scanner.dry_run report potential reclamation
without truncating logs. The daemon rechecks live policy and configuration before
each mutation, so a reload or policy demotion revokes an in-flight sweep.
The automatic age exception uses each log's own filesystem free percentage
against pressure_free_pct_ceiling. It is renewed on the verified open file
immediately before truncation. A queued scan's old pressure, or a full tmpfs
on another mount, cannot shorten min_age_minutes. If local pressure recovers
or cannot be established, ordinary age-qualified maintenance remains eligible.
Source: src/scanner/log_truncator.rs
Guardrails and Drift Detection
The guardrail system continuously validates that the EWMA forecaster's predictions match reality. When predictions diverge from actuals, the guardrails trigger policy fallback before bad predictions can drive bad deletion decisions.
Calibration Monitoring
Each observation window compares the forecaster's predictions against actual outcomes:
- Rate error:
|predicted_rate - actual_rate| / |actual_rate|. Must stay below 0.3 (30%). - Time-to-red coverage: the conformal lower bound on the time to red (below) must have covered the true time in at least
coverage_target - 0.05of the resolved predictions.
Guard status transitions from Unknown to Pass after 60 observations if calibration holds, and transitions to Fail if the median rate error exceeds 0.3, the empirical coverage falls below the tolerance, or the e-process alarms.
Conformal Time-to-Red Bound
The EWMA forecaster's time-to-red is a point estimate; acting on it has no stated error rate. Each mount keeps an online split-conformal calibrator (monitor::conformal): every prediction inside a two-hour horizon is enrolled while the mount is filling at a material rate, and resolves either when the red threshold is crossed (the elapsed time is the truth) or when its own horizon passes without a crossing (a censored observation scored as zero). Pending predictions are discarded when an intervention (ballast release, a reclaim) changes the trajectory. The nonconformity score is the relative under-prediction of time, and the bound is the point estimate shrunk by the (1 - alpha) quantile of the last 500 scores. Adaptive conformal inference keeps the guarantee under a shift such as a build burst by moving alpha after every resolved prediction:
s_t = max(0, tte_pred - tte_actual) / tte_pred
tte_lo = tte_pred * (1 - q_{1-alpha}(s))
err_t = 1[tte_actual < tte_lo issued with the prediction]
alpha_t+1 = alpha_t + 0.01 * ((1 - coverage_target) - err_t)
The controllers act on tte_lo: it is the PID feedforward input, the mount controller's seconds-to-red, and the predictive policy's estimate (the time to exhaustion is shrunk by the same factor). Below 30 resolved samples the bound is the point estimate and the state is warming. pressure.prediction.coverage_target (0.90) sets the guarantee; sbh status shows red in >=<lo> (point <estimate>), sbh check --predict uses the bound, state.json carries rates.<mount>.forecast, decision records carry the bound and coverage at decision time, and the daemon logs a forecast mount=.. tte_point=.. tte_lo=.. alpha=.. coverage=.. samples=.. line per filling mount per minute that sbh stats --json aggregates as forecast.coverage_by_day.
If calibration collapses the bound to zero or below one percent of a positive
point estimate, the lower bound cannot support an informative deadline. This
also covers the first tiny positive bounds as calibration recovers from severe
misses. sbh status reports
red runway unknown with the point estimate and observed coverage. Numerical
notifications derived from that bound are suppressed; the unadjusted forecast
can still support a warning after passing the predictive policy's normal gates.
Measured pressure alerts and conservative controller actions still apply. The forecast object
sets runway_unknown: true and retains both tte_point_s and tte_lo_s, while
the reported seconds_to_red and seconds_to_full are null. sbh check --predict
still uses the original bound and exits with code 1 when that bound cannot
establish the requested safe window, with reason: "forecast_runway_unknown",
null deadline fields, and the exact lower bound preserved in
seconds_to_red_lower_bound and the nested forecast. A reached red threshold
keeps its measured zero and normal warning behavior; a genuinely short point
forecast remains reportable.
The dashboard shows the same mount's published time to red, distinguishing the
point estimate from its conservative bound. Missing, stopped, stale or invalid
forecasts remain unknown; a trend without a forecast never substitutes an
invented filesystem capacity. The horizon stays visible in compact overview cards.
E-Process Drift Detection
The e-process is an anytime-valid sequential hypothesis test that detects systematic miscalibration without parametric assumptions. It works as a running likelihood ratio:
For each observation:
if well-calibrated: e_process_log += ln(0.8) (reward, moves toward 0)
if miscalibrated: e_process_log += ln(1.5) (penalty, moves toward alarm)
e_process_log = clamp(e_process_log, -5.0, 5.0)
e_process_value = exp(e_process_log)
alarm = (e_process_value >= 20.0)
The clamping bounds serve specific purposes:
- Lower bound (-5): Prevents "banking" too much credit from long good streaks.
exp(-5) ~ 0.0067, ensuring that even after extended good behavior, the alarm can fire within ~10-15 bad observations. - Upper bound (3.5): Prevents runaway alarm state.
exp(3.5) ~ 33, so an alarm clears after a bounded number of good observations once the anomaly passes.
When the e-process value reaches the threshold (20), it signals systematic drift in the forecaster's calibration and triggers GuardrailDrift fallback in the policy engine. On recovery from fallback, the e-process resets to 0.0 so accumulated history doesn't bias future detection.
Dual Logging and Observability
Every significant event is logged to two independent backends: SQLite for queryable analytics and JSONL for crash-safe audit trails.
SQLite Backend
The SQLite logger operates in WAL (Write-Ahead Logging) mode with synchronous=NORMAL, trading some crash durability for write throughput. It stores structured rows for pressure changes, artifact deletions, ballast operations, errors, and policy transitions.
The stats engine queries this data for sbh stats reports: time-window aggregation, top-N deleted patterns, deletion success rates, and pressure-level distribution over time. The sbh blame command combines live process observations with recent I/O history from io_history.bin beside the daemon's state file. The daemon loads, samples, and saves this optional history on one background worker, so a slow process probe or snapshot write cannot delay pressure handling. A blocked operation retains its worker slot; shutdown stops further probes and prevents a new snapshot from starting.
Deleted files that still occupy space. On Linux, a process can keep a file's allocated blocks after its last directory link is removed. Directory scans cannot attribute that allocation. Inspect these holders without a running daemon or a readable configuration file:
sbh blame --deleted-open
sudo sbh --json blame --deleted-open --top 50 --timeout-secs 30
The report ranks unique (device, inode) observations by allocated bytes and
lists their process holders, descriptors, running executables, file-backed
memory mappings, logical lengths and observed mount identities. It finds
unlinked executable images and mapped files even after their descriptors close.
Repeated descriptors, mappings and files shared by several processes contribute
only once to the allocation total. --top limits each displayed list; totals
still include every verified file in the bounded inventory.
--since and --tree belong to ordinary I/O blame and cannot be combined with
this mode.
Inspection reads metadata, process identities and kernel reference links; it never
reads file contents, signals a process or truncates a descriptor. The default
cooperative deadline is 10 seconds (--timeout-secs accepts
files and 16384 holders (including unverified mapping records). Kernel I/O
already in progress can overrun the deadline.
Permission failures, changed identities, unknown mount attribution and exhausted
budgets remain explicit coverage issues. Partial inspection exits 4
(partial success) and retains
the observed allocations. An unsupported platform reports supported: false
with a null byte total and exits 0 (ok).
JSON uses sbh.deleted_open.v2, with observed_allocated_bytes,
observed_unique_files, files, files_omitted, complete and issues.
Each holder has a nullable fd, descriptor_count, mapping_count,
representative_mapping and executable flag. reference_target and mount
paths also have byte-preserving hexadecimal fields. Scope is the references
visible in the caller's process namespace; processes hidden in other namespaces
are excluded. RAM-backed files can appear too. Observations are not an atomic
snapshot, and shared extents or snapshots may retain blocks after a holder
closes them. Review the owning application's close/reopen operation or a graceful
service restart; deleting the former pathname again cannot free these blocks.
Linux may allow reading a mapping's target name while denying the metadata
needed to measure its allocation, even for root in a restricted container.
Such deleted-looking mappings appear in unverified_mappings, with their PID,
address range, native target bytes and reason. They make the result incomplete
and contribute no bytes to observed_allocated_bytes. A (deleted) suffix
alone does not prove that no hardlink remains, and can be part of a literal
filename. Mapped lengths and RSS are never substituted for filesystem allocation.
Automatic retention pruning removes rows older than 30 days, triggered every 3600 events (approximately hourly at typical event rates).
JSONL Backend
The JSONL writer appends one JSON object per line to a file, providing a portable, grep-friendly, append-only log. Lines are assembled in memory and written atomically to prevent interleaved partial lines when multiple tools tail the file.
In the daemon, rotation triggers when the file exceeds 50 MiB, keeping up to 5 rotated files, and fsync runs every 30 seconds: on the next write once the interval has passed, or from an idle timer when no write arrives, so a burst of lines before a quiet spell is still made durable. (The library defaults, used by tools that embed the writer, are 100 MiB and 10 seconds.)
Degradation Chain
If the SQLite backend fails (disk full, corruption, permission error), the logger falls through a degradation chain:
- Track consecutive SQLite write failures (events that produce no SQLite row do not reset the count).
- After 3 consecutive failures, disable SQLite and log only to JSONL.
- Every 50 events while disabled, attempt to reopen the SQLite connection; on success the counter resets and rows resume from the next event.
- If the JSONL file cannot be written, fall back to a RAM-backed file:
/dev/shm/sbh-<uid>.jsonlon Linux,$TMPDIR/sbh.jsonlon macOS. The fallback is never rotated; it is truncated when it would exceed 16 MiB, so a long outage of the primary path cannot fill/dev/shm. The primary path is retried periodically and writing returns to it as soon as it works. - If that fails, write to stderr with
[SBH-JSONL]prefix. - If even stderr fails, silently discard (the daemon never blocks on logging).
At open, a database whose auto_vacuum is not FULL is converted with one VACUUM only when it is larger than 64 MiB; smaller files keep their setting, because the rewrite would cost more than it could ever reclaim.
The daemon's own files on a volume it reclaims. A full disk breaks the logger exactly when it matters, so at startup the daemon checks whether the activity database, the JSONL log and state.json share a mount with a scan root, a special location or a ballast pool. It is not a refusal (single-volume hosts are common): the daemon logs one logging.on_monitored_fs=... device=... paths=[...] line, records it in state.json under logging, sbh status prints a warning, and sbh doctor --system reports logging.on_monitored_fs (WARN, or FAIL while that mount is at Orange or worse). While the mount is pressured the daemon mirrors every JSONL line to the RAM fallback as well and says so once per level change. state.json itself is padded to a fixed 64 KiB and, when the atomic temp-file write cannot allocate, is rewritten in place, so status keeps updating on a full volume.
The logger thread runs on a bounded channel (capacity 1024). When the channel is full, events are dropped and a counter is incremented. The drop count is reported periodically as a delta (not cumulative) to avoid alarm fatigue.
Notification Channels
The daemon dispatches alerts through four notification channels, each with independent severity filtering:
| Channel | Transport | Default Min Level |
|---|---|---|
| Desktop | notify-send (Linux) / osascript (macOS) |
Orange |
| Webhook | HTTP POST via curl (5-second timeout) |
Red |
| File | JSONL append to ~/.local/share/sbh/notifications.jsonl |
Info |
| Journal | systemd/launchd stderr capture; macOS unified logging | Warning |
Default active channels are journal and file. Desktop and webhook channels are opt-in.
Each channel has one retained delivery worker and a 64-entry queue. Notification
enqueue and configuration reload do not wait for the destination; a stalled
channel retains its worker while the other channels can continue. Reloads cancel
queued deliveries for changed or disabled destinations, although a delivery
already in progress may still finish. Full or disconnected queues drop new
deliveries, and the daemon reports the loss count through [SBH-NOTIFY] activity
events. Shutdown gives pending notifications one shared one-second delivery
window. This is best-effort delivery, and other synchronous daemon diagnostics
can still wait on service-log I/O.
Special-location alerts, swap-thrash warnings, and combined critical memory/disk alerts remain eligible for retry while their incident continues if no channel accepts them. Episode suppression and delivery cooldowns begin after a successful enqueue; activity-log throttling remains independent. A pending combined emergency is discarded after the effective behavior recovers or the configured cell stops requesting emergency notifications. A recovery still waiting for its hysteresis window does not clear the active emergency.
On macOS, the desktop channel uses osascript -e 'display notification ...' as the
first supported user-notification path. The root LaunchDaemon runs it in the
console user's session (launchctl asuser), and does nothing when nobody is
logged in. It is on by default on macOS at critical only, because the
LaunchDaemon's other channels write to files nobody watches; configs written
by an older install keep their explicit enabled = false until edited. Red and Critical events are still
throttled per event category by urgent_notify_interval_secs (default five
minutes), so a Critical+Critical memory/disk event can alert promptly without
spamming Notification Center.
Notification event types: PressureChanged, PredictiveWarning, CleanupCompleted, BallastReleased, BallastReplenished, BehaviorEmergency, DaemonStarted, DaemonStopped, Error.
Severity levels (ordered): Info, Warning, Orange, Red, Critical. Each channel only dispatches events at or above its configured min_level.
The webhook channel supports template strings with placeholder substitution:
[notifications.webhook]
enabled = true
url = "https://hooks.example.com/sbh"
min_level = "red"
template = '{"text": "sbh: ${SUMMARY}", "level": "${LEVEL}", "mount": "${MOUNT}", "free_pct": "${FREE_PCT}"}'
Source: src/daemon/notifications.rs
Emergency Recovery
When a disk is at 99%+ utilization, normal operations may fail because they need to write temporary files, state, or logs. sbh emergency begins reclamation without a database or configuration-file prerequisite. It uses built-in defaults and in-memory scoring, reports to stdout/stderr, and leaves daemon state files untouched.
After a quarantine drain physically removes payloads and finalizes their recovery records, the command tries to save completion receipts in the default activity ledger. Payloads left partial, absent, restored, or refused produce no success receipt. A drain without completions never opens the ledger; a receipt-write failure warns and does not stop recovery.
Independently of SQLite, emergency unlinks and quarantine purges write a private JSONL audit record before attempting irreversible work, then a correlated completion, cancellation, or incomplete outcome. A recursive removal can fail after deleting some children: incomplete records keep reclaimed bytes unknown and never count as successful deletions. An attempt with no terminal record means the outcome is unknown, including after a crash. Receipt I/O is advisory; failed writes cannot prevent emergency recovery. The executor renews live deletion authority after the attempt is written. Declined prompts, previews, and candidates refused before an attempt do not create receipts.
Receipt destinations are /var/lib/sbh/emergency for root, then $XDG_STATE_HOME/sbh/emergency and $HOME/.local/state/sbh/emergency. If these locations cannot accept a record, the command tries the originally requested directories in order and writes to <target>/.sbh-emergency-<effective-uid>/. The target must still identify the original directory and protect its children against removal by other users. The private receipt directory carries a .sbh-protect marker. Use --receipt-dir DIR to select a single destination, including one on another filesystem. A receipt destination inside the payload being removed is refused. Stderr prints the selected file. Records include the decision ID, attempt ID, path, size estimate, classification, score, outcome time, and invoking process. Artifact unlinks include the checked identity and modification time. Each record is synchronized. Creating a receipt store also synchronizes every new directory entry before writing records; a retry repairs any interrupted directory synchronization before claiming durable coverage.
Use sbh explain --id ID to inspect the latest emergency audit record in the default private receipt directories, even if the configuration or activity ledger is unreadable. To recover the history without knowing a decision ID, use sbh explain --last 20, sbh explain --path /path/to/removed/target, or sbh explain --since 2h --limit 50. These selectors combine the default emergency audit stores with the available SQLite or retained JSONL decision ledger, sort by the recorded instant, and apply one limit across both sources. Each audit phase is a separate history row with its original receipt; attempted or incomplete work is never presented as a completed deletion. Identical copies of the same identified attempt's record, left by a retry in another store, count once before history limits apply. Different outcomes and older receipts without attempt IDs remain separate. Scored decisions retain their factors, recovery state, outcomes, and planner evidence. Relative paths still work after an artifact is removed, and recorded raw path bytes distinguish non-UTF-8 names.
sbh log --type deletion remains a view of completed removals across the daemon activity log and your default receipt locations; attempts and incomplete work are excluded. The combined snapshot applies --tail across both sources. --follow watches the selected file. For a target-local receipt, a custom receipt directory, or a copied file, inspect all audit events with sbh log --emergency-receipt FILE, or resolve an operation with sbh explain --emergency-receipt FILE --id ID.
For target-local receipts across runs, use sbh log --emergency-receipt DIR --tail 50 on the private directory to see all audit phases in chronological order. Add --type deletion for completed removals only, or an event filter such as --type emergency_deletion_attempt. For example, after a root-run emergency targeting /data/tmp, use sudo sbh log --emergency-receipt /data/tmp/.sbh-emergency-0. Directory imports enforce the same owner-private, regular-file checks as default receipt discovery and work without a readable configuration.
To investigate a decision ID across all runs in a target-local store, use sudo sbh explain --emergency-receipt /data/tmp/.sbh-emergency-0 --id ID. It returns the latest audit record for that ID, including an attempt without an outcome or an incomplete removal.
The emergency command scans the specified paths, scores candidates using the standard multi-factor engine, and presents them for immediate deletion. With --yes, it executes deletions immediately without interactive confirmation, prioritizing the highest-scoring candidates until the target free space is reached or all candidates are exhausted. Because no config is read, --min-age <MINUTES> (default 5) is the only age floor: artifacts modified more recently are left alone, and --min-age 0 reclaims fresh builds too. Every candidate is printed with its decision id (id <hex> in the plan, candidates[].decision_id in --json), the same id sbh scan and sbh clean would record, so a later sbh explain --id can be matched against what emergency acted on.
Directory discovery uses a 60-second budget and retains at most 100,000 directory
observations by default. Set --scan-budget-secs SECONDS and
--max-scan-entries COUNT to adjust these positive limits, or select narrower
paths. Discovery cancellation allows up to two additional seconds for coverage
evidence; a blocking filesystem call can outlast the time budget. Scoring and
cleanup have their own work after discovery.
When a limit interrupts discovery, only fully inspected subtrees remain eligible
for removal. Unseen descendants and unavailable coverage always keep an
enclosing artifact safe. JSON reports discovery_budget.limit_reached and
stop_reason (entry_limit or time_budget). An interrupted best-effort scan
returns partial-success status 4 unless every recovery goal is verified;
existing failures keep their nonzero status. A filesystem that has already
recovered does not need a complete inventory to succeed.
The default emergency byte target is 10% free. A byte or inode target above 10% requires
--force, including when --target-free-inodes is the only elevated target.
Emergency admits Review-classified artifacts that ordinary
cleanup retains. The command rejects an unacknowledged larger target before
scanning or purging quarantine. Use sbh clean --target-free N for routine
headroom maintenance. --force acknowledges only the larger recovery target;
--yes or interactive consent and every protection, identity, age and open-file
check still apply. Emergency uses this built-in ceiling without reading config.
The final report measures available bytes on each requested path, including when the scan finds no candidates. A script can require verified headroom before restarting work.
sbh emergency /data --target-free 15 --force --require-target --yes
Success then requires verified recovery on every path. The command skips
already recovered peer roots when choosing quarantine stores and directory
walks. It refreshes each requested root's capacity after reserve release and
again after quarantine, before choosing which roots still need a scan.
Explicitly selected nested filesystems retain their own recovery goals. Missing,
changed, or unobservable roots remain unverified in the final report. A skipped
healthy nested root also prevents cleanup of an enclosing artifact whose scan
could omit that root's safety evidence. When all
requested byte and inode targets are already met, verified recovery reports the
measurements immediately. A quarantine drain that supplies the remaining
headroom also avoids a subsequent scan. Ordinary byte-only emergency runs
without --require-target or --ballast-dir retain their full candidate inventory.
An unmet target exits 1, unavailable evidence exits 2, and either condition after
a completed removal exits 4. Without --require-target or --ballast-dir,
byte-only cleanup keeps its usual exit behavior. Both modes report the measured
outcome in --json under
recovery_goals.
If files cannot be created because the filesystem has exhausted its inodes, request an inode recovery target even when plenty of bytes remain:
sbh emergency /data --target-free-inodes 10 --yes
--target-free-inodes PERCENT adds an available-inode goal to the existing
--target-free byte goal; cleanup stops on each filesystem only when both are
met. It requires fresh, finite, consistent inode accounting and holds cleanup
when that evidence is unavailable. The final human report shows the remaining
capacity; --json includes recovery_goals with observed inode counts and
target outcomes. An unmet or unverifiable explicit goal produces a nonzero
exit status, including partial success when artifacts were reclaimed. Omitting
the flag keeps the usual byte-only stopping rule.
Emergency escalation: unlike sbh clean, emergency mode also acts on candidates whose decision-theoretic outcome is Review (score cleared the threshold and nothing vetoed them, but the keep-vs-delete loss margin was too ambiguous for unattended deletion). Review means "a human should look" — in emergency mode the human is looking, via the interactive confirmation or an explicit --yes. Without this escalation, a candidate corpus that is 100% Review would make the last line of defence a silent no-op on a critically full disk. Unambiguous Delete decisions are still executed first; every hard safety rail (vetoes, sacred paths, .sbh-protect markers, and the .git/Cargo-manifest/source-tree/open-file/active-lease pre-flight checks) applies unchanged.
Emergency confirmation also covers permanent removal of quarantined undo copies. When a requested directory is below an earlier cleanup root, emergency also searches that filesystem's ancestor stores for entries originally beneath the requested directory. A shared store's unrelated entries remain available to undo. The command renews the selected scope, original parent and store identity before removing each reviewed payload; a missing or changed parent cannot authorize removal.
Noninteractive use requires --yes before any drain; interactive use
asks separately before removing the reviewed quarantine entries. Refusing
that prompt preserves them. Draining honors the target on each filesystem and
stops on missing capacity evidence. Completed removals contribute to the
command's totals even when the later scan finds no candidates; JSON also
reports the separate quarantine_drain outcome. Failed or unfinished drains
produce a partial-success result, while a satisfied filesystem does not stop
cleanup on other requested filesystems.
Emergency recovery does not require a successful ledger write, so unavailable logging cannot prevent reclamation on a full disk.
Scanner Indexes
The live daemon has two index-related code paths:
src/scanner/index.rsis the v2 daemon candidate index. It stores one record per candidate root keyed by filesystem identity, persists toscanner-index-v2.json, records event generations, and keeps per-candidate deletion-failure backoff. It is active only whenscanner.engine = "v2".src/scanner/merkle.rsis an older Merkle-tree index implementation. It remains tested library code, but it is not the live daemon scanner index and should not be read as the current daemon behavior.
v2 uses the candidate index to avoid cold full walks under pressure. At Green or Yellow pressure with no dirty event roots, it can report a no-op scan without recursively walking configured roots. Under Orange or higher pressure, it ranks persisted candidates first and only runs bounded reconciliation when the index or event state requires it. All deletion still goes through the same policy engine and final pre-flight safety checks.
Completed scanner passes also check up to 256 indexed path bindings for confirmed disappearance or replacement, advancing across candidates and their aliases on successive passes. This retires deleted event-invalidated entries even when the event generation has not changed or a pass finds no new candidates. Unreadable bindings retain their safety vetoes and failure backoff; surviving aliases keep their safety relationships and require fresh scoring before replay if promoted. The probe budget bounds maintenance work, not the total size of a live index or the duration of an individual filesystem call.
What feeds the index is platform-specific, and the daemon says which at startup (scanner_events: backend=... complete=... reason=... in the activity log, sbh scan --json capability fields):
- Linux: recursive
inotifywatches over the configured roots, planned againstscanner.event_watch_budget(8192 by default). Every root and every depth-1 directory always gets a watch; the rest of the budget goes to the most active directories, ranked by a per-directory event-rate EWMA with a directory-mtime prior for subtrees that have never been watched. Directories left without a watch under a watched parent form the frontier: they are reconciled as their own scan paths (never the whole root, unless a root has more than 256 of them) and afterwards rely on the maintenance pass. While the plan is incomplete the daemon re-plans every 15 minutes from the observed rates, restarting the watches without losing events. A change under a project resolves to that project directory (the depth-1 directory below the configured root) as the scan path; the root itself is used when the change is at the root, when that directory is an artifact tree, or when more than 64 projects are dirty at once. The scanner polls the event source every 2 seconds while idle and runs the scoped pass itself at Green or Yellow (reason=eventinscan_complete), paced by the basemin_rescan_interval_secsonly, so a newtarget/is seen within seconds instead of at the next maintenance walk. An inotify queue overflow reconciles everything once and then backs off: overflows inside the backoff window (30 s, doubling per consecutive overflow up to 30 min) are coalesced into one deferred reconciliation. The activity log carriesfrontier_dirs,overflows,backoff_secsandreplans, andscan_completedetails carryevent_overflowsandevent_watch_replans.fanotifyis not implemented: the crate forbidsunsafe, the safe wrapper available to it does not report file handles (FAN_REPORT_FID), and filesystem-wide marks needCAP_SYS_ADMIN, which a user-scope service does not have. The capability probe reports it as deferred. - macOS: a recursive FSEvents stream over the configured roots (
crates/sbh_machowns the native stream behind safe wrappers;src/scanner/events/fsevents.rstranslates paths and invalidates the scanner view). Startup and every replan mark the roots dirty, so the first pass after a daemon start reconciles instead of replaying the candidate index; a dropped or overflowing stream forces a full reconciliation.scanner.event_source = "reconciliation-only"turns it off. - Everything else: reconciliation only; the bound on staleness is the maintenance cadence (
pressure.maintenance_interval_secs) plus the pressure-driven passes.
On Linux and macOS, a configured root whose initial metadata lookup reports that it does not exist is tracked separately from coverage gaps. Existing roots retain their watches; absent roots are checked every 30 seconds without rebuilding healthy coverage. When one appears, the scanner immediately revokes the old index generation, reconciles the roots, and installs coverage for the new directory. Permission failures, unreadable directory listings, disappearing descendants, invalid root types, dangling root links and exhausted watch budgets still require reconciliation. Both platforms follow explicitly configured directory links, preserving their configured spelling and periodically rechecking their canonical identity; links discovered inside the scanned tree remain excluded. On Linux, configured links to the same canonical directory share physical watches, and events invalidate each configured spelling. A changed or unverifiable root binding withdraws event coverage and triggers reconciliation and watch repair. Linux root-identity audits run on a bounded background worker, so a stalled lookup cannot block event draining or accumulate replacement workers. Explicit reconciliation-only mode and a zero watch budget continue to disable event subscriptions. The default roots remain /tmp, /data/tmp, /var/tmp on Linux; other platforms default to /tmp, /var/tmp (macOS configuration loading also includes the user's temporary directory unless opted out).
Subscriptions follow the configured roots, independently of which roots a particular pressure or maintenance pass selects. Alternating pass scopes no longer rebuilds watches or invalidates the whole index. Events outside the current request remain pending until a relevant pass covers them; pending work does not widen that request's scan scope. Special or catalog-derived request paths outside the subscription set receive explicit reconciliation. Genuine configuration changes and overflow recovery still invalidate stale evidence.
For validation and A/B artifacts, sbh scan --json reports scanner_engine, scanner_dispatch, opaque_pruning, opaque_pruned_dirs, scanned_entries, and nullable process_cpu_micros alongside the existing candidate totals. Daemon scan_complete activity events also include the selected dispatch, pruning state, dirty event-root count, index generation, indexed-record count, candidate bytes seen, and timeout state in their details payload, plus process_cpu_micros= when the pass measured its CPU. sbh stats --json aggregates those events into a scanner block (cpu_seconds_by_day, passes, entries_scanned, opaque_pruned_dirs), and human sbh stats prints the scanner's 7-day CPU-seconds/day average. These fields are intended to make v1/v2 scan captures auditable without scraping human output.
The in-repo scanner-v2 validation tests emit focused JSON artifacts for synthetic v1/v2 walk effort and safety parity, event-overflow reconciliation fallback, and memory-pressure transition latency. v2 has been the default engine since v0.4.32 (it is what the production fleet runs and it is required for structural detection of caches under arbitrary names, such as Go's GOCACHE); the A/B evidence measured on 2026-09-02 is in docs/internal/scanner-ab-2026-09-02.md and does not yet meet the design document's promotion criteria (a one-shot sbh scan of a large project tree costs v2 3.4x the CPU of v1 because of its opaque-root size probes, and the daemon's v2 steady state was a replay hot loop rather than a cheap rescan), so engine = "v1" remains available as the rollback.
For a live A/B capture, one command runs v1 then v2 in-process over the same roots (the page cache is warmed by an untimed v2 pass first, so both measured passes see the same state) and emits the comparison artifact, including the promotion blocker v2_candidates_vetoed_by_v1:
sbh scan --ab /data/projects --top 200 # human summary
sbh scan --ab /data/projects --top 200 --json --out ab.json # artifact JSON
Compare scanned_entries, process_cpu_micros, candidates, hard vetoes, and the only_in_v1 / only_in_v2 sets; v2 promotion requires v2_candidates_vetoed_by_v1 to be empty.
The v2 checkpoint contains a version, root/config fingerprint, event generation, serialized candidate records, and a SHA-256 integrity hash. If it is missing, stale, or corrupt, v2 rebuilds conservatively through bounded reconciliation rather than trusting stale state.
Source: src/scanner/index.rs; legacy Merkle implementation: src/scanner/merkle.rs
Parallel Directory Walker
The walker is the scanner's "eyes": it discovers candidate files and directories, collects structural markers for the scoring engine, and integrates with the protection system to skip .sbh-protected subtrees.
Work-Stealing Parallelism
The walker uses an unbounded work queue shared across N worker threads (configurable via scanner.parallelism) and a bounded result channel (up to 10000 entries) back to the collector. Root paths are seeded into the queue, and each worker pulls a directory, processes its entries, and enqueues discovered subdirectories back onto the shared queue. A worker sends its results in batches of up to 64, and sends whatever it holds before it waits for more work, so the collector waits once per batch instead of once per directory. Workers that find an empty queue wait briefly (50ms timeout) before checking whether all work is complete. This design provides natural load balancing — workers that finish fast directories steal work from threads processing slower ones — without requiring explicit work-stealing data structures.
On Linux, each detected btrfs device admits at most 1 directory task at a time. Deferred directories wait outside the ready queue, leaving workers available for other devices and filesystems. Opaque candidate sizing uses the same admission queue, and directories crossing a mount are assigned to their actual device before traversal. Configured roots, opaque candidates, and crossed mounts are checked again after waiting so a replaced path cannot inherit an earlier directory's identity or classification.
An atomic in_flight counter tracks ready, deferred, and running work. When the last item completes (counter reaches zero), workers exit. The work queue is unbounded so workers never deadlock when enqueuing discovered subdirectories, while the result channel is bounded to prevent unbounded memory growth on deep trees. Cancellation reports both ready and deferred directories as unfinished.
Per-Directory Iteration Cap
Directories with tens of thousands of entries (e.g., /data/tmp with 60K+ children, node_modules flats) can monopolize a worker thread for seconds. A pass stats and queues at most 65536 entries of one directory. A directory with more is taken a window at a time: the next pass continues where this one stopped, and after the last entry the window starts over, so no entry is skipped on every pass. Every name in the listing, up to 1048576, is still read: a .sbh-protect marker anywhere in it protects the directory, and structural signals (.git, Cargo.lock, deps/, build/) count wherever they appear. This keeps any single pathological directory from starving other workers.
Open-File Detection
Before any candidate is scored for deletion, the walker collects active-reference evidence across visible processes. On Linux, this scans /proc/*/fd symlinks to build a set of (device_id, inode) pairs representing currently open files. On macOS, it uses PAL/libproc process, fd, executable, and mmap probes to produce the same safety signal. Two budget limits prevent this scan from hanging the daemon on busy machines:
| Budget | Limit | Purpose |
|---|---|---|
| Time | 30 seconds | Bounds the sweep while leaving a CPU-capped (CPUQuota=10%) daemon room to finish on a loaded host |
| PIDs | 50,000 | Caps scan even if individual PIDs are fast |
If either budget is exhausted, the scan returns a partial set. The system fails conservative: a partial open-file set means some open files might be missed, but the pre-flight safety checks provide a second layer of defense.
During scoring, an OpenPathCache provides memoized subtree-open checks. For each candidate directory, it walks the directory tree checking inodes against the open set, caching results so that parent directories are not re-scanned for sibling candidates.
Cross-Device and Symlink Safety
Two invariants prevent the walker from escaping its intended scope:
Cross-device guard: Unless
scanner.cross_devicesis explicitly enabled, the walker records each root path's device ID at seed time. When processing subdirectories, any entry on a different device (i.e., a mount point) is skipped entirely. This prevents accidentally walking into large foreign filesystems mounted under a watched path.Symlink safety: By default, the walker uses
symlink_metadata()(lstat) rather thanmetadata()(stat), so symlinks are examined without following them. Symlinks to directories are not enqueued for traversal, preventing symlink loops and escapes outside watched paths. The pre-flight safety checks independently reject symlinks at deletion time.
Source: src/scanner/walker.rs
Signal Handling and Daemon Lifecycle
The daemon responds to Unix signals for graceful lifecycle management. All signal flags are polled by the main loop each iteration rather than processed in signal handler context, avoiding async-signal-safety concerns.
| Signal | Effect |
|---|---|
SIGTERM / SIGINT |
Graceful shutdown: completes the current operation, writes final state, exits cleanly |
SIGHUP |
Configuration reload: re-reads config.toml and applies changes without restart |
SIGUSR1 |
Immediate scan trigger: bypasses the VOI scheduler and runs a full scan on the next iteration |
Signal registration uses the signal-hook crate for safe, portable signal handling. Registration is best-effort: failures are logged to stderr but do not prevent daemon startup. The SignalHandler can also be triggered programmatically (e.g., by the watchdog timeout or error escalation logic) for shutdown requests that originate from within the daemon.
Control Socket
A running daemon also answers requests on a Unix domain socket,
control.sock beside state.json (mode 0600, so only the daemon's user
can connect). One JSON line in, one JSON line out:
{"cmd": "ping", "args": {}, "token": "<32 hex characters>"}
{"ok": true, "result": {"pid": 4242, "started_at": "...", "version": "0.6.0", "uptime_secs": 91, "policy_mode": "enforce"}}
{"ok": false, "result": null, "error": {"code": "unauthorized", "message": "token does not match the running daemon's lock file"}}
The token is minted at every start and written into daemon.lock, so a
client that can read the lock file can talk and a client left over from a
previous boot cannot. The lock file also records where the socket was
bound: normally beside state.json, but a data directory whose path is
longer than a Unix socket address allows (100 bytes) gets a short
sbh-control-<hash>.sock under the temp directory instead, and clients
read that path rather than deriving it. Every command that changes state
is logged with the caller's uid and pid.
| Command | What it does |
|---|---|
sbh daemon ping |
Identity and liveness from the process itself: pid, start time, version, uptime, policy mode |
sbh status |
Asks the daemon to rewrite state.json first; the JSON reports "source": "socket" (or "state_file" when no daemon answered) |
sbh daemon scan-now |
Queues a forced scan of the configured roots on the next tick (the SIGUSR1 path) |
sbh daemon scan-now PATH... [--force] |
Queues only the selected directories within configured roots; --force bypasses scan pacing |
sbh daemon reload |
Re-reads the config (the SIGHUP path) |
sbh policy status|promote|demote |
Shows or moves the policy mode (observe → canary → enforce and back) and persists the new mode to [policy] initial_mode after backing the config file up |
explain {id} (protocol only) |
The decision ledger record for a decision id, read-only |
ballast {release: N | replenish: true} (protocol only) |
Releases or rebuilds ballast through the coordinator |
sbh daemon shutdown |
A clean stop; the socket file is removed as part of it |
Reload applies pressure, scanner, policy, notification, and telemetry settings
while preserving the current daemon identity. Changing paths.state_file,
paths.sqlite_db, paths.jsonl_log, the active config pathname, or
core.control_socket_enabled requires a daemon restart: those settings bind
the run lease, control socket, and persistence workers at startup. A reload
that changes any of them rejects the entire update, logs SBH-1001 with the
changed keys and a restart instruction, and retains the running configuration.
paths.ballast_dir still supports live rediscovery, and
telemetry.metrics_enabled takes effect on the next state publication.
Selected scans retain their own bounded queue, so routine pressure work cannot
replace an accepted request. Without --force, a selected request waits through
scan cooldown, CPU budgeting, and duty-cycle pacing. --force changes scheduling;
protection, active-reference checks, age rules, dry-run, and the current policy
still govern every deletion. A mixed-filesystem selection is partitioned by its
observed mount so each partition uses that mount's byte-pressure evidence.
Each selected path stays on its own device. When configured cross-device
traversal permits a nested mount, include that mount explicitly to scan it.
sbh daemon scan-now /data/projects/project-a
sbh daemon scan-now /data/projects/project-a /tmp/build-workspace --force
Selected directories are traversal roots. For fresh discovery of an artifact
directory such as target, select its containing project directory so the
artifact itself is considered during traversal.
The daemon rejects the whole request if any selected directory is outside its
current scanner authority or the operator queue cannot accept all partitions.
CLI relative paths are resolved against the client's working directory;
paths containing .. are rejected. Configured-root aliases, directory
identities, exclusions, and protection markers are checked again before the
scan and each mutation. A scope revoked while queued is dropped; revocations
detected during queue refresh are logged. The response's queued: true
acknowledges admission, not completed
cleanup. The protocol accepts args.paths and args.force; an omitted
force preserves the immediate all-root behavior when paths is empty, while
an explicit force: false requests paced reconciliation.
The socket serves eight connections at a time, ten requests per second,
and drops request lines over 64 KiB. [core] control_socket_enabled = false
turns it off, in which case the daemon answers signals and the state file
only and sbh daemon ping explains that no socket exists.
Systemd Watchdog
When running as a system-scope systemd service (Type=notify), the daemon sends sd_notify heartbeats at a configurable interval (default: WatchdogSec=60). If the main loop stalls (blocked IO, deadlock, infinite loop), systemd detects the missing heartbeat and restarts the service automatically via Restart=on-failure. The restart delay (RestartSec=10) prevents tight restart loops.
User-scope services use Type=simple instead, since user session supervisors typically do not support the sd_notify protocol.
Shutdown Coordinator
On receiving a shutdown signal, the daemon runs this sequence:
- Tells the service manager an orderly stop has begun (
sd_notify STOPPING=1). - Sets the shutdown flag (atomic boolean, visible to all threads) and drops the work channels; the scanner and executor stop at their next check.
- Joins the scanner and executor within one shared 25-second budget, five
seconds under the unit's
TimeoutStopSec=30; a worker still running at the deadline is abandoned rather than trapping the stop behind it. - Writes the final
state.json(stopped_at,exit_reason, final counters) sosbh statusreports a clean exit rather than a stalled daemon. - Logs
daemon_stop, flushes the logger, releases the lock and exits with code 0.
state.json also carries a threads block (monitor, scanner, executor,
logger) with each thread's status and seconds since its last heartbeat; a
worker is reported stalled after 60 seconds without a beat and dead when
its thread has exited.
Source: src/daemon/signals.rs, src/daemon/loop_main.rs
Daemon Self-Monitoring
The self-monitor tracks daemon health from within, providing introspection data for the dashboard's Diagnostics screen and for sbh status queries.
Prometheus Textfile Export
With every state.json write (every 30 seconds, or on request from sbh status) the daemon also renders metrics.prom beside it, atomically and world-readable, in the Prometheus text exposition format. Point node_exporter's textfile collector at the data directory (--collector.textfile.directory=/var/lib/sbh for a system install) and the sbh_* families appear with no network surface and no new dependency; sbh metrics prints the same text for hosts without a collector.
The families describe the published state document: sbh_up, sbh_info{version,git_sha,policy_mode,run_id}, sbh_daemon_uptime_seconds, sbh_daemon_cpu_seconds_total, sbh_daemon_rss_bytes, sbh_daemon_cpu_budget_used_ratio, sbh_daemon_cpu_budget_deficit_seconds; per mount sbh_mount_free_ratio, sbh_mount_pressure_level{level} (one-hot), sbh_mount_fill_rate_bytes_per_second, sbh_mount_seconds_to_red, sbh_mount_reclaim_capability{capability}, sbh_mount_controller_state{state}, sbh_ballast_present_bytes, sbh_ballast_target_bytes, sbh_quarantine_bytes; sbh_ballast_files{state}, sbh_ballast_releases_total, sbh_scans_total, sbh_deletions_total, sbh_bytes_freed_total, sbh_bytes_freed_basis{basis} (one-hot: observed, or estimated_allocated / estimated_upper_bound where ext4 or btrfs frees blocks only at commit), sbh_errors_total, sbh_log_events_dropped_total, sbh_last_scan_candidates, sbh_policy_mode{mode} (one-hot), sbh_policy_mode_seconds, sbh_thread_up{thread}. Scan CPU seconds, per-engine scan counts and guard e-values are not exported yet because the state document does not carry them. [telemetry] metrics_enabled = false turns the export off and removes a stale file at startup.
Reserve metrics use observed inventory, independently of disk pressure and the
allocator's cached bookkeeping. Per-pool families carry mount and
ballast_dir; paths containing non-UTF-8 bytes also receive native hexadecimal
identity labels so distinct pools cannot collapse to the same series.
| Metric | Meaning |
|---|---|
sbh_ballast_reserve_state{state} |
One-hot reserve condition: healthy, depleted, critical, exhausted, unknown or unconfigured. |
sbh_ballast_inventory_authoritative |
Whether this pool's availability is confirmed. |
sbh_ballast_inventory_complete |
Whether authoritative observations cover every managed pool; zero while discovery or reload is pending, observations are absent, or any pool is unknown. |
sbh_ballast_present_bytes |
Confirmed releasable bytes; a real empty pool emits zero, while unknown availability omits the sample. |
sbh_ballast_target_bytes |
Reserve target independent of observed availability. |
sbh_ballast_files{state="available"} |
Aggregate available files, omitted if any managed pool is unknown. The total sample retains the configured count. Both samples are omitted while discovery or reload is pending. |
sbh_ballast_refill_blocked{reason} |
Binary indicators for the current policy, safety-floor and observation blockers; several blockers can apply together. |
sbh_ballast_refill_in_progress |
Whether an authorized refill worker is reported for this pool. |
sbh_ballast_reserve_observed_timestamp_seconds |
Timestamp of the pool's last valid observation. |
sbh_state_last_updated_timestamp_seconds |
Timestamp of the state publication that produced the export. |
Textfiles remain on disk if a daemon crashes. Alerting must check publication and observation ages as well as the reserve condition: treat missing timestamps, negative ages, and ages of 90 seconds or more as unavailable evidence. A fresh state publication alone cannot renew an older inventory observation. Use the configured total to distinguish intentionally unconfigured ballast from missing observations; do not replace an absent availability sample with zero or a saved positive value.
Inode metrics remain independent: sbh_mount_inode_accounting_known distinguishes
available evidence from unavailable or disabled accounting;
sbh_mount_inodes_total, sbh_mount_inodes_available,
sbh_mount_inode_free_ratio, and the one-hot
sbh_mount_inode_pressure_level{level} report finite counters and pressure.
The counter and level samples are absent when accounting is unavailable, so an
unknown reading cannot masquerade as either zero available inodes or Green.
Thread Heartbeats
Each worker thread (monitor, scanner, executor, logger) periodically calls a heartbeat function that updates a monotonic timestamp. The self-monitor checks these timestamps against a staleness threshold (60 seconds). If a thread misses its window, its status transitions from Running to Stalled. If a thread panics and is not respawned, its status becomes Dead with the captured error message.
The heartbeat uses a process-local monotonic clock (Instant) rather than SystemTime to avoid false readings when the system clock is adjusted (NTP corrections, daylight saving changes, manual adjustments).
Thread statuses are reported in the state file and displayed on the dashboard Diagnostics screen (key 7).
RSS Memory Tracking
The daemon samples its own RSS through the PAL self_stats() method on each state file write. Linux uses /proc/self data; macOS uses Mach task and libproc resource usage. If RSS exceeds the configured warning level (512 MiB by default), a warning is logged to stderr when it crosses, then again hourly or after another 64 MiB of growth while it stays above. The RSS value is included in the state file for external monitoring tools.
The daemon warns at 512 MiB of RSS and exits at 1 GiB so the service manager restarts it clean; the generated systemd unit caps the cgroup at MemoryMax=<!-- claim:constants.service.SYSTEMD_MEMORY_MAX -->4096M<!-- /claim -->, above that hard limit, so the daemon's own clean exit comes before the kernel's OOM kill (which could land mid-deletion). The RSS limit is what keeps sbh from competing with build workloads for memory. The cgroup is also charged for the dentry and inode cache the walker fills, which is reclaimable and never shows in RSS; a cap too close to the RSS limit leaves the daemon reclaiming its own cache instead of working (one large host spent most of its time stalled on memory under MemoryMax=768M, and its monitor tick stretched to minutes). On machines with constrained RAM, lower the RSS limits in [telemetry], or the cap in the unit file (sbh service --systemd reinstall-unit rewrites it).
State File Protocol
The state file (state.json) is the primary mechanism for CLI-to-daemon communication. It is written atomically (write to .tmp, then rename()) to prevent readers from seeing partial writes.
| Parameter | Value | Purpose |
|---|---|---|
| Write interval | 30 seconds | Balances freshness with IO overhead |
| Stale threshold | 90 seconds | >= 2x write interval, prevents false "daemon absent" reports |
| Write method | Atomic rename | Guarantees CLI always reads a complete JSON document |
The schema uses #[serde(default)] on all fields, so minor version differences between daemon and CLI (e.g., during a rolling update) degrade gracefully: new fields are ignored by old CLI versions, and missing fields use defaults rather than causing parse failures. The dashboard adapter layer detects schema drift and surfaces warnings rather than crashing.
Source: src/daemon/self_monitor.rs
state.json Fields (schema 2)
The top-level fields of the state document, generated from DaemonState by sbh docs --render README.md (sbh docs --section state-fields). Every field defaults, so a file written by an older daemon simply lacks the newer sections; schema_version is 2 for the current layout.
| Field | JSON | Meaning |
|---|---|---|
version |
string | Daemon version |
pid |
number | Daemon process id |
started_at |
string | RFC 3339 start time |
uptime_seconds |
number | Seconds since start |
last_updated |
string | RFC 3339 time of this write |
pressure |
object | Per-mount pressure levels and free space |
ballast |
object | Ballast summary: provisioned and released counts |
ballast_pools |
array | One record per managed pool (mount, directory, counts) |
voi |
object | VOI scan scheduler snapshot as of the last plan |
last_scan |
object | The last scan pass |
counters |
object | Scans, deletions, errors, bytes freed |
memory_rss_bytes |
number | Daemon RSS at this write |
policy_mode |
string | Policy engine mode name |
mount_controllers |
array | Per-mount control state and idle reasons |
schema_version |
number | State schema version (2) |
run_id |
string | One daemon run (pid + start time) |
rates |
object | Per-mount EWMA rate estimates, keyed by mount |
threads |
object | Worker thread health |
cpu_secs_total |
number | CPU seconds (user + system) consumed |
cpu_budget |
object | CPU budget: percent, last-minute use, deficit |
idle_reason |
absent or value | Dominant idle reason when no mount works (absent otherwise) |
policy |
object | Policy engine record: mode, held since, fallback reason, recovery |
logging |
object | Where the daemon's own files live relative to what it reclaims |
stopped_at |
absent or value | Set by the final write on shutdown |
exit_reason |
absent or value | Why the daemon stopped (final write only) |
Reserve availability in CLI reports
sbh status reports the observed reserve condition separately from disk
pressure. Its Mount Control table and sbh doctor --system use the same
per-pool evidence: an exhausted reserve has no bytes left to release, while
unknown inventory cannot establish either available protection or exhaustion.
The CLI checks the daemon's liveness, document timestamp, pool identity and
inventory age before using an observation. A healthy pool on another mount
does not hide an impaired reserve.
In sbh status --json,
pressure.mount_controllers[].reserve_state includes state and
inventory_authoritative. present_bytes is a confirmed byte count or null;
target_bytes retains a known configured target or is null when unavailable.
horizon_minutes requires a confirmed positive reserve and a usable current
fill rate, and floor_limited is null when the current floor result is
unknown. Consumers must accept these nullable presentation fields. Burst
sizing history remains available, but its cached horizon_minutes is cleared.
The daemon's internal state.json controller schema remains unchanged.
For mounts under pressure, doctor reports confirmed exhausted or critically
depleted reserves as FAIL, and partial depletion or unknown availability as
WARN. Doctor names an observed safety-floor blocker and recommends freeing
space; rebuilding a reserve continues to obey the existing pressure policy and
headroom floor.
Service Management
sbh generates platform-native service configurations for both Linux (systemd) and macOS (launchd), with security hardening appropriate to each platform.
Systemd (Linux)
The generated systemd unit file includes several layers of hardening:
Scheduling (lowest priority):
Nice=19— lowest CPU scheduling priorityIOSchedulingClass=idle— only uses disk IO when no other process needs itIOSchedulingPriority=7— lowest IO priority within the idle class
This keeps sbh at background priority. System-scope systemd units also add a cgroup CPU quota; v2 adds in-process scan budgeting so a relaxed or stale service override does not make the scanner unbounded.
Security sandboxing (system scope only):
ProtectSystem=strict— mounts the entire filesystem read-only except explicitly allowed pathsReadWritePaths=— only the data directory and watched paths are writableNoNewPrivileges=true— prevents privilege escalation via setuid/setgid binariesProtectKernelTunables=true— blocks writes to/proc/sys,/sysProtectControlGroups=true— prevents cgroup manipulationRestrictSUIDSGID=true— blocks creation of setuid/setgid filesLimitNOFILE=4096— caps file descriptor count
Resource limits:
MemoryMax=4096M— cgroup ceiling, set above the daemon's own 1 GiB exit so a clean restart comes first, with room for the walker's reclaimable dentry/inode cache, which the cgroup is charged forCPUQuota=100%— caps CPU at one core as a runaway backstopCPUWeight=1— the lowest CPU share, so builds win whenever cores are busyEnvironment=MALLOC_ARENA_MAX=2— two glibc malloc arenas rather than one per scanner thread, so on a large tree RSS stays near the live set instead of settling at about twice it
Lifecycle:
Type=notify(system scope) withWatchdogSec=60for automatic restart on stallType=simple(user scope) for compatibility with user session managersRestart=on-failurewithRestartSec=10andTimeoutStopSec=30ExecReload=/bin/kill -HUP $MAINPIDfor live configuration reload
User-scope services skip ProtectSystem and kernel/cgroup protections because these directives are not available in user session scope.
Launchd (macOS)
The generated launchd plist provides equivalent lifecycle management:
RunAtLoad=true— starts the daemon on login (user agent) or boot (system daemon)KeepAlivewithSuccessfulExit=false— auto-restarts on non-zero exit, stays stopped on clean shutdownThrottleInterval=60— minimum 60 seconds between restart attemptsNice=19— lowest scheduling priorityLowPriorityIO=true— marks all IO as low-priority
User agents install to ~/Library/LaunchAgents/, system daemons to /Library/LaunchDaemons/. Log output goes to ~/Library/Logs/sbh/ (user) or /var/log/sbh/ (system).
Source: src/daemon/service/systemd.rs, src/daemon/service/launchd.rs
Kernel Writeback Tuning
Running the daemon at Nice=19 + IOSchedulingClass=idle keeps sbh out of the way, but it cannot fix the most common interactive-latency problem on a busy build host, because that problem is in the kernel, not in any one process.
On a high-RAM machine the default percentage-based dirty-page limits are too coarse. With vm.dirty_ratio=10 on a 247 GiB host the kernel lets roughly 24 GiB of dirty pages accumulate before it throttles writers, and vm.dirty_background_ratio=5 waits for ~12 GiB before starting background flush. Those huge pools then flush in bursts through kernel writeback threads (btrfs-endio-write and friends) that run outside the ionice class of the build processes that produced the writes — so even with every build ionice-idled, the interactive terminal stalls behind each multi-GiB flush.
The fix is to replace the ratio knobs with absolute byte limits (vm.dirty_bytes / vm.dirty_background_bytes) so writeback is continuous and gentle instead of bursty. sbh sizes those limits to the backing device's write bandwidth:
dirty_background_bytes = clamp(bandwidth × target_drain_secs, min, max) # default drain 1.0s
dirty_bytes = hard_ratio × dirty_background_bytes # default ratio 4
Bandwidth is measured by a short, bounded, non-destructive on-volume micro-benchmark (random data so btrfs/zfs cannot compress or dedup it away); --no-benchmark falls back to an NVMe/SSD/HDD device-class heuristic. At a typical ~512 MiB/s SSD this yields dirty_background_bytes=512 MiB / dirty_bytes=2 GiB.
# Show the recommendation (read-only; uses the device-class heuristic)
sbh tune
# Measure bandwidth, apply to the running kernel, and persist (root)
sudo sbh tune --apply --yes
# Flag a dangerous configuration without changing anything (WARN, escalated on btrfs/zfs)
sbh doctor --system
# Undo: restore the backup of the sbh snippet (or remove it) and reload sysctl
sudo sbh tune --revert-writeback
--apply writes the live /proc/sys/vm knobs and persists a backup-first, self-documenting /etc/sysctl.d/99-sbh-writeback.conf, validates it with sysctl -p, and warns about any later-loading sysctl.d file that would override the byte limits with a ratio (setting vm.dirty_bytes auto-zeros vm.dirty_ratio — they are mutually exclusive). sbh install applies the same tuning automatically when run as root.
The daemon never applies this at runtime. The hardened system-scope unit sets ProtectKernelTunables=true, which makes /proc/sys read-only for the daemon, and silently mutating global kernel state from a background daemon would violate sbh's explainability and least-surprise principles. All writeback mutation is operator-invoked (or install-time), root-gated, backup-first, and reversible. On platforms without tunable writeback limits (macOS) the recommendation is simply not generated and doctor --system reports not-applicable.
Configure under [system_tuning] (see the config example) or via SBH_SYSTEM_TUNING_WRITEBACK_* environment variables.
sbh uninstall deliberately does not revert this tuning — the byte limits are a beneficial host setting that should outlive sbh, and undoing them would silently reintroduce the write-burst stalls. Run sudo sbh tune --revert-writeback first if you want the original vm.dirty_* behavior back.
Reserve sizing from observed bursts. The daemon also measures, per mount, how much used space grows inside each reaction window (an EWMA of poll + scan + reclaim latency, five-minute prior) and keeps those samples in a t-digest persisted as burst_stats.bin beside state.json. The reserve a mount needs is the 0.99 quantile of the windows: the digest's quantile after 50 windows, a generalized Pareto tail extrapolated from the exceedances above the 0.9 quantile from 10 windows, and never less than two ballast files. sbh tune turns it into file_count = ceil(reserve / file_size) (ballast.file_count for a single pool without an override, otherwise ballast.overrides.<mount>.file_count, which --apply writes), sbh doctor --system reports ballast.reserve_coverage and FAILs when a pool's releasable bytes fall short, sbh status shows the required bytes with the estimate method and window count, and state.json carries reserve_state.burst per mount (recommended_bytes, q99_bytes, windows, reaction_window_secs, method, and horizon_minutes, how long the present reserve buys at the burst rate).
Source: src/tuning/writeback.rs, src/tuning/bandwidth.rs, src/platform/linux/writeback.rs
Supply Chain Verification
Binary releases, installers, and updates pass through a verification pipeline before installation. The pipeline has three layers where applicable: mandatory checksum verification, optional cryptographic signature verification, and macOS binary trust checks.
SHA-256 Checksums
Every release artifact ships with a .sha256 checksum file. During install or update, the pipeline downloads the artifact, computes its SHA-256 hash, and compares it against the expected value from the checksum file. A mismatch halts installation with a structured IntegrityDecision::Deny outcome that includes both expected and actual hashes for diagnostics.
The checksum parser handles both bare hex digests and BSD-style sha256sum output (hash followed by filename), normalizing to lowercase hex for comparison.
Sigstore Signature Verification
When a Sigstore bundle (.sigstore file) is present alongside the release artifact, the pipeline upgrades to cryptographic signature verification using cosign. The verification policy is determined by the presence of the bundle:
| Bundle Present | Policy | Behavior |
|---|---|---|
| No | Disabled |
Checksum-only verification |
| Yes | Required |
Must pass cosign verify-blob or install is denied |
If the cosign binary is not installed on the system, the pipeline probes for it at verification time. When cosign is absent and the policy is Required, the outcome is Deny with reason code sigstore_required_unavailable. When the policy is Optional, missing cosign degrades to checksum-only with a warning.
macOS Binary Trust Checks
On macOS, the Unix installer and self-update path also run codesign --verify --strict --verbose=2 and inspect codesign --display --verbose=4 output before installing or replacing sbh. This rejects unsigned, malformed, or incorrectly signed binaries unless they are signed by the expected Developer ID Application: Jeffrey Emanuel (AU8V2Z6NKY) identity and TeamIdentifier=AU8V2Z6NKY.
Bypass and Audit Trail
The --no-verify flag explicitly bypasses release-binary artifact verification, including checksum, signature, and macOS trust checks. This is a loud operation: the outcome includes bypass_used: true, a warning message, and reason code verify_bypass. The structured VerificationOutcome captures the full decision trail (bypass, checksum status, signature status, reason codes, warnings) for audit logging. On macOS, sbh install --no-verify --offline <bundle-manifest.json> forwards the same unsafe bypass into the release-binary install path; use it only for deliberate recovery from a trusted local bundle.
For airgapped environments, the --offline flag accepts a local bundle manifest, allowing updates without network access while maintaining checksum verification.
Source: src/cli/mod.rs, src/cli/assets.rs
Uninstall and Cleanup Modes
sbh uninstall supports five cleanup modes that control how aggressively the system is cleaned up, from conservative to full purge:
| Mode | Binary | Service | Config | Data/Logs | Assets | Ballast |
|---|---|---|---|---|---|---|
| Conservative (default) | removed | removed | kept | kept | kept | kept |
| KeepData | removed | removed | removed | kept | removed | removed |
| KeepConfig | removed | removed | kept | removed | removed | removed |
| KeepAssets | removed | removed | removed | removed | kept | removed |
| Purge | removed | removed | removed | removed | removed | removed |
Every removal action includes:
- Category tagging: Each item is classified (binary, config-file, data-directory, state-file, sqlite-db, jsonl-log, asset-cache, systemd-unit, launchd-plist, shell-completion, shell-profile-entry, ballast-pool, backup-file) for structured reporting.
- macOS service teardown:
sbh uninstall --launchdcallslaunchctl bootout, removes the matching LaunchAgent or LaunchDaemon plist, and exits successfully when the service is already unloaded or the plist is already absent. - Custom launchd labels: Uninstall discovery checks both
com.sbh.daemonand a validSBH_LAUNCHD_LABEL, so isolated CI/test installs clean up the same plist label they installed. - Backup-first semantics: Items marked with
backup_first: trueare copied to a timestamped backup before removal. - Dry-run support:
sbh uninstall --dry-rungenerates the full removal plan without unloading the service or executing any deletions, showing exactly what would be removed and backed up. A dry run of a system-scope install does not need root. - Structured output: The plan and execution results are available as JSON (
--json) as one payload: the service teardown result (service_type,scope,unit_path,success,error) pluscleanup(the plan or results, withactions,kept,removed_count,failed_count,bytes_freed). - Scope-safe discovery: a user-scope uninstall only touches the home footprint (
~/.local/bin/sbh,~/.cargo/bin/sbh, the user unit or LaunchAgent, user completions, shell-profile PATH lines) and the paths in the loaded config; a system-scope uninstall only touches/usr/local/bin/sbh, the system unit or LaunchDaemon, and system completions. - Confirmation: data-removing modes (
--purge,--keep-*) prompt on a terminal and require--yeswhen stdin is not a terminal. The conservative default needs no confirmation.
# Preview what would be removed (conservative mode)
sbh uninstall --dry-run
# Full cleanup with --purge (prompts; --yes for scripts)
sbh uninstall --purge --yes
# Remove everything except logs and database
sbh uninstall --keep-data
# Keep backups of config/database in one place
sbh uninstall --purge --backup-dir ~/sbh-backups --yes
# Machine-readable plan
sbh uninstall --dry-run --json
Source: src/cli/uninstall.rs
Source Layout
src/
lib.rs Crate root: re-exports all modules
main.rs Binary entry: CLI parse + dispatch
cli_app.rs Full CLI definition (clap derive) + command handlers
decision_plane_tests.rs Replay-based policy engine integration tests
core/
config.rs TOML config model + env var overrides + validation
errors.rs SbhError enum with SBH-XXXX codes + retryable flag
monitor/
fs_stats.rs Filesystem stats via statvfs with mount-aware caching
ewma.rs Adaptive EWMA and elapsed-time net-consumption forecasts
pid.rs PID pressure controller with predictive urgency boost
predictive.rs Predictive action pipeline with early warning
guardrails.rs E-process drift detection + calibration monitoring
special_locations.rs /tmp, /data/tmp, swap surveillance
voi_scheduler.rs Value-of-Information scan budget allocator
scanner/
walker.rs Parallel directory walker with open-file detection
patterns.rs Artifact pattern registry (~200 known patterns)
scoring.rs Multi-factor scoring + Bayesian decision framework
deletion.rs Circuit-breaker-guarded deletion executor
protection.rs .sbh-protect markers + config glob patterns
index.rs Candidate index v2 (persisted candidate records + event tracking)
merkle.rs Legacy incremental Merkle index (inactive)
ballast/
manager.rs Ballast pool lifecycle (provision, verify, inventory)
release.rs Pressure-responsive ballast release controller
coordinator.rs Multi-volume ballast coordination with flock
daemon/
loop_main.rs Main monitoring loop (poll -> decide -> act -> log)
policy.rs Progressive delivery engine (observe/canary/enforce)
signals.rs Signal handling (SIGTERM, SIGHUP reload, SIGUSR1 scan)
self_monitor.rs Daemon health self-checks (RSS, state writes, panics)
service.rs systemd unit + launchd plist generation
notifications.rs Multi-channel notification system
logger/
dual.rs Dual-write logger with degradation chain
sqlite.rs SQLite WAL-mode activity logger with retention
jsonl.rs JSONL append-only log with rotation
stats.rs Stats engine for time-window queries + blame
cli/
mod.rs Shared installer/update contracts, supply chain verification
bootstrap.rs Bootstrap migration and self-healing
assets.rs Asset manifest download/verify/cache with SHA-256
dashboard.rs Dashboard launcher and mode selection
install.rs Install orchestration with wizard, auto mode, and service setup
from_source.rs From-source build fallback mode
uninstall.rs Uninstall with 5 cleanup modes
update.rs Self-update with rollback, cache control, and backup management
wizard.rs Guided first-run install wizard + --auto mode
tui/
model.rs Elm-style state model (7 screens, overlays, telemetry)
update.rs Pure update function (message → model mutation + command)
render.rs Text-mode render pipeline (all screens + overlays)
input.rs Three-layer key routing (overlay → global → screen)
incident.rs Severity classification, playbook, incident shortcuts
adapters.rs State-file adapter with schema drift detection
layout.rs Responsive layout builders with priority-based hiding
preferences.rs Persisted UX preferences with atomic writes
runtime.rs Terminal lifecycle, event loop, panic safety
theme.rs Color palette with NO_COLOR/high-contrast support
telemetry.rs Telemetry data types for timeline/candidates/decisions
widgets.rs Reusable gauge, badge, sparkline components
terminal_guard.rs Raw mode cleanup and signal-safe terminal restore
platform/
pal.rs Platform trait and implementations: LinuxPal (procfs/statvfs), MacOsPal (statfs/APFS/libproc), MockPlatform
Exit Codes
Every command's error goes through one mapping (C-EXIT). --json reports carry exit_code; human reports go to stdout and diagnostics to stderr. Vetoes and skips are never an exit-code class: they appear in the report. Generated from the code by sbh docs --render README.md; sbh --help prints the same list.
| Code | Meaning | Examples |
|---|---|---|
| 0 | ok | clean/emergency with nothing to reclaim, check above threshold |
| 1 | user error, or a pressure condition | bad arguments, check below threshold or --need unmet, predicted full |
| 2 | runtime or I/O failure | cannot stat a path, config unreadable |
| 3 | internal error | invariant violation, JSON encoding failure |
| 4 | partial success | clean/emergency with failed deletions, ballast/setup with failed steps |
Error Codes
sbh uses structured error codes in the format SBH-XXXX for machine-parseable error identification. The catalog below is generated from the code by sbh docs --render README.md (sbh docs --section error-codes prints it):
| Code | Variant | Family | Retryable | Typical cause |
|---|---|---|---|---|
SBH-1001 |
InvalidConfig |
Configuration | no | A config value or structure failed validation |
SBH-1002 |
MissingConfig |
Configuration | no | No config file at the expected path |
SBH-1003 |
ConfigParse |
Configuration | no | Invalid TOML syntax or types |
SBH-1101 |
UnsupportedPlatform |
Platform | no | The feature is unavailable on this OS |
SBH-1102 |
Pal |
Platform | no | A platform abstraction call is not implemented or failed |
SBH-2001 |
FsStats |
Runtime | yes | Cannot stat a watched path or special location |
SBH-2002 |
MountParse |
Runtime | no | The mount table could not be parsed |
SBH-2003 |
SafetyVeto |
Runtime | no | A hard veto stopped a deletion |
SBH-2101 |
Serialization |
Serialization | no | JSON or TOML encoding/decoding failed |
SBH-2102 |
Sql |
Serialization | yes | SQLite query, schema, or lock failure |
SBH-3001 |
PermissionDenied |
System | no | Insufficient filesystem permissions |
SBH-3002 |
Io |
System | yes | File read/write error |
SBH-3003 |
ChannelClosed |
System | yes | A daemon thread went away; its channel is closed |
SBH-3900 |
Runtime |
System | yes | Any other runtime failure |
All errors implement code() for the stable string code, is_retryable() to indicate whether retry might help, and standard Display formatting with the code prefix.
Two more codes appear only in the activity log and are not SbhError variants: SBH-3004 (warning: the daemon exceeded its CPU budget) and SBH-3005 (error: the open-file or process scan was incomplete, so the deletion batch was aborted; an sbh without root gets this on every batch on Linux).
Testing
# Unit tests (core)
rch exec "cargo test --lib"
# TUI tests (requires tui feature flag)
rch exec "cargo test --lib --features tui -- tui::"
# Dashboard operator benchmarks
rch exec "cargo test --lib --features tui -- tui::test_operator_benchmark"
# Integration tests
rch exec "cargo test --test integration_tests"
# End-to-end scripts with detailed logs
./scripts/e2e_test.sh
# Stress scenarios
rch exec "cargo test --test stress_tests -- --nocapture"
# Quality gates
cargo fmt --check
rch exec "cargo check --all-targets"
rch exec "cargo clippy --all-targets -- -D warnings"
For test harness conventions and structured logging registration, see docs/testing-and-logging.md.
Troubleshooting
"No candidates found, but disk is full"
- The daemon says where the bytes are: when a mount has stayed at Red or Critical for 10 minutes (reclaim is not keeping up), it logs an
SBH-2007warning (journal and activity log, at most hourly per mount) naming the largest directories on that filesystem, with containers such as/homeand/databroken down one level (/home/ubuntu 278.1 GiB, /data/projects >=235.0 GiB, ...;>=marks a size probe that hit its budget,~a sampled estimate). It then names the five largest directories inside the largest one, and inside the largest of those while it holds at least half of its parent (; inside "/home/ubuntu": "/home/ubuntu/.cache" ~210.4 GiB est., ...), so the report points at a tree to move rather than at a home or project root.sbh statusshows the latest report per mount from the last 3 hours under "Space Attribution", andsbh status --jsoncarries it asspace_reports(mount,level,logged_at,age_seconds,report). These sizes say where the bytes are; they never authorize a deletion. - Ask the scorer directly:
sbh explain --why-not <dir>scores that directory now, runs the deletion preflight, and prints the first thing standing in the way (a.sbh-protectmarker or protected pattern, an exclusion, a scoring veto, a preflight refusal such as a source tree or an active lease, or a score belowscoring.min_score) followed by the full factor table. Add--counterfactualto see the smallest change of age, size, or pressure that would flip it to Delete, and--jsonfor the same report as data. sbh scan <path> --min-score 0.0lists everything the scorer saw; each line ends with an id forsbh explain --id.- Check protections via
sbh protect --list. - Use
sbh emergency <path>for immediate recovery.
"Cleanup is too conservative"
- Inspect policy mode (
observe/canary/enforce). - Review
sbh explain --id <decision-id>for veto/guard reasons. - Adjust scoring weights and thresholds in config.
"Ballast release did not free expected space"
- Verify target mount with
sbh ballast status. - Ensure the pressured path has a corresponding ballast pool.
- Check for read-only/tmpfs/NFS skip rules.
- macOS/APFS: local Time Machine snapshots may retain released ballast blocks.
Run
sbh clean --thin-local-snapshots --dry-runand, if appropriate,sudo sbh clean --thin-local-snapshots --yes.
"macOS Full Disk Access is missing"
- Run
sbh doctor --paland check themacos.full_disk_accessentry. - Follow
docs/macos-full-disk-access.md. - Restart the launchd service after changing the grant:
sbh service --launchd --scope user restart.
"Dashboard shows DEGRADED"
- Confirm daemon is running: Linux
systemctl status sbh; macOSsbh service --launchd --scope user status; foreground debuggingsbh daemon. - Check state file path and permissions (default:
/var/lib/sbh/state.json). - Validate config with
sbh config validate. - Press
7to view Diagnostics screen for connection error details. - Press
rto force a data refresh.
"Dashboard or status looks stale"
- Press
rto force a data refresh. - Confirm daemon is running.
- Check state/log paths and permissions.
- Validate config with
sbh config validate.
"Dashboard keybindings don't work"
- Check if an overlay is active (help, palette, playbook). Overlays consume input before screen keys.
- Press
Escto close any active overlay. - Press
?to see available keybindings for the current context.
"Incident shortcuts not appearing"
- Incident hints only appear at Elevated severity or higher (Yellow/Orange/Red pressure).
- Check that hint verbosity is not set to
off(use:then typepref.hints.full). - Press
!to manually open the incident playbook regardless of severity.
"Service fails to start"
- Linux: inspect
systemctl status sbhandjournalctl -u sbh -efor logs. - macOS: run
sbh service --launchd --scope user status, inspectlaunchctl list | grep sbh, and check~/Library/Logs/sbh/for log output. Seedocs/launchd-troubleshooting.mdfor interpretinglaunchctl printoutput and stale-state recovery. - Run
sbh daemondirectly to capture startup errors. - Verify binary path is correct:
sbh config show --json | jq '.paths'.
"Daemon seems stuck or unresponsive"
- Send
SIGUSR1to trigger an immediate scan:kill -USR1 $(pidof sbh). - Send
SIGHUPto reload configuration:kill -HUP $(pidof sbh). - Check the Diagnostics screen (
key 7) for thread health — aStalledthread indicates a blocked operation. - If using systemd with
Type=notify, the watchdog will auto-restart after 60 seconds of no heartbeat.
"Memory usage keeps growing"
- The daemon warns at 512 MiB of RSS and exits at 1 GiB; the systemd unit caps it at
MemoryMax=<!-- claim:constants.service.SYSTEMD_MEMORY_MAX -->4096M<!-- /claim -->. Checksbh status --json | jq '.memory_rss_bytes'. - Systemd's
MemoryMax=4096Mis a backstop above the daemon's own exit. The cgroup'smemory.currentalso counts the kernel's dentry/inode cache from scanning, so it runs well above RSS on large trees; that cache is reclaimable. A unit or drop-in that still setsMemoryMax=768M(generated before v0.7.10) can leave the daemon stalled on memory: checkmemory.pressurein its cgroup. - Large candidate scan indexes on machines with many directories can increase baseline memory. Consider reducing
scanner.root_pathsscope.
Limitations
- Process attribution relies on platform-specific process inspection and may be reduced on restricted environments.
- Extremely bursty workloads may require tighter sample intervals and controller tuning.
- Network and ephemeral filesystems are intentionally conservative for ballast and cleanup safety.
- Ballast provisioning never takes a volume below the provisioning floor (
yellow_min_free_pct + hysteresis_pctwith the default matrix; see The Ballast System in Depth); on volumes below the floor, ballast provisioning is deferred and catalog roots serve as the fallback.
FAQ
Does sbh delete source code?
No. Early development incidents on 2026-05-16 and 2026-05-22 led to hardcoded vetoes that cannot be disabled by configuration. Specifically, HardcodedSourceTree vetoes any directory with known source structures, and LooksLikeSourceCode vetoes directories containing source manifests (Cargo.toml, package.json, pyproject.toml, go.mod, etc.) lacking build markers. These hardcoded vetoes are checked during pre-flight before any deletion can occur. You can verify safety for any path using sbh scan <path> --explain or sbh explain --why-not <dir>, which reveals exact factor scores and any vetoes that apply. Additionally, permanent protection can be established via .sbh-protect marker files or scanner.protected_paths in config.toml.
Can I force cleanup during an incident?
Yes. Use sbh emergency ... for immediate recovery, then return to normal policy modes.
Can I run sbh without the daemon?
Yes. scan, clean, check, and emergency support operational workflows without a long-running service. The dashboard will enter degraded mode but remains functional for navigation and overlay features.
How do I switch back to the legacy dashboard?
Use sbh dashboard --legacy-dashboard, set dashboard.mode = "legacy" in config, or set SBH_DASHBOARD_KILL_SWITCH=true as an environment variable for emergency fallback.
How do I audit why something was deleted?
Use sbh explain --id <decision-id> and inspect structured logs/evidence records.
How do I reload configuration without restarting?
Send SIGHUP to the daemon process: kill -HUP $(pidof sbh). On systemd, use systemctl reload sbh. The daemon re-reads config.toml and applies changes on the next loop iteration.
How do I trigger an immediate scan?
Send SIGUSR1 to the daemon: kill -USR1 $(pidof sbh). This bypasses the VOI scheduler and runs a full scan on the next iteration, useful for verifying cleanup behavior after a configuration change.
Does the candidate index persist across daemon restarts?
Yes. The v2 candidate index (src/scanner/index.rs, persisted to scanner-index-v2.json) records event generations, candidate records, and SHA-256 checksums across restarts under scanner.engine = "v2" (default since v0.4.32). If the checkpoint is corrupt or missing, v2 rebuilds through bounded reconciliation. (The legacy src/scanner/merkle.rs implementation remains in the repository as reference code but is not active in the live daemon.)
How much memory does sbh use?
Under normal operation, 20-60 MB of RSS. The daemon's own self-monitor warns at 512 MiB and exits at 1 GiB; the systemd unit's MemoryMax=<!-- claim:constants.service.SYSTEMD_MEMORY_MAX -->4096M<!-- /claim --> is a backstop above that. Machines with hundreds of thousands of directories in watched paths use more: a host scanning about 470k entries per pass ran at 260–410 MiB over six hours with two malloc arenas, and one whose passes stopped at 500k entries settled at 460–490 MiB and passed 545 MiB at the end of a pass once its cgroup no longer pushed pages into swap.
Is this Linux-only?
No. It is cross-platform, with service integration for systemd (Linux) and launchd (macOS). Open-file vetoes are platform-specific internally: Linux uses /proc/*/fd, while macOS uses PAL/libproc evidence for visible processes. Other safety layers, including age, sacred-path, protected-path, active executable/mmap, and .git guards, remain active on both platforms.
About Contributions
About Contributions: Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via
ghand independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.
License
MIT License (with OpenAI/Anthropic Rider). See LICENSE.
Explorar proyectos relacionados
Cargando…