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.

feat(ops-mac): bundle maintenance helpers (follow-up to #1033) (#1039)

Aurora Capital996d61a7a20a
diff --git a/claude-ops/bin/ops-mac b/claude-ops/bin/ops-mac
index 5ab9fc8c..960ede17 100755
--- a/claude-ops/bin/ops-mac
+++ b/claude-ops/bin/ops-mac
@@ -36,6 +36,7 @@
# ops-mac defaults [args] # macfig hidden-preferences passthrough
# ops-mac update # updater app-update check
# ops-mac run <tool> [args...] # raw passthrough to any toolkit binary
+# ops-mac maintenance <helper> # bundled maintenance safety helpers
set -uo pipefail
@@ -240,6 +241,29 @@ audit() {
echo "Tip: this is read-only. Remediate with /ops:mac fix (stale daemons, cache clean)."
}
+# Maintenance helpers are bundled source, not automatically installed jobs.
+# No toolkit provisioning, launchd registration or background work here.
+maintenance() {
+ local helper="${1:-}" root
+ [[ $# -gt 0 ]] && shift || true
+ root=$(python3 -c 'import os,sys; print(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[1]))))' "$0") || return 2
+ case "$helper" in
+ agent-log-rotate)
+ # Read-only when called without arguments; rotation needs explicit flags.
+ if [[ $# = 0 ]]; then set -- --list; fi
+ python3 "$root/scripts/ops-mac/$helper" "$@" ;;
+ brain-recall-seed)
+ python3 "$root/scripts/ops-mac/$helper" "$@" ;;
+ mac-hypertune-guard|claude-reaper.sh)
+ /bin/bash "$root/scripts/ops-mac/$helper" "$@" ;;
+ install)
+ python3 "$root/scripts/ops-mac/install-helper.py" "$@" ;;
+ *)
+ echo 'ops-mac maintenance <agent-log-rotate|brain-recall-seed|mac-hypertune-guard|claude-reaper.sh|install>' >&2
+ return 2 ;;
+ esac
+}
+
# ─── dispatch ────────────────────────────────────────────────────────────────
cmd="${1:-}"; [[ $# -gt 0 ]] && shift || true
case "$cmd" in
@@ -255,6 +279,7 @@ case "$cmd" in
power) p_power ;;
defaults) p_defaults "$@" ;;
update|updates) p_update ;;
+ maintenance) maintenance "$@" ;;
run) t="${1:-}"; shift || true; require_tool "$t"; "$t" "$@" ;;
-h|--help|help)
sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//'
diff --git a/claude-ops/scripts/ops-mac/agent-log-rotate b/claude-ops/scripts/ops-mac/agent-log-rotate
new file mode 100755
index 00000000..9296fafa
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/agent-log-rotate
@@ -0,0 +1,252 @@
+#!/usr/bin/env python3
+"""agent-log-rotate — bounded copy/truncate rotation for launchd service logs.
+
+WHY COPY-TRUNCATE AND NOT RENAME
+launchd opens a job's StandardOutPath/StandardErrorPath itself and hands the
+process an fd. Renaming the file (what newsyslog and logrotate do by default)
+leaves the service writing into the *renamed* file forever while the fresh one
+stays empty at 0 bytes. So this copies the content out to a compressed archive
+and then truncates the original IN PLACE, which keeps the inode and the fd
+valid. Copy/truncate is BEST EFFORT, not lossless: the final unchanged-file
+check and the truncate are separate syscalls, and launchd-owned writers do not
+honor flock, so a line written in that window is lost. The window is kept as
+small as possible and a change detected before truncation preserves the file.
+Prefer producer-native rotation when available.
+
+NOTHING IS EVER DELETED without an explicit --prune, and even then only
+archives beyond --keep. Log retention must not be shortened during debugging, so the default keep
+count is deliberately generous and `--prune` is opt-in.
+
+Discovery is bounded: it reads launchd plists and rotates only paths those
+plists actually name. It never walks the filesystem looking for logs.
+"""
+
+from __future__ import annotations
+
+import argparse
+import fcntl
+import tempfile
+import gzip
+import os
+import plistlib
+import shutil
+import subprocess
+import sys
+import time
+
+PLIST_DIRS = [
+ os.path.expanduser("~/Library/LaunchAgents"),
+ "/Library/LaunchDaemons",
+ "/Library/LaunchAgents",
+]
+ARCHIVE_SUBDIR = "rotated"
+
+
+def human(n: float) -> str:
+ for u in ("B", "K", "M", "G"):
+ if n < 1024:
+ return f"{n:.0f}{u}"
+ n /= 1024
+ return f"{n:.0f}T"
+
+
+def load_plist(path) -> dict:
+ """Prefer plistlib; normalize Apple-valid XML without changing its file."""
+ with open(path, "rb") as fh:
+ raw = fh.read()
+ try:
+ result = plistlib.loads(raw)
+ except Exception:
+ try:
+ converted = subprocess.run(
+ ["/usr/bin/plutil", "-convert", "xml1", "-o", "-", "--", str(path)],
+ capture_output=True, check=True, timeout=5,
+ )
+ result = plistlib.loads(converted.stdout)
+ except Exception as exc:
+ raise ValueError("plistlib and plutil could not parse plist") from exc
+ if not isinstance(result, dict):
+ raise ValueError("plist root must be a dictionary")
+ return result
+
+
+def discover() -> list[tuple[str, str]]:
+ """(label, path) for every log a user-installed launchd job declares."""
+ out, seen = [], set()
+ for d in PLIST_DIRS:
+ if not os.path.isdir(d):
+ continue
+ try:
+ names = sorted(os.listdir(d))
+ except PermissionError:
+ continue
+ for n in names:
+ if not n.endswith(".plist"):
+ continue
+ path = os.path.join(d, n)
+ try:
+ pl = load_plist(path)
+ except Exception as exc:
+ print(f"agent-log-rotate: cannot parse {path}: {exc}", file=sys.stderr)
+ continue
+ # A valid plist can still carry wrongly typed fields. Skip and
+ # report the malformed entry; one bad file never aborts the scan.
+ label = pl.get("Label", n[:-6])
+ if not isinstance(label, str):
+ print(f"agent-log-rotate: skipping {path}: Label is "
+ f"{type(label).__name__}, not a string", file=sys.stderr)
+ continue
+ if label.startswith(("com.apple.", "org.")):
+ continue
+ for key in ("StandardOutPath", "StandardErrorPath"):
+ p = pl.get(key)
+ if p is None:
+ continue
+ if not isinstance(p, str):
+ print(f"agent-log-rotate: skipping {key} in {path}: "
+ f"{type(p).__name__}, not a string", file=sys.stderr)
+ continue
+ if not p or p == "/dev/null" or p in seen:
+ continue
+ seen.add(p)
+ out.append((label, p))
+ return out
+
+
+def rotate(path: str, label: str, threshold: int, keep: int,
+ dry_run: bool, prune: bool) -> tuple[bool, str]:
+ path = os.path.realpath(path)
+ try:
+ sz = os.path.getsize(path)
+ except OSError:
+ return False, "missing"
+ if sz < threshold:
+ return False, f"{human(sz)} under threshold"
+ archdir = os.path.join(os.path.dirname(path), ARCHIVE_SUBDIR)
+ base = os.path.basename(path)
+ if dry_run:
+ return True, f"would create a unique archive of {human(sz)} in {archdir} and truncate in place"
+
+ lock_fd = None
+ temporary = None
+ try:
+ # The kernel releases the lock on exit; retain its path for other writers.
+ lock_fd = os.open(path + ".rotate.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
+ try:
+ fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ return False, "rotation already in progress; live file preserved"
+ with open(path, "r+b") as src:
+ # The inode lock also serializes hardlink aliases of the same log.
+ try:
+ fcntl.flock(src.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ return False, "rotation already in progress; live file preserved"
+ before = os.fstat(src.fileno())
+ sz = before.st_size
+ if sz < threshold:
+ return False, f"{human(sz)} under threshold"
+ os.makedirs(archdir, exist_ok=True)
+ stamp = time.strftime("%Y%m%dT%H%M%S")
+ fd, temporary = tempfile.mkstemp(prefix=f"{base}.{stamp}.", suffix=".partial", dir=archdir)
+ dest = temporary[:-len(".partial")] + ".gz"
+ # Close the gzip footer and persist every archive byte before publishing.
+ with os.fdopen(fd, "wb") as archive:
+ with gzip.GzipFile(fileobj=archive, mode="wb", compresslevel=6) as compressed:
+ shutil.copyfileobj(src, compressed, length=1024 * 1024)
+ archive.flush()
+ os.fsync(archive.fileno())
+ os.chown(temporary, before.st_uid, before.st_gid)
+ # Exclusive link: even a same-second collision cannot overwrite history.
+ os.link(temporary, dest)
+ os.unlink(temporary)
+ temporary = None
+ signature = lambda st: (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns)
+ if signature(os.stat(path)) != signature(before):
+ return False, "FAILED: source changed during archival; archive retained, live file preserved"
+ # BEST EFFORT, NOT A GUARANTEE. The final check and the truncate are two
+ # syscalls, and launchd-owned writers do not honor flock, so a line
+ # written between them is lost. Keep the window minimal: the fd check
+ # is the last call before truncation. Prefer producer-native rotation.
+ if signature(os.fstat(src.fileno())) != signature(before):
+ return False, "FAILED: source changed during archival; archive retained, live file preserved"
+ src.truncate(0)
+
+ msg = (f"archived {human(sz)} -> {os.path.basename(dest)}, truncated in place "
+ "(best-effort: writes racing the final check can be lost)")
+ if prune:
+ arch = sorted((f for f in os.listdir(archdir)
+ if f.startswith(base + ".") and f.endswith(".gz")), reverse=True)
+ for old in arch[keep:]:
+ os.unlink(os.path.join(archdir, old))
+ if len(arch) > keep:
+ msg += f", pruned {len(arch) - keep} old archive(s)"
+ return True, msg
+ except (OSError, EOFError, ValueError) as exc:
+ return False, f"FAILED: {exc}; live source is not truncated before complete archival"
+ finally:
+ # A failed compress, ownership, link or publish step never leaves a
+ # .partial behind; an already published .gz is kept.
+ if temporary is not None:
+ try:
+ os.unlink(temporary)
+ except FileNotFoundError:
+ pass
+ if lock_fd is not None:
+ os.close(lock_fd)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ ap.add_argument("--threshold-mb", type=float, default=25.0,
+ help="rotate logs larger than this (default 25)")
+ ap.add_argument("--keep", type=int, default=10,
+ help="archives to keep per log when --prune is used (default 10)")
+ ap.add_argument("--prune", action="store_true",
+ help="delete archives beyond --keep. OFF by default; "
+ "preserve logs during debugging.")
+ ap.add_argument("--dry-run", action="store_true")
+ ap.add_argument("--list", action="store_true", help="show sizes and exit")
+ args = ap.parse_args()
+
+ logs = discover()
+ if args.list:
+ rows = []
+ for label, p in logs:
+ try:
+ rows.append((os.path.getsize(p), label, p))
+ except OSError:
+ pass
+ rows.sort(reverse=True)
+ total = 0
+ for sz, label, p in rows:
+ total += sz
+ print(f" {human(sz):>7} {label}")
+ print(f" {'':>7} {p}")
+ print(f"\n {len(rows)} logs, {human(total)} total")
+ return 0
+
+ threshold = int(args.threshold_mb * 1024 * 1024)
+ did = 0
+ freed = 0
+ failed = False
+ for label, p in logs:
+ try:
+ before = os.path.getsize(p)
+ except OSError:
+ continue
+ changed, msg = rotate(p, label, threshold, args.keep, args.dry_run, args.prune)
+ if changed:
+ did += 1
+ freed += before
+ print(f" {label}: {msg}")
+ elif msg.startswith("FAILED:"):
+ failed = True
+ print(f" {label}: {msg}", file=sys.stderr)
+ verb = "would rotate" if args.dry_run else "rotated"
+ print(f"\n {verb} {did} log(s), {human(freed)} reclaimed from live files")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/claude-ops/scripts/ops-mac/brain-recall-seed b/claude-ops/scripts/ops-mac/brain-recall-seed
new file mode 100755
index 00000000..ceaed928
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/brain-recall-seed
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+"""brain-recall-seed — render fresh standing context for hook-less CLIs.
+
+Codex, Gemini, opencode, aider, amp, and windsurf have no per-prompt hook
+surface, so they cannot get live mem0/gbrain injection the way Claude, Cursor,
+and Grok do. This writes a compact markdown seed they read at session start
+(referenced from ~/AGENTS.md). Can be refreshed by an operator-managed schedule. Fail-safe: on any error the previous seed file is left untouched.
+"""
+from __future__ import annotations
+
+import datetime
+import json
+import os
+import re
+import sys
+import time
+import tempfile
+import urllib.request
+from pathlib import Path
+
+# Endpoint and user scope are machine-local, never committed defaults.
+CONFIG_PATH = Path(os.getenv("OPS_MAC_RECALL_CONFIG", str(Path.home() / ".config/claude-ops/ops-mac-recall.json")))
+CONFIG = {}
+CONFIG_ERROR = False
+if CONFIG_PATH.exists():
+ try:
+ CONFIG = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
+ if not isinstance(CONFIG, dict) or any(not isinstance(v, str) for v in CONFIG.values()):
+ raise ValueError("configuration values must be strings")
+ except (ValueError, OSError):
+ CONFIG_ERROR = True
+ CONFIG = {}
+MEM0_URL = os.getenv("PERSONAL_MEM0_MCP_URL", CONFIG.get("mem0_url", ""))
+USER_ID = os.getenv("MEM0_USER_ID", CONFIG.get("user_id", ""))
+OUT = Path(os.getenv("RECALL_SEED_PATH", CONFIG.get("seed_path", str(Path.home() / ".local/share/agent-harness/state/recall-seed.md"))))
+TIMEOUT = 20.0
+
+QUERIES = [
+ "standing preferences rules corrections",
+ "current projects decisions infrastructure",
+]
+
+
+def mcp_post(url: str, body: dict, sid: str | None = None) -> tuple[str | None, str]:
+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+ if sid:
+ headers["mcp-session-id"] = sid
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers=headers, method="POST")
+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
+ return resp.headers.get("mcp-session-id") or sid, resp.read().decode(errors="replace")
+
+
+class RecallError(ValueError):
+ """Invalid protocol or explicit tool failure, not an empty search."""
+
+
+def parse_sse(raw: str, expected_id: int) -> dict:
+ candidates = [raw]
+ # SSE events may contain multiple data lines and unrelated notifications.
+ for event in raw.replace("\r\n", "\n").split("\n\n"):
+ data = [line[5:].lstrip() for line in event.splitlines() if line.startswith("data:")]
+ if data:
+ candidates.append("\n".join(data))
+ for candidate in candidates:
+ try:
+ obj = json.loads(candidate)
+ except ValueError:
+ continue
+ if not isinstance(obj, dict) or obj.get("id") != expected_id:
+ continue
+ if "error" in obj:
+ raise RecallError("JSON-RPC error")
+ if not isinstance(obj.get("result"), dict):
+ raise RecallError("missing result object")
+ return obj
+ raise RecallError("missing matching JSON-RPC response")
+
+
+def mcp_tool(url: str, tool: str, args: dict) -> str:
+ sid, initialized = mcp_post(url, {
+ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": {"protocolVersion": "2024-11-05", "capabilities": {},
+ "clientInfo": {"name": "brain-recall-seed", "version": "1.0"}}})
+ parse_sse(initialized, 1)
+ try:
+ mcp_post(url, {"jsonrpc": "2.0", "method": "notifications/initialized"}, sid=sid)
+ except Exception:
+ pass
+ _, raw = mcp_post(url, {"jsonrpc": "2.0", "id": 2, "method": "tools/call",
+ "params": {"name": tool, "arguments": args}}, sid=sid)
+ result = parse_sse(raw, 2)["result"]
+ if result.get("isError"):
+ raise RecallError("MCP tool returned isError")
+ content = result.get("content")
+ if not isinstance(content, list):
+ raise RecallError("missing content array")
+ texts = [item["text"] for item in content
+ if isinstance(item, dict) and isinstance(item.get("text"), str)]
+ if not texts:
+ raise RecallError("empty tool payload")
+ return "\n".join(texts)
+
+
+def query_with_retry(query: str) -> str:
+ for attempt in range(3):
+ try:
+ return mcp_tool(MEM0_URL, "search_memories",
+ {"query": query, "user_id": USER_ID, "limit": 8})
+ except RecallError:
+ raise
+ except (OSError, TimeoutError):
+ if attempt == 2:
+ raise
+ time.sleep(2 ** attempt)
+ raise AssertionError("unreachable")
+
+
+def extract_memories(raw: str) -> list[str]:
+ try:
+ data = json.loads(raw)
+ if isinstance(data, str):
+ data = json.loads(data)
+ except ValueError as exc:
+ raise RecallError("malformed memory payload") from exc
+ if isinstance(data, dict):
+ if "results" in data:
+ data = data["results"]
+ elif "memories" in data:
+ data = data["memories"]
+ else:
+ raise RecallError("missing memory results")
+ if not isinstance(data, list):
+ raise RecallError("memory results must be an array")
+ out = []
+ for item in data:
+ if not isinstance(item, dict):
+ raise RecallError("invalid memory item")
+ text = item.get("memory") or item.get("text") or ""
+ if not isinstance(text, str):
+ raise RecallError("invalid memory text")
+ if text:
+ out.append(text)
+ return out
+
+
+def main() -> int:
+ if CONFIG_ERROR or not MEM0_URL or not USER_ID:
+ print("brain-recall-seed: configure endpoint and user scope; previous seed preserved", file=sys.stderr)
+ return 2
+ seen: set[str] = set()
+ lines: list[str] = []
+ failed = False
+ for q in QUERIES:
+ try:
+ memories = extract_memories(query_with_retry(q))
+ except Exception as exc:
+ kind = "timeout" if isinstance(exc, TimeoutError) else "protocol/tool error" if isinstance(exc, RecallError) else "service unavailable"
+ print(f"brain-recall-seed: {kind}; previous seed preserved", file=sys.stderr)
+ failed = True
+ continue
+ for m in memories:
+ key = re.sub(r"[^a-z0-9]", "", m.lower())[:80]
+ if key in seen:
+ continue
+ seen.add(key)
+ lines.append(f"- {m[:300]}")
+ if failed:
+ return 2
+ if not lines:
+ # Keep the previous seed rather than writing an empty one.
+ print("brain-recall-seed: no results; previous seed left in place", file=sys.stderr)
+ return 1
+
+ now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
+ body = (
+ f"# Standing context seed (auto-generated {now})\n\n"
+ "Freshest personal mem0 standing rules and active-project facts for CLIs\n"
+ "without per-prompt recall hooks. For deeper recall, call the mem0 /\n"
+ "gbrain MCP tools directly. Do not edit; regenerated 6-hourly.\n\n"
+ + "\n".join(lines[:20]) + "\n"
+ )
+ tmp = None
+ try:
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=OUT.parent,
+ prefix=OUT.name + ".", delete=False) as fh:
+ tmp = Path(fh.name)
+ fh.write(body)
+ tmp.replace(OUT)
+ except OSError:
+ print("brain-recall-seed: seed write failed; previous seed preserved", file=sys.stderr)
+ return 2
+ finally:
+ if tmp is not None:
+ tmp.unlink(missing_ok=True)
+ print(f"brain-recall-seed: wrote {len(lines[:20])} items to {OUT}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/claude-ops/scripts/ops-mac/claude-reaper.sh b/claude-ops/scripts/ops-mac/claude-reaper.sh
new file mode 100755
index 00000000..c9599260
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/claude-reaper.sh
@@ -0,0 +1,170 @@
+#!/usr/bin/env bash
+# claude-reaper.sh — periodic safety net against the 2026-05-23 incident class.
+# Prevents recurrence of: (1) orphaned MCP server trees (ppid=1) from dead Claude
+# sessions piling up into a memory hog; (2) stacked duplicate singleton daemons /
+# SessionStart scripts compounding into a CPU avalanche; (3) stuck worktree scans.
+# Runs via launchd every 5 min — independent of any Claude session being open.
+# Conservative: only acts on ppid==1 orphans, true duplicates, and long-stuck scans.
+
+# ── Stacking guard ──────────────────────────────────────────────────────────
+# Prevent multiple reaper instances from running concurrently.
+if [[ -f "$HOME/.claude/scripts/lib/once.sh" ]]; then
+ # shellcheck source=lib/once.sh
+ source "$HOME/.claude/scripts/lib/once.sh"
+ claude_once "claude-reaper" 60 || exit 0 # one instance max, min 60s between runs
+fi
+
+set -uo pipefail
+SAFETY="$(cd "$(dirname "$0")" && pwd)/reaper-safety.sh"
+[ -r "$SAFETY" ] || exit 2
+source "$SAFETY"
+POLICY="${OPS_MAC_POLICY:-$HOME/.config/claude-ops/ops-mac-policy.sh}"
+[ -r "$POLICY" ] || exit 2
+SINGLETON_NAMES=()
+ORPHAN_PAT="a^"
+STATEFUL_PAT="a^"
+source "$POLICY"
+if [ -f "$HOME/.claude/.disable-reaper" ] || [ -f "$HOME/.claude/.no-auto-kill-work" ]; then
+ exit 0
+fi
+LOG="${HOME}/.claude/claude-reaper.log"
+log(){ printf '%s %s\n' "$(date '+%F %T')" "$*" >> "$LOG"; }
+
+# etime ([[dd-]hh:]mm:ss) → seconds. Robust: always returns non-negative int.
+age_secs(){
+ local pid=${1:-0}
+ local etime
+ etime=$(ps -o etime= -p "$pid" 2>/dev/null | tr -d '[:space:]')
+ [ -z "$etime" ] && { echo 0; return 0; }
+ local d=0 h=0 m=0 s=0
+ if [[ $etime == *-* ]]; then
+ d=${etime%%-*}
+ etime=${etime#*-}
+ fi
+ IFS=: read -r a b c <<<"$etime" 2>/dev/null || true
+ if [ -n "${c:-}" ]; then h=$a; m=$b; s=$c
+ elif [ -n "${b:-}" ]; then m=$a; s=$b
+ else s=${a:-0}
+ fi
+ echo $(( 10#${d:-0} * 86400 + 10#${h:-0} * 3600 + 10#${m:-0} * 60 + 10#${s:-0} ))
+}
+
+# --- (1) Reap orphaned MCP/tool server trees (ppid==1) — never the whatsapp-bridge ---
+# ORPHAN_PAT is an explicit operator allowlist from local policy.
+for pid in $(pgrep -f "$ORPHAN_PAT" 2>/dev/null); do
+ identity=$(ops_reaper_identity "$pid") || continue
+ ps -o command= -p "$pid" 2>/dev/null | grep -q 'whatsapp-bridge' && continue
+ ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
+ [ "$ppid" = "1" ] || continue # live servers have a session parent
+ [ "$(age_secs "$pid")" -gt 300 ] || continue # grace for just-spawned
+ ops_reaper_unmanaged_orphan "$pid" || continue
+ [ "$(ops_reaper_identity "$pid")" = "$identity" ] || continue
+ pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null && log "reaped orphan MCP pid=$pid"
+done
+
+# --- (2) Observe apparent duplicates; PID ordering is not ownership. ---
+# Instance/profile, wrapper-child and active-task ownership belong to the
+# dedicated process policy. Do not introduce a competing blind singleton killer.
+for name in ${SINGLETON_NAMES[@]+"${SINGLETON_NAMES[@]}"}; do
+ pids=$(pgrep -f "$name" 2>/dev/null | sort -n)
+ [ "$(printf '%s\n' "$pids" | grep -c .)" -gt 1 ] || continue
+ log "observed multiple $name processes; ownership policy required, none killed"
+done
+
+# --- (3) Observe old scans; age and command do not establish ownership. ---
+for pid in $(pgrep -f 'find [^ ]*\.worktrees|lsof -a -d cwd' 2>/dev/null); do
+ [ "$(age_secs "$pid")" -gt 300 ] && log "observed old scan pid=$pid; ownership unknown, no action"
+done
+
+# --- (4) Reap MCP children whose claude parent has died (not ppid==1, but parent gone) ---
+# STATEFUL_PAT is an explicit operator allowlist from local policy.
+for pid in $(pgrep -f "$STATEFUL_PAT" 2>/dev/null); do
+ identity=$(ops_reaper_identity "$pid") || continue
+ ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
+ [ -z "$ppid" ] && continue
+ # Any live parent owns its child, including non-Claude wrappers.
+ if [ "$ppid" = 1 ]; then
+ ops_reaper_unmanaged_orphan "$pid" || continue
+ else
+ ops_reaper_parent_absent "$ppid" || continue
+ fi
+ [ "$(age_secs "$pid")" -gt 300 ] || continue
+ # Recheck ownership after the age probe; unknown state means no action.
+ current_ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
+ [ "$current_ppid" = "$ppid" ] || continue
+ if [ "$ppid" = 1 ]; then
+ ops_reaper_unmanaged_orphan "$pid" || continue
+ else
+ ops_reaper_parent_absent "$ppid" || continue
+ fi
+ [ "$(ops_reaper_identity "$pid")" = "$identity" ] || continue
+ pkill -P "$pid" 2>/dev/null; kill "$pid" 2>/dev/null \
+ && log "reaped abandoned MCP pid=$pid (ex-parent=$ppid)"
+done
+
+# --- (5) Idle-session lifecycle: native Claude daemon owns it. ---
+# Do not query, stop, or respawn sessions here.
+
+# --- (6) bg-spare prewarm pool: native daemon owned ---
+# Culling the native daemon's --bg-spare prewarm pool fights its lifecycle: it
+# refills spares in <60s, and killing one mid-claim SIGTERMs the worker being
+# promoted into a real session → `worker crashed (exit 143) — respawning` loops in
+# `claude agents`. Let native Claude Code manage its own prewarm pool. Do NOT
+# re-add a bg-spare killer here or as a launchd job.
+
+
+# --- (7) Observe broad old rg scans; their live owner may still need them. ---
+# No process action is authorized by a command-pattern/elapsed-time match.
+pgrep -f 'rg.*--files' 2>/dev/null | while read -r pid; do
+ [ "$(age_secs "$pid")" -gt 120 ] || continue
+ cmd=$(ps -o args= -p "$pid" 2>/dev/null || true)
+ echo "$cmd" | grep -qE '(^|[[:space:]])/(home|mnt|Users|private|var|)([[:space:]]|$)|--follow[[:space:]]+/' || continue
+ log "observed broad old rg scan pid=$pid; ownership unknown, no action"
+done
+
+# --- (8) Cap runaway background-task output files ---
+# A background task output in the per-user temporary task tree grew to 98GB
+# (self-referential echo loop) and filled the disk to 100%. Sweep: any task
+# *.output >2GB with no open writer and idle >30min gets truncated in place
+# (truncate, not delete — a late writer reopening by path still works).
+# FAIL CLOSED: only lsof's explicit "nothing has it open" result (exit 1 with no
+# output and no diagnostics) permits truncation. A missing lsof, an error, a
+# diagnostic or any other status is an unknown writer state: log and keep.
+find "${REAPER_TASK_ROOT:-/private/tmp/claude-$(id -u)}" -type f -name '*.output' -size +2G -mmin +30 2>/dev/null | while read -r f; do
+ if ! command -v lsof >/dev/null 2>&1; then
+ log "kept task output (lsof unavailable; writer state unknown): $f"
+ continue
+ fi
+ lsof_out=$(lsof -- "$f" 2>&1)
+ lsof_rc=$?
+ if [ "$lsof_rc" -eq 0 ]; then
+ continue
+ fi
+ if [ "$lsof_rc" -ne 1 ] || [ -n "$lsof_out" ]; then
+ log "kept task output (lsof rc=$lsof_rc, writer state unknown): $f"
+ continue
+ fi
+ sz=$(du -m "$f" 2>/dev/null | cut -f1)
+ : > "$f" && log "truncated runaway task output ${sz}MB: $f"
+done
+
+# --- (9) Observe old authentication processes; never infer permission to stop. ---
+# PID 1 and elapsed time do not prove an unmanaged, noninteractive orphan.
+# Authentication/account lifecycle belongs to its owner, not this broad scan.
+if ! pgrep -f 'rotate\.mjs|force-rotate' >/dev/null 2>&1; then
+ ROTLOCK="$HOME/.claude/scripts/account-rotation/.rotating"
+ rot_live=0
+ if [ -f "$ROTLOCK" ]; then
+ lp=$(tail -1 "$ROTLOCK" 2>/dev/null | tr -d '[:space:]')
+ [ -n "$lp" ] && kill -0 "$lp" 2>/dev/null && rot_live=1
+ fi
+ if [ "$rot_live" = 0 ]; then
+ for pid in $(pgrep -f 'auth login --email' 2>/dev/null); do
+ [ "$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')" = "1" ] || continue
+ [ "$(age_secs "$pid")" -gt 900 ] || continue
+ rss=$(ps -o rss= -p "$pid" 2>/dev/null | tr -d ' ')
+ log "observed old auth-login pid=$pid rss=${rss}KB; ownership unknown, no action"
+ done
+ fi
+fi
+exit 0
diff --git a/claude-ops/scripts/ops-mac/install-helper.py b/claude-ops/scripts/ops-mac/install-helper.py
new file mode 100644
index 00000000..97bae60f
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/install-helper.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""Install one verified helper without starting jobs or changing local policy.
+
+Requires an expected hash of the current destination. Prints its backup path.
+Reaper installation also requires its adjacent safety library to be installed
+first. Rollback uses the recorded backup; no service is restarted here.
+
+Concurrency: every install holds an exclusive cooperative lock (flock on the
+sidecar file "<target>.install.lock") from the first digest through the final
+recheck and replace, so two installers can never interleave. The lock is
+advisory: a writer that does not take it (an editor, another tool) can still
+change the destination between the final recheck and os.replace. That window
+is two syscalls wide, but it is not closed; POSIX offers no portable
+compare-and-swap for file contents. The sidecar lock file is kept.
+"""
+import argparse
+import contextlib
+import datetime
+import fcntl
+import hashlib
+import os
+from pathlib import Path
+import shutil
+import stat
+import tempfile
+
+HELPERS = {"agent-log-rotate", "brain-recall-seed", "mac-hypertune-guard",
+ "claude-reaper.sh", "reaper-safety.sh"}
+
+
+def digest(path):
+ return hashlib.sha256(Path(path).read_bytes()).hexdigest()
+
+
+def target_lock(target):
+ """Exclusive cooperative lock on the target; refuse rather than wait."""
+ fd = os.open(str(target) + ".install.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
+ try:
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except BlockingIOError:
+ raise ValueError("another install holds the target lock; refusing install") from None
+ yield
+ finally:
+ # Closing the descriptor releases the lock.
+ os.close(fd)
+
+
+def install(source, target, expected):
+ source, target = Path(source), Path(target)
+ with target_lock(target):
+ return _install_locked(source, target, expected)
+
+
+def _install_locked(source, target, expected):
+ if expected == "absent":
+ if target.exists() or target.is_symlink():
+ raise ValueError("destination already exists")
+ temporary = None
+ try:
+ with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + ".install.", delete=False) as fh:
+ temporary = Path(fh.name)
+ fh.write(source.read_bytes())
+ temporary.chmod(stat.S_IMODE(source.stat().st_mode))
+ # Link a fully written file exclusively; never leave a partial target.
+ os.link(temporary, target)
+ finally:
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+ return None
+ if target.is_symlink() or not target.is_file():
+ raise ValueError("destination must be an existing plain file")
+ if digest(target) != expected:
+ raise ValueError("current destination bytes differ; refusing install")
+ original_stat = target.stat()
+ original_mode = stat.S_IMODE(original_stat.st_mode)
+ stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%S.%fZ")
+ backup = Path(str(target) + ".bak." + stamp)
+ shutil.copy2(target, backup)
+ os.chown(backup, original_stat.st_uid, original_stat.st_gid)
+ if digest(backup) != expected or digest(target) != expected:
+ raise ValueError("destination changed during backup; refusing install")
+ temporary = None
+ try:
+ with tempfile.NamedTemporaryFile(dir=target.parent, prefix=target.name + ".install.", delete=False) as fh:
+ temporary = Path(fh.name)
+ fh.write(source.read_bytes())
+ os.chown(temporary, original_stat.st_uid, original_stat.st_gid)
+ temporary.chmod(original_mode)
+ staged_stat = temporary.stat()
+ if (staged_stat.st_uid, staged_stat.st_gid) != (original_stat.st_uid, original_stat.st_gid):
+ raise ValueError("could not preserve destination ownership")
+ source_hash = digest(source)
+ # Final recheck and replace run inside the target lock (see module docstring).
+ if digest(temporary) != source_hash or digest(target) != expected:
+ raise ValueError("bytes changed before install")
+ os.replace(temporary, target)
+ if digest(target) != source_hash:
+ # Only restore our own failed replacement, never overwrite a peer.
+ raise RuntimeError("installed bytes differ; backup retained for controlled rollback")
+ finally:
+ if temporary is not None:
+ temporary.unlink(missing_ok=True)
+ return backup
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("helper", choices=sorted(HELPERS))
+ parser.add_argument("--target", type=Path, required=True)
+ parser.add_argument("--expected-sha256", required=True)
+ parser.add_argument("--apply", action="store_true")
+ parser.add_argument("--rollback-from", type=Path)
+ args = parser.parse_args()
+ source = args.rollback_from or Path(__file__).resolve().parent / args.helper
+ if not source.is_file() or source.is_symlink():
+ parser.error("source must be a plain file")
+ if not args.apply:
+ if args.expected_sha256 == "absent":
+ if args.target.exists() or args.target.is_symlink():
+ parser.error("destination already exists")
+ elif not args.target.is_file() or args.target.is_symlink():
+ parser.error("destination must be an existing plain file")
+ elif digest(args.target) != args.expected_sha256:
+ parser.error("destination bytes changed")
+ print("verified; dry-run only, no files installed")
+ return 0
+ if args.helper == "claude-reaper.sh" and not args.rollback_from:
+ safety = args.target.parent / "reaper-safety.sh"
+ canonical = Path(__file__).resolve().parent / "reaper-safety.sh"
+ if not safety.is_file() or digest(safety) != digest(canonical):
+ parser.error("install verified adjacent reaper-safety.sh first")
+ backup = install(source, args.target, args.expected_sha256)
+ print(backup if backup is not None else "created previously absent destination; no prior version")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/claude-ops/scripts/ops-mac/mac-hypertune-guard b/claude-ops/scripts/ops-mac/mac-hypertune-guard
new file mode 100755
index 00000000..409a5ea6
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/mac-hypertune-guard
@@ -0,0 +1,131 @@
+#!/usr/bin/env bash
+# Login once: enforce SSOT agents; remove recreations that hurt cold boot.
+set -euo pipefail
+export PATH="/opt/homebrew/bin:$HOME/.local/bin:/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
+LOG_DIR="${HOME}/.local/share/agent-logs"
+mkdir -p "$LOG_DIR" "${HOME}/.config/hypertune/disabled-launchagents"
+LOG="${LOG_DIR}/hypertune-guard.log"
+ts() { date -u +%Y-%m-%dT%H:%M:%SZ; }
+log() { echo "$(ts) $*" >>"$LOG"; }
+UID_NUM="$(id -u)"
+GUI="gui/${UID_NUM}"
+ARCH="${HOME}/.config/hypertune/disabled-launchagents"
+LA="${HOME}/Library/LaunchAgents"
+
+# Only operator-owned local policy may name machine-specific jobs.
+POLICY="${OPS_MAC_POLICY:-$HOME/.config/claude-ops/ops-mac-policy.sh}"
+[ -r "$POLICY" ] || { echo "mac-hypertune-guard: local policy required" >&2; exit 2; }
+NEVER_AUTO=()
+KEEP_LABEL=""
+MESH_LABEL=""
+source "$POLICY"
+
+failed=0
+for bad in ${NEVER_AUTO[@]+"${NEVER_AUTO[@]}"}; do
+ # FAIL CLOSED: a loaded job must be booted out, disabled and verified absent
+ # before its plist is archived. Otherwise keep the plist for a clean retry.
+ unloaded=1
+ if launchctl print "${GUI}/${bad}" >/dev/null 2>&1; then
+ launchctl bootout "${GUI}/${bad}" 2>/dev/null || unloaded=0
+ launchctl disable "${GUI}/${bad}" 2>/dev/null || unloaded=0
+ if launchctl print "${GUI}/${bad}" >/dev/null 2>&1; then unloaded=0; fi
+ if [ "$unloaded" = 1 ]; then
+ log "booted out $bad (verified)"
+ else
+ log "ERROR $bad NOT booted out or disabled; plist preserved"
+ printf 'mac-hypertune-guard: bootout of %s unverified; plist preserved\n' "$bad" >&2
+ failed=1
+ fi
+ fi
+ f="${LA}/${bad}.plist"
+ if [ "$unloaded" = 1 ] && [ -f "$f" ]; then
+ if mv "$f" "${ARCH}/${bad}.plist.$(date -u +%Y%m%dT%H%M%SZ)"; then
+ log "archived ${bad}.plist (forbidden auto agent)"
+ else
+ log "ERROR archive failed for $bad; original preserved"
+ printf 'mac-hypertune-guard: archive failed; original preserved\n' >&2
+ failed=1
+ fi
+ fi
+done
+
+# Mesh: keep but enforce deferred policy (no RunAtLoad, interval >= 600)
+MESH="${LA}/${MESH_LABEL}.plist"
+if [ -f "$MESH" ]; then
+ run=$(/usr/libexec/PlistBuddy -c 'Print :RunAtLoad' "$MESH" 2>/dev/null || echo missing)
+ iv=$(/usr/libexec/PlistBuddy -c 'Print :StartInterval' "$MESH" 2>/dev/null || echo missing)
+ # FAIL CLOSED: only an explicit RunAtLoad=false and an integer interval of at
+ # least 600 are compliant. Missing, malformed or other values get repaired.
+ need=1
+ if [ "$run" = "false" ] && [[ "$iv" =~ ^[0-9]+$ ]] && [ "$iv" -ge 600 ]; then need=0; fi
+ if [ "$need" -eq 1 ]; then
+ # Every mutation is checked and the result read back. Only a verified
+ # result is logged as enforced; anything else marks the run failed.
+ mesh_ok=1
+ # Bootout of an unloaded job is not a failure; a loaded job must be gone after it.
+ launchctl bootout "${GUI}/${MESH_LABEL}" 2>/dev/null || true
+ if launchctl print "${GUI}/${MESH_LABEL}" >/dev/null 2>&1; then mesh_ok=0; fi
+ if [ "$mesh_ok" = 1 ]; then
+ # Delete then Add rewrites a malformed or wrongly typed value with the
+ # correct type; Delete of an absent key is not an error worth stopping on.
+ /usr/libexec/PlistBuddy -c 'Delete :RunAtLoad' "$MESH" >/dev/null 2>&1 || true
+ /usr/libexec/PlistBuddy -c 'Add :RunAtLoad bool false' "$MESH" 2>/dev/null || mesh_ok=0
+ if ! [[ "$iv" =~ ^[0-9]+$ ]] || [ "$iv" -lt 600 ]; then
+ /usr/libexec/PlistBuddy -c 'Delete :StartInterval' "$MESH" >/dev/null 2>&1 || true
+ /usr/libexec/PlistBuddy -c 'Add :StartInterval integer 600' "$MESH" 2>/dev/null || mesh_ok=0
+ fi
+ run=$(/usr/libexec/PlistBuddy -c 'Print :RunAtLoad' "$MESH" 2>/dev/null || echo unknown)
+ iv=$(/usr/libexec/PlistBuddy -c 'Print :StartInterval' "$MESH" 2>/dev/null || echo missing)
+ [ "$run" = "false" ] || mesh_ok=0
+ { [[ "$iv" =~ ^[0-9]+$ ]] && [ "$iv" -ge 600 ]; } || mesh_ok=0
+ fi
+ if [ "$mesh_ok" = 1 ]; then
+ launchctl bootstrap "$GUI" "$MESH" 2>/dev/null || mesh_ok=0
+ launchctl print "${GUI}/${MESH_LABEL}" >/dev/null 2>&1 || mesh_ok=0
+ fi
+ if [ "$mesh_ok" = 1 ]; then
+ log "mesh policy enforced RunAtLoad=false StartInterval=$iv (verified)"
+ else
+ log "ERROR mesh policy NOT enforced; plist or launchd result unverified"
+ printf 'mac-hypertune-guard: mesh policy not enforced\n' >&2
+ failed=1
+ fi
+ fi
+fi
+
+# Keepawake SSOT only
+KEEP="${LA}/${KEEP_LABEL}.plist"
+if [ -f "$KEEP" ]; then
+ if ! launchctl print "${GUI}/${KEEP_LABEL}" >/dev/null 2>&1; then
+ if launchctl bootstrap "$GUI" "$KEEP" 2>/dev/null &&
+ launchctl print "${GUI}/${KEEP_LABEL}" >/dev/null 2>&1; then
+ log "bootstrapped keepawake SSOT (verified)"
+ else
+ log "ERROR keepawake SSOT bootstrap unverified"
+ failed=1
+ fi
+ fi
+fi
+# Extra caffeinate processes can belong to active agents/evals. Count is not
+# ownership or a health check: never stop them or restart our healthy job.
+if matches=$(pgrep -x caffeinate 2>/dev/null); then
+ n=$(printf '%s\n' "$matches" | wc -l | tr -d ' ')
+ if [ "$n" -gt 1 ]; then
+ log "INFO multiple caffeinate ($n); unrelated sleep protection preserved"
+ fi
+else
+ rc=$?
+ if [ "$rc" -ne 1 ]; then
+ log "ERROR pgrep failed rc=$rc"
+ failed=1
+ fi
+fi
+
+wired="$(sysctl -n iogpu.wired_limit_mb 2>/dev/null || echo missing)"
+mem="$(orbctl config get memory_mib 2>/dev/null || echo n/a)"
+if [ "$failed" = 0 ]; then
+ log "guard ok wired=$wired orb_mem=$mem keepawake=owned mesh=deferred"
+else
+ log "guard failed wired=$wired orb_mem=$mem; see earlier errors"
+fi
+exit "$failed"
diff --git a/claude-ops/scripts/ops-mac/reaper-safety.sh b/claude-ops/scripts/ops-mac/reaper-safety.sh
new file mode 100644
index 00000000..21430244
--- /dev/null
+++ b/claude-ops/scripts/ops-mac/reaper-safety.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+# Ownership checks only. Sourcing this file performs no process actions.
+# Return success only when absence of a live/managed parent is established.
+ops_reaper_identity() {
+ local pid="$1" identity tty
+ tty=$(ps -p "$pid" -o tty= 2>/dev/null | tr -d '[:space:]') || return 1
+ case "$tty" in '?'|'??'|'-') ;; *) return 1 ;; esac
+ identity=$(ps -p "$pid" -o lstart= -o comm= 2>/dev/null) || return 1
+ [ -n "$identity" ] || return 1
+ printf '%s\n' "$identity"
+}
+
+ops_reaper_parent_absent() {
+ local ppid="$1" status
+ case "$ppid" in ''|*[!0-9]*|0) return 1 ;; esac
+ if ps -p "$ppid" -o pid= >/dev/null 2>&1; then
+ return 1
+ else
+ status=$?
+ # ps status 1 is no selected process; other errors are unknown ownership.
+ [ "$status" = 1 ] || return 1
+ fi
+ return 0
+}
+
+ops_reaper_unmanaged_orphan() {
+ local pid="$1" user_jobs system_jobs user_domain gui_domain ppid uid
+ case "$pid" in ''|*[!0-9]*|0|1) return 1 ;; esac
+ ppid=$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d '[:space:]') || return 1
+ [ "$ppid" = 1 ] || return 1
+ # Missing launchd inventory means do not act. PID 1 alone proves nothing.
+ user_jobs=$(launchctl list 2>/dev/null) || return 1
+ system_jobs=$(launchctl print system 2>/dev/null) || return 1
+ uid=$(id -u) || return 1
+ user_domain=$(launchctl print "user/$uid" 2>/dev/null) || return 1
+ gui_domain=$(launchctl print "gui/$uid" 2>/dev/null) || return 1
+ if printf '%s\n' "$user_jobs" | awk -v pid="$pid" '$1 == pid {found=1} END {exit !found}'; then
+ return 1
+ fi
+ if printf '%s\n' "$system_jobs" "$user_domain" "$gui_domain" | awk -v pid="$pid" '$1 == pid || ($1 == "pid" && $2 == "=" && $3 == pid) {found=1} END {exit !found}'; then
+ return 1
+ fi
+ # Recheck parent immediately before the caller's action.
+ ppid=$(ps -p "$pid" -o ppid= 2>/dev/null | tr -d '[:space:]') || return 1
+ [ "$ppid" = 1 ]
+}
diff --git a/claude-ops/skills/ops-mac/SKILL.md b/claude-ops/skills/ops-mac/SKILL.md
index ba47eda4..b205ccd0 100644
--- a/claude-ops/skills/ops-mac/SKILL.md
+++ b/claude-ops/skills/ops-mac/SKILL.md
@@ -138,6 +138,18 @@ ${CLAUDE_PLUGIN_ROOT}/bin/ops-mac update # updater check — then confirm bef
After any fix, re-run the relevant probe and show before→after.
+## Maintenance safety helpers
+
+`ops-mac maintenance <helper>` exposes bundled source helpers. Without arguments,
+`agent-log-rotate` lists logs only. Its copy/truncate rotation is best-effort, not
+lossless: launchd writers ignore locks, so a line written between the final check
+and the truncate can be lost; prefer producer-native rotation where available. Machine labels, endpoints, user scope and process
+allowlists stay in untracked files under `~/.config/claude-ops/`. Installing a
+helper never registers, starts, restarts or kills a job. Use
+`ops-mac maintenance install <helper> --target <path> --expected-sha256 <current>`
+first as a dry-run, then add `--apply` only after a backup and peer check. Use
+`--expected-sha256 absent` only for a new target; prior versions get timestamped backups.
+
## Mobile mode (Rule 7)
If `$SSH_CONNECTION`/`$SSH_CLIENT`/`$SSH_TTY` is set, `$OPS_MOBILE=1`, or `$COLUMNS` < 80: drop the boxes/tables, emit 3–8 plain lines, one fact each. Example:
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index ae7a46ac..a83bc883 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -41,6 +41,7 @@ run_suite "$TESTS_DIR/test-ops-credentials.sh"
run_suite "$TESTS_DIR/test-gog-account.sh"
run_suite "$TESTS_DIR/test-ops-ci.sh"
run_suite "$TESTS_DIR/test-ops-speedup.sh"
+run_suite "$TESTS_DIR/test-ops-mac-maintenance.sh"
run_suite "$TESTS_DIR/test-ops-update-stale-clone.sh"
run_suite "$TESTS_DIR/test-ops-update-downgrade-guard.sh"
run_suite "$TESTS_DIR/test-skill-update-gate.sh"
diff --git a/claude-ops/tests/test-ops-mac-maintenance.sh b/claude-ops/tests/test-ops-mac-maintenance.sh
new file mode 100644
index 00000000..145901a4
--- /dev/null
+++ b/claude-ops/tests/test-ops-mac-maintenance.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# Mocked or isolated tests only; does not register or execute live jobs.
+set -euo pipefail
+TESTS_DIR="$(cd "$(dirname "$0")" && pwd)"
+python3 "$TESTS_DIR/test_ops_mac_log_rotate.py"
+python3 "$TESTS_DIR/test_ops_mac_recall_seed.py"
+python3 "$TESTS_DIR/test_ops_mac_hypertune.py"
+python3 "$TESTS_DIR/test_ops_mac_reaper.py"
+python3 "$TESTS_DIR/test_ops_mac_installer.py"
diff --git a/claude-ops/tests/test_ops_mac_hypertune.py b/claude-ops/tests/test_ops_mac_hypertune.py
new file mode 100644
index 00000000..a6ee8e4e
--- /dev/null
+++ b/claude-ops/tests/test_ops_mac_hypertune.py
@@ -0,0 +1,202 @@
+"""Mock every service/process command; never affect live launchd."""
+import os
+import pathlib
+import subprocess
+import tempfile
+import unittest
+
+SCRIPT = pathlib.Path(os.getenv('OPS_MAC_GUARD_SOURCE', str(pathlib.Path(__file__).resolve().parents[1] / 'scripts/ops-mac/mac-hypertune-guard')))
+
+
+class GuardTests(unittest.TestCase):
+ def run_guard(self, failure=False, matches='', empty_policy=False):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ root = pathlib.Path(tmp.name)
+ (root / 'Library/LaunchAgents').mkdir(parents=True)
+ (root / 'Library/LaunchAgents/com.example.forbidden.plist').write_text('fixture')
+ policy = root / 'policy.sh'
+ policy.write_text('NEVER_AUTO=()\nKEEP_LABEL=\nMESH_LABEL=\n' if empty_policy else 'NEVER_AUTO=(com.example.forbidden)\nKEEP_LABEL=com.example.keepawake\nMESH_LABEL=\n')
+ mocks = root / 'mocks.sh'
+ mocks.write_text('''launchctl() { printf '%s\\n' "$*" >>"$HOME/actions"; return 1; }
+mv() { if [ "$FAIL_MOVE" = 1 ]; then return 1; fi; /bin/mv "$@"; }
+rm() { echo rm >>"$HOME/actions"; return 99; }
+pgrep() { if [ -n "$MATCHES" ]; then printf '%s\\n' "$MATCHES"; else return 1; fi; }
+killall() { echo killall >>"$HOME/actions"; return 99; }
+sysctl() { echo 0; }
+orbctl() { echo 0; }
+''')
+ env = dict(os.environ, HOME=str(root), OPS_MAC_POLICY=str(policy), BASH_ENV=str(mocks), FAIL_MOVE=str(int(failure)), MATCHES=matches)
+ result = subprocess.run(['/bin/bash', str(SCRIPT)], env=env, capture_output=True)
+ actions = (root / 'actions').read_text() if (root / 'actions').exists() else ''
+ return result, root, actions
+
+ def test_failed_archive_preserves_file_and_never_deletes(self):
+ result, root, actions = self.run_guard(True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertTrue((root / 'Library/LaunchAgents/com.example.forbidden.plist').exists())
+ self.assertNotIn('rm\n', actions)
+
+ def test_empty_policy_is_bash32_safe(self):
+ result, root, _ = self.run_guard(empty_policy=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue((root / 'Library/LaunchAgents/com.example.forbidden.plist').exists())
+
+ def test_zero_matches_is_normal(self):
+ result, _, _ = self.run_guard()
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_multiple_unowned_sleep_protectors_never_killed(self):
+ result, _, actions = self.run_guard(matches='100\n200')
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotIn('killall', actions)
+ self.assertNotIn('kickstart', actions)
+
+
+class LoadedForbiddenJobTests(unittest.TestCase):
+ """A loaded forbidden job: launchctl is a state-file mock, never the real one."""
+
+ def run_loaded(self, bootout_rc=0, bootout_unloads=True, disable_rc=0):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ root = pathlib.Path(tmp.name)
+ la = root / 'Library/LaunchAgents'
+ la.mkdir(parents=True)
+ (la / 'com.example.forbidden.plist').write_text('fixture')
+ (root / 'loaded').touch()
+ policy = root / 'policy.sh'
+ policy.write_text('NEVER_AUTO=(com.example.forbidden)\nKEEP_LABEL=\nMESH_LABEL=\n')
+ mocks = root / 'mocks.sh'
+ mocks.write_text('''launchctl() {
+ printf '%s\\n' "$*" >>"$HOME/actions"
+ case "$1" in
+ print) [ -e "$HOME/loaded" ] ;;
+ list) [ -e "$HOME/loaded" ] ;;
+ bootout) [ "$BOOTOUT_UNLOADS" = 1 ] && /bin/rm -f "$HOME/loaded"; return "$BOOTOUT_RC" ;;
+ disable) return "$DISABLE_RC" ;;
+ *) return 0 ;;
+ esac
+}
+rm() { echo rm >>"$HOME/actions"; return 99; }
+pgrep() { return 1; }
+sysctl() { echo 0; }
+orbctl() { echo 0; }
+''')
+ env = dict(os.environ, HOME=str(root), OPS_MAC_POLICY=str(policy), BASH_ENV=str(mocks),
+ BOOTOUT_RC=str(bootout_rc), BOOTOUT_UNLOADS=str(int(bootout_unloads)),
+ DISABLE_RC=str(disable_rc))
+ result = subprocess.run(['/bin/bash', str(SCRIPT)], env=env, capture_output=True)
+ log = (root / '.local/share/agent-logs/hypertune-guard.log').read_text()
+ plist = la / 'com.example.forbidden.plist'
+ return result, log, plist
+
+ def test_verified_bootout_archives_and_succeeds(self):
+ result, log, plist = self.run_loaded()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertFalse(plist.exists())
+ self.assertIn('booted out com.example.forbidden (verified)', log)
+ self.assertIn('archived com.example.forbidden.plist', log)
+
+ def test_failed_bootout_keeps_plist_and_fails(self):
+ result, log, plist = self.run_loaded(bootout_rc=5, bootout_unloads=False)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertTrue(plist.exists(), 'plist must be kept for a clean retry')
+ self.assertNotIn('booted out com.example.forbidden', log.replace('NOT booted out', ''))
+ self.assertNotIn('archived com.example.forbidden.plist', log)
+ self.assertIn('guard failed', log)
+
+ def test_bootout_success_but_still_loaded_fails_closed(self):
+ result, log, plist = self.run_loaded(bootout_rc=0, bootout_unloads=False)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertTrue(plist.exists())
+ self.assertNotIn('archived com.example.forbidden.plist', log)
+
+ def test_failed_disable_keeps_plist_and_fails(self):
+ result, log, plist = self.run_loaded(disable_rc=5)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertTrue(plist.exists())
+ self.assertNotIn('archived com.example.forbidden.plist', log)
+
+
[email protected](os.path.exists('/usr/libexec/PlistBuddy'), 'SKIP: mesh enforcement needs macOS PlistBuddy')
+class MeshEnforcementTests(unittest.TestCase):
+ """Real PlistBuddy on a temporary plist; launchctl is a state-file mock."""
+
+ def run_mesh(self, bootstrap_ok=True, loads_after=True,
+ plist_commands=('Add :RunAtLoad bool true', 'Add :StartInterval integer 60')):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ root = pathlib.Path(tmp.name)
+ la = root / 'Library/LaunchAgents'
+ la.mkdir(parents=True)
+ mesh = la / 'com.example.mesh.plist'
+ command = ['/usr/libexec/PlistBuddy', '-c', 'Add :Label string com.example.mesh']
+ for entry in plist_commands:
+ command += ['-c', entry]
+ subprocess.run(command + [str(mesh)], check=True, capture_output=True)
+ (root / 'loaded').touch()
+ policy = root / 'policy.sh'
+ policy.write_text('NEVER_AUTO=()\nKEEP_LABEL=\nMESH_LABEL=com.example.mesh\n')
+ mocks = root / 'mocks.sh'
+ mocks.write_text('''launchctl() {
+ printf '%s\\n' "$*" >>"$HOME/actions"
+ case "$1" in
+ print) [ -e "$HOME/loaded" ] ;;
+ bootout) rm -f "$HOME/loaded" ;;
+ bootstrap) [ "$BOOTSTRAP_OK" = 1 ] || return 5; [ "$LOADS_AFTER" = 1 ] && touch "$HOME/loaded"; return 0 ;;
+ *) return 0 ;;
+ esac
+}
+pgrep() { return 1; }
+sysctl() { echo 0; }
+orbctl() { echo 0; }
+''')
+ env = dict(os.environ, HOME=str(root), OPS_MAC_POLICY=str(policy), BASH_ENV=str(mocks),
+ BOOTSTRAP_OK=str(int(bootstrap_ok)), LOADS_AFTER=str(int(loads_after)))
+ result = subprocess.run(['/bin/bash', str(SCRIPT)], env=env, capture_output=True)
+ log = (root / '.local/share/agent-logs/hypertune-guard.log').read_text()
+ values = [subprocess.run(['/usr/libexec/PlistBuddy', '-c', 'Print :' + key, str(mesh)],
+ capture_output=True, text=True).stdout.strip()
+ for key in ('RunAtLoad', 'StartInterval')]
+ return result, log, values
+
+ def test_verified_mesh_enforcement_succeeds(self):
+ result, log, values = self.run_mesh()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('mesh policy enforced', log)
+ self.assertEqual(values, ['false', '600'])
+
+ def test_malformed_or_missing_values_are_repaired_not_trusted(self):
+ cases = {
+ 'malformed both': ('Add :RunAtLoad string unexpected', 'Add :StartInterval string unexpected'),
+ 'missing both': (),
+ 'missing interval': ('Add :RunAtLoad bool false',),
+ 'malformed interval': ('Add :RunAtLoad bool false', 'Add :StartInterval string soon'),
+ }
+ for name, commands in cases.items():
+ with self.subTest(case=name):
+ result, log, values = self.run_mesh(plist_commands=commands)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn('mesh policy enforced', log)
+ self.assertEqual(values, ['false', '600'])
+
+ def test_compliant_values_are_left_alone(self):
+ result, log, values = self.run_mesh(plist_commands=('Add :RunAtLoad bool false', 'Add :StartInterval integer 900'))
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertNotIn('mesh policy enforced', log)
+ self.assertEqual(values, ['false', '900'])
+
+ def test_failed_bootstrap_is_not_logged_as_enforced(self):
+ result, log, _ = self.run_mesh(bootstrap_ok=False)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('mesh policy enforced', log)
+ self.assertIn('NOT enforced', log)
+
+ def test_unverified_load_is_not_logged_as_enforced(self):
+ result, log, _ = self.run_mesh(loads_after=False)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertNotIn('mesh policy enforced', log)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/claude-ops/tests/test_ops_mac_installer.py b/claude-ops/tests/test_ops_mac_installer.py
new file mode 100644
index 00000000..7e78c584
--- /dev/null
+++ b/claude-ops/tests/test_ops_mac_installer.py
@@ -0,0 +1,185 @@
+"""Only temporary file fixtures; installer never executes helper payloads."""
+import importlib.util
+import os
+import pathlib
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+PATH = pathlib.Path(__file__).resolve().parents[1] / 'scripts/ops-mac/install-helper.py'
+spec = importlib.util.spec_from_file_location('installer', PATH)
+installer = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(installer)
+
+
+class InstallerTests(unittest.TestCase):
+ def test_backup_install_and_rollback_preserve_mode(self):
+ with tempfile.TemporaryDirectory() as d:
+ root = pathlib.Path(d)
+ source, target = root / 'source', root / 'target'
+ source.write_bytes(b'new\n')
+ target.write_bytes(b'old "caf\xc3\xa9"\n')
+ target.chmod(0o751)
+ old = target.read_bytes()
+ backup = installer.install(source, target, installer.digest(target))
+ self.assertEqual(backup.read_bytes(), old)
+ self.assertEqual(target.read_bytes(), b'new\n')
+ self.assertEqual(target.stat().st_mode & 0o777, 0o751)
+ installer.install(backup, target, installer.digest(target))
+ self.assertEqual(target.read_bytes(), old)
+
+ def test_preserves_owner_and_refuses_chown_failure(self):
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'new')
+ target.write_bytes(b'old')
+ original = target.stat()
+ with mock.patch.object(installer.os, 'chown', wraps=installer.os.chown) as chown:
+ installer.install(source, target, installer.digest(target))
+ self.assertEqual(chown.call_count, 2)
+ for call in chown.call_args_list:
+ self.assertEqual(call.args[1:], (original.st_uid, original.st_gid))
+ self.assertEqual((target.stat().st_uid, target.stat().st_gid), (original.st_uid, original.st_gid))
+ with mock.patch.object(installer.os, 'chown', side_effect=PermissionError('fixture refusal')):
+ with self.assertRaises(PermissionError):
+ installer.install(source, target, installer.digest(target))
+ self.assertEqual(target.read_bytes(), b'new')
+
+ def test_changed_bytes_refused(self):
+ with tempfile.TemporaryDirectory() as d:
+ target = pathlib.Path(d) / 'target'
+ target.write_bytes(b'old')
+ with self.assertRaises(ValueError):
+ installer.install(target, target, 'wrong')
+ self.assertEqual(target.read_bytes(), b'old')
+
+ def test_new_library_exclusive_creation(self):
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'library')
+ self.assertIsNone(installer.install(source, target, 'absent'))
+ self.assertEqual(target.read_bytes(), b'library')
+ with self.assertRaises(ValueError):
+ installer.install(source, target, 'absent')
+
+ def test_router_refuses_non_macos_before_any_install(self):
+ # Runs on every platform: a uname fixture reports Linux, and the product
+ # gate must refuse before touching the target.
+ with tempfile.TemporaryDirectory() as d:
+ root = pathlib.Path(d)
+ (root / 'uname').write_text('#!/bin/sh\necho Linux\n')
+ (root / 'uname').chmod(0o755)
+ target = root / 'fixture'
+ target.write_bytes(b'original')
+ command = PATH.parents[2] / 'bin/ops-mac'
+ env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'])
+ result = subprocess.run(['/bin/bash', str(command), 'maintenance', 'install', 'agent-log-rotate', '--target', str(target), '--expected-sha256', installer.digest(target)], capture_output=True, env=env)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(b'macOS only', result.stderr)
+ self.assertEqual(target.read_bytes(), b'original')
+
+ @unittest.skipUnless(sys.platform == 'darwin',
+ 'SKIP: ops-mac router is macOS-only; installer itself is covered above')
+ def test_router_installer_is_dry_run_without_toolkit(self):
+ with tempfile.TemporaryDirectory() as d:
+ target = pathlib.Path(d) / 'fixture'
+ target.write_bytes(b'original')
+ command = PATH.parents[2] / 'bin/ops-mac'
+ result = subprocess.run(['/bin/bash', str(command), 'maintenance', 'install', 'agent-log-rotate', '--target', str(target), '--expected-sha256', installer.digest(target)], capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(result.stdout, b'verified; dry-run only, no files installed\n')
+ self.assertEqual(target.read_bytes(), b'original')
+
+ def test_cooperative_lock_held_across_final_check_and_replace(self):
+ # A cooperating peer that tries to take the target lock while the
+ # installer is replacing must be refused: check and replace are one
+ # critical section, so the peer cannot slip new bytes in between.
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'new')
+ target.write_bytes(b'old')
+ lock_path = pathlib.Path(str(target) + '.install.lock')
+ observed = []
+ real_replace = installer.os.replace
+
+ def peer_then_replace(src, dst):
+ fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ installer.fcntl.flock(fd, installer.fcntl.LOCK_EX | installer.fcntl.LOCK_NB)
+ observed.append('peer acquired lock')
+ installer.fcntl.flock(fd, installer.fcntl.LOCK_UN)
+ except BlockingIOError:
+ observed.append('peer blocked')
+ finally:
+ os.close(fd)
+ return real_replace(src, dst)
+
+ with mock.patch.object(installer.os, 'replace', side_effect=peer_then_replace):
+ installer.install(source, target, installer.digest(target))
+ self.assertEqual(observed, ['peer blocked'])
+ self.assertEqual(target.read_bytes(), b'new')
+
+ def test_install_refuses_while_peer_holds_lock(self):
+ import fcntl
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'new')
+ target.write_bytes(b'old')
+ fd = os.open(str(target) + '.install.lock', os.O_CREAT | os.O_RDWR, 0o600)
+ try:
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ for expected in (installer.digest(target), 'absent'):
+ with self.subTest(expected=expected):
+ with self.assertRaises(ValueError):
+ installer.install(source, target, expected)
+ self.assertEqual(target.read_bytes(), b'old')
+ self.assertEqual(list(pathlib.Path(d).glob('target.bak.*')), [])
+ finally:
+ os.close(fd)
+
+ def test_peer_change_after_backup_is_refused_under_lock(self):
+ # Bytes that change before the locked recheck are never overwritten.
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'new')
+ target.write_bytes(b'old')
+ expected = installer.digest(target)
+ real_chown = installer.os.chown
+
+ def chown_then_peer_write(path, uid, gid):
+ real_chown(path, uid, gid)
+ if '.install.' in str(path):
+ target.write_bytes(b'peer')
+
+ with mock.patch.object(installer.os, 'chown', side_effect=chown_then_peer_write):
+ with self.assertRaises(ValueError):
+ installer.install(source, target, expected)
+ self.assertEqual(target.read_bytes(), b'peer')
+
+ def test_replace_failure_leaves_original(self):
+ with tempfile.TemporaryDirectory() as d:
+ source, target = pathlib.Path(d) / 'source', pathlib.Path(d) / 'target'
+ source.write_bytes(b'new')
+ target.write_bytes(b'old')
+ with mock.patch.object(installer.os, 'replace', side_effect=OSError('fixture failure')):
+ with self.assertRaises(OSError):
+ installer.install(source, target, installer.digest(target))
+ self.assertEqual(target.read_bytes(), b'old')
+
+ def test_dry_run_missing_target_is_user_friendly_error(self):
+ with tempfile.TemporaryDirectory() as d:
+ root = pathlib.Path(d)
+ target = root / 'missing-target'
+ result = subprocess.run(
+ [sys.executable, str(PATH), 'agent-log-rotate',
+ '--target', str(target), '--expected-sha256', '0' * 64],
+ capture_output=True)
+ self.assertNotEqual(result.returncode, 0)
+ self.assertIn(b'destination must be an existing plain file', result.stderr)
+ self.assertNotIn(b'Traceback', result.stderr)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/claude-ops/tests/test_ops_mac_log_rotate.py b/claude-ops/tests/test_ops_mac_log_rotate.py
new file mode 100644
index 00000000..eb967a71
--- /dev/null
+++ b/claude-ops/tests/test_ops_mac_log_rotate.py
@@ -0,0 +1,219 @@
+"""Isolated compatibility tests; never rotate live logs or run jobs."""
+import contextlib
+import importlib.machinery
+import importlib.util
+import io
+import os
+import pathlib
+import plistlib
+import subprocess
+import tempfile
+import unittest
+from unittest import mock
+
+SOURCE = pathlib.Path(os.getenv("OPS_MAC_LOG_SOURCE", str(pathlib.Path(__file__).resolve().parents[1] / "scripts/ops-mac/agent-log-rotate")))
+loader = importlib.machinery.SourceFileLoader("log_rotate", str(SOURCE))
+spec = importlib.util.spec_from_loader(loader.name, loader)
+module = importlib.util.module_from_spec(spec)
+loader.exec_module(module)
+
+
+class PlistTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = pathlib.Path(self.tmp.name)
+
+ def write(self, data):
+ path = self.root / "fixture.plist"
+ path.write_bytes(data)
+ return path
+
+ def test_standard_xml_and_binary_need_no_fallback(self):
+ for fmt in (plistlib.FMT_XML, plistlib.FMT_BINARY):
+ expected = {"Label": "com.example.worker", "StandardOutPath": "a.log"}
+ path = self.write(plistlib.dumps(expected, fmt=fmt))
+ with mock.patch.object(module.subprocess, "run") as run:
+ self.assertEqual(module.load_plist(path), expected)
+ run.assert_not_called()
+
+ def test_apple_valid_nonstandard_xml(self):
+ data = b'<plist version="1.0"><!-- command --flag is opt-in --><dict><key>Label</key><string>com.example.worker</string><key>StandardOutPath</key><string>a&amp;b.log</string></dict></plist>'
+ path = self.write(data)
+ with self.assertRaises(Exception):
+ plistlib.loads(data)
+ normalized = plistlib.dumps({"Label": "com.example.worker", "StandardOutPath": "a&b.log"})
+ with mock.patch.object(module.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, normalized, b"")) as run:
+ self.assertEqual(module.load_plist(path)["StandardOutPath"], "a&b.log")
+ self.assertEqual(run.call_args.args[0], ["/usr/bin/plutil", "-convert", "xml1", "-o", "-", "--", str(path)])
+ self.assertEqual(path.read_bytes(), data)
+
+ def test_real_apple_conversion_on_isolated_fixture(self):
+ if not pathlib.Path("/usr/bin/plutil").exists():
+ self.skipTest("Apple plutil unavailable")
+ path = self.write(b'<plist version="1.0"><!-- command --flag is opt-in --><dict><key>Label</key><string>com.example.worker</string><key>StandardOutPath</key><string>a&amp;b.log</string></dict></plist>')
+ self.assertEqual(module.load_plist(path)["StandardOutPath"], "a&b.log")
+
+ def test_invalid_plist_reported_on_stderr_only(self):
+ self.write(b"not a plist")
+ out, err = io.StringIO(), io.StringIO()
+ with mock.patch.object(module, "PLIST_DIRS", [str(self.root)]), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ self.assertEqual(module.discover(), [])
+ self.assertEqual(out.getvalue(), "")
+ self.assertIn("cannot parse", err.getvalue())
+
+ def test_empty_directory(self):
+ with mock.patch.object(module, "PLIST_DIRS", [str(self.root)]):
+ self.assertEqual(module.discover(), [])
+
+ def test_multiline_quotes_unicode_preserved_and_deduplicated(self):
+ value = 'logs/"café"\nsecond.log'
+ self.write(plistlib.dumps({"Label": "com.example.worker", "StandardOutPath": value, "StandardErrorPath": value}))
+ with mock.patch.object(module, "PLIST_DIRS", [str(self.root)]):
+ self.assertEqual(module.discover(), [("com.example.worker", value)])
+
+ def test_malformed_field_types_skipped_and_valid_logs_kept(self):
+ # Valid plists whose fields have the wrong type must not abort the scan.
+ fixtures = {
+ "a-int-label.plist": {"Label": 42, "StandardOutPath": "int-label.log"},
+ "b-list-path.plist": {"Label": "com.example.listpath", "StandardOutPath": ["x.log"],
+ "StandardErrorPath": "listpath-err.log"},
+ "c-dict-path.plist": {"Label": "com.example.dictpath", "StandardErrorPath": {"p": 1}},
+ "d-data-label.plist": {"Label": b"bytes", "StandardOutPath": "data-label.log"},
+ "e-valid.plist": {"Label": "com.example.valid", "StandardOutPath": "valid.log"},
+ }
+ for name, data in fixtures.items():
+ (self.root / name).write_bytes(plistlib.dumps(data))
+ out, err = io.StringIO(), io.StringIO()
+ with mock.patch.object(module, "PLIST_DIRS", [str(self.root)]), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ found = module.discover()
+ self.assertEqual(found, [("com.example.listpath", "listpath-err.log"),
+ ("com.example.valid", "valid.log")])
+ self.assertEqual(out.getvalue(), "")
+ report = err.getvalue()
+ for name in ("a-int-label.plist", "b-list-path.plist", "c-dict-path.plist", "d-data-label.plist"):
+ self.assertIn(name, report)
+ self.assertNotIn("e-valid.plist", report)
+
+ def test_non_dictionary_rejected(self):
+ path = self.write(plistlib.dumps(["unexpected"]))
+ with self.assertRaises(ValueError):
+ module.load_plist(path)
+
+ def test_failed_converter_and_timeout_visible(self):
+ path = self.write(b"bad")
+ for effect in (OSError("unavailable"), subprocess.TimeoutExpired("plutil", 5)):
+ with mock.patch.object(module.subprocess, "run", side_effect=effect):
+ with self.assertRaises(ValueError):
+ module.load_plist(path)
+
+
+class RotationTests(unittest.TestCase):
+ def fixture(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ path = pathlib.Path(tmp.name) / 'worker.log'
+ path.write_bytes(b'original log\n' * 100)
+ return path
+
+ def test_main_reports_archive_failure_and_returns_nonzero(self):
+ path = self.fixture()
+ out, err = io.StringIO(), io.StringIO()
+ with mock.patch.object(module, 'discover', return_value=[('fixture', str(path))]), mock.patch.object(module, 'rotate', return_value=(False, 'FAILED: archival incomplete')), mock.patch.object(module.sys, 'argv', ['agent-log-rotate']), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = module.main()
+ self.assertNotEqual(code, 0)
+ self.assertIn('FAILED: archival incomplete', err.getvalue())
+
+ def test_same_second_archive_collision_never_overwrites(self):
+ path = self.fixture()
+ archive = path.parent / module.ARCHIVE_SUBDIR
+ archive.mkdir()
+ previous = archive / 'worker.log.fixed.gz'
+ previous.write_bytes(module.gzip.compress(b'previous archive'))
+ original = previous.read_bytes()
+ source_bytes = path.read_bytes()
+ with mock.patch.object(module.time, 'strftime', return_value='fixed'):
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertTrue(changed, message)
+ self.assertEqual(previous.read_bytes(), original)
+ archives = list(archive.glob('*.gz'))
+ self.assertEqual(len(archives), 2)
+ self.assertEqual({module.gzip.decompress(item.read_bytes()) for item in archives}, {b'previous archive', source_bytes})
+ self.assertEqual(path.read_bytes(), b'')
+
+ def test_competing_writer_lock_keeps_live_file_unchanged(self):
+ import fcntl
+ path = self.fixture()
+ original = path.read_bytes()
+ with open(str(path) + '.rotate.lock', 'w') as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertFalse(changed, message)
+ self.assertEqual(path.read_bytes(), original)
+ self.assertFalse((path.parent / module.ARCHIVE_SUBDIR).exists())
+
+ def test_failed_steps_never_leave_partial_files(self):
+ targets = (('compress', 'gzip', 'GzipFile'), ('ownership', 'os', 'chown'), ('publish', 'os', 'link'))
+ for name, owner, attribute in targets:
+ with self.subTest(step=name):
+ path = self.fixture()
+ original = path.read_bytes()
+ target = getattr(module, owner)
+ with mock.patch.object(target, attribute, side_effect=OSError('fixture ' + name)):
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertFalse(changed, message)
+ self.assertEqual(path.read_bytes(), original)
+ archive = path.parent / module.ARCHIVE_SUBDIR
+ leftovers = list(archive.glob('*.partial')) if archive.exists() else []
+ self.assertEqual(leftovers, [])
+ self.assertEqual(list(archive.glob('*.gz')) if archive.exists() else [], [])
+
+ def test_published_archive_is_kept_when_source_changes_afterwards(self):
+ path = self.fixture()
+ original = path.read_bytes()
+ link = module.os.link
+ def link_then_append(source, dest):
+ link(source, dest)
+ with path.open('ab') as writer:
+ writer.write(b'late line\n')
+ with mock.patch.object(module.os, 'link', side_effect=link_then_append):
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertFalse(changed, message)
+ archive = path.parent / module.ARCHIVE_SUBDIR
+ self.assertEqual(list(archive.glob('*.partial')), [])
+ published = list(archive.glob('*.gz'))
+ self.assertEqual(len(published), 1)
+ self.assertEqual(module.gzip.decompress(published[0].read_bytes()), original)
+ self.assertEqual(path.read_bytes(), original + b'late line\n')
+
+ def test_success_reports_best_effort_truncation(self):
+ path = self.fixture()
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertTrue(changed, message)
+ self.assertIn('best-effort', message)
+ self.assertIn('BEST EFFORT', module.__doc__)
+
+ def test_archival_failure_never_truncates(self):
+ path = self.fixture()
+ original = path.read_bytes()
+ with mock.patch.object(module.gzip, 'GzipFile', side_effect=OSError('fixture compression failure')):
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertFalse(changed, message)
+ self.assertEqual(path.read_bytes(), original)
+
+ def test_appends_during_archive_are_preserved_not_truncated(self):
+ path = self.fixture()
+ original = path.read_bytes()
+ copy = module.shutil.copyfileobj
+ def append_after_copy(src, dst, length):
+ copy(src, dst, length)
+ with path.open('ab') as writer:
+ writer.write(b'new line\n')
+ with mock.patch.object(module.shutil, 'copyfileobj', side_effect=append_after_copy):
+ changed, message = module.rotate(str(path), 'fixture', 1, 10, False, False)
+ self.assertFalse(changed, message)
+ self.assertEqual(path.read_bytes(), original + b'new line\n')
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/claude-ops/tests/test_ops_mac_reaper.py b/claude-ops/tests/test_ops_mac_reaper.py
new file mode 100644
index 00000000..b1561a4f
--- /dev/null
+++ b/claude-ops/tests/test_ops_mac_reaper.py
@@ -0,0 +1,137 @@
+"""Ownership tests call only sourced predicates with mocked process tools."""
+import os
+import pathlib
+import subprocess
+import tempfile
+import unittest
+
+LIB = pathlib.Path(os.getenv('OPS_MAC_REAPER_LIBRARY', str(pathlib.Path(__file__).resolve().parents[1] / 'scripts/ops-mac/reaper-safety.sh')))
+
+
+class ReaperTests(unittest.TestCase):
+ def predicate(self, body, call):
+ return subprocess.run(['/bin/bash', '-c', 'set -uo pipefail; source "$1"; ' + body + '; ' + call, 'test', str(LIB)], capture_output=True).returncode
+
+ def test_alive_non_claude_parent_protected(self):
+ self.assertNotEqual(self.predicate('ps() { echo 42; return 0; }', 'ops_reaper_parent_absent 42'), 0)
+
+ def test_dead_parent_permitted(self):
+ self.assertEqual(self.predicate('ps() { return 1; }', 'ops_reaper_parent_absent 42'), 0)
+
+ def test_unknown_parent_protected(self):
+ self.assertNotEqual(self.predicate('ps() { return 2; }', 'ops_reaper_parent_absent 42'), 0)
+
+ def test_user_managed_pid1_protected(self):
+ body = 'ps() { echo 1; }; launchctl() { if [ "$1" = list ]; then printf "PID Status Label\\n100 0 com.example.worker\\n"; else echo system; fi; }'
+ self.assertNotEqual(self.predicate(body, 'ops_reaper_unmanaged_orphan 100'), 0)
+
+ def test_system_managed_pid1_protected(self):
+ body = 'ps() { echo 1; }; launchctl() { if [ "$1" = list ]; then echo "PID Status Label"; else echo "pid = 100"; fi; }'
+ self.assertNotEqual(self.predicate(body, 'ops_reaper_unmanaged_orphan 100'), 0)
+
+ def test_unmanaged_pid1_permitted(self):
+ body = 'ps() { echo 1; }; launchctl() { echo "PID Status Label"; }'
+ self.assertEqual(self.predicate(body, 'ops_reaper_unmanaged_orphan 100'), 0)
+
+ def test_missing_launchd_inventory_protected(self):
+ self.assertNotEqual(self.predicate('ps() { echo 1; }; launchctl() { return 1; }', 'ops_reaper_unmanaged_orphan 100'), 0)
+
+ def test_invalid_identity_protected(self):
+ self.assertNotEqual(self.predicate('ps() { return 1; }', 'ops_reaper_parent_absent ""'), 0)
+
+ def integration(self, parent, managed, age='10:00', tty='?', protected=False, reused=False, broad=False):
+ with tempfile.TemporaryDirectory() as d:
+ root = pathlib.Path(d)
+ (root / '.claude').mkdir()
+ if protected:
+ (root / '.claude/.no-auto-kill-work').touch()
+ policy = root / 'policy.sh'
+ policy.write_text('ORPHAN_PAT=orphan-allow\nSTATEFUL_PAT=stateful-allow\nSINGLETON_NAMES=(example-singleton)\n')
+ mocks = root / 'mocks.sh'
+ mocks.write_text('''pgrep() { case "$*" in *orphan-allow*|*stateful-allow*) echo 100;; *example-singleton*) printf '200\n201\n';; *'find '*|*'rg.*--files'*|*'auth login --email'*) [ "$BROAD" = 1 ] && echo 101 || return 1;; *) return 1;; esac; }
+ps() { case "$*" in *tty=*) echo "${MOCK_TTY:-?}";; *lstart=*) if [ "$REUSED" = 1 ]; then echo start >>"$HOME/starts"; wc -l <"$HOME/starts"; else echo 'fixture-start node'; fi;; *etime=*) echo "$AGE";; *ppid=*) echo "$PARENT";; *command=*) echo node;; *args=*) echo 'rg --files /';; *rss=*) echo 1000;; *pid=*) return 0;; *) return 1;; esac; }
+launchctl() { if [ "$MANAGED" = 1 ] && [ "$1" = list ]; then echo '100 0 com.example.worker'; else echo 'PID Status Label'; fi; }
+kill() { echo "kill $*" >>"$HOME/actions"; }
+pkill() { echo "pkill $*" >>"$HOME/actions"; }
+find() { return 0; }
+lsof() { return 1; }
+sleep() { return 0; }
+''')
+ env = dict(os.environ, HOME=str(root), BASH_ENV=str(mocks), OPS_MAC_POLICY=str(policy), PARENT=str(parent), MANAGED=str(int(managed)), AGE=age, MOCK_TTY=tty, REUSED=str(int(reused)), BROAD=str(int(broad)))
+ result = subprocess.run(['/bin/bash', str(LIB.parent / 'claude-reaper.sh')], env=env, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ return (root / 'actions').read_text() if (root / 'actions').exists() else ''
+
+ def task_output(self, lsof_mode):
+ with tempfile.TemporaryDirectory() as d:
+ root = pathlib.Path(d)
+ (root / '.claude').mkdir()
+ task = root / 'task.output'
+ task.write_bytes(b'still needed\n')
+ policy = root / 'policy.sh'
+ policy.write_text('ORPHAN_PAT=a^\nSTATEFUL_PAT=a^\nSINGLETON_NAMES=()\n')
+ mocks = root / 'mocks.sh'
+ mocks.write_text('''pgrep() { return 1; }
+find() { printf '%s\\n' "$TASK_FILE"; }
+du() { printf '2049\\t%s\\n' "$2"; }
+lsof() { case "$LSOF_MODE" in
+ none) return 1 ;;
+ open) echo "cat 1 user 3w REG"; return 0 ;;
+ diag) echo "lsof: WARNING: can't stat() fuse file system" >&2; return 1 ;;
+ error) return 2 ;;
+esac; }
+command() { if [ "$1" = -v ] && [ "$2" = lsof ] && [ "$LSOF_MODE" = missing ]; then return 1; fi; builtin command "$@"; }
+kill() { echo "kill $*" >>"$HOME/actions"; }
+pkill() { echo "pkill $*" >>"$HOME/actions"; }
+''')
+ env = dict(os.environ, HOME=str(root), BASH_ENV=str(mocks), OPS_MAC_POLICY=str(policy),
+ TASK_FILE=str(task), REAPER_TASK_ROOT=str(root), LSOF_MODE=lsof_mode)
+ result = subprocess.run(['/bin/bash', str(LIB.parent / 'claude-reaper.sh')], env=env, capture_output=True)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ log = (root / '.claude/claude-reaper.log').read_text() if (root / '.claude/claude-reaper.log').exists() else ''
+ return task.read_bytes(), log
+
+ def test_task_output_truncated_only_on_explicit_no_writer(self):
+ content, log = self.task_output('none')
+ self.assertEqual(content, b'')
+ self.assertIn('truncated runaway task output', log)
+
+ def test_task_output_kept_when_writer_state_unknown(self):
+ for mode in ('open', 'diag', 'error', 'missing'):
+ with self.subTest(lsof=mode):
+ content, log = self.task_output(mode)
+ self.assertEqual(content, b'still needed\n')
+ self.assertNotIn('truncated runaway task output', log)
+ if mode != 'open':
+ self.assertIn('kept task output', log)
+
+ def test_broad_scan_and_auth_candidates_are_observation_only(self):
+ for parent, managed, tty, reused in ((42, False, '?', False), (1, True, '?', False), (1, False, 'ttys001', False), (1, False, '?', True)):
+ with self.subTest(parent=parent, managed=managed, tty=tty, reused=reused):
+ actions = self.integration(parent, managed, age='20:00', tty=tty, reused=reused, broad=True)
+ self.assertNotIn('101', actions)
+
+ def test_full_reaper_protects_live_non_claude_parent(self):
+ self.assertEqual(self.integration(42, False), '')
+
+ def test_full_reaper_protects_managed_pid1(self):
+ self.assertEqual(self.integration(1, True), '')
+
+ def test_full_reaper_allows_old_unmanaged_orphan(self):
+ self.assertIn('kill 100', self.integration(1, False))
+
+ def test_full_reaper_protects_fresh_orphan(self):
+ self.assertEqual(self.integration(1, False, '00:10'), '')
+
+ def test_interactive_process_protected(self):
+ self.assertEqual(self.integration(1, False, tty='ttys001'), '')
+
+ def test_existing_active_work_guard_protected(self):
+ self.assertEqual(self.integration(1, False, protected=True), '')
+
+ def test_changed_process_identity_protected(self):
+ self.assertEqual(self.integration(1, False, reused=True), '')
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/claude-ops/tests/test_ops_mac_recall_seed.py b/claude-ops/tests/test_ops_mac_recall_seed.py
new file mode 100644
index 00000000..77908259
--- /dev/null
+++ b/claude-ops/tests/test_ops_mac_recall_seed.py
@@ -0,0 +1,90 @@
+"""All transport and seed-writing tests use mocks and isolated files."""
+import importlib.machinery
+import importlib.util
+import json
+import os
+import pathlib
+import subprocess
+import tempfile
+import unittest
+from unittest import mock
+
+SOURCE = pathlib.Path(os.getenv("OPS_MAC_RECALL_SOURCE", str(pathlib.Path(__file__).resolve().parents[1] / "scripts/ops-mac/brain-recall-seed")))
+loader = importlib.machinery.SourceFileLoader("seed", str(SOURCE))
+spec = importlib.util.spec_from_loader(loader.name, loader)
+seed = importlib.util.module_from_spec(spec)
+loader.exec_module(seed)
+
+
+def response(text, error=False):
+ return json.dumps({"jsonrpc": "2.0", "id": 2, "result": {"isError": error, "content": [{"type": "text", "text": text}]}})
+
+
+class RecallTests(unittest.TestCase):
+ def setUp(self):
+ scope = mock.patch.object(seed, "USER_ID", "owner")
+ scope.start()
+ self.addCleanup(scope.stop)
+
+ def test_json_and_sse_matching_id_not_notification(self):
+ raw = response('{"results": []}')
+ for value in (raw, 'data: {"method":"notice"}\n\ndata: ' + raw + '\n\n'):
+ self.assertEqual(seed.parse_sse(value, 2)["id"], 2)
+
+ def test_rpc_error_and_tool_error(self):
+ for raw in ('{"jsonrpc":"2.0","id":2,"error":{"code":-1}}', response("bad", True)):
+ with mock.patch.object(seed, "mcp_post", side_effect=[(None, '{"id":1,"result":{}}'), (None, ''), (None, raw)]):
+ with self.assertRaises(seed.RecallError):
+ seed.mcp_tool("unused", "search", {})
+
+ def test_invalid_and_missing_response(self):
+ for raw in ('', 'invalid', '{"id":9,"result":{}}', '[]', '{"id":2}'):
+ with self.assertRaises(seed.RecallError):
+ seed.parse_sse(raw, 2)
+
+ def test_empty_is_valid_not_rpc_failure(self):
+ with mock.patch.object(seed, "mcp_post", side_effect=[(None, '{"id":1,"result":{}}'), (None, ''), (None, response('{"results": []}'))]):
+ self.assertEqual(seed.extract_memories(seed.mcp_tool("unused", "search", {})), [])
+
+ def test_initialization_error_stops_tool_call(self):
+ with mock.patch.object(seed, "mcp_post", return_value=(None, '{"id":1,"error":{"code":-1}}')) as post:
+ with self.assertRaises(seed.RecallError):
+ seed.mcp_tool("unused", "search", {})
+ self.assertEqual(post.call_count, 1)
+
+ def test_preserve_previous_on_empty_error_and_partial_failure(self):
+ with tempfile.TemporaryDirectory() as d:
+ path = pathlib.Path(d) / "seed.md"
+ original = 'last good "café"\nsecond line\n'.encode()
+ for outcomes, expected in ((["[]", "[]"], 1), ([TimeoutError(), TimeoutError()], 2), ([json.dumps([{"memory": "new"}]), seed.RecallError("tool error")], 2)):
+ path.write_bytes(original)
+ with mock.patch.object(seed, "OUT", path), mock.patch.object(seed, "MEM0_URL", "unused"), mock.patch.object(seed, "query_with_retry", side_effect=outcomes):
+ self.assertEqual(seed.main(), expected)
+ self.assertEqual(path.read_bytes(), original)
+
+ def test_finite_retry_delays(self):
+ with mock.patch.object(seed, "mcp_tool", side_effect=TimeoutError()) as tool, mock.patch.object(seed.time, "sleep") as sleep:
+ with self.assertRaises(TimeoutError):
+ seed.query_with_retry("query")
+ self.assertEqual(tool.call_count, 3)
+ self.assertEqual([c.args[0] for c in sleep.call_args_list], [1, 2])
+
+ def test_protocol_failure_not_retried(self):
+ with mock.patch.object(seed, "mcp_tool", side_effect=seed.RecallError("isError")) as tool, mock.patch.object(seed.time, "sleep") as sleep:
+ with self.assertRaises(seed.RecallError):
+ seed.query_with_retry("query")
+ self.assertEqual(tool.call_count, 1)
+ sleep.assert_not_called()
+
+ def test_success_keeps_quotes_unicode_and_timestamp(self):
+ with tempfile.TemporaryDirectory() as d:
+ path = pathlib.Path(d) / "seed.md"
+ value = '"café"\nsecond line'
+ with mock.patch.object(seed, "OUT", path), mock.patch.object(seed, "MEM0_URL", "unused"), mock.patch.object(seed, "query_with_retry", return_value=json.dumps([{"memory": value}])):
+ self.assertEqual(seed.main(), 0)
+ self.assertIn(value, path.read_text())
+ self.assertIn("auto-generated", path.read_text())
+
+
+if __name__ == "__main__":
+ unittest.main()