Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix: require sustained evidence before acting on macOS pressure (#837)

Aurora Capitalebc895bf9459
diff --git a/claude-ops/bin/ops-speedup b/claude-ops/bin/ops-speedup
index ad8643e8..ced637e9 100755
--- a/claude-ops/bin/ops-speedup
+++ b/claude-ops/bin/ops-speedup
@@ -23,20 +23,66 @@ else
RST=""; DIM=""; CYN=""; BCYN=""; BWHT=""; GRN=""; BGRN=""; RED=""; YLW=""
fi
+# Count the latest runnable/zombie states and only call a PID stuck when the
+# same PID remains blocked across all three samples. Kept as one shared helper
+# so regression checks exercise the exact classifier used by the live probe.
+classify_process_state_samples() {
+ awk '
+ FNR == 1 { sample++ }
+ {
+ pid=$1; state=$2
+ if (!(pid in seen)) { seen[pid]=1; total++ }
+ if (sample == 3 && state ~ /^R/) running++
+ if (sample == 3 && state ~ /^Z/) zombies++
+ if (state ~ /^U/) blocked[pid]++
+ }
+ END {
+ if (sample != 3) {
+ print "classify_process_state_samples: expected 3 samples, got " sample+0 " (empty or missing ps output?)" > "/dev/stderr"
+ exit 1
+ }
+ persistent=0
+ for (pid in blocked) if (blocked[pid] == 3) persistent++
+ printf "%d %d %d %d", total+0, running+0, persistent+0, zombies+0
+ }
+ ' "$1" "$2" "$3"
+}
+
# ── Mode flags ───────────────────────────────────────────────────
MODE_JSON=false; MODE_SCAN=false; MODE_CLEAN=false; MODE_DEEP=false; MODE_AGGRESSIVE=false
-for arg in "$@"; do
- case "$arg" in
+MODE_CLASSIFY_STATES=false; CLASSIFY_STATE_FILES=()
+while [[ $# -gt 0 ]]; do
+ case "$1" in
--json) MODE_JSON=true ;;
--scan|--scan-only) MODE_SCAN=true; MODE_JSON=true ;;
--clean) MODE_CLEAN=true ;;
--deep) MODE_DEEP=true; MODE_CLEAN=true ;;
--aggressive) MODE_AGGRESSIVE=true; MODE_DEEP=true; MODE_CLEAN=true ;;
+ --classify-process-states)
+ MODE_CLASSIFY_STATES=true
+ shift
+ CLASSIFY_STATE_FILES=("${1:-}" "${2:-}" "${3:-}")
+ shift 2
+ ;;
# Legacy no-ops: defaults already include these
--safe|--full|--all) ;;
esac
+ shift
done
+if $MODE_CLASSIFY_STATES; then
+ [[ -n "${CLASSIFY_STATE_FILES[0]}" && -f "${CLASSIFY_STATE_FILES[0]}" &&
+ -n "${CLASSIFY_STATE_FILES[1]}" && -f "${CLASSIFY_STATE_FILES[1]}" &&
+ -n "${CLASSIFY_STATE_FILES[2]}" && -f "${CLASSIFY_STATE_FILES[2]}" ]] || {
+ echo "usage: ops-speedup --classify-process-states SAMPLE1 SAMPLE2 SAMPLE3" >&2
+ exit 2
+ }
+ classify_process_state_samples "${CLASSIFY_STATE_FILES[@]}"
+ rc=$?
+ printf '\n'
+ exit "$rc"
+fi
+
# ── OS detection ─────────────────────────────────────────────────
OS="unknown"; DISTRO=""; IS_MACOS=false; IS_LINUX=false; IS_WSL=false; IS_WINDOWS=false
case "$(uname -s)" in
@@ -268,7 +314,17 @@ probe_runtime() {
cpu_sys=$(echo "$top_out" | awk -F'[:,%]' '/CPU usage/ {gsub(/^ +| +$/, "", $4); print $4; exit}')
cpu_idle=$(echo "$top_out" | awk -F'[:,%]' '/CPU usage/ {gsub(/^ +| +$/, "", $6); print $6; exit}')
load=$(sysctl -n vm.loadavg 2>/dev/null | tr -d '{}')
- process_counts=$(ps -Ao stat= 2>/dev/null | awk 'BEGIN{r=0;u=0;z=0;t=0} {t++} /^R/{r++} /^U/{u++} /^Z/{z++} END{printf "%d %d %d %d",t,r,u,z}')
+ # A single ps snapshot routinely catches short filesystem waits as U.
+ # Report a PID as stuck only when it remains in U across three samples.
+ local states1 states2 states3
+ states1=$(mktemp "${TMPDIR%/}/ops-speedup-states.XXXXXX")
+ states2=$(mktemp "${TMPDIR%/}/ops-speedup-states.XXXXXX")
+ states3=$(mktemp "${TMPDIR%/}/ops-speedup-states.XXXXXX")
+ ps -Ao pid=,stat= 2>/dev/null >"$states1"; sleep 1
+ ps -Ao pid=,stat= 2>/dev/null >"$states2"; sleep 1
+ ps -Ao pid=,stat= 2>/dev/null >"$states3"
+ process_counts=$(classify_process_state_samples "$states1" "$states2" "$states3")
+ rm -f "$states1" "$states2" "$states3"
tcp_counts=$(netstat -an 2>/dev/null | awk '$6=="CLOSE_WAIT"{cw++} $6=="TIME_WAIT"{tw++} END{printf "%d %d",cw+0,tw+0}')
elif $IS_LINUX || $IS_WSL; then
local top_out
diff --git a/claude-ops/scripts/macos/pid-performance-monitor.py b/claude-ops/scripts/macos/pid-performance-monitor.py
new file mode 100755
index 00000000..b187923e
--- /dev/null
+++ b/claude-ops/scripts/macos/pid-performance-monitor.py
@@ -0,0 +1,438 @@
+#!/usr/bin/env python3
+"""Persistent, PID-attributed macOS responsiveness monitor.
+
+Default mode is safe apply: QoS-demote known background workloads during sustained
+pressure and terminate only exact, repeatedly-observed Hermes-owned broad rg scans.
+Use --dry-run for a side-effect-free decision report and --status for current health.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import pathlib
+import re
+import shlex
+import signal
+import subprocess
+import time
+from dataclasses import dataclass
+from datetime import datetime, timezone
+
+HOME = pathlib.Path.home()
+STATE_DIR = HOME / ".claude" / ".resource-monitor"
+STATE_FILE = STATE_DIR / "pid-performance-state.json"
+FEATURE_OFF = STATE_DIR / "pid-performance.off"
+TELEMETRY = HOME / ".local" / "share" / "agent-logs" / "pid-performance.jsonl"
+MAX_LOG_BYTES = 5 * 1024 * 1024
+NCPU = os.cpu_count() or 8
+BROAD_ROOTS = tuple(str(p) for p in (HOME, HOME / "Developer", HOME / "Developer" / "active", HOME / "Developer" / "scratch"))
+RG_PREFIX = "rg --files --sortr=modified"
+LOAD_PRESSURE_MULTIPLIER = 2.0
+RG_OBSERVATION_MAX_GAP_S = 180
+QOS_PATTERNS = (
+ "gradle-daemon",
+ "org.gradle.launcher.daemon",
+ "eas-build-local",
+ "expo export",
+ "jest-worker",
+ "pytest",
+)
+PROTECTED_PATTERNS = (
+ "WindowServer", "kernel_task", "launchd", "loginwindow", "Finder.app",
+ "Cursor.app", "Claude.app", "hermes_cli.main gateway", "tailscale",
+ "OrbStack Helper", "Docker", "postgres", "dragonfly", "qdrant",
+ "mcp-proxy", "gbrain serve", "coreaudiod", "Terminal.app", "Ghostty.app",
+ "qemu-system-aarch64", "xcodebuild", "swift-frontend",
+)
+
+# Machine-scoped extras: one command substring per line, blank lines and
+# `#` comments ignored. Your own apps and build tools belong here rather than
+# in this file — the repo is public, so a hardcoded product name would leak
+# whoever runs it.
+EXTRA_PROTECTED_FILE = pathlib.Path(
+ os.environ.get(
+ "CLAUDE_OPS_PROTECTED_PATTERNS_FILE",
+ HOME / ".config" / "claude-ops" / "protected-patterns.txt",
+ )
+)
+
+
+def extra_protected_patterns() -> tuple[str, ...]:
+ try:
+ lines = EXTRA_PROTECTED_FILE.read_text(encoding="utf-8").splitlines()
+ except OSError:
+ return ()
+ return tuple(
+ stripped for line in lines if (stripped := line.strip()) and not stripped.startswith("#")
+ )
+
+@dataclass
+class Proc:
+ pid: int
+ ppid: int
+ cpu: float
+ rss_kb: int
+ elapsed_s: int
+ state: str
+ nice: int
+ command: str
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def run(args: list[str], timeout: float = 10) -> str:
+ return subprocess.run(args, capture_output=True, text=True, timeout=timeout, check=False).stdout
+
+
+def elapsed_seconds(value: str) -> int:
+ days = 0
+ if "-" in value:
+ day, value = value.split("-", 1)
+ days = int(day)
+ parts = [int(x) for x in value.split(":")]
+ if len(parts) == 3:
+ h, m, s = parts
+ elif len(parts) == 2:
+ h, (m, s) = 0, parts
+ else:
+ h, m, s = 0, 0, parts[0]
+ return days * 86400 + h * 3600 + m * 60 + s
+
+
+def processes() -> dict[int, Proc]:
+ out = run(["ps", "-Ao", "pid=,ppid=,pcpu=,rss=,etime=,state=,ni=,command="], 15)
+ result: dict[int, Proc] = {}
+ for line in out.splitlines():
+ parts = line.strip().split(None, 7)
+ if len(parts) < 8:
+ continue
+ try:
+ p = Proc(int(parts[0]), int(parts[1]), float(parts[2]), int(parts[3]),
+ elapsed_seconds(parts[4]), parts[5], int(parts[6]), parts[7])
+ result[p.pid] = p
+ except (ValueError, IndexError):
+ continue
+ return result
+
+
+def cpu_sample() -> dict[str, float]:
+ out = run(["top", "-l", "1", "-n", "0"], 15)
+ match = re.search(r"CPU usage:\s*([0-9.]+)% user,\s*([0-9.]+)% sys,\s*([0-9.]+)% idle", out)
+ if not match:
+ return {"user": 0.0, "sys": 0.0, "idle": 0.0}
+ return {"user": float(match.group(1)), "sys": float(match.group(2)), "idle": float(match.group(3))}
+
+
+def memory_free_pct() -> int:
+ out = run(["memory_pressure", "-Q"], 10)
+ match = re.search(r"free percentage:\s*(\d+)%", out)
+ return int(match.group(1)) if match else 0
+
+
+def swap_mb() -> float:
+ out = run(["sysctl", "-n", "vm.swapusage"], 5)
+ match = re.search(r"used\s*=\s*([0-9.]+)M", out)
+ return float(match.group(1)) if match else 0.0
+
+
+def load_averages() -> list[float]:
+ out = run(["sysctl", "-n", "vm.loadavg"], 5)
+ return [float(x) for x in re.findall(r"[0-9.]+", out)[:3]] or [0.0, 0.0, 0.0]
+
+
+def ancestor_chain(pid: int, table: dict[int, Proc], limit: int = 12) -> list[Proc]:
+ chain: list[Proc] = []
+ seen = set()
+ current = table.get(pid)
+ while current and current.ppid not in seen and len(chain) < limit:
+ seen.add(current.pid)
+ parent = table.get(current.ppid)
+ if not parent:
+ break
+ chain.append(parent)
+ current = parent
+ return chain
+
+
+def is_broad_rg(p: Proc) -> bool:
+ first = p.command.split(None, 1)[0] if p.command else ""
+ if pathlib.Path(first).name != "rg":
+ return False
+ if RG_PREFIX not in p.command:
+ return False
+ return any(re.search(rf"(?:^|\s){re.escape(root)}(?:\s|$)", p.command) for root in BROAD_ROOTS)
+
+
+def is_hermes_gateway_command(command: str) -> bool:
+ """Exact identity check: the real Hermes gateway invocation, not a wrapper payload.
+
+ A substring match on "hermes_cli.main gateway" also matches a wrapper such
+ as `zsh -c "python -m hermes_cli.main gateway"`, whose own argv0 is the
+ shell, not Hermes. Parse argv and require a python interpreter followed by
+ `-m hermes_cli.main gateway` as literal, adjacent tokens.
+ """
+ try:
+ tokens = shlex.split(command)
+ except ValueError:
+ return False
+ if not tokens:
+ return False
+ executable = pathlib.Path(tokens[0]).name
+ if not (executable == "python" or executable.startswith("python3")):
+ return False
+ try:
+ idx = tokens.index("-m")
+ except ValueError:
+ return False
+ return tokens[idx + 1 : idx + 3] == ["hermes_cli.main", "gateway"]
+
+
+def is_hermes_owned(p: Proc, table: dict[int, Proc]) -> bool:
+ return any(is_hermes_gateway_command(parent.command) for parent in ancestor_chain(p.pid, table))
+
+
+def protected(p: Proc) -> bool:
+ patterns = PROTECTED_PATTERNS + extra_protected_patterns()
+ return any(pattern.lower() in p.command.lower() for pattern in patterns)
+
+
+def qos_candidate(p: Proc) -> bool:
+ command = p.command.lower()
+ first = command.split(None, 1)[0] if command else ""
+ executable = pathlib.Path(first).name
+ # Never classify a wrapper shell or installer from words in its payload.
+ if executable in {"sh", "bash", "zsh", "fish", "env", "timeout", "pip", "pip3"}:
+ return False
+ if executable.startswith("pytest") or re.search(r"\bpython(?:[0-9.]*)?\s+-m\s+pytest\b", command):
+ return True
+ if "/jest-worker/" in command or "jest-worker/processchild" in command:
+ return True
+ return any(
+ pattern.lower() in command
+ for pattern in QOS_PATTERNS
+ if pattern not in {"jest-worker", "pytest"}
+ )
+
+
+def parse_utc(value: object) -> datetime | None:
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
+
+
+def prior_observation_is_recent(prior: dict, now: datetime) -> bool:
+ last_seen = parse_utc(prior.get("last_seen"))
+ if last_seen is None:
+ return False
+ age = (now - last_seen).total_seconds()
+ return 0 <= age <= RG_OBSERVATION_MAX_GAP_S
+
+
+def load_state() -> dict:
+ try:
+ return json.loads(STATE_FILE.read_text())
+ except (OSError, json.JSONDecodeError):
+ return {"rg": {}, "last_condition": "unknown", "last_action_ts": None}
+
+
+def save_state(state: dict) -> None:
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
+ tmp = STATE_FILE.with_suffix(".tmp")
+ tmp.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n")
+ tmp.replace(STATE_FILE)
+
+
+def append_telemetry(record: dict, *, dry_run: bool = False) -> None:
+ # --dry-run is documented as side-effect-free: it must not create, rotate,
+ # or append the telemetry file on disk.
+ if dry_run:
+ return
+ TELEMETRY.parent.mkdir(parents=True, exist_ok=True)
+ if TELEMETRY.exists() and TELEMETRY.stat().st_size > MAX_LOG_BYTES:
+ rotated = TELEMETRY.with_suffix(".jsonl.1")
+ rotated.unlink(missing_ok=True)
+ TELEMETRY.replace(rotated)
+ with TELEMETRY.open("a") as f:
+ f.write(json.dumps(record, separators=(",", ":")) + "\n")
+
+
+def taskpolicy_background(pid: int) -> bool:
+ return subprocess.run(["taskpolicy", "-b", "-p", str(pid)], capture_output=True).returncode == 0
+
+
+def renice_background(pid: int, current_nice: int) -> bool:
+ if current_nice >= 10:
+ return True
+ return subprocess.run(["renice", "10", "-p", str(pid)], capture_output=True).returncode == 0
+
+
+def health_score(cpu: dict[str, float], running: int, stuck: int, mem: int, swap: float) -> int:
+ score = 100
+ if cpu["idle"] < 20:
+ score -= 25
+ elif cpu["idle"] < 35:
+ score -= 15
+ elif cpu["idle"] < 60:
+ score -= 5
+ if running + stuck > NCPU * 2:
+ score -= 15
+ elif running + stuck > NCPU:
+ score -= 7
+ if stuck:
+ score -= min(15, stuck * 5)
+ if mem < 20:
+ score -= 15
+ elif mem < 40:
+ score -= 5
+ if swap > 1024:
+ score -= 10
+ return max(0, score)
+
+
+def persistent_state_counts(samples: list[dict[int, Proc]]) -> tuple[int, int, int]:
+ """Return latest runnable/zombie counts and same-PID U across all samples."""
+ latest = samples[-1] if samples else {}
+ running = sum(p.state.startswith("R") for p in latest.values())
+ zombies = sum(p.state.startswith("Z") for p in latest.values())
+ pid_sets = [
+ {pid for pid, p in table.items() if p.state.startswith("U")}
+ for table in samples
+ ]
+ stuck = len(set.intersection(*pid_sets)) if pid_sets else 0
+ return running, stuck, zombies
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--dry-run", action="store_true")
+ parser.add_argument("--status", action="store_true")
+ parser.add_argument("--force-pressure", action="store_true", help="test QoS decisions without fabricating PIDs")
+ parser.add_argument("--rg-min-age", type=int, default=60, help=argparse.SUPPRESS)
+ parser.add_argument("--rg-consecutive", type=int, default=2, help=argparse.SUPPRESS)
+ args = parser.parse_args()
+
+ table = processes()
+ process_samples = [table]
+ samples = [cpu_sample()]
+ if not args.status:
+ time.sleep(2)
+ process_samples.append(processes())
+ samples.append(cpu_sample())
+ time.sleep(2)
+ process_samples.append(processes())
+ samples.append(cpu_sample())
+ table = process_samples[-1]
+ avg_cpu = {k: round(sum(s[k] for s in samples) / len(samples), 2) for k in samples[0]}
+ running, stuck, zombies = persistent_state_counts(process_samples)
+ mem = memory_free_pct()
+ swap = swap_mb()
+ loads = load_averages()
+ # macOS load includes runnable tasks and tasks blocked in kernel I/O. A machine
+ # can be overloaded while CPU remains partly idle, and CPU can look busy from a
+ # single short spike that load hasn't caught up to yet. Requiring both load1
+ # and load5 over threshold avoids reacting to that spike.
+ sustained_low_idle_cpu = all(s["idle"] < 35 for s in samples)
+ sustained_load = len(loads) >= 2 and loads[0] > NCPU * LOAD_PRESSURE_MULTIPLIER and loads[1] > NCPU * LOAD_PRESSURE_MULTIPLIER
+ # Contract: mitigation requires BOTH sustained signals, not either alone —
+ # three low-idle CPU samples AND elevated sustained load. A single signal is
+ # not sufficient evidence for a script that terminates processes.
+ pressure = args.force_pressure or (sustained_low_idle_cpu and sustained_load)
+ state = load_state()
+ prior_rg = state.get("rg", {})
+ current_rg: dict[str, dict] = {}
+ actions: list[dict] = []
+ observation_time = datetime.now(timezone.utc)
+ observation_ts = observation_time.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ for p in table.values():
+ # protected() guards this same list for QoS below; reuse it here so an
+ # operator-protected command is never a TERM candidate either.
+ if protected(p) or not is_broad_rg(p) or not is_hermes_owned(p, table):
+ continue
+ key = f"{p.pid}:{p.command}"
+ prior = prior_rg.get(key, {})
+ prior_count = int(prior.get("consecutive", 0)) if prior_observation_is_recent(prior, observation_time) else 0
+ consecutive = prior_count + 1
+ current_rg[key] = {"consecutive": consecutive, "last_seen": observation_ts, "elapsed_s": p.elapsed_s, "state": p.state}
+ # A one-frame U state is a normal filesystem wait on macOS, not enough
+ # evidence to terminate work. Every TERM candidate must be observed in
+ # monitor runs no more than RG_OBSERVATION_MAX_GAP_S apart; CPU, U state,
+ # and system pressure only describe why the repeated scan is harmful.
+ pathological = (
+ p.elapsed_s >= args.rg_min_age
+ and consecutive >= args.rg_consecutive
+ and (p.cpu >= 10 or p.state.startswith("U") or pressure)
+ )
+ if pathological:
+ decision = {"type": "term_runaway_rg", "pid": p.pid, "cpu": p.cpu, "elapsed_s": p.elapsed_s,
+ "state": p.state, "consecutive": consecutive, "command": p.command}
+ if not args.dry_run and not args.status and not FEATURE_OFF.exists():
+ # Re-read exact PID and command immediately before TERM to guard PID reuse.
+ fresh_table = processes()
+ fresh = fresh_table.get(p.pid)
+ if (
+ fresh
+ and fresh.command == p.command
+ and not protected(fresh)
+ and is_broad_rg(fresh)
+ and is_hermes_owned(fresh, fresh_table)
+ ):
+ try:
+ os.kill(p.pid, signal.SIGTERM)
+ decision["result"] = "terminated"
+ except OSError as exc:
+ decision["result"] = f"failed:{exc.__class__.__name__}"
+ else:
+ decision["result"] = "skipped_pid_changed"
+ else:
+ decision["result"] = "would_terminate"
+ actions.append(decision)
+
+ if pressure:
+ for p in table.values():
+ if protected(p) or not qos_candidate(p):
+ continue
+ decision = {"type": "qos_background", "pid": p.pid, "cpu": p.cpu, "nice_before": p.nice, "command": p.command}
+ if not args.dry_run and not args.status and not FEATURE_OFF.exists():
+ # p was captured in an earlier ps snapshot; the PID can have exited
+ # and been reused by the time we act. Re-read it immediately before
+ # applying a QoS change and require the same command, still
+ # unprotected, and still a qos_candidate on the fresh read.
+ fresh_table = processes()
+ fresh = fresh_table.get(p.pid)
+ if fresh and fresh.command == p.command and not protected(fresh) and qos_candidate(fresh):
+ q = taskpolicy_background(fresh.pid)
+ n = renice_background(fresh.pid, fresh.nice)
+ decision["result"] = "applied" if q and n else "partial"
+ else:
+ decision["result"] = "skipped_pid_changed"
+ else:
+ decision["result"] = "would_apply"
+ actions.append(decision)
+
+ condition = "pressure" if pressure else "healthy"
+ if not args.status and not args.dry_run:
+ state.update({"rg": current_rg, "last_condition": condition, "last_run_ts": utc_now()})
+ if actions:
+ state["last_action_ts"] = utc_now()
+ save_state(state)
+
+ record = {"ts": utc_now(), "mode": "status" if args.status else "dry-run" if args.dry_run else "apply",
+ "feature_off": FEATURE_OFF.exists(), "cpu": avg_cpu, "pressure": pressure,
+ "pressure_reasons": {"cpu": sustained_low_idle_cpu, "sustained_load": sustained_load},
+ "load": loads, "mem_free_pct": mem, "swap_mb": swap,
+ "running": running, "stuck": stuck, "zombies": zombies,
+ "health_score": health_score(avg_cpu, running, stuck, mem, swap), "actions": actions}
+ append_telemetry(record, dry_run=args.dry_run)
+ print(json.dumps(record, indent=2))
+ return 0
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/claude-ops/scripts/macos/run-pressure-monitor-if-needed b/claude-ops/scripts/macos/run-pressure-monitor-if-needed
new file mode 100755
index 00000000..93864375
--- /dev/null
+++ b/claude-ops/scripts/macos/run-pressure-monitor-if-needed
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+# Invoke the PID-attributed pressure monitor only for sustained high macOS load.
+set -euo pipefail
+
+if [[ $# -ne 4 ]]; then
+ echo "usage: run-pressure-monitor-if-needed LOAD1 LOAD5 NCPU MONITOR" >&2
+ exit 2
+fi
+
+load1="$1"
+load5="$2"
+ncpu="$3"
+monitor="$4"
+
+if ! awk -v l1="$load1" -v l5="$load5" -v n="$ncpu" \
+ 'BEGIN { exit !(n > 0 && l1 > n*2 && l5 > n*2) }'; then
+ exit 0
+fi
+
+[[ -x "$monitor" ]] || exit 0
+exec "$monitor"
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index 212f30bc..8d95221f 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -37,6 +37,8 @@ run_suite "$TESTS_DIR/test-skills-lint.sh"
run_suite "$TESTS_DIR/test-agents-lint.sh"
run_suite "$TESTS_DIR/test-bin-scripts.sh"
run_suite "$TESTS_DIR/test-ops-speedup.sh"
+run_suite "$TESTS_DIR/test-pid-performance-monitor.sh"
+run_suite "$TESTS_DIR/test-run-pressure-monitor-if-needed.sh"
run_suite "$TESTS_DIR/test-hooks.sh"
run_suite "$TESTS_DIR/test-specialist-agent-swap.sh"
run_suite "$TESTS_DIR/test-rotate-cliproxy-integration.sh"
diff --git a/claude-ops/tests/test-ops-speedup.sh b/claude-ops/tests/test-ops-speedup.sh
index 486749fb..398ec119 100644
--- a/claude-ops/tests/test-ops-speedup.sh
+++ b/claude-ops/tests/test-ops-speedup.sh
@@ -55,6 +55,96 @@ assert_true "CPU hog kill gated by aggressive" grep -q 'Despite the legacy name,
assert_true "GPU probe uses ioreg without sudo" grep -q 'ioreg -r -d1 -w0 -c IOGPU' "$BIN"
assert_true "long-lived hog threshold is 3 hours" grep -q 'elapsed >= 10800' "$BIN"
+# Drive the shipped process-state classifier through the real binary. A PID that
+# appears blocked in only one sample is transient; only the PID blocked in all
+# three samples is counted as stuck. Runnable and zombie counts use the latest
+# sample, matching the live probe.
+cat >"$tmpdir/states-1" <<'EOF'
+101 U
+202 U
+303 R
+404 S
+EOF
+cat >"$tmpdir/states-2" <<'EOF'
+101 S
+202 U
+303 S
+404 S
+EOF
+cat >"$tmpdir/states-3" <<'EOF'
+101 R
+202 U
+303 S
+404 Z
+505 R
+EOF
+state_counts=$(bash "$BIN" --classify-process-states \
+ "$tmpdir/states-1" "$tmpdir/states-2" "$tmpdir/states-3")
+assert_eq "transient U is ignored and persistent U is counted" "5 2 1 1" "$state_counts"
+
+cat >"$tmpdir/states-none-1" <<'EOF'
+11 U
+12 S
+EOF
+cat >"$tmpdir/states-none-2" <<'EOF'
+11 S
+12 U
+EOF
+cat >"$tmpdir/states-none-3" <<'EOF'
+11 R
+12 S
+EOF
+no_stuck=$(bash "$BIN" --classify-process-states \
+ "$tmpdir/states-none-1" "$tmpdir/states-none-2" "$tmpdir/states-none-3")
+assert_eq "one-frame U states never become stuck" "2 1 0 0" "$no_stuck"
+
+# On macOS, also drive the normal --json probe with a ps shim. This proves the
+# public runtime.stuck result uses all three PID/state observations rather than
+# only proving the helper in isolation.
+if [[ "$(uname -s)" == "Darwin" ]]; then
+ real_ps=$(command -v ps)
+ mkdir -p "$tmpdir/mock-bin"
+ cat >"$tmpdir/mock-bin/ps" <<'SH'
+#!/usr/bin/env bash
+set -euo pipefail
+if [[ "$*" == "-Ao pid=,stat=" ]]; then
+ count_file="$OPS_SPEEDUP_PS_COUNT"
+ count=0
+ [[ -f "$count_file" ]] && count=$(cat "$count_file")
+ count=$((count + 1))
+ printf '%s\n' "$count" >"$count_file"
+ case "${OPS_SPEEDUP_PS_SCENARIO}:${count}" in
+ transient:1) printf '101 U\n202 S\n' ;;
+ transient:2) printf '101 S\n202 U\n' ;;
+ transient:3) printf '101 R\n202 S\n' ;;
+ persistent:*) printf '101 U\n202 S\n' ;;
+ *) exit 3 ;;
+ esac
+else
+ exec "$OPS_SPEEDUP_REAL_PS" "$@"
+fi
+SH
+ chmod +x "$tmpdir/mock-bin/ps"
+
+ run_state_scenario() {
+ local scenario="$1"
+ local output count_file="$tmpdir/ps-${scenario}.count"
+ rm -f "$count_file"
+ output=$(PATH="$tmpdir/mock-bin:$PATH" \
+ OPS_SPEEDUP_REAL_PS="$real_ps" \
+ OPS_SPEEDUP_PS_SCENARIO="$scenario" \
+ OPS_SPEEDUP_PS_COUNT="$count_file" \
+ bash "$BIN" --json)
+ python3 - "$output" <<'PY'
+import json, sys
+print(json.loads(sys.argv[1])["runtime"]["stuck"])
+PY
+ }
+
+ assert_eq "real JSON probe ignores transient U states" "0" "$(run_state_scenario transient)"
+ assert_eq "real JSON probe counts a persistent U PID" "1" "$(run_state_scenario persistent)"
+fi
+
json_out=$(bash "$BIN" --json)
python3 - "$json_out" <<'PY'
import json, sys
diff --git a/claude-ops/tests/test-pid-performance-monitor.py b/claude-ops/tests/test-pid-performance-monitor.py
new file mode 100755
index 00000000..7a3b1461
--- /dev/null
+++ b/claude-ops/tests/test-pid-performance-monitor.py
@@ -0,0 +1,350 @@
+#!/usr/bin/env python3
+"""Regression tests for the shipped macOS PID pressure monitor."""
+from __future__ import annotations
+
+import contextlib
+import importlib.util
+import io
+import pathlib
+import sys
+import tempfile
+import unittest
+import unittest.mock as mock
+from datetime import datetime, timedelta, timezone
+
+ROOT = pathlib.Path(__file__).resolve().parents[1]
+MONITOR_PATH = ROOT / "scripts" / "macos" / "pid-performance-monitor.py"
+SPEC = importlib.util.spec_from_file_location("pid_performance_monitor", MONITOR_PATH)
+assert SPEC and SPEC.loader
+monitor = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = monitor
+SPEC.loader.exec_module(monitor)
+REAL_APPEND_TELEMETRY = monitor.append_telemetry
+
+
+def proc(
+ pid: int,
+ command: str,
+ *,
+ ppid: int = 1,
+ cpu: float = 0.0,
+ elapsed_s: int = 120,
+ state: str = "S",
+ nice: int = 0,
+) -> monitor.Proc:
+ return monitor.Proc(pid, ppid, cpu, 1024, elapsed_s, state, nice, command)
+
+
+class PressureMonitorTests(unittest.TestCase):
+ def setUp(self) -> None:
+ self.telemetry: list[dict] = []
+ self.common = [
+ mock.patch.object(monitor, "memory_free_pct", return_value=90),
+ mock.patch.object(monitor, "swap_mb", return_value=0.0),
+ mock.patch.object(monitor, "load_state", return_value={"rg": {}}),
+ mock.patch.object(
+ monitor, "append_telemetry",
+ side_effect=lambda record, **_kwargs: self.telemetry.append(record),
+ ),
+ mock.patch.object(monitor.time, "sleep", return_value=None),
+ mock.patch.object(monitor, "FEATURE_OFF", pathlib.Path("/path/that/does/not/exist")),
+ ]
+ for patcher in self.common:
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ @staticmethod
+ def recent_timestamp(seconds_ago: int = 1) -> str:
+ return (datetime.now(timezone.utc) - timedelta(seconds=seconds_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+ def run_main(
+ self,
+ *,
+ table: dict[int, monitor.Proc],
+ cpu_samples: list[dict[str, float]],
+ loads: list[float],
+ argv: list[str] | None = None,
+ prior_state: dict | None = None,
+ ) -> dict:
+ if prior_state is not None:
+ state_patch = mock.patch.object(monitor, "load_state", return_value=prior_state)
+ state_patch.start()
+ self.addCleanup(state_patch.stop)
+ with (
+ mock.patch.object(sys, "argv", [str(MONITOR_PATH), *(argv or ["--dry-run"])]),
+ mock.patch.object(monitor, "processes", side_effect=lambda: table),
+ mock.patch.object(monitor, "cpu_sample", side_effect=cpu_samples),
+ mock.patch.object(monitor, "load_averages", return_value=loads),
+ contextlib.redirect_stdout(io.StringIO()),
+ ):
+ self.assertEqual(0, monitor.main())
+ self.assertTrue(self.telemetry)
+ return self.telemetry[-1]
+
+ def test_persistent_state_counts_ignore_one_frame_u(self) -> None:
+ samples = [
+ {1: proc(1, "one", state="U"), 2: proc(2, "two", state="U")},
+ {1: proc(1, "one", state="S"), 2: proc(2, "two", state="U")},
+ {1: proc(1, "one", state="R"), 2: proc(2, "two", state="U"), 3: proc(3, "three", state="Z")},
+ ]
+ self.assertEqual((1, 1, 1), monitor.persistent_state_counts(samples))
+
+ def test_cpu_pressure_requires_all_three_low_idle_samples(self) -> None:
+ record = self.run_main(
+ table={},
+ cpu_samples=[
+ {"user": 70.0, "sys": 10.0, "idle": 20.0},
+ {"user": 20.0, "sys": 10.0, "idle": 70.0},
+ {"user": 65.0, "sys": 10.0, "idle": 25.0},
+ ],
+ loads=[1.0, 1.0, 1.0],
+ )
+ self.assertFalse(record["pressure"])
+ self.assertFalse(record["pressure_reasons"]["cpu"])
+
+ def test_sustained_load_requires_both_load1_and_load5_over_threshold(self) -> None:
+ high = monitor.NCPU * monitor.LOAD_PRESSURE_MULTIPLIER + 1
+ normal_cpu = [{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3
+ transient = self.run_main(table={}, cpu_samples=normal_cpu, loads=[high, 1.0, 1.0])
+ self.assertFalse(transient["pressure"])
+ # Load alone, even sustained across load1 and load5, is not sufficient:
+ # the contract requires BOTH signals. CPU stayed idle here, so no pressure.
+ load_only = self.run_main(table={}, cpu_samples=normal_cpu, loads=[high, high, 1.0])
+ self.assertFalse(load_only["pressure"])
+ self.assertTrue(load_only["pressure_reasons"]["sustained_load"])
+ self.assertFalse(load_only["pressure_reasons"]["cpu"])
+
+ def test_pressure_requires_both_low_idle_cpu_and_sustained_load(self) -> None:
+ high = monitor.NCPU * monitor.LOAD_PRESSURE_MULTIPLIER + 1
+ low_idle_cpu = [{"user": 70.0, "sys": 10.0, "idle": 20.0}] * 3
+ # Low-idle CPU alone (normal load) is not sufficient either.
+ cpu_only = self.run_main(table={}, cpu_samples=low_idle_cpu, loads=[1.0, 1.0, 1.0])
+ self.assertFalse(cpu_only["pressure"])
+ self.assertTrue(cpu_only["pressure_reasons"]["cpu"])
+ self.assertFalse(cpu_only["pressure_reasons"]["sustained_load"])
+ # Both signals together produce pressure.
+ both = self.run_main(table={}, cpu_samples=low_idle_cpu, loads=[high, high, 1.0])
+ self.assertTrue(both["pressure"])
+ self.assertTrue(both["pressure_reasons"]["cpu"])
+ self.assertTrue(both["pressure_reasons"]["sustained_load"])
+
+ def test_broad_scan_requires_exact_command_root_and_hermes_ancestor(self) -> None:
+ hermes = proc(10, "python -m hermes_cli.main gateway")
+ broad = proc(20, f"rg --files --sortr=modified {monitor.HOME / 'Developer'}", ppid=10, cpu=20.0, state="U")
+ narrow = proc(21, "rg --files --sortr=modified .", ppid=10, cpu=20.0, state="U")
+ foreign = proc(22, f"rg --files --sortr=modified {monitor.HOME}", ppid=1, cpu=20.0, state="U")
+ table = {p.pid: p for p in (hermes, broad, narrow, foreign)}
+ first = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ )
+ self.assertEqual([], first["actions"])
+ key = f"{broad.pid}:{broad.command}"
+ repeated = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ prior_state={"rg": {key: {"consecutive": 1, "last_seen": self.recent_timestamp()}}},
+ )
+ term_actions = [a for a in repeated["actions"] if a["type"] == "term_runaway_rg"]
+ self.assertEqual([20], [a["pid"] for a in term_actions])
+ self.assertEqual("would_terminate", term_actions[0]["result"])
+
+ def test_protected_workloads_are_never_qos_or_termination_targets(self) -> None:
+ table: dict[int, monitor.Proc] = {}
+ pid = 100
+ for pattern in monitor.PROTECTED_PATTERNS:
+ table[pid] = proc(pid, f"/usr/bin/{pattern} pytest", cpu=90.0, state="U")
+ pid += 1
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 80.0, "sys": 10.0, "idle": 10.0}] * 3,
+ loads=[100.0, 100.0, 100.0],
+ )
+ self.assertEqual([], record["actions"])
+
+ def test_xcode_simulator_and_native_builds_are_directly_protected(self) -> None:
+ protected_commands = {
+ 301: "/usr/bin/xcodebuild -workspace MyApp.xcworkspace build",
+ 302: "/usr/bin/swift-frontend -frontend -c Sources/App.swift",
+ 303: "/Applications/OrbStack.app/qemu-system-aarch64 -machine virt",
+ }
+ table = {pid: proc(pid, command, cpu=99.0, state="U") for pid, command in protected_commands.items()}
+ for p in table.values():
+ self.assertTrue(monitor.protected(p), p.command)
+ self.assertFalse(monitor.qos_candidate(p), p.command)
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 80.0, "sys": 10.0, "idle": 10.0}] * 3,
+ loads=[100.0, 100.0, 100.0],
+ )
+ self.assertEqual([], record["actions"])
+
+ def test_operator_supplied_protected_patterns_are_honoured(self) -> None:
+ target = proc(401, "/Applications/MyCoach.app/MyCoach", cpu=99.0, state="U")
+ # Not protected by the shipped list alone.
+ self.assertFalse(monitor.protected(target))
+ with tempfile.TemporaryDirectory() as tmp:
+ extras = pathlib.Path(tmp) / "protected-patterns.txt"
+ extras.write_text("# operator extras\n\nMyCoach.app/MyCoach\n", encoding="utf-8")
+ with mock.patch.object(monitor, "EXTRA_PROTECTED_FILE", extras):
+ self.assertEqual(("MyCoach.app/MyCoach",), monitor.extra_protected_patterns())
+ self.assertTrue(monitor.protected(target))
+ self.assertFalse(monitor.qos_candidate(target))
+
+ def test_missing_operator_pattern_file_is_not_fatal(self) -> None:
+ with mock.patch.object(monitor, "EXTRA_PROTECTED_FILE", pathlib.Path("/nonexistent/protected.txt")):
+ self.assertEqual((), monitor.extra_protected_patterns())
+ self.assertTrue(monitor.protected(proc(402, "/usr/bin/xcodebuild build")))
+
+ def test_qos_candidate_rejects_wrappers_and_installers(self) -> None:
+ self.assertFalse(monitor.qos_candidate(proc(1, '/bin/zsh -c "python -m pytest tests"')))
+ self.assertFalse(monitor.qos_candidate(proc(2, "/opt/homebrew/bin/pip install -q ruff pytest")))
+ self.assertTrue(monitor.qos_candidate(proc(3, "/opt/homebrew/bin/pytest tests")))
+ self.assertTrue(monitor.qos_candidate(proc(4, "/opt/homebrew/bin/python3 -m pytest tests")))
+ self.assertTrue(monitor.qos_candidate(proc(5, "/repo/node_modules/jest-worker/build/workers/processChild.js")))
+
+ def test_pressure_qos_actions_exclude_payload_substring_false_positives(self) -> None:
+ table = {
+ 201: proc(201, '/bin/zsh -c "python -m pytest tests"', cpu=80.0),
+ 202: proc(202, "/opt/homebrew/bin/pip install -q ruff pytest", cpu=80.0),
+ 203: proc(203, "/opt/homebrew/bin/pytest tests", cpu=80.0),
+ }
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 80.0, "sys": 10.0, "idle": 10.0}] * 3,
+ loads=[100.0, 100.0, 100.0],
+ )
+ qos_pids = [action["pid"] for action in record["actions"] if action["type"] == "qos_background"]
+ self.assertEqual([203], qos_pids)
+
+ def test_repeated_broad_scan_is_required_when_not_blocked(self) -> None:
+ hermes = proc(10, "python -m hermes_cli.main gateway")
+ broad = proc(20, f"rg --files --sortr=modified {monitor.HOME}", ppid=10, cpu=20.0, state="R")
+ table = {10: hermes, 20: broad}
+ key = f"{broad.pid}:{broad.command}"
+ first = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ )
+ self.assertEqual([], first["actions"])
+ second = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ prior_state={"rg": {key: {"consecutive": 1, "last_seen": self.recent_timestamp()}}},
+ )
+ term_actions = [a for a in second["actions"] if a["type"] == "term_runaway_rg"]
+ self.assertEqual([20], [a["pid"] for a in term_actions])
+
+ def test_stale_broad_scan_observation_does_not_count_as_consecutive(self) -> None:
+ hermes = proc(10, "python -m hermes_cli.main gateway")
+ broad = proc(20, f"rg --files --sortr=modified {monitor.HOME}", ppid=10, cpu=20.0, state="R")
+ table = {10: hermes, 20: broad}
+ key = f"{broad.pid}:{broad.command}"
+ stale_timestamp = self.recent_timestamp(monitor.RG_OBSERVATION_MAX_GAP_S + 30)
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ prior_state={"rg": {key: {"consecutive": 99, "last_seen": stale_timestamp}}},
+ )
+ self.assertEqual([], record["actions"])
+
+ def test_protected_broad_scan_is_never_a_term_candidate(self) -> None:
+ hermes = proc(10, "python -m hermes_cli.main gateway")
+ # Matches is_broad_rg (rg, RG_PREFIX, a broad root) and also matches the
+ # "Docker" protected pattern, so it must never be TERM'd even though it
+ # is otherwise an exact broad-scan, Hermes-owned candidate.
+ protected_rg = proc(
+ 20, f"rg --files --sortr=modified {monitor.HOME / 'Developer'} Docker",
+ ppid=10, cpu=20.0, state="U",
+ )
+ self.assertTrue(monitor.protected(protected_rg))
+ self.assertTrue(monitor.is_broad_rg(protected_rg))
+ table = {p.pid: p for p in (hermes, protected_rg)}
+ key = f"{protected_rg.pid}:{protected_rg.command}"
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ prior_state={"rg": {key: {"consecutive": 1, "last_seen": self.recent_timestamp()}}},
+ )
+ term_actions = [a for a in record["actions"] if a["type"] == "term_runaway_rg"]
+ self.assertEqual([], term_actions)
+
+ def test_hermes_identity_requires_exact_argv_not_wrapper_substring(self) -> None:
+ self.assertTrue(monitor.is_hermes_gateway_command("python -m hermes_cli.main gateway"))
+ self.assertTrue(monitor.is_hermes_gateway_command("/usr/bin/python3 -m hermes_cli.main gateway --flag"))
+ # A shell wrapper whose payload merely contains the marker text must not qualify.
+ self.assertFalse(monitor.is_hermes_gateway_command('/bin/zsh -c "python -m hermes_cli.main gateway"'))
+ self.assertFalse(monitor.is_hermes_gateway_command("echo hermes_cli.main gateway"))
+
+ def test_wrapper_payload_hermes_ancestor_does_not_qualify_a_foreign_rg(self) -> None:
+ wrapper = proc(10, '/bin/zsh -c "python -m hermes_cli.main gateway"')
+ foreign_rg = proc(20, f"rg --files --sortr=modified {monitor.HOME / 'Developer'}", ppid=10, cpu=20.0, state="U")
+ table = {p.pid: p for p in (wrapper, foreign_rg)}
+ key = f"{foreign_rg.pid}:{foreign_rg.command}"
+ record = self.run_main(
+ table=table,
+ cpu_samples=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3,
+ loads=[1.0, 1.0, 1.0],
+ prior_state={"rg": {key: {"consecutive": 1, "last_seen": self.recent_timestamp()}}},
+ )
+ self.assertEqual([], [a for a in record["actions"] if a["type"] == "term_runaway_rg"])
+
+ def test_qos_revalidates_process_identity_before_applying(self) -> None:
+ original = proc(500, "/opt/homebrew/bin/pytest tests", cpu=90.0)
+ reused = proc(500, "/usr/bin/legit-unrelated-daemon", cpu=1.0)
+ calls = {"n": 0}
+
+ def fake_processes() -> dict[int, monitor.Proc]:
+ calls["n"] += 1
+ return {500: original} if calls["n"] <= 3 else {500: reused}
+
+ with (
+ mock.patch.object(sys, "argv", [str(MONITOR_PATH)]),
+ mock.patch.object(monitor, "processes", side_effect=fake_processes),
+ mock.patch.object(monitor, "cpu_sample", side_effect=[{"user": 80.0, "sys": 10.0, "idle": 10.0}] * 3),
+ mock.patch.object(monitor, "load_averages", return_value=[100.0, 100.0, 100.0]),
+ mock.patch.object(monitor, "taskpolicy_background") as taskpolicy,
+ mock.patch.object(monitor, "renice_background") as renice,
+ contextlib.redirect_stdout(io.StringIO()),
+ ):
+ self.assertEqual(0, monitor.main())
+ taskpolicy.assert_not_called()
+ renice.assert_not_called()
+ record = self.telemetry[-1]
+ qos_actions = [a for a in record["actions"] if a["type"] == "qos_background"]
+ self.assertEqual(["skipped_pid_changed"], [a["result"] for a in qos_actions])
+
+ def test_dry_run_writes_nothing_to_disk(self) -> None:
+ # Exercise the real append_telemetry (not the mock from setUp) to confirm
+ # --dry-run truly performs no filesystem write, per the documented contract.
+ with tempfile.TemporaryDirectory() as tmp:
+ telemetry_path = pathlib.Path(tmp) / "pid-performance.jsonl"
+ with (
+ mock.patch.object(monitor, "TELEMETRY", telemetry_path),
+ # setUp mocks append_telemetry away; swap in the real function so
+ # this test exercises the actual disk-write guard.
+ mock.patch.object(monitor, "append_telemetry", side_effect=REAL_APPEND_TELEMETRY),
+ mock.patch.object(sys, "argv", [str(MONITOR_PATH), "--dry-run"]),
+ mock.patch.object(monitor, "processes", side_effect=lambda: {}),
+ mock.patch.object(monitor, "cpu_sample", side_effect=[{"user": 10.0, "sys": 5.0, "idle": 85.0}] * 3),
+ mock.patch.object(monitor, "load_averages", return_value=[1.0, 1.0, 1.0]),
+ contextlib.redirect_stdout(io.StringIO()),
+ ):
+ self.assertEqual(0, monitor.main())
+ self.assertFalse(telemetry_path.exists())
+
+ def test_missing_or_invalid_timestamp_does_not_count_as_consecutive(self) -> None:
+ now = datetime.now(timezone.utc)
+ self.assertFalse(monitor.prior_observation_is_recent({"consecutive": 1}, now))
+ self.assertFalse(monitor.prior_observation_is_recent({"last_seen": "not-a-time"}, now))
+ self.assertFalse(monitor.prior_observation_is_recent({"last_seen": "2000-01-01T00:00:00Z"}, now))
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/claude-ops/tests/test-pid-performance-monitor.sh b/claude-ops/tests/test-pid-performance-monitor.sh
new file mode 100755
index 00000000..dd838272
--- /dev/null
+++ b/claude-ops/tests/test-pid-performance-monitor.sh
@@ -0,0 +1,6 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+python3 -m py_compile "$ROOT/scripts/macos/pid-performance-monitor.py"
+python3 "$ROOT/tests/test-pid-performance-monitor.py"
diff --git a/claude-ops/tests/test-run-pressure-monitor-if-needed.sh b/claude-ops/tests/test-run-pressure-monitor-if-needed.sh
new file mode 100755
index 00000000..dfc62890
--- /dev/null
+++ b/claude-ops/tests/test-run-pressure-monitor-if-needed.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+RUNNER="$ROOT/scripts/macos/run-pressure-monitor-if-needed"
+tmpdir=$(mktemp -d)
+trap 'rm -rf "$tmpdir"' EXIT
+calls="$tmpdir/calls"
+monitor="$tmpdir/monitor"
+
+cat >"$monitor" <<SH
+#!/usr/bin/env bash
+printf 'called\n' >>"$calls"
+SH
+chmod +x "$monitor"
+
+assert_calls() {
+ local label="$1" expected="$2"
+ local actual=0
+ [[ -f "$calls" ]] && actual=$(wc -l <"$calls" | tr -d ' ')
+ if [[ "$actual" != "$expected" ]]; then
+ echo "FAIL: $label (expected=$expected actual=$actual)" >&2
+ exit 1
+ fi
+ echo "PASS: $label"
+}
+
+bash -n "$RUNNER"
+"$RUNNER" 37 10 18 "$monitor"
+assert_calls "one high load sample does not call the monitor" 0
+"$RUNNER" 10 37 18 "$monitor"
+assert_calls "high load5 alone does not call the monitor" 0
+"$RUNNER" 37 37 18 "$monitor"
+assert_calls "sustained high load calls the monitor once" 1
+"$RUNNER" 37 37 18 "$tmpdir/missing"
+assert_calls "missing monitor is ignored" 1