maintaining-macos-health
Hands-on playbook for macOS disk cleanup, dev-machine optimization, and proactive health alerting. Use when the Mac is full or slow, when a process persistently burns CPU, when a kernel panic / watchdog timeout / vm-compressor-space-shortage / Jetsam event happened, when the user
Install
npx skills add https://github.com/CodeAlive-AI/ai-driven-development/tree/main/skills/maintaining-macos-health
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install codealive-ai-ai-driven-development@llmmart
git clone https://github.com/CodeAlive-AI/ai-driven-development.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole codealive-ai/ai-driven-development collection as a plugin from our marketplace. Git is the plain clone.
README
maintaining-macos-health
v1.2.0 — Recovery and prevention playbook for macOS disk, memory, and persistent CPU problems, with an interactive HTML cleanup UI, a noise-resistant actionable LaunchAgent alerter, and Mole-grounded safety guards. Built for Apple Silicon dev machines that run heavy workloads — Docker, multiple AI tools, IDEs, browsers.

Table of contents
- Why this skill
- Install
- Prerequisites
- Quick start
- What it does
- Key features
- Sources and methodology
- File structure
- License
Why this skill
Modern macOS dev machines hit a specific failure mode that's not covered well anywhere else: a watchdog-timeout kernel panic caused by vm_compressor segments saturating to 100 % while the disk is too full to extend swap. The symptom is "Mac freezes for ~90 seconds, then reboots." The signal that always precedes it is JetsamEvent files containing vm-compressor-space-shortage — Apple's kernel killing processes for memory minutes before it gives up.
This skill packages three complementary capabilities for that failure mode:
- A triage playbook with a first-five-minutes decision tree and a 10-tier cleanup catalogue.
- An interactive HTML cleanup UI the agent renders after scanning, so the user picks exactly what gets deleted instead of trusting the agent's memory.
- An active LaunchAgent alerter with critical disk/memory/Jetsam triggers plus persistent CPU anomaly detection, hysteresis, incident deduplication, and safe diagnostic snapshots.
Validated against a real watchdog-timeout panic on Apple Silicon caused by vm_compressor segments saturated at 100 % with the disk over 90 % full. The same playbook works for routine cleanup or first-time setup on a new machine.
Install
npx skills add CodeAlive-AI/ai-driven-development@maintaining-macos-health -g -y
Prerequisites
| Tool | Why | Install |
|---|---|---|
Mole (mo) |
Safety floor for cleanup — marker-based project artifact detection (mo purge), system cache cleanup (mo clean), thorough app uninstall (mo uninstall) |
brew install mole |
| alerter | macOS notifications from launchd (replaces dead terminal-notifier) |
brew install vjeantet/tap/alerter |
| Python 3 (Apple-shipped) | Powers the cleanup UI server and the apply helper. stdlib only — no pip install required | (preinstalled) |
| Stats (recommended) | Passive menubar monitoring (memory pressure, disk, swap) | brew install --cask stats |
Apple Silicon Mac running macOS Sequoia (15.x) or Tahoe (26.x) recommended. Bash 3.2 (Apple-shipped) is the minimum — no Homebrew bash required.
Quick start
The skill is consulted by an agent when the user reports macOS health trouble. The agent reads SKILL.md and runs one of these workflows:
# Free space NOW (incident response)
"My Mac is full" / "out of disk space" / kernel panic happened
→ agent: triage → scan everything → resolve unknown items (web-search if needed)
→ build cleanup-data.json → render UI in browser
→ user picks via HTML checkboxes → submit
→ agent shows selection in chat → user confirms "go"
→ apply-cleanup-selection.py executes only what was picked
→ df checkpoint
# Set up alerting on a new machine
"set up disk alert" / "monitor memory pressure" / restoring after macOS reinstall
→ agent reads alerting.md, copies assets/ to ~/bin and ~/Library/LaunchAgents
# Audit storage
"what's eating my disk?" / "audit storage"
→ agent runs Mole's `mo analyze`, then suggests targeted tier from cleanup-tiers.md
Manual install of the alerter (without an agent):
SKILL=$HOME/.claude/skills/maintaining-macos-health
mkdir -p ~/bin ~/.config/mac-health ~/Library/Logs/mac-health ~/.local/state/mac-health
cp "$SKILL/assets/mac-health-check" ~/bin/
cp "$SKILL/assets/mac-health-action" ~/bin/
cp "$SKILL/assets/config.sh" ~/.config/mac-health/
sed "s|__HOME__|$HOME|g" "$SKILL/assets/com.local.mac-health-check.plist" \
> ~/Library/LaunchAgents/com.local.mac-health-check.plist
chmod +x ~/bin/mac-health-check ~/bin/mac-health-action
launchctl load -w ~/Library/LaunchAgents/com.local.mac-health-check.plist
Manual run of the cleanup UI (without an agent):
# 1. Build a data JSON yourself (see assets/render-cleanup-plan.py docstring for schema)
# 2. Start the UI server:
python3 ~/.claude/skills/maintaining-macos-health/assets/render-cleanup-plan.py /tmp/cleanup-data.json
# 3. Browser opens to http://127.0.0.1:18347/. Tick checkboxes. Click Submit.
# 4. Apply the selection (with --dry-run first):
python3 ~/.claude/skills/maintaining-macos-health/assets/apply-cleanup-selection.py \
/tmp/cleanup-selection-<ts>.json --dry-run
python3 ~/.claude/skills/maintaining-macos-health/assets/apply-cleanup-selection.py \
/tmp/cleanup-selection-<ts>.json
What it does
The skill packages three complementary capabilities, each with its own entry point and assets:
| Capability | Entry point | Use |
|---|---|---|
| Triage + cleanup playbook | references/triage.md, references/cleanup-tiers.md, references/never-touch.md, references/mole-techniques.md |
Tells the agent how to classify a health signal, which 10-tier cleanup block to run, and what categories to never touch |
| Interactive cleanup UI | assets/render-cleanup-plan.py + assets/apply-cleanup-selection.py |
Renders a categorised, sortable, checkbox-driven HTML report from the agent's scan, serves it on 127.0.0.1:18347, captures the user's selection, and feeds it to a sanctioned apply script that only deletes what was actually picked |
| Active alerter | references/alerting.md + assets/{mac-health-check, mac-health-action, config.sh, com.local.mac-health-check.plist} |
Bash + launchd implementation. Critical disk/memory/Jetsam triggers plus whole-system and per-process CPU incident tracking with explicit investigation/stop actions |
Triage flow (signal classification)
Read references/triage.md. First-five-minutes decision tree:
- Disk-driven (most common):
df< 20 % free → run cleanup tiers - Memory-driven:
memory_pressure≠ Normal + sustained swap → check Docker memory limit - Kernel-panic / watchdog-timeout: parse panic file, identify top-RSS process, install alerter
- JetsamEvent with
vm-compressor-space-shortage: imminent panic — close apps, do not run heavy cleanup - Thermal: powermetrics, let it cool
Interactive cleanup UI
The agent never decides what to delete on its own. After scanning, it builds a JSON of candidates and hands the decision to the user through a local HTML UI.

Key properties:
- Local-only HTTP server at
127.0.0.1:18347, Python stdlib (ThreadingHTTPServer), no dependencies, no network calls. - Categorised cards with colour-coded tier badges (🟢 safe, 🔵 medium, 🟠 careful, 🔴 protected).
- Sorted by size within each category (largest first).
- Live counters per category and a sticky footer with
selected GB / total GBand an "after cleanup → X GB free (Y %)" preview. - Custom tooltips on every row: russian/localised
descriptionof what the item is, full path, kind, size, age, command, and any warning. - Hard-protected items appear dimmed with a 🔒 badge and require a per-item confirm dialog before they can be checked.
- Single source of truth: submit writes
/tmp/cleanup-selection-<ts>.jsonand exits. The apply script reads only that file. Drift protection is structural — items the user unchecked are physically absent from the JSON and cannot be deleted, even if the agent "remembered" the default-selected list. - Esc = Cancel,
prefers-reduced-motionrespected.
Cleanup tiers (10 levels, risk-ordered)
Read references/cleanup-tiers.md. Each tier ends with a df checkpoint so the agent knows when to stop:
- Trivial wins (~25 GB) — Aerial wallpapers, Trash, Warp updates, orphan app data, hang traces, cached extension VSIXs
- Package manager caches (~10 GB) — npm
_npx, Playwright, Puppeteer, NuGet, Gradle, Cargo, brew cleanup - Electron caches (~4 GB) — Slack, Notion, Arc, Cursor, etc. (Quit apps first)
- Stale IDE versions (~10 GB) — JetBrains old major.minor data dirs
~/Downloads(~15-20 GB, interactive) — installers, recordings, archived repos- System logs + vendor depots (sudo, ~5-8 GB) —
/private/var/db/diagnostics, Logitech depots mo purge(~30-50 GB) — project artifacts via Mole's marker-based detection- Docker (~10-40 GB) — unused images, dead builders, orphan volumes (
buildx_buildkit_*_stateis often huge) - Dev artifacts (~5 GB, manual) — venvs, node_modules in inactive projects
- Discuss-first — Maven repo, Rust nightly, dotTrace workspaces,
~/.AzureToolsForIntelliJ, Claude Cowork VM, etc.
Active alerter
Read references/alerting.md. Runs every 5 min via StartCalendarInterval. Triggers:
- Disk free < 10 % for 3 consecutive readings (15 min sustained)
- Memory pressure Critical AND swap > 8 GB for 3 consecutive readings
- New
JetsamEvent-*.ipscontainingvm-compressor-space-shortage(immediate, no hysteresis — this is the early-warning signal)
CPU monitoring adds two deliberately different signals:
- Whole-system CPU busy >= 90 % for 3 readings — audible critical alert.
- One persistent process >= 80 % of a core for ~1 hour or >= 40 % for ~6 hours — silent advisory, once per incident.
Every five-minute run logs whole-system CPU and a safe top-process summary. Alerts show the owning application and process separately—for example, App=ChatGPT; process=Codex (Renderer) or App=Playwriter; process=Google Chrome for Testing Helper. App attribution uses known tool paths and the executable/parent .app chain without reading command arguments. CPU alerts offer Investigate in Codex, Investigate in Claude, and Stop Process… from an Actions… menu. Investigations start read-only; Claude Desktop is preferred through its documented deep link, with interactive terminal CLIs as fallback. Stop is never automatic: it revalidates PID identity, ownership and current CPU, asks for confirmation, sends SIGTERM first, and requires a second confirmation before SIGKILL. Sleep gaps reset consecutive counters. Alert-time top-10 snapshots are retained for 30 days in ~/Library/Logs/mac-health/cpu-incidents/.
Plus: 30-min cooldown and 7-day calibration for the original resource alerts, ~/.config/mac-health/silent for manual suppression, and optional ntfy.sh phone push. CPU starts immediately with conservative defaults; process advisories are silent and incident-deduplicated.
Key features
- Drift protection (apply-cleanup-selection.py) — the apply phase reads only
selected_itemsfrom the selection JSON. The skill's safety rules forbid hand-rolledrmblocks at apply time. Items the user unchecked are physically absent and cannot be deleted; protected items must additionally appear inprotected_overridesor are skipped. - Path validator — every command runs through a Mole-style check:
/System,/bin,/sbin,/usr,/etc,/Library/Extensions,/private/var/db/uuidtextare blocked;..rejected as a path component; wrapper commands (brew,docker,nvm,dotnet,pnpm,osascript) whitelisted. - Web-search-on-uncertainty — for any candidate > 500 MB the agent can't describe in one sentence, the skill mandates a
web-searcherlookup before showing the report. Prevents "unknown / ML data" vague descriptions. - Claude Cowork aware — the skill knows
~/Library/Application Support/Claude/vm_bundles/claudevm.bundle/is the Cowork VM (Ubuntu 22.04 in Apple Virtualization.framework). It auto-recreates on every Claude Desktop launch via SHA1 integrity check, classified as Tier 10 discuss-first with the quit-Claude-Desktop pre-step and recreation warning (open issue anthropics/claude-code#57371). - Never-touch list — explicit blacklist with consequence notes: Mole's curated app-protection rules (
com.apple.coreaudioissue #553,controlcenter*issue #136,org.cups.*issue #731) plus auth/credential dotfiles (~/.ssh/*,~/.gnupg,~/.aws/*,~/.kube/config,~/.nuget,~/.git-credentials), AI/password/VPN/keychain bundle IDs,Telegram tdata, crypto wallets, terminal saved state, container VM images. Reasoning included for every entry. - Noise-resistant actionable alerting — critical resource signals remain audible; persistent per-process CPU is a silent, once-per-incident advisory. Investigation is read-only, and process stopping is explicit, identity-checked, confirm-first, and graceful-first. No auto-cleanup or auto-kill hooks.
- 2026 macOS quirks captured —
terminal-notifieris dead (last release 2019-11), usealerter.StartIntervalclock pauses during sleep on laptops (radar 6630231), useStartCalendarIntervalwith explicit minute-entries. LaunchAgent defaultPATHdoes not include/opt/homebrew/bin, must declare in plist.osascript display notificationfrom launchd attributes to Script Editor and is unreliable.mo clean/mo purgepiped through| headraises SIGPIPE and exits 144 — capture to a file or usetailinstead. - Bash 3.2 compatible — runs against Apple-shipped
/bin/bash3.2.57 with noset -uquirks. Label-awareawkparsing forvm.swapusage(survives field-position changes). - Low-overhead CPU evidence —
pssupplies a one-minute decaying per-process average; the secondiostatsample supplies 0–100 % whole-machine utilization. Alerts resolve the owning app through known tool paths and.appancestry, while executable names, PIDs, elapsed time, and CPU remain available for diagnosis. Command arguments are deliberately excluded. - File-polling JetsamEvent —
log show --last 6mis too slow (30+ s) on a busy machine; polling/Library/Logs/DiagnosticReports/JetsamEvent-*.ipshas acceptable async-write latency on a 5-min cadence.
Sources and methodology
- Apple TN3155 — Reading a kernel panic, panic JSON layout, Compressor Info interpretation
- Apple developer docs — Identifying high-memory use with Jetsam Event Reports
- xnu vm_compressor — segments-vs-pages distinction,
vm-compressor-space-shortagereason code - Mole (github.com/tw93/mole) — battle-tested cleanup safety guards (path validator, project-artifact marker→target map, age thresholds, protected app bundle list)
- Google SRE Workbook — alert-fatigue prevention, "every alert must require intelligence to resolve"
- Prometheus alerting practices — symptom-based paging, cause-based diagnostics, pending duration, and actionable notifications
- alerter (github.com/vjeantet/alerter) — Swift-based notification CLI that works in launchd background context (issue #259 of
terminal-notifierdocuments the failure mode being avoided) - launchd quirks — radar 6630231 documents
StartIntervalclock-pause during sleep - Claude Cowork research — PVIEITO, Pluto Security, Anthropic Help Center, GitHub issues #47039, #57371
- Real-incident validation — two confirmed runs: (1) recovered ~25 % of total disk on Apple Silicon across all 10 cleanup tiers after a watchdog-timeout panic; (2) recovered +92.8 GB in a single UI-driven session (116.2 → 209.0 GB Container Free, 76 % used → 56 %, 51 items applied via the apply script, 0 protected items deleted without explicit override). Alerter verified via synthetic disk-trigger test.
File structure
skills/maintaining-macos-health/
├── .gitignore # ignore __pycache__, .DS_Store, .pyc
├── README.md # this file (public, rendered on skills.sh / GitHub)
├── SKILL.md # agent-facing entry point with workflows
├── docs/
│ ├── screenshot.png # main UI view (categorised checkboxes, sticky footer)
│ └── screenshot-tooltip.png # tooltip detail with description + path + command
├── references/
│ ├── triage.md # First 5 min: signal classification + decision tree
│ ├── cleanup-tiers.md # 10 risk-ordered cleanup tiers, copy-paste-safe
│ ├── never-touch.md # Hard-protected categories with consequence notes
│ ├── mole-techniques.md # Marker→target map, safety guards, SIGPIPE-safe dry-run capture
│ └── alerting.md # Alerter design + install + troubleshoot
├── assets/
├── mac-health-check # Bash 3.2-compatible health-check script
├── mac-health-action # Action dispatcher: read-only investigation + confirmed graceful stop
├── config.sh # Default thresholds (sourced by the script)
├── com.local.mac-health-check.plist # LaunchAgent (uses __HOME__ placeholder)
├── render-cleanup-plan.py # Interactive HTML cleanup-plan UI (local HTTP server)
└── apply-cleanup-selection.py # Sanctioned apply path — reads selection JSON, validates, executes
└── tests/
├── test-cpu-monitor.sh # CPU pending/firing/recovery/rearm/gap fixture tests
└── test-cpu-actions.sh # Prompt routing, PID identity, system selection, dry-run stop tests
License
MIT
Skill manifest
Maintaining macOS Health
Recovery and prevention playbook for macOS disk and memory crises. Validated against a real watchdog-timeout kernel panic on Apple Silicon caused by vm_compressor segments saturated to 100 % with the disk over 90 % full. The same playbook works for routine cleanup or first-time setup on a new machine.
Table of contents
- When to use
- Skill layout
- Core mental model
- Standard workflows
- Safety rules (non-negotiable)
- Domain quirks captured
- Outcomes scale
When to use
Trigger on any of:
- Disk free < 20 % or user complains about being out of space
- Watchdog-timeout / kernel panic / "no checkins from watchdogd"
- New
JetsamEvent-*.ipswithvm-compressor-space-shortage - "Mac is slow", swap > 6 GB, sustained Critical memory pressure
- A process persistently consumes a core, or the whole machine stays CPU-saturated
- User wants to set up monitoring/alerting from scratch
- Migration to a new Mac → restore the same alerter
- General "clean my Mac" / "audit storage" / "free space" requests
Skill layout
| File | Use for |
|---|---|
references/triage.md |
First 5 minutes — which signal fired, which tier of cleanup to start with |
references/cleanup-tiers.md |
Tiered cleanup playbook (10 tiers, zero-risk → discuss-first), copy-paste-safe shell blocks |
references/never-touch.md |
Categories that must not be deleted even under sudo (Mole-derived blacklist + incident-derived additions) |
references/mole-techniques.md |
What Mole does that we borrow: marker→target map for mo purge, safe-path validators, age thresholds |
references/alerting.md |
Full alerter design: disk/memory/Jetsam critical triggers plus sustained CPU anomaly detection, incident lifecycle, hysteresis, notifier choices, install/restore commands |
references/optional-disk-responses.md |
First-use offer, installation and operation of two independent opt-ins: emergency Mole cache cleanup below 2%, and a Codex cleanup plan/page at or below 5% with exact-session continuation. |
assets/mac-health-disk, assets/disk_*.py |
Consent-gated disk controller, deterministic inventory, restricted Codex runner and authenticated local selection/confirmation page. Both modes default off. |
assets/mole-exact-file.sh, assets/mole-core-1.39.0.json |
Compatibility-pinned exact-file adapter to Mole; no general mo clean, sudo, or shell commands from the agent. |
assets/space-scan/, assets/build-space-scan.sh |
Read-only bulk metadata scanner with explicit directory exclusions and a compact full folder tree; see references/storage-report.md for manual inventory |
assets/render-storage-report.py, assets/storage-tree.js |
Append scanner output to the report; lazily expand folders and show largest files |
assets/mac-health-check |
Production-ready bash script (~250 lines, bash 3.2 compatible) |
assets/mac-health-action |
Background action dispatcher for read-only Codex/Claude investigations and explicitly confirmed graceful process stopping |
assets/com.local.mac-health-check.plist |
LaunchAgent plist with StartCalendarInterval (StartInterval is broken on laptops) |
assets/config.sh |
Default config with safe thresholds |
assets/render-cleanup-plan.py |
Interactive HTML cleanup-plan UI. Renders categorised checkboxes from a JSON of scan findings, serves on 127.0.0.1:18347, opens browser, waits for the user's selection, writes it to /tmp/cleanup-selection-<ts>.json. Used by Workflow A. |
assets/apply-cleanup-selection.py |
The only sanctioned way to apply a cleanup selection. Reads selected_items from a selection JSON and executes each item's command field. Enforces protected-override check + path validation + Mole-compatible operations log. Prevents drift between what the user picked and what gets deleted. Supports --dry-run. |
Read the relevant reference before acting. Do NOT operate from memory of these files — the details are calibrated to a real incident and small changes break safety.
Core mental model
- Monitor passively — Stats menubar (
brew install --cask stats) — you see issues forming, not just when they explode. - Alert actively, diagnose quietly — disk, memory, Jetsam, and whole-system CPU saturation are critical. A single process burning CPU is a silent advisory only after a long sustained window; routine samples stay in the log.
- Cleanup tiers — start zero-risk (caches, orphan data), only escalate to project artifacts and sudo categories if needed. Mole's
mo purgeandmo cleanare the right primary tools. - Mole is the safety floor — even when running shell commands by hand, follow Mole's path-validation rules: never delete inside
/System,/bin,/usr,/etc,/var/dboutside specific allowlisted subpaths; bin/ only under .NET; vendor/ only under PHP; protect AI/password/VPN/keychain bundle IDs.
Standard workflows
First interactive use: optional disk responses
On the first operational, interactive use on a Mac (including an existing installation upgraded to this skill), read references/optional-disk-responses.md and offer both options separately in the user's language. Do this before routine setup; during an incident, do not delay immediate triage. A request to edit or review this skill is not consent to activate it on the development machine. Background invocations must never prompt for enrollment.
- Emergency cleanup, free space < 2%: permission for a bounded Mole cleanup of explicitly approved regenerable caches without another question at incident time. Explain the exact profile, irreversible deletion, possible cache rebuild/download cost, and exclusions before accepting consent. This is not permission for general
mo clean, project purge, Trash emptying, sudo, or process termination. - Agent cleanup plan, free space <= 5%: permission to launch the chosen agent automatically, inspect non-secret storage metadata, and open the local selection page in the default browser. Explain provider usage/cost and what metadata leaves the Mac. The agent may propose deletion but may not perform it; Submit is a selection, and applying still requires a separate confirmation.
Record each explicit answer independently; silence, a generic "set up monitoring", or approval of one option does not authorize the other. Keep declined choices across sessions and upgrades. Ask again only on user request, a new machine, or a material change to the consent scope. Existing monitoring continues without either option.
Implementation scope: the bundled controller supports a pinned Mole 1.39.0 adapter and a restricted Codex CLI session with the same cleanup-plan UI used by Workflow A. Emergency cleanup covers only old Homebrew package downloads and npm content-cache files. Automated planning runs Workflow A's fixed read-only bulk metadata scan, Mole clean/purge preview, Docker inventory and Downloads audit. The automatic executor remains narrower: it can delete only controller-verified regenerable cache files; storage-map and possible user-data findings are visible but disabled and require a later interactive Workflow A session. Read the reference, disclose these limits and verify local compatibility before recording approval with mac-health-disk configure. Installation alone never enables a mode. No consent is inferred from a feature-development request.
A. "Free space NOW" (incident response)
- Triage — read
references/triage.md, identify which signal fired and how urgent. - Snapshot baseline —
df -h /System/Volumes/Dataand write down free GB. - Run all scans, don't delete yet — for a large local disk inventory, use the bundled bulk scanner and full folder tree described in
references/storage-report.md; build the scanner before use and report build or scan failures explicitly; do not silently substitute another scan method. Also runmo clean --dry-run,mo purge --dry-run --debug,docker system df -v,~/Downloadsaudit. Capture everything; deletion comes only after user picks via the UI. - Resolve unknown items before building JSON — for every candidate > 500 MB whose purpose you cannot explain in one sentence (unfamiliar app, unfamiliar bundle ID, unfamiliar dotfolder, vendor-specific cache, ML model weights, VM image, etc.), research it first: check
references/never-touch.mdfor a known entry, then delegate a quick lookup to theweb-searchersubagent ("what is<path or bundle id>on macOS, is it safe to delete in 2026"). Wait for the answer, then write a concretedescription(1-3 sentences in the user's language) into the item — what it is, who created it, what feature uses it, what breaks if deleted, whether it auto-recreates. Never show the report with vague placeholders like "unknown" or "ML data" — that defeats the point of the UI. If a web lookup contradictsnever-touch.md, prefer the web answer (it's fresher) and propose an update to the reference file. - Build the data JSON — every candidate becomes a structured
item(id, label, path, size_bytes, age_days, kind, command, mandatorydescription, optionalprotected+warning). Write to/tmp/cleanup-data-<ts>.json. Use schema fromassets/render-cleanup-plan.pydocstring. Append a read-only disk inventory at the bottom of the report: a collapsible folder-size hierarchy followed by the largest files in descending allocated size. Followreferences/storage-report.mdfor thestorage_scaninput, coverage labels, and size semantics. These rows are informational and must not become deletion candidates automatically. - Render and open the cleanup UI:
The script starts a one-shot HTTP server onpython3 .../assets/render-cleanup-plan.py /tmp/cleanup-data-<ts>.json127.0.0.1:18347, opens the page in the user's default browser, and blocks until the user clicks Submit or Cancel. On submit it writes/tmp/cleanup-selection-<ts>.jsonand prints that path to stdout. Tell the user out loud: "браузер открыт — поставь галочки, нажми Submit, потом пингани меня". Then stop and wait. - After the user pings — read the selection JSON, render the user's choices back in chat (categories, item list, total GB, any protected overrides flagged ⚠), and ask one explicit confirmation before deleting. Don't run anything until they say "go".
- Apply via the helper script — never hand-rolled
rm:
The script readspython3 .../assets/apply-cleanup-selection.py /tmp/cleanup-selection-<ts>.jsonselected_itemsfrom the selection JSON and executes each item'scommandfield, with built-in safeguards: protected items must appear inprotected_overridesor are skipped; commands are validated against a hard-protected path list and a..-component check before execution; every action is logged to~/.config/mole/operations.login Mole-compatible TSV.--dry-runpreviews without executing. Do not write your ownrmblocks in the apply phase — that's how you delete items the user explicitly unchecked. The selection JSON is the single source of truth; if it's not inselected_items, it does not get deleted. Rundf -h /System/Volumes/Databefore and after for the user-visible delta. - Stop at goal — most users target 100 GB free. Don't go below that just for sport.
The Python script is bash-3.2-friendly, uses only stdlib, and is safe to run from inside the agent's shell. Hard-protected items (per references/never-touch.md) must always appear in the UI with "protected": true + a concrete warning string — the UI dims them and requires a per-item confirm dialog before they can be checked. Never omit a protected item that user data depends on (Telegram tdata, Bear database, password-manager containers, etc.) — visibility teaches the user the surrounding risk.
B. "Set up alerting" (new machine or first time)
Complete the first-use offer above; preserve existing choices when restoring monitoring. For the optional disk responses, also follow references/optional-disk-responses.md to install the bundled helper and dependencies without enabling either mode. Record activation only after independent explicit consent.
- Copy
assets/mac-health-checkandassets/mac-health-actionto~/bin/(mkdir first; chmod +x). - Copy
assets/com.local.mac-health-check.plistto~/Library/LaunchAgents/. - Copy
assets/config.shto~/.config/mac-health/config.sh(mkdir first). brew install vjeantet/tap/alerter(NOT terminal-notifier — it's broken in 2026 on Sequoia/Tahoe).brew install --cask statsfor passive layer.launchctl load -w ~/Library/LaunchAgents/com.local.mac-health-check.plist.- First run permission prompt: open
alerteronce interactively (alerter --message test) so macOS asks for Notification Center permission. - Tell the user: 7-day calibration is silent (logs only). Edit
config.shafter a week if pattern noisy.
The calibration window applies to the original disk/memory/Jetsam critical sensors. CPU uses conservative developer-workstation defaults and starts immediately; process advisories are silent and deduplicated for the full incident lifetime.
Verify with launchctl list | grep mac-health (should show PID and exit 0) and tail -f ~/Library/Logs/mac-health/health.log.
C. "Already have alerter, but it stopped working / making noise"
Read references/alerting.md § Troubleshooting. Common causes:
- Stuck/old
terminal-notifier(the cask) instead ofalerter— replace. - LaunchAgent not loading after macOS update —
launchctl bootstrap gui/$(id -u) <plist>. - Notifications going to Script Editor — TCC permission was revoked, re-grant.
- Constant alerts during heavy dev work —
touch ~/.config/mac-health/silentto suppress.
D. "Uninstall an app cleanly"
mo uninstall <app> — Mole scans 12+ locations for app traces (Application Support, Containers, Group Containers, Caches, Preferences, Saved State, LaunchAgents, LaunchDaemons, login items, etc.). Always show dry-run first, never bypass.
Safety rules (non-negotiable)
- Never delete without dry-run + user confirmation for any tier ≥ 5 or any sudo operation.
- Never bypass
references/never-touch.md— even if user explicitly asks. Push back, explain the consequence. mo purgeandmo cleanalways with--dry-runfirst. Show estimated reclaim, get confirm.- For Time Machine backups:
tmutil delete <path>, neverrm. TM-tagged paths require thetmutilAPI. - For sudo cleanup of
/Library,/private/var/db/*: only the allowlisted subpaths fromreferences/never-touch.md§ Sudo allowlist. - No unrestricted auto-cleanup hooks tied to alerts. The only exception is the independently approved, bounded emergency Mole cache profile below 2% in
references/optional-disk-responses.md. Its exact-file dry-run is mandatory; prior profile consent replaces the incident-time confirmation only for that profile. Planning at <= 5% never grants deletion permission. Emergency consent cannot authorize ordinary cleanup tiers or protected paths. - No auto-kill hooks tied to CPU alerts. A CPU advisory may offer
Stop Process…, but only as an explicit user action. Revalidate PID/executable identity and ownership, confirm, send SIGTERM first, and require a separate confirmation before SIGKILL. - Don't delete swap files.
rm /private/var/vm/swapfile*while running = guaranteed kernel panic. - Apply phase reads only the selection JSON. Never hand-roll
rmblocks or hard-code paths from the earlier scan when applying. Real incident: agent applied the default-selected recordings list from the original scan, ignoring that the user had unchecked them in the UI before submitting. The fix is structural — useassets/apply-cleanup-selection.pywhich iteratesselected_itemsfrom the selection JSON only.
Automated planning uses the helper's typed format_version: 2 branch, with a separate confirmation on the local page bound to that exact selection. The emergency executor is the sole separate profile-consent path described in rule 6; it cannot reuse or broaden a user's interactive selection.
Domain quirks captured
- macOS Tahoe (26.x) ships
/bin/bash3.2.57.set -u+local var(no init) = unbound on first reference. The shipped script handles this. - LaunchAgent does not inherit user PATH. Plist must declare
EnvironmentVariables.PATHand use absolute paths for interpreters. StartIntervalclock pauses during sleep on Apple Silicon laptops (radar 6630231). UseStartCalendarIntervalwith explicit minute entries (the shipped plist has all 12).terminal-notifieris effectively unmaintained (last release 2019-11) and silently fails on Sequoia/Tahoe Apple Silicon. Usealerterinstead.osascript display notificationfrom launchd attributes to "Script Editor" and is unreliable. Usealerterfrom launchd context.log show --last 6mis too slow (30+ s) for periodic checks. Poll/Library/Logs/DiagnosticReports/JetsamEvent-*.ipsinstead — async write delay is acceptable on a 5-min cadence.JetsamEvent-*.ipsfiles live in/Library/Logs/DiagnosticReports/(system-wide), NOT~/Library/Logs/DiagnosticReports/.- macOS
ps %cpuis a decaying average over up to one minute and is measured relative to one logical core, so a process may exceed 100 %. Whole-system CPU from the secondiostatsample is 0–100 % across the machine.iostatis much lighter than startingtopevery five minutes. - CPU notifications resolve an owning app without reading command arguments: first from known tool paths (Playwriter, SourceCraft, Logi Options+), then from the outer
.appbundle in the executable/parent chain, then from the executable fallback. Alerts show bothAppandProcessso helpers such asCodex (Renderer)are attributed to ChatGPT. - CPU counters reset after a gap longer than 15 minutes, so sleep and missed calendar firings cannot masquerade as consecutive high-CPU readings. Open incidents remain open but need fresh recovery readings before rearming.
- APFS purgeable space lags behind actual deletion by minutes. After cleanup,
dfmay not show the change immediately; wait or rundiskutil info /System/Volumes/Data | grep "Container Free". - Claude Desktop
vm_bundles/claudevm.bundle/is Claude Cowork, not "Claude Code sandbox" — it's a ~10 GB Ubuntu VM image (rootfs.img,sessiondata.img,efivars.fd,vmIP) for Anthropic's sandboxed code-execution feature. It is auto-provisioned at every Claude Desktop launch via an SHA1 integrity check, so its recent mtime ≠ user activity. Technically safe to delete (no chat/MCP impact), but Claude Desktop silently re-downloads ~10 GB on next launch and runs at ~55 % CPU while doing so. The Claude Code CLI does NOT use this bundle. Recommended classification: Tier 10 discuss-first with quit-Claude-Desktop pre-step and a warning that the bundle returns until Anthropic ships an opt-out toggle (open in anthropics/claude-code#57371). - General rule: if you encounter a folder/bundle you can't describe in one sentence (especially > 500 MB), don't guess — delegate a quick lookup to the
web-searchersubagent before writing the item'sdescription. See Workflow A step 4.
Outcomes scale
A representative recovery from a Mac that hit ~8 % free after long memory-pressure sessions on a heavily-loaded dev profile (Docker, multiple AI tools, IDEs, browsers):
- ~25 % of total disk capacity recovered in a 4-hour session
- Largest single contribution: project build artifacts via
mo purge(~30–50 GB across many scan paths) - Stale IDE installations + caches + preferences: ~10 GB
- Docker reclaim (unused images, dead builders, orphan volumes): ~10 GB
~/Downloadsreview (old installers, recordings, archived repos): ~15 GB- Package-manager caches (npm, pnpm, gradle, maven, cargo, brew): ~5 GB
- Sudo-tier cleanup (system logs, vendor-app depots): ~5–10 GB
Active alerter installed with 7-day calibration window; verified via synthetic disk-trigger test before going live. Stats menubar app installed for passive monitoring.
Numbers scale with workload and disk size. Light users will see less; heavy AI/Docker/IDE users will see more.
Files (ai-driven-development)
-
assets
-
space-scan
-
tests
-
core_tests.cpp 3.5 KB · in bundle
-
integration_macos.py 4.6 KB
Loading… -
tree_macos.py 1.4 KB
Loading…
-
-
.gitignore 12 B · in bundle
-
core.hpp 6.1 KB · in bundle
-
space_scan.cpp 19.9 KB · in bundle
-
test.sh 662 B
Loading…
-
-
apply-cleanup-selection.py 10.2 KB
Loading… -
build-space-scan.sh 347 B
Loading… -
com.local.mac-health-check.plist 2.2 KB · in bundle
-
config.sh 2.7 KB
Loading… -
disk_agent.py 7.5 KB
Loading… -
disk_responses.py 19 KB
Loading… -
disk_review.py 13.5 KB
Loading… -
disk_safety.py 16.6 KB
Loading… -
mac-health-action 14.9 KB · in bundle
-
mac-health-check 26.9 KB · in bundle
-
mac-health-disk 199 B · in bundle
-
mole-core-1.39.0.json 344 B
Loading… -
mole-exact-file.sh 2 KB
Loading… -
render-cleanup-plan.py 49.6 KB
Loading… -
render-storage-report.py 1.5 KB
Loading… -
storage-tree.js 2.4 KB
Loading…
-
-
docs
-
screenshot-tooltip.png 129.5 KB · in bundle
-
screenshot.png 131.5 KB · in bundle
-
-
references
-
alerting.md 17.9 KB
Loading… -
cleanup-tiers.md 15.3 KB
Loading… -
mole-techniques.md 10.2 KB
Loading… -
never-touch.md 26.9 KB
Loading… -
optional-disk-responses.md 13.8 KB
Loading… -
storage-report.md 5.1 KB
Loading… -
triage.md 6.8 KB
Loading…
-
-
tests
-
test-cpu-actions.sh 4.3 KB
Loading… -
test-cpu-monitor.sh 6.4 KB
Loading… -
test_bulk_audit.py 1.7 KB
Loading… -
test_disk_responses.py 18.6 KB
Loading… -
test_storage_report.py 2.6 KB
Loading… -
test_storage_tree.js 1.7 KB
Loading…
-
-
.gitignore 44 B · in bundle
-
README.md 18.5 KB
# maintaining-macos-health > **v1.2.0** — Recovery and prevention playbook for macOS disk, memory, and persistent CPU problems, with an **interactive HTML cleanup UI**, a noise-resistant actionable LaunchAgent alerter, and Mole-grounded safety guards. Built for Apple Silicon dev machines that run heavy workloads — Docker, multiple AI tools, IDEs, browsers.  ## Table of contents - [Why this skill](#why-this-skill) - [Install](#install) - [Prerequisites](#prerequisites) - [Quick start](#quick-start) - [What it does](#what-it-does) - [Triage flow (signal classification)](#triage-flow-signal-classification) - [Interactive cleanup UI](#interactive-cleanup-ui) - [Cleanup tiers (10 levels, risk-ordered)](#cleanup-tiers-10-levels-risk-ordered) - [Active alerter](#active-alerter) - [Key features](#key-features) - [Sources and methodology](#sources-and-methodology) - [File structure](#file-structure) - [License](#license) ## Why this skill Modern macOS dev machines hit a specific failure mode that's not covered well anywhere else: a **watchdog-timeout kernel panic** caused by `vm_compressor` segments saturating to 100 % while the disk is too full to extend swap. The symptom is "Mac freezes for ~90 seconds, then reboots." The signal that always precedes it is `JetsamEvent` files containing `vm-compressor-space-shortage` — Apple's kernel killing processes for memory minutes before it gives up. This skill packages **three complementary capabilities** for that failure mode: 1. A **triage playbook** with a first-five-minutes decision tree and a 10-tier cleanup catalogue. 2. An **interactive HTML cleanup UI** the agent renders after scanning, so the user picks exactly what gets deleted instead of trusting the agent's memory. 3. An **active LaunchAgent alerter** with critical disk/memory/Jetsam triggers plus persistent CPU anomaly detection, hysteresis, incident deduplication, and safe diagnostic snapshots. Validated against a real watchdog-timeout panic on Apple Silicon caused by `vm_compressor` segments saturated at 100 % with the disk over 90 % full. The same playbook works for routine cleanup or first-time setup on a new machine. ## Install ```bash npx skills add CodeAlive-AI/ai-driven-development@maintaining-macos-health -g -y ``` ## Prerequisites | Tool | Why | Install | |---|---|---| | [Mole](https://github.com/tw93/mole) (`mo`) | Safety floor for cleanup — marker-based project artifact detection (`mo purge`), system cache cleanup (`mo clean`), thorough app uninstall (`mo uninstall`) | `brew install mole` | | [alerter](https://github.com/vjeantet/alerter) | macOS notifications from launchd (replaces dead `terminal-notifier`) | `brew install vjeantet/tap/alerter` | | Python 3 (Apple-shipped) | Powers the cleanup UI server and the apply helper. stdlib only — no pip install required | (preinstalled) | | [Stats](https://github.com/exelban/stats) (recommended) | Passive menubar monitoring (memory pressure, disk, swap) | `brew install --cask stats` | Apple Silicon Mac running macOS Sequoia (15.x) or Tahoe (26.x) recommended. Bash 3.2 (Apple-shipped) is the minimum — no Homebrew bash required. ## Quick start The skill is consulted by an agent when the user reports macOS health trouble. The agent reads `SKILL.md` and runs one of these workflows: ```text # Free space NOW (incident response) "My Mac is full" / "out of disk space" / kernel panic happened → agent: triage → scan everything → resolve unknown items (web-search if needed) → build cleanup-data.json → render UI in browser → user picks via HTML checkboxes → submit → agent shows selection in chat → user confirms "go" → apply-cleanup-selection.py executes only what was picked → df checkpoint # Set up alerting on a new machine "set up disk alert" / "monitor memory pressure" / restoring after macOS reinstall → agent reads alerting.md, copies assets/ to ~/bin and ~/Library/LaunchAgents # Audit storage "what's eating my disk?" / "audit storage" → agent runs Mole's `mo analyze`, then suggests targeted tier from cleanup-tiers.md ``` Manual install of the alerter (without an agent): ```bash SKILL=$HOME/.claude/skills/maintaining-macos-health mkdir -p ~/bin ~/.config/mac-health ~/Library/Logs/mac-health ~/.local/state/mac-health cp "$SKILL/assets/mac-health-check" ~/bin/ cp "$SKILL/assets/mac-health-action" ~/bin/ cp "$SKILL/assets/config.sh" ~/.config/mac-health/ sed "s|__HOME__|$HOME|g" "$SKILL/assets/com.local.mac-health-check.plist" \ > ~/Library/LaunchAgents/com.local.mac-health-check.plist chmod +x ~/bin/mac-health-check ~/bin/mac-health-action launchctl load -w ~/Library/LaunchAgents/com.local.mac-health-check.plist ``` Manual run of the cleanup UI (without an agent): ```bash # 1. Build a data JSON yourself (see assets/render-cleanup-plan.py docstring for schema) # 2. Start the UI server: python3 ~/.claude/skills/maintaining-macos-health/assets/render-cleanup-plan.py /tmp/cleanup-data.json # 3. Browser opens to http://127.0.0.1:18347/. Tick checkboxes. Click Submit. # 4. Apply the selection (with --dry-run first): python3 ~/.claude/skills/maintaining-macos-health/assets/apply-cleanup-selection.py \ /tmp/cleanup-selection-<ts>.json --dry-run python3 ~/.claude/skills/maintaining-macos-health/assets/apply-cleanup-selection.py \ /tmp/cleanup-selection-<ts>.json ``` ## What it does The skill packages three complementary capabilities, each with its own entry point and assets: | Capability | Entry point | Use | |---|---|---| | **Triage + cleanup playbook** | `references/triage.md`, `references/cleanup-tiers.md`, `references/never-touch.md`, `references/mole-techniques.md` | Tells the agent how to classify a health signal, which 10-tier cleanup block to run, and what categories to never touch | | **Interactive cleanup UI** | `assets/render-cleanup-plan.py` + `assets/apply-cleanup-selection.py` | Renders a categorised, sortable, checkbox-driven HTML report from the agent's scan, serves it on `127.0.0.1:18347`, captures the user's selection, and feeds it to a sanctioned apply script that only deletes what was actually picked | | **Active alerter** | `references/alerting.md` + `assets/{mac-health-check, mac-health-action, config.sh, com.local.mac-health-check.plist}` | Bash + launchd implementation. Critical disk/memory/Jetsam triggers plus whole-system and per-process CPU incident tracking with explicit investigation/stop actions | ### Triage flow (signal classification) Read `references/triage.md`. First-five-minutes decision tree: - **Disk-driven** (most common): `df` < 20 % free → run cleanup tiers - **Memory-driven**: `memory_pressure` ≠ Normal + sustained swap → check Docker memory limit - **Kernel-panic / watchdog-timeout**: parse panic file, identify top-RSS process, install alerter - **JetsamEvent with `vm-compressor-space-shortage`**: imminent panic — close apps, do not run heavy cleanup - **Thermal**: powermetrics, let it cool ### Interactive cleanup UI The agent never decides what to delete on its own. After scanning, it builds a JSON of candidates and hands the decision to the user through a local HTML UI.  Key properties: - **Local-only HTTP server** at `127.0.0.1:18347`, Python stdlib (`ThreadingHTTPServer`), no dependencies, no network calls. - **Categorised cards** with colour-coded tier badges (🟢 safe, 🔵 medium, 🟠 careful, 🔴 protected). - **Sorted by size** within each category (largest first). - **Live counters** per category and a sticky footer with `selected GB / total GB` and an **"after cleanup → X GB free (Y %)"** preview. - **Custom tooltips** on every row: russian/localised `description` of what the item is, full path, kind, size, age, command, and any warning. - **Hard-protected items** appear dimmed with a 🔒 badge and require a per-item confirm dialog before they can be checked. - **Single source of truth**: submit writes `/tmp/cleanup-selection-<ts>.json` and exits. The apply script reads only that file. **Drift protection** is structural — items the user unchecked are physically absent from the JSON and cannot be deleted, even if the agent "remembered" the default-selected list. - **Esc** = Cancel, `prefers-reduced-motion` respected. ### Cleanup tiers (10 levels, risk-ordered) Read `references/cleanup-tiers.md`. Each tier ends with a `df` checkpoint so the agent knows when to stop: 1. **Trivial wins** (~25 GB) — Aerial wallpapers, Trash, Warp updates, orphan app data, hang traces, cached extension VSIXs 2. **Package manager caches** (~10 GB) — npm `_npx`, Playwright, Puppeteer, NuGet, Gradle, Cargo, brew cleanup 3. **Electron caches** (~4 GB) — Slack, Notion, Arc, Cursor, etc. (Quit apps first) 4. **Stale IDE versions** (~10 GB) — JetBrains old major.minor data dirs 5. **`~/Downloads`** (~15-20 GB, interactive) — installers, recordings, archived repos 6. **System logs + vendor depots** (sudo, ~5-8 GB) — `/private/var/db/diagnostics`, Logitech depots 7. **`mo purge`** (~30-50 GB) — project artifacts via Mole's marker-based detection 8. **Docker** (~10-40 GB) — unused images, dead builders, orphan volumes (`buildx_buildkit_*_state` is often huge) 9. **Dev artifacts** (~5 GB, manual) — venvs, node_modules in inactive projects 10. **Discuss-first** — Maven repo, Rust nightly, dotTrace workspaces, `~/.AzureToolsForIntelliJ`, Claude Cowork VM, etc. ### Active alerter Read `references/alerting.md`. Runs every 5 min via `StartCalendarInterval`. Triggers: 1. **Disk free < 10 %** for 3 consecutive readings (15 min sustained) 2. **Memory pressure Critical AND swap > 8 GB** for 3 consecutive readings 3. **New `JetsamEvent-*.ips` containing `vm-compressor-space-shortage`** (immediate, no hysteresis — this is the early-warning signal) CPU monitoring adds two deliberately different signals: 4. **Whole-system CPU busy >= 90 %** for 3 readings — audible critical alert. 5. **One persistent process** >= 80 % of a core for ~1 hour or >= 40 % for ~6 hours — silent advisory, once per incident. Every five-minute run logs whole-system CPU and a safe top-process summary. Alerts show the owning application and process separately—for example, `App=ChatGPT; process=Codex (Renderer)` or `App=Playwriter; process=Google Chrome for Testing Helper`. App attribution uses known tool paths and the executable/parent `.app` chain without reading command arguments. CPU alerts offer `Investigate in Codex`, `Investigate in Claude`, and `Stop Process…` from an `Actions…` menu. Investigations start read-only; Claude Desktop is preferred through its documented deep link, with interactive terminal CLIs as fallback. Stop is never automatic: it revalidates PID identity, ownership and current CPU, asks for confirmation, sends SIGTERM first, and requires a second confirmation before SIGKILL. Sleep gaps reset consecutive counters. Alert-time top-10 snapshots are retained for 30 days in `~/Library/Logs/mac-health/cpu-incidents/`. Plus: 30-min cooldown and 7-day calibration for the original resource alerts, `~/.config/mac-health/silent` for manual suppression, and optional `ntfy.sh` phone push. CPU starts immediately with conservative defaults; process advisories are silent and incident-deduplicated. ## Key features - **Drift protection (apply-cleanup-selection.py)** — the apply phase reads only `selected_items` from the selection JSON. The skill's safety rules **forbid hand-rolled `rm` blocks** at apply time. Items the user unchecked are physically absent and cannot be deleted; protected items must additionally appear in `protected_overrides` or are skipped. - **Path validator** — every command runs through a Mole-style check: `/System`, `/bin`, `/sbin`, `/usr`, `/etc`, `/Library/Extensions`, `/private/var/db/uuidtext` are blocked; `..` rejected as a path component; wrapper commands (`brew`, `docker`, `nvm`, `dotnet`, `pnpm`, `osascript`) whitelisted. - **Web-search-on-uncertainty** — for any candidate > 500 MB the agent can't describe in one sentence, the skill mandates a `web-searcher` lookup before showing the report. Prevents "unknown / ML data" vague descriptions. - **Claude Cowork aware** — the skill knows `~/Library/Application Support/Claude/vm_bundles/claudevm.bundle/` is the Cowork VM (Ubuntu 22.04 in Apple Virtualization.framework). It auto-recreates on every Claude Desktop launch via SHA1 integrity check, classified as **Tier 10 discuss-first** with the quit-Claude-Desktop pre-step and recreation warning (open issue [anthropics/claude-code#57371](https://github.com/anthropics/claude-code/issues/57371)). - **Never-touch list** — explicit blacklist with consequence notes: Mole's curated app-protection rules (`com.apple.coreaudio` issue #553, `controlcenter*` issue #136, `org.cups.*` issue #731) plus auth/credential dotfiles (`~/.ssh/*`, `~/.gnupg`, `~/.aws/*`, `~/.kube/config`, `~/.nuget`, `~/.git-credentials`), AI/password/VPN/keychain bundle IDs, `Telegram tdata`, crypto wallets, terminal saved state, container VM images. Reasoning included for every entry. - **Noise-resistant actionable alerting** — critical resource signals remain audible; persistent per-process CPU is a silent, once-per-incident advisory. Investigation is read-only, and process stopping is explicit, identity-checked, confirm-first, and graceful-first. No auto-cleanup or auto-kill hooks. - **2026 macOS quirks captured** — `terminal-notifier` is dead (last release 2019-11), use `alerter`. `StartInterval` clock pauses during sleep on laptops (radar 6630231), use `StartCalendarInterval` with explicit minute-entries. LaunchAgent default `PATH` does not include `/opt/homebrew/bin`, must declare in plist. `osascript display notification` from launchd attributes to Script Editor and is unreliable. `mo clean` / `mo purge` piped through `| head` raises SIGPIPE and exits 144 — capture to a file or use `tail` instead. - **Bash 3.2 compatible** — runs against Apple-shipped `/bin/bash` 3.2.57 with no `set -u` quirks. Label-aware `awk` parsing for `vm.swapusage` (survives field-position changes). - **Low-overhead CPU evidence** — `ps` supplies a one-minute decaying per-process average; the second `iostat` sample supplies 0–100 % whole-machine utilization. Alerts resolve the owning app through known tool paths and `.app` ancestry, while executable names, PIDs, elapsed time, and CPU remain available for diagnosis. Command arguments are deliberately excluded. - **File-polling JetsamEvent** — `log show --last 6m` is too slow (30+ s) on a busy machine; polling `/Library/Logs/DiagnosticReports/JetsamEvent-*.ips` has acceptable async-write latency on a 5-min cadence. ## Sources and methodology - **Apple TN3155** — Reading a kernel panic, panic JSON layout, Compressor Info interpretation - **Apple developer docs** — [Identifying high-memory use with Jetsam Event Reports](https://developer.apple.com/documentation/xcode/identifying-high-memory-use-with-jetsam-event-reports) - **xnu vm_compressor** — segments-vs-pages distinction, `vm-compressor-space-shortage` reason code - **Mole** ([github.com/tw93/mole](https://github.com/tw93/mole)) — battle-tested cleanup safety guards (path validator, project-artifact marker→target map, age thresholds, protected app bundle list) - **Google SRE Workbook** — alert-fatigue prevention, "every alert must require intelligence to resolve" - **Prometheus alerting practices** — symptom-based paging, cause-based diagnostics, pending duration, and actionable notifications - **alerter** ([github.com/vjeantet/alerter](https://github.com/vjeantet/alerter)) — Swift-based notification CLI that works in launchd background context (issue #259 of `terminal-notifier` documents the failure mode being avoided) - **launchd quirks** — radar 6630231 documents `StartInterval` clock-pause during sleep - **Claude Cowork research** — [PVIEITO](https://pvieito.com/2026/01/inside-claude-cowork), [Pluto Security](https://blog.pluto.security/p/inside-claude-cowork-how-anthropics), [Anthropic Help Center](https://support.claude.com/en/articles/14479288), GitHub issues [#47039](https://github.com/anthropics/claude-code/issues/47039), [#57371](https://github.com/anthropics/claude-code/issues/57371) - **Real-incident validation** — two confirmed runs: (1) recovered ~25 % of total disk on Apple Silicon across all 10 cleanup tiers after a watchdog-timeout panic; (2) recovered **+92.8 GB** in a single UI-driven session (116.2 → 209.0 GB Container Free, 76 % used → 56 %, 51 items applied via the apply script, 0 protected items deleted without explicit override). Alerter verified via synthetic disk-trigger test. ## File structure ``` skills/maintaining-macos-health/ ├── .gitignore # ignore __pycache__, .DS_Store, .pyc ├── README.md # this file (public, rendered on skills.sh / GitHub) ├── SKILL.md # agent-facing entry point with workflows ├── docs/ │ ├── screenshot.png # main UI view (categorised checkboxes, sticky footer) │ └── screenshot-tooltip.png # tooltip detail with description + path + command ├── references/ │ ├── triage.md # First 5 min: signal classification + decision tree │ ├── cleanup-tiers.md # 10 risk-ordered cleanup tiers, copy-paste-safe │ ├── never-touch.md # Hard-protected categories with consequence notes │ ├── mole-techniques.md # Marker→target map, safety guards, SIGPIPE-safe dry-run capture │ └── alerting.md # Alerter design + install + troubleshoot ├── assets/ ├── mac-health-check # Bash 3.2-compatible health-check script ├── mac-health-action # Action dispatcher: read-only investigation + confirmed graceful stop ├── config.sh # Default thresholds (sourced by the script) ├── com.local.mac-health-check.plist # LaunchAgent (uses __HOME__ placeholder) ├── render-cleanup-plan.py # Interactive HTML cleanup-plan UI (local HTTP server) └── apply-cleanup-selection.py # Sanctioned apply path — reads selection JSON, validates, executes └── tests/ ├── test-cpu-monitor.sh # CPU pending/firing/recovery/rearm/gap fixture tests └── test-cpu-actions.sh # Prompt routing, PID identity, system selection, dry-run stop tests ``` ## License MIT -
SKILL.md 21.5 KB
--- name: maintaining-macos-health version: 1.4.0 description: Hands-on playbook for macOS disk cleanup, dev-machine optimization, and proactive health alerting. Use when the Mac is full or slow, when a process persistently burns CPU, when a kernel panic / watchdog timeout / vm-compressor-space-shortage / Jetsam event happened, when the user asks to free disk space, audit storage, set up disk/memory/CPU alerts, or restore the same monitoring on a new Mac. Built around Mole (`mo` CLI) for safety guards plus a custom LaunchAgent-based alerter for active warnings. Covers Apple Silicon laptops with heavy AI/Docker workloads. Not for general macOS support, hardware diagnostics, networking issues, GUI / window-manager bugs, Time Machine recovery, or broken app installs. --- # Maintaining macOS Health Recovery and prevention playbook for macOS disk and memory crises. Validated against a real watchdog-timeout kernel panic on Apple Silicon caused by `vm_compressor` segments saturated to 100 % with the disk over 90 % full. The same playbook works for routine cleanup or first-time setup on a new machine. ## Table of contents - [When to use](#when-to-use) - [Skill layout](#skill-layout) - [Core mental model](#core-mental-model) - [Standard workflows](#standard-workflows) - [First interactive use: optional disk responses](#first-interactive-use-optional-disk-responses) - [A. "Free space NOW" (incident response)](#a-free-space-now-incident-response) - [B. "Set up alerting" (new machine or first time)](#b-set-up-alerting-new-machine-or-first-time) - [C. Alerter stopped working / making noise](#c-already-have-alerter-but-it-stopped-working--making-noise) - [D. "Uninstall an app cleanly"](#d-uninstall-an-app-cleanly) - [Safety rules (non-negotiable)](#safety-rules-non-negotiable) - [Domain quirks captured](#domain-quirks-captured) - [Outcomes scale](#outcomes-scale) ## When to use Trigger on any of: - Disk free < 20 % or user complains about being out of space - Watchdog-timeout / kernel panic / "no checkins from watchdogd" - New `JetsamEvent-*.ips` with `vm-compressor-space-shortage` - "Mac is slow", swap > 6 GB, sustained Critical memory pressure - A process persistently consumes a core, or the whole machine stays CPU-saturated - User wants to set up monitoring/alerting from scratch - Migration to a new Mac → restore the same alerter - General "clean my Mac" / "audit storage" / "free space" requests ## Skill layout | File | Use for | |---|---| | `references/triage.md` | First 5 minutes — which signal fired, which tier of cleanup to start with | | `references/cleanup-tiers.md` | Tiered cleanup playbook (10 tiers, zero-risk → discuss-first), copy-paste-safe shell blocks | | `references/never-touch.md` | Categories that **must not** be deleted even under sudo (Mole-derived blacklist + incident-derived additions) | | `references/mole-techniques.md` | What Mole does that we borrow: marker→target map for `mo purge`, safe-path validators, age thresholds | | `references/alerting.md` | Full alerter design: disk/memory/Jetsam critical triggers plus sustained CPU anomaly detection, incident lifecycle, hysteresis, notifier choices, install/restore commands | | `references/optional-disk-responses.md` | First-use offer, installation and operation of two independent opt-ins: emergency Mole cache cleanup below 2%, and a Codex cleanup plan/page at or below 5% with exact-session continuation. | | `assets/mac-health-disk`, `assets/disk_*.py` | Consent-gated disk controller, deterministic inventory, restricted Codex runner and authenticated local selection/confirmation page. Both modes default off. | | `assets/mole-exact-file.sh`, `assets/mole-core-1.39.0.json` | Compatibility-pinned exact-file adapter to Mole; no general `mo clean`, sudo, or shell commands from the agent. | | `assets/space-scan/`, `assets/build-space-scan.sh` | Read-only bulk metadata scanner with explicit directory exclusions and a compact full folder tree; see `references/storage-report.md` for manual inventory | | `assets/render-storage-report.py`, `assets/storage-tree.js` | Append scanner output to the report; lazily expand folders and show largest files | | `assets/mac-health-check` | Production-ready bash script (~250 lines, bash 3.2 compatible) | | `assets/mac-health-action` | Background action dispatcher for read-only Codex/Claude investigations and explicitly confirmed graceful process stopping | | `assets/com.local.mac-health-check.plist` | LaunchAgent plist with `StartCalendarInterval` (StartInterval is broken on laptops) | | `assets/config.sh` | Default config with safe thresholds | | `assets/render-cleanup-plan.py` | Interactive HTML cleanup-plan UI. Renders categorised checkboxes from a JSON of scan findings, serves on `127.0.0.1:18347`, opens browser, waits for the user's selection, writes it to `/tmp/cleanup-selection-<ts>.json`. Used by Workflow A. | | `assets/apply-cleanup-selection.py` | The **only sanctioned way** to apply a cleanup selection. Reads `selected_items` from a selection JSON and executes each item's `command` field. Enforces protected-override check + path validation + Mole-compatible operations log. Prevents drift between what the user picked and what gets deleted. Supports `--dry-run`. | Read the relevant reference before acting. Do NOT operate from memory of these files — the details are calibrated to a real incident and small changes break safety. ## Core mental model 1. **Monitor passively** — Stats menubar (`brew install --cask stats`) — you see issues forming, not just when they explode. 2. **Alert actively, diagnose quietly** — disk, memory, Jetsam, and whole-system CPU saturation are critical. A single process burning CPU is a silent advisory only after a long sustained window; routine samples stay in the log. 3. **Cleanup tiers** — start zero-risk (caches, orphan data), only escalate to project artifacts and sudo categories if needed. Mole's `mo purge` and `mo clean` are the right primary tools. 4. **Mole is the safety floor** — even when running shell commands by hand, follow Mole's path-validation rules: never delete inside `/System`, `/bin`, `/usr`, `/etc`, `/var/db` outside specific allowlisted subpaths; bin/ only under .NET; vendor/ only under PHP; protect AI/password/VPN/keychain bundle IDs. ## Standard workflows ### First interactive use: optional disk responses On the first **operational, interactive** use on a Mac (including an existing installation upgraded to this skill), read `references/optional-disk-responses.md` and offer both options separately in the user's language. Do this before routine setup; during an incident, do not delay immediate triage. A request to edit or review this skill is not consent to activate it on the development machine. Background invocations must never prompt for enrollment. - **Emergency cleanup, free space < 2%:** permission for a bounded Mole cleanup of explicitly approved regenerable caches without another question at incident time. Explain the exact profile, irreversible deletion, possible cache rebuild/download cost, and exclusions before accepting consent. This is not permission for general `mo clean`, project purge, Trash emptying, sudo, or process termination. - **Agent cleanup plan, free space <= 5%:** permission to launch the chosen agent automatically, inspect non-secret storage metadata, and open the local selection page in the default browser. Explain provider usage/cost and what metadata leaves the Mac. The agent may propose deletion but may not perform it; Submit is a selection, and applying still requires a separate confirmation. Record each explicit answer independently; silence, a generic "set up monitoring", or approval of one option does not authorize the other. Keep declined choices across sessions and upgrades. Ask again only on user request, a new machine, or a material change to the consent scope. Existing monitoring continues without either option. **Implementation scope:** the bundled controller supports a pinned Mole 1.39.0 adapter and a restricted Codex CLI session with the same cleanup-plan UI used by Workflow A. Emergency cleanup covers only old Homebrew package downloads and npm content-cache files. Automated planning runs Workflow A's fixed read-only bulk metadata scan, Mole clean/purge preview, Docker inventory and Downloads audit. The automatic executor remains narrower: it can delete only controller-verified regenerable cache files; storage-map and possible user-data findings are visible but disabled and require a later interactive Workflow A session. Read the reference, disclose these limits and verify local compatibility before recording approval with `mac-health-disk configure`. Installation alone never enables a mode. No consent is inferred from a feature-development request. ### A. "Free space NOW" (incident response) 1. **Triage** — read `references/triage.md`, identify which signal fired and how urgent. 2. **Snapshot baseline** — `df -h /System/Volumes/Data` and write down free GB. 3. **Run all scans, don't delete yet** — for a large local disk inventory, use the bundled bulk scanner and full folder tree described in `references/storage-report.md`; build the scanner before use and report build or scan failures explicitly; do not silently substitute another scan method. Also run `mo clean --dry-run`, `mo purge --dry-run --debug`, `docker system df -v`, `~/Downloads` audit. Capture everything; **deletion comes only after user picks via the UI**. 4. **Resolve unknown items before building JSON** — for every candidate > 500 MB whose purpose you cannot explain in one sentence (unfamiliar app, unfamiliar bundle ID, unfamiliar dotfolder, vendor-specific cache, ML model weights, VM image, etc.), **research it first**: check `references/never-touch.md` for a known entry, then delegate a quick lookup to the `web-searcher` subagent ("what is `<path or bundle id>` on macOS, is it safe to delete in 2026"). Wait for the answer, then write a concrete `description` (1-3 sentences in the user's language) into the item — *what it is*, *who created it*, *what feature uses it*, *what breaks if deleted*, *whether it auto-recreates*. **Never show the report with vague placeholders like "unknown" or "ML data"** — that defeats the point of the UI. If a web lookup contradicts `never-touch.md`, prefer the web answer (it's fresher) and propose an update to the reference file. 5. **Build the data JSON** — every candidate becomes a structured `item` (id, label, path, size_bytes, age_days, kind, command, **mandatory `description`**, optional `protected` + `warning`). Write to `/tmp/cleanup-data-<ts>.json`. Use schema from `assets/render-cleanup-plan.py` docstring. Append a read-only disk inventory at the bottom of the report: a collapsible folder-size hierarchy followed by the largest files in descending allocated size. Follow `references/storage-report.md` for the `storage_scan` input, coverage labels, and size semantics. These rows are informational and must not become deletion candidates automatically. 6. **Render and open the cleanup UI**: ```bash python3 .../assets/render-cleanup-plan.py /tmp/cleanup-data-<ts>.json ``` The script starts a one-shot HTTP server on `127.0.0.1:18347`, opens the page in the user's default browser, and **blocks** until the user clicks Submit or Cancel. On submit it writes `/tmp/cleanup-selection-<ts>.json` and prints that path to stdout. Tell the user out loud: "браузер открыт — поставь галочки, нажми Submit, потом пингани меня". Then **stop and wait**. 7. **After the user pings** — read the selection JSON, render the user's choices back in chat (categories, item list, total GB, any protected overrides flagged ⚠), and **ask one explicit confirmation** before deleting. Don't run anything until they say "go". 8. **Apply via the helper script — never hand-rolled `rm`**: ```bash python3 .../assets/apply-cleanup-selection.py /tmp/cleanup-selection-<ts>.json ``` The script reads `selected_items` from the selection JSON and executes each item's `command` field, with built-in safeguards: protected items must appear in `protected_overrides` or are skipped; commands are validated against a hard-protected path list and a `..`-component check before execution; every action is logged to `~/.config/mole/operations.log` in Mole-compatible TSV. `--dry-run` previews without executing. **Do not write your own `rm` blocks in the apply phase** — that's how you delete items the user explicitly unchecked. The selection JSON is the single source of truth; if it's not in `selected_items`, it does not get deleted. Run `df -h /System/Volumes/Data` before and after for the user-visible delta. 9. **Stop at goal** — most users target 100 GB free. Don't go below that just for sport. The Python script is bash-3.2-friendly, uses only stdlib, and is safe to run from inside the agent's shell. Hard-protected items (per `references/never-touch.md`) must always appear in the UI with `"protected": true` + a concrete `warning` string — the UI dims them and requires a per-item confirm dialog before they can be checked. **Never** omit a protected item that user data depends on (Telegram tdata, Bear database, password-manager containers, etc.) — visibility teaches the user the surrounding risk. ### B. "Set up alerting" (new machine or first time) Complete the first-use offer above; preserve existing choices when restoring monitoring. For the optional disk responses, also follow `references/optional-disk-responses.md` to install the bundled helper and dependencies without enabling either mode. Record activation only after independent explicit consent. 1. Copy `assets/mac-health-check` and `assets/mac-health-action` to `~/bin/` (mkdir first; chmod +x). 2. Copy `assets/com.local.mac-health-check.plist` to `~/Library/LaunchAgents/`. 3. Copy `assets/config.sh` to `~/.config/mac-health/config.sh` (mkdir first). 4. `brew install vjeantet/tap/alerter` (NOT terminal-notifier — it's broken in 2026 on Sequoia/Tahoe). 5. `brew install --cask stats` for passive layer. 6. `launchctl load -w ~/Library/LaunchAgents/com.local.mac-health-check.plist`. 7. First run permission prompt: open `alerter` once interactively (`alerter --message test`) so macOS asks for Notification Center permission. 8. Tell the user: 7-day calibration is silent (logs only). Edit `config.sh` after a week if pattern noisy. The calibration window applies to the original disk/memory/Jetsam critical sensors. CPU uses conservative developer-workstation defaults and starts immediately; process advisories are silent and deduplicated for the full incident lifetime. Verify with `launchctl list | grep mac-health` (should show PID and exit 0) and `tail -f ~/Library/Logs/mac-health/health.log`. ### C. "Already have alerter, but it stopped working / making noise" Read `references/alerting.md` § Troubleshooting. Common causes: - Stuck/old `terminal-notifier` (the cask) instead of `alerter` — replace. - LaunchAgent not loading after macOS update — `launchctl bootstrap gui/$(id -u) <plist>`. - Notifications going to Script Editor — TCC permission was revoked, re-grant. - Constant alerts during heavy dev work — `touch ~/.config/mac-health/silent` to suppress. ### D. "Uninstall an app cleanly" `mo uninstall <app>` — Mole scans 12+ locations for app traces (Application Support, Containers, Group Containers, Caches, Preferences, Saved State, LaunchAgents, LaunchDaemons, login items, etc.). Always show dry-run first, never bypass. ## Safety rules (non-negotiable) 1. **Never delete without dry-run + user confirmation** for any tier ≥ 5 or any sudo operation. 2. **Never bypass `references/never-touch.md`** — even if user explicitly asks. Push back, explain the consequence. 3. **`mo purge` and `mo clean` always with `--dry-run` first.** Show estimated reclaim, get confirm. 4. **For Time Machine backups: `tmutil delete <path>`, never `rm`.** TM-tagged paths require the `tmutil` API. 5. **For sudo cleanup of `/Library`, `/private/var/db/*`**: only the allowlisted subpaths from `references/never-touch.md` § Sudo allowlist. 6. **No unrestricted auto-cleanup hooks tied to alerts.** The only exception is the independently approved, bounded emergency Mole cache profile below 2% in `references/optional-disk-responses.md`. Its exact-file dry-run is mandatory; prior profile consent replaces the incident-time confirmation only for that profile. Planning at <= 5% never grants deletion permission. Emergency consent cannot authorize ordinary cleanup tiers or protected paths. 7. **No auto-kill hooks tied to CPU alerts.** A CPU advisory may offer `Stop Process…`, but only as an explicit user action. Revalidate PID/executable identity and ownership, confirm, send SIGTERM first, and require a separate confirmation before SIGKILL. 8. **Don't delete swap files.** `rm /private/var/vm/swapfile*` while running = guaranteed kernel panic. 9. **Apply phase reads only the selection JSON.** Never hand-roll `rm` blocks or hard-code paths from the earlier scan when applying. Real incident: agent applied the default-selected recordings list from the original scan, ignoring that the user had unchecked them in the UI before submitting. The fix is structural — use `assets/apply-cleanup-selection.py` which iterates `selected_items` from the selection JSON only. Automated planning uses the helper's typed `format_version: 2` branch, with a separate confirmation on the local page bound to that exact selection. The emergency executor is the sole separate profile-consent path described in rule 6; it cannot reuse or broaden a user's interactive selection. ## Domain quirks captured - macOS Tahoe (26.x) ships `/bin/bash` 3.2.57. `set -u` + `local var` (no init) = unbound on first reference. The shipped script handles this. - LaunchAgent **does not inherit user PATH**. Plist must declare `EnvironmentVariables.PATH` and use absolute paths for interpreters. - `StartInterval` clock pauses during sleep on Apple Silicon laptops (radar 6630231). Use `StartCalendarInterval` with explicit minute entries (the shipped plist has all 12). - `terminal-notifier` is effectively unmaintained (last release 2019-11) and silently fails on Sequoia/Tahoe Apple Silicon. Use `alerter` instead. - `osascript display notification` from launchd attributes to "Script Editor" and is unreliable. Use `alerter` from launchd context. - `log show --last 6m` is too slow (30+ s) for periodic checks. Poll `/Library/Logs/DiagnosticReports/JetsamEvent-*.ips` instead — async write delay is acceptable on a 5-min cadence. - `JetsamEvent-*.ips` files live in `/Library/Logs/DiagnosticReports/` (system-wide), NOT `~/Library/Logs/DiagnosticReports/`. - macOS `ps %cpu` is a decaying average over up to one minute and is measured relative to one logical core, so a process may exceed 100 %. Whole-system CPU from the second `iostat` sample is 0–100 % across the machine. `iostat` is much lighter than starting `top` every five minutes. - CPU notifications resolve an owning app without reading command arguments: first from known tool paths (Playwriter, SourceCraft, Logi Options+), then from the outer `.app` bundle in the executable/parent chain, then from the executable fallback. Alerts show both `App` and `Process` so helpers such as `Codex (Renderer)` are attributed to ChatGPT. - CPU counters reset after a gap longer than 15 minutes, so sleep and missed calendar firings cannot masquerade as consecutive high-CPU readings. Open incidents remain open but need fresh recovery readings before rearming. - APFS purgeable space lags behind actual deletion by minutes. After cleanup, `df` may not show the change immediately; wait or run `diskutil info /System/Volumes/Data | grep "Container Free"`. - **Claude Desktop `vm_bundles/claudevm.bundle/` is Claude Cowork**, not "Claude Code sandbox" — it's a ~10 GB Ubuntu VM image (`rootfs.img`, `sessiondata.img`, `efivars.fd`, `vmIP`) for Anthropic's sandboxed code-execution feature. It is **auto-provisioned at every Claude Desktop launch** via an SHA1 integrity check, so its recent mtime ≠ user activity. Technically safe to delete (no chat/MCP impact), but Claude Desktop **silently re-downloads ~10 GB on next launch** and runs at ~55 % CPU while doing so. The Claude Code CLI does NOT use this bundle. Recommended classification: Tier 10 discuss-first with quit-Claude-Desktop pre-step and a warning that the bundle returns until Anthropic ships an opt-out toggle (open in [anthropics/claude-code#57371](https://github.com/anthropics/claude-code/issues/57371)). - **General rule**: if you encounter a folder/bundle you can't describe in one sentence (especially > 500 MB), don't guess — delegate a quick lookup to the `web-searcher` subagent before writing the item's `description`. See Workflow A step 4. ## Outcomes scale A representative recovery from a Mac that hit ~8 % free after long memory-pressure sessions on a heavily-loaded dev profile (Docker, multiple AI tools, IDEs, browsers): - ~25 % of total disk capacity recovered in a 4-hour session - Largest single contribution: project build artifacts via `mo purge` (~30–50 GB across many scan paths) - Stale IDE installations + caches + preferences: ~10 GB - Docker reclaim (unused images, dead builders, orphan volumes): ~10 GB - `~/Downloads` review (old installers, recordings, archived repos): ~15 GB - Package-manager caches (npm, pnpm, gradle, maven, cargo, brew): ~5 GB - Sudo-tier cleanup (system logs, vendor-app depots): ~5–10 GB Active alerter installed with 7-day calibration window; verified via synthetic disk-trigger test before going live. Stats menubar app installed for passive monitoring. Numbers scale with workload and disk size. Light users will see less; heavy AI/Docker/IDE users will see more.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.