看门狗
- 作者仓库星标 0
- 作者更新于 2026年8月24日 07:33
- 作者仓库 claude-code-skills
- 领域
- 通用
- 作者声明的智能体
- 未找到明确声明;不据此推断已兼容或已测试
- 静态检查
- 88 / 100 · 启发式扫描,不代表运行安全
- 运行环境证据
- 未执行;当前没有隔离运行测试证据
- 作者 / 版本 / 许可证
- @daymade · 未声明许可证
- 上下文用量评级
- 低消耗
- 接入复杂程度
- 需简单配置
- 是否需要外部接口密钥
- 不需要
- 兼容的系统
- macOS
- 运行环境要求
- 未检出明确要求
- 检测到的文件与系统行为
-
- 只读
- 允许写入 / 修改
- 命令执行
- 网络行为
- 仅限本地
- 安装命令数
- 无(仅作为资料)
需要注意: 未声明工具权限范围;实际权限由运行环境决定。
# macOS Watchdog
A watchdog is a launchd job that periodically detects a recurring problem and remediates it without a human. The craft is not "how to install a plist" — it is **how to keep the watchdog from becoming a new disturbance**: every watchdog on this machine was born from an incident, and the recurring failure mode afterward is the watchdog itself (false "all good" reports, notification floods, re-launching apps the user quit, fork-bomb replays).
The governing principle, learned the expensive way: **a watchdog's lifecycle is bound to its premise state**. When the condition it exists to fix cannot be fixed by it (broken WiFi, user quit the target app, prerequisite state gone), the watchdog must stand down *by itself* — not wait for a human to disable it.
## Entry decision tree
| The situation is… | Go to |
|---|---|
| Installing a NEW watchdog from scratch | § Deploy, then § The quiet-watchdog contract |
| An existing watchdog misbehaves (spam, re-launches apps, hammers) | § The quiet-watchdog contract, diagnose which clause it violates |
| Stopping / disabling / restarting a job | § Stop semantics |
| plist key details (KeepAlive forms, domains, logging, resource limits) | `references/launchd-plist-reference.md` |
| Cooldown/backoff/notification-throttle patterns + sanitized war stories | `references/quiet-watchdog-patterns.md` |
| SRE alert layering (page vs ticket, fatigue numbers) | `references/alert-discipline.md` |
## The quiet-watchdog contract (the four clauses)
Before shipping or blessing any watchdog, all four must hold. Each clause exists because a real watchdog violated it.
### 1. Premise-state self-check — it knows when it has no job
The script's first act on every run: verify the state that justifies its existence still holds. If not, exit silently — no remediation, no notification, no side effects.
- A proxy-repair watchdog checks the proxy app is running first; user quit it → skip the cycle.
- A "did the config switch back" watcher checks the config state it watches; already switched → self-stop, not another round of misleading notifications. (Real case: a recovery watcher kept firing for 2h after its premise resolved, sending 3 spurious notices, because nothing told it to stop.)
### 2. Remediate first, page only on sustained failure
Detection stays honest on every cycle, but the *disruptive action* defers until the failure persists across N consecutive cycles (patient mode). Rationale: oscillating chains self-recover in minutes; a force-reconnect on a self-limiting blip is net-harmful. Measure your system's real self-recovery window before choosing N (one chain's 94-min observatory run showed ≤3 min self-recovery → N=2 cycles at 5-min interval).
Escalation ladder (cheap → disruptive): refresh state → restart connection → remote repair. Each rung verifies before climbing.
### 3. Escalating auto-cooldown — an unfixable environment means silence
When the full repair ladder fails, the environment is unfixable by the watchdog (broken WiFi, captive portal, dead upstream). The naive behavior — re-run the entire ladder + notification every interval forever — is exactly "the watchdog keeps re-launching the app every 10 minutes."
`ThrottleInterval` does **not** fix this: it throttles process respawn, is a fixed delay with no backoff, and does nothing for a job that exits 0 after spamming. Cool-down must live in the application layer:
- Record consecutive exhausted rounds in a state file.
- After each exhausted round, stand down for an escalating tier (e.g. 30 min → 2 h → 6 h, last tier repeats).
- One notification when *entering* cool-down; zero during it. On tier expiry, retry one round; any real heal clears the counter and the cool-down state.
- A manual `pause [duration]` command with a TTL state file is the fallback — but the auto path must work with no human command at all. A disable mechanism that requires the user to remember a command is not a mechanism.
Reusable implementation: `scripts/watchdog-cooldown.sh` (source it; provides `paused_any`, `record_exhausted`, `clear_exhausted`, `cmd_pause`/`cmd_resume`).
### 4. Never resurrect what the user explicitly quit
On macOS, `open <url-scheme>` **launches the app** when it isn't running, and `open` without `-g` steals foreground. A watchdog whose remediation uses URL schemes (or `open -a`, or restarting a GUI app) will read to the user as "I quit it and it came back."
Gate every such action: check the target process is alive before invoking its scheme, and pass `-g` so a legitimate action never pops a window. If the user quit the app mid-remediation, abort the ladder — cleanup traps must honor the same gate, or the "ensure connected on exit" fallback becomes the resurrector.
## Deploy (mechanics that bite)
1. **Location**: user agent → `~/Library/LaunchAgents/` (GUI session context: can `open` apps, show notifications); system daemon → `/Library/LaunchDaemons/` (root, no GUI access). Choose by whether the job needs the user's GUI session, not by habit.
2. **plist**: start from `assets/launchagent.template.plist` (annotated: Label, ProgramArguments, StartInterval, StandardOutPath/StandardErrorPath, ThrottleInterval, Nice). Validate with `plutil -lint`. `ProgramArguments` element 0 = absolute path; never rely on PATH inheritance.
3. **Load/reload**: `launchctl bootstrap gui/$(id -u) <plist>`; after editing a plist, `bootout` then `bootstrap` again — launchd's active state must match disk. Force one run with `launchctl kickstart -k gui/$(id -u)/<label>`.
4. **Logs**: `StandardOutPath`/`StandardErrorPath` are non-negotiable (without them failures vanish), plus in-script log rotation (cap ~1 MB).
5. **Idempotency guard**: re-running your deploy must not double-install. `scripts/new-launchagent.sh <label> <script> <interval>` is the idempotent wrapper (bootout-if-loaded → write plist → bootstrap → verify `launchctl list`).
6. **TCC / Full Disk Access**: a LaunchAgent reading another app's Group Container or protected dirs needs FDA granted to the *actual interpreter* — Xcode's python3 stub fails where your real python3 works. Verify with the exact binary from `ProgramArguments`, not the one your shell resolves.
7. **Batch throttling by default**: any watchdog loop that spawns work (replays, fuzz, batch scans, parallel API calls) needs an explicit rate cap as a default parameter, not a later optimization. To the machine, an unthrottled loop and a runaway process are indistinguishable (real case: an unthrottled test replay forked 1,041 processes/sec for 7 minutes and pushed the die to 83 °C).
## Stop semantics (the deprecated trap)
| Intent | Command |
|---|---|
| Stop now, allow re-bootstrap later | `launchctl bootout gui/$(id -u)/<label>` (daemon: `sudo launchctl bootout system/<label>`) |
| Stop now AND keep stopped across login | `launchctl disable user/$(id -u)/<label>` (reverse: `enable`) |
| Edit then reload | `bootout` → edit plist → `bootstrap` |
**Never `launchctl unload`**: deprecated, and on Ventura+ the job re-loads via `RunAtLoad` when the plist stays in place — the "disabled" watchdog fires again (observed: an `unload`ed watcher re-firing 3 times in 2h). `bootstrap`/`bootout` are the modern pair.
## Troubleshooting quick map
| Symptom | First check |
|---|---|
| "It re-launches the app I quit" | URL-scheme/`open` calls missing the process-alive gate (clause 4) |
| "It spams the same repair every few minutes" | No exhausted-round cool-down (clause 3); also check the ladder's failure path doesn't reset its dead-counter |
| "It reports healthy through a real outage" | Health check certifies only the path it probes — one green probe ≠ all planes healthy (add the second plane's probe) |
| "bootout didn't stick / it came back" | `unload` used instead of `bootout`, or `RunAtLoad` + plist still in place |
| Silent no-runs | `StandardErrorPath` missing → failures invisible; then `log show --predicate 'process == "launchd"' --last 15m` |
| Works interactively, fails under launchd | TCC/FDA on the wrong interpreter; PATH assumptions in `ProgramArguments` |
Details and the sanitized war stories behind each clause: `references/quiet-watchdog-patterns.md`.
章节与文件索引
按说明文件中的顺序排列。
进入决策树
安静看门狗合约(四个条款)
1. 前提状态自检——它知道什么时候没有工作
2. 首先修复,仅针对持续故障进行寻呼
3. 不断升级的自动冷却时间——无法修复的环境意味着沉默
文件/命令 -> references/launchd-plist-reference.md · references/quiet-watchdog-patterns.md · references/alert-discipline.md · ThrottleInterval · pause [duration] · scripts/watchdog-cooldown.sh · paused_any · record_exhausted
内容校验值 -> 63d645fc2acf
当前原文的自动摘译,尚未人工审校。
进入决策树
情况是…… · 从头开始安装新的看门狗 · § 部署,然后 § 安静看门狗合约 现有看门狗行为不当(垃圾邮件、重新启动应用程序、锤子) · § 安静看门狗合约,诊断它违反了哪个条款 停止/禁用/重新启动作业 · § 停止语义 plist 关键详细信息(KeepAlive 表单、域、日志记录、资源限制) ·
references/launchd-plist-reference.md安静看门狗合约(四个条款)
在运输或祝福任何看门狗之前,所有四个都必须保持。每个条款之所以存在,是因为真正的监管机构违反了它。
1. 前提状态自检——它知道什么时候没有工作
脚本每次运行时的第一个动作是:验证证明其存在合理性的状态仍然成立。如果没有,请静默退出——无需补救,无需通知,无副作用。代理修复看门狗首先检查代理应用程序是否正在运行;用户退出→跳过循环。 “配置是否切换回来”观察者检查它观察的配置状态;已经切换→自动停止,而不是另一轮误导性通知。 (真实案例:恢复观察者在其前提解决后持续触发了 2 小时,发送了 3 个虚假通知,因为没有任何东西告诉它停止。)
2. 首先修复,仅针对持续故障进行寻呼
检测在每个周期中都保持诚实,但“破坏性操作”会推迟,直到故障在 N 个连续周期中持续存在(患者模式)。原理:摆动链在几分钟内自动恢复;对自限制信号进行强制重新连接是有害的。在选择 N 之前测量系统的真实自我恢复窗口(一条链的 94 分钟观测运行显示 ≤3 分钟自我恢复 → N=2 个周期,间隔 5 分钟)。
3. 不断升级的自动冷却时间——无法修复的环境意味着沉默
当完整的修复阶梯失败时,看门狗无法修复环境(WiFi 损坏、强制门户、上游死机)。天真的行为 - 重新运行整个梯子 + 永远每隔一段时间发出通知 - 正是“看门狗每 10 分钟不断重新启动应用程序”。
ThrottleInterval没有解决这个问题:它限制进程重生,是一个没有退避的固定延迟,并且对于垃圾邮件后退出 0 的作业没有任何作用。冷却必须存在于应用层: