rigops 0.13.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rigops/__init__.py +3 -0
- rigops/__main__.py +7 -0
- rigops/authprobe.py +106 -0
- rigops/backlog.py +107 -0
- rigops/cause.py +151 -0
- rigops/cli/__init__.py +66 -0
- rigops/cli/authprobe.py +47 -0
- rigops/cli/backlog.py +93 -0
- rigops/cli/config.py +61 -0
- rigops/cli/doctor.py +666 -0
- rigops/cli/eit.py +225 -0
- rigops/cli/eval.py +370 -0
- rigops/cli/hook.py +7 -0
- rigops/cli/janitor.py +88 -0
- rigops/cli/jobs.py +122 -0
- rigops/cli/ledger.py +350 -0
- rigops/cli/mine.py +7 -0
- rigops/cli/reap.py +110 -0
- rigops/cli/tax.py +238 -0
- rigops/cli/version.py +12 -0
- rigops/config.py +83 -0
- rigops/config_spec.py +336 -0
- rigops/core/__init__.py +224 -0
- rigops/corpus.py +44 -0
- rigops/cost.py +37 -0
- rigops/detector.py +91 -0
- rigops/doctor/__init__.py +81 -0
- rigops/doctor/check_agents.py +85 -0
- rigops/doctor/check_budget.py +110 -0
- rigops/doctor/check_jobs.py +30 -0
- rigops/doctor/check_levers.py +328 -0
- rigops/doctor/check_mcp.py +104 -0
- rigops/doctor/check_memory.py +92 -0
- rigops/doctor/check_pointers.py +358 -0
- rigops/doctor/ids.py +32 -0
- rigops/doctor/pointer_grammar.py +147 -0
- rigops/errors.py +5 -0
- rigops/eval/__init__.py +35 -0
- rigops/eval/cases.py +188 -0
- rigops/eval/checks.py +117 -0
- rigops/eval/client.py +190 -0
- rigops/eval/diff.py +108 -0
- rigops/eval/score.py +90 -0
- rigops/fmt.py +62 -0
- rigops/frontmatter.py +36 -0
- rigops/guard_state.py +69 -0
- rigops/hook.py +245 -0
- rigops/janitor.py +384 -0
- rigops/jobs.py +203 -0
- rigops/judge.py +364 -0
- rigops/launchd.py +194 -0
- rigops/ledger_row.py +88 -0
- rigops/levers.py +397 -0
- rigops/mine.py +195 -0
- rigops/mine_group.py +111 -0
- rigops/mine_redact.py +192 -0
- rigops/modelmix.py +36 -0
- rigops/notify.py +114 -0
- rigops/procgroup.py +37 -0
- rigops/reap.py +917 -0
- rigops/reap_guards.py +70 -0
- rigops/reap_owned.py +44 -0
- rigops/reap_procs.py +382 -0
- rigops/reap_report.py +78 -0
- rigops/reap_selftest.py +94 -0
- rigops/rebuilds.py +163 -0
- rigops/redaction-patterns.public.txt +40 -0
- rigops/registry.py +137 -0
- rigops/sources/__init__.py +19 -0
- rigops/sources/ccusage.py +44 -0
- rigops/sources/command.py +50 -0
- rigops/starts.py +247 -0
- rigops/state.py +159 -0
- rigops/templates/cron/crontab.example +21 -0
- rigops/templates/launchd/doctor.plist.in +44 -0
- rigops/templates/launchd/janitor.plist.in +50 -0
- rigops/templates/launchd/ledger.plist.in +48 -0
- rigops/templates/launchd/reap.plist.in +48 -0
- rigops/transcripts.py +369 -0
- rigops/watermarks.py +116 -0
- rigops-0.13.0.dist-info/METADATA +300 -0
- rigops-0.13.0.dist-info/RECORD +86 -0
- rigops-0.13.0.dist-info/WHEEL +5 -0
- rigops-0.13.0.dist-info/entry_points.txt +2 -0
- rigops-0.13.0.dist-info/licenses/LICENSE +21 -0
- rigops-0.13.0.dist-info/top_level.txt +1 -0
rigops/cli/doctor.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import shlex
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import time
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from rigops import cause as rigops_cause
|
|
16
|
+
from rigops import cli
|
|
17
|
+
from rigops import config as rigops_config
|
|
18
|
+
from rigops import core as rigops_core
|
|
19
|
+
from rigops import doctor as config_checks
|
|
20
|
+
from rigops import fmt, guard_state, launchd, procgroup, state
|
|
21
|
+
from rigops import notify as rigops_notify
|
|
22
|
+
from rigops import registry as rigops_registry
|
|
23
|
+
from rigops.judge import ( # noqa: F401
|
|
24
|
+
_judge_evidence_only_item,
|
|
25
|
+
_judge_launchd_item,
|
|
26
|
+
_label_for_item,
|
|
27
|
+
_run_probe,
|
|
28
|
+
cadence_interval_hours,
|
|
29
|
+
newest_evidence_mtime,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
EVIDENCE_LINE_RE = re.compile(r":\d+$")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _load_json(path: Path, default):
|
|
36
|
+
if not path.exists():
|
|
37
|
+
return default
|
|
38
|
+
try:
|
|
39
|
+
return json.loads(path.read_text())
|
|
40
|
+
except (ValueError, OSError): # JSONDecodeError and UnicodeDecodeError are ValueErrors
|
|
41
|
+
return default
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _load_entries(path: Path, default):
|
|
45
|
+
data, version = guard_state.unwrap(_load_json(path, default))
|
|
46
|
+
return default if version > state.VERSION else data
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _load_dict(path: Path) -> dict:
|
|
50
|
+
data = _load_entries(path, {})
|
|
51
|
+
return data if isinstance(data, dict) else {}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _save_json(path: Path, data) -> None:
|
|
55
|
+
state.atomic_write(path, json.dumps(data, indent=2, sort_keys=True))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _save_entries(path: Path, entries) -> None:
|
|
59
|
+
_save_json(path, guard_state.wrap(entries))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
NOTIFY_TIMEOUT_S = 60
|
|
63
|
+
KILL_PREFIX = "kill:"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _guard_finding(path: Path, reason: str, outcome: str) -> rigops_core.Finding:
|
|
67
|
+
return rigops_core.Finding(
|
|
68
|
+
check="heal-state", area="doctor", symptom=f"{path.name} rejected: {reason}",
|
|
69
|
+
evidence=str(path), fix=outcome, key=path.name,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _cooldown_active(heal_stamps: dict, job_id: str, cooldown_h: float, now: float) -> bool:
|
|
74
|
+
last = heal_stamps.get(job_id)
|
|
75
|
+
return last is not None and (now - last) < cooldown_h * 3600
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _first_stdout_line(text: str) -> str:
|
|
80
|
+
for line in (text or "").splitlines():
|
|
81
|
+
line = line.strip()
|
|
82
|
+
if line:
|
|
83
|
+
return line[:200]
|
|
84
|
+
return ""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def run_custom_check(check_cfg: dict) -> dict:
|
|
88
|
+
name = check_cfg.get("name", "custom")
|
|
89
|
+
command = check_cfg.get("command", "")
|
|
90
|
+
timeout_s = check_cfg.get("timeout_s", 10)
|
|
91
|
+
warn_exit = check_cfg.get("warn_exit")
|
|
92
|
+
fail_exit = check_cfg.get("fail_exit")
|
|
93
|
+
try:
|
|
94
|
+
out = procgroup.run_group(command, shell=True, timeout=timeout_s)
|
|
95
|
+
code = out.returncode
|
|
96
|
+
except subprocess.TimeoutExpired:
|
|
97
|
+
return {"name": name, "status": "warn", "detail": f"timed out after {timeout_s}s"}
|
|
98
|
+
except OSError as exc:
|
|
99
|
+
return {"name": name, "status": "fail", "detail": str(exc)}
|
|
100
|
+
if fail_exit is not None and code == fail_exit:
|
|
101
|
+
return {"name": name, "status": "fail",
|
|
102
|
+
"detail": _first_stdout_line(out.stdout) or f"exit {code}"}
|
|
103
|
+
if warn_exit is not None and code == warn_exit:
|
|
104
|
+
return {"name": name, "status": "warn",
|
|
105
|
+
"detail": _first_stdout_line(out.stdout) or f"exit {code}"}
|
|
106
|
+
if code == 0:
|
|
107
|
+
return {"name": name, "status": "ok", "detail": "exit 0"}
|
|
108
|
+
return {"name": name, "status": "warn",
|
|
109
|
+
"detail": _first_stdout_line(out.stdout) or f"unexpected exit {code}"}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def run_disk_free_check(check_cfg: dict) -> dict:
|
|
113
|
+
# detail keeps the configured string: reports get pasted around, and the
|
|
114
|
+
# expanded path would put the home directory into every one of them.
|
|
115
|
+
raw_path = check_cfg.get("path", "/")
|
|
116
|
+
warn_gb = check_cfg.get("warn_gb", 25)
|
|
117
|
+
fail_gb = check_cfg.get("fail_gb", 10)
|
|
118
|
+
try:
|
|
119
|
+
free_gb = shutil.disk_usage(str(rigops_config.expand(raw_path))).free / (1024 ** 3)
|
|
120
|
+
except OSError as exc:
|
|
121
|
+
reason = exc.strerror or type(exc).__name__
|
|
122
|
+
detail = f"cannot stat {raw_path}: {reason}"
|
|
123
|
+
return {"name": "disk-free", "status": "fail", "detail": detail}
|
|
124
|
+
if free_gb < fail_gb:
|
|
125
|
+
status = "fail"
|
|
126
|
+
elif free_gb < warn_gb:
|
|
127
|
+
status = "warn"
|
|
128
|
+
else:
|
|
129
|
+
status = "ok"
|
|
130
|
+
return {"name": "disk-free", "status": status, "detail": f"{free_gb:.1f}GB free on {raw_path}"}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _notify(command: str, report_path: Path) -> str:
|
|
134
|
+
"""Runs the configured notify command; returns an event message on
|
|
135
|
+
timeout/failure, or "" once it ran (or there's no command configured)."""
|
|
136
|
+
if not command:
|
|
137
|
+
return ""
|
|
138
|
+
cmd = f"{command} {shlex.quote(str(report_path))}"
|
|
139
|
+
try:
|
|
140
|
+
proc = procgroup.run_group(cmd, shell=True, timeout=NOTIFY_TIMEOUT_S)
|
|
141
|
+
except subprocess.TimeoutExpired:
|
|
142
|
+
return f"notify command timed out after {NOTIFY_TIMEOUT_S}s"
|
|
143
|
+
except OSError as exc:
|
|
144
|
+
return f"notify command failed: {exc}"
|
|
145
|
+
if proc.returncode != 0:
|
|
146
|
+
return f"notify command exited {proc.returncode}"
|
|
147
|
+
return ""
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _is_unjudged(job: dict) -> bool:
|
|
151
|
+
"""No label and no evidence: the row would carry nothing but its own id."""
|
|
152
|
+
return (
|
|
153
|
+
job["status"] == "unknown"
|
|
154
|
+
and job["label"] is None
|
|
155
|
+
and job["evidence_age_h"] is None
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def render_report(ts: str, jobs: list, checks: list, heal_log: list, supervisor: str,
|
|
160
|
+
red_for: dict | None = None) -> str:
|
|
161
|
+
red_for = red_for or {}
|
|
162
|
+
lines = [f"rigops doctor report {ts}", f"supervisor: {supervisor}", "", "== jobs =="]
|
|
163
|
+
unjudged = [j for j in jobs if _is_unjudged(j)]
|
|
164
|
+
job_rows = [
|
|
165
|
+
[
|
|
166
|
+
j["id"], j["status"],
|
|
167
|
+
f"{j['runtime_h']:.1f}h" if j["runtime_h"] is not None else "-",
|
|
168
|
+
f"{j['evidence_age_h']:.1f}h" if j["evidence_age_h"] is not None else "-",
|
|
169
|
+
j["action"], red_for.get(("job", j["id"]), ""),
|
|
170
|
+
]
|
|
171
|
+
for j in jobs if not _is_unjudged(j)
|
|
172
|
+
]
|
|
173
|
+
if job_rows:
|
|
174
|
+
lines.append(fmt.table(
|
|
175
|
+
job_rows, ["id", "status", "runtime", "evidence age", "action", "red for"]))
|
|
176
|
+
elif not jobs:
|
|
177
|
+
lines.append("no registry items")
|
|
178
|
+
if unjudged:
|
|
179
|
+
ids = ", ".join(j["id"] for j in unjudged)
|
|
180
|
+
lines.append(f"not judged (no launchd label, no evidence): {ids}")
|
|
181
|
+
lines.append("")
|
|
182
|
+
lines.append("== checks ==")
|
|
183
|
+
check_rows = [[c["name"], c["status"], red_for.get(("check", c["name"]), ""), c["detail"]]
|
|
184
|
+
for c in checks]
|
|
185
|
+
lines.append(
|
|
186
|
+
fmt.table(check_rows, ["name", "status", "red for", "detail"])
|
|
187
|
+
if check_rows else "none configured"
|
|
188
|
+
)
|
|
189
|
+
if heal_log:
|
|
190
|
+
lines.append("")
|
|
191
|
+
lines.append("== heal actions ==")
|
|
192
|
+
lines.extend(heal_log)
|
|
193
|
+
return "\n".join(lines) + "\n"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
RED = config_checks.ids.EXIT_1_STATUSES
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def render_summary(jobs: list, checks: list, findings: list, gates: list, ts: str) -> str:
|
|
200
|
+
counts = [
|
|
201
|
+
(sum(1 for j in jobs if j["status"] in ("failing", "hung")), "failing/hung job"),
|
|
202
|
+
(sum(1 for c in checks if c["status"] == "fail"), "failing check"),
|
|
203
|
+
(len(_failing(findings)), "failing config finding"),
|
|
204
|
+
(len(_errors(findings)), "config check error"),
|
|
205
|
+
]
|
|
206
|
+
summary = ", ".join(f"{n} {noun}{'' if n == 1 else 's'}" for n, noun in counts if n)
|
|
207
|
+
lines = [f"rigops doctor: {summary or 'OK'} ({len(jobs)} jobs checked)"]
|
|
208
|
+
red = [g for g in gates if g["status"] in RED]
|
|
209
|
+
if red:
|
|
210
|
+
lines.append("red for: " + ", ".join(
|
|
211
|
+
f"{g['name']} {_red_for(g['since'], ts)}" for g in red))
|
|
212
|
+
return "\n".join(lines) + "\n"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _failing(findings: list) -> list:
|
|
216
|
+
return [f for f in findings if f.severity not in ("warn", "error")]
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _errors(findings: list) -> list:
|
|
220
|
+
return [f for f in findings if f.severity == "error"]
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def default_supervisor() -> str:
|
|
224
|
+
return "launchd" if sys.platform == "darwin" else "none"
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def default_registry() -> Path:
|
|
228
|
+
xdg = os.environ.get("XDG_CONFIG_HOME") or "~/.config"
|
|
229
|
+
return rigops_config.expand(Path(xdg) / "rigops" / "registry.md")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def exit_code(findings: list, verdict: bool, exit_zero: bool) -> int:
|
|
233
|
+
if _errors(findings):
|
|
234
|
+
return 2
|
|
235
|
+
return 1 if verdict and not exit_zero else 0
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def render_unknown_keys(keys: list) -> str:
|
|
239
|
+
if not keys:
|
|
240
|
+
return ""
|
|
241
|
+
noun = "key" if len(keys) == 1 else "keys"
|
|
242
|
+
return f"info: {len(keys)} unknown config {noun}: {', '.join(keys)} (rigops config check)\n"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def render_findings(findings: list) -> str:
|
|
246
|
+
failing = _failing(findings)
|
|
247
|
+
warnings = [f for f in findings if f.severity == "warn"]
|
|
248
|
+
lines = [f"config checks: {len(failing)} findings"]
|
|
249
|
+
lines.extend(f.line() for f in failing)
|
|
250
|
+
errors = _errors(findings)
|
|
251
|
+
if errors:
|
|
252
|
+
lines.append(f"errors: {len(errors)} (a check could not measure; the run exits 2)")
|
|
253
|
+
lines.extend(f.line() for f in errors)
|
|
254
|
+
if warnings:
|
|
255
|
+
lines.append(f"warnings: {len(warnings)} (reported, never fail the run)")
|
|
256
|
+
lines.extend(f.line() for f in warnings)
|
|
257
|
+
return "\n".join(lines) + "\n"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _finding_paths(finding) -> set:
|
|
261
|
+
"""The files a finding is about, absolute, for the staged filter to match on.
|
|
262
|
+
|
|
263
|
+
Checks that measure several files at once list them in ``extra``; everything
|
|
264
|
+
else carries one path as its evidence, with a line number the filter drops.
|
|
265
|
+
"""
|
|
266
|
+
listed = finding.extra.get("paths")
|
|
267
|
+
if listed:
|
|
268
|
+
return {str(rigops_config.expand(p)) for p in listed}
|
|
269
|
+
return {str(rigops_config.expand(EVIDENCE_LINE_RE.sub("", finding.evidence)))}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def report_config_checks(cfg: dict, args) -> int:
|
|
273
|
+
# --staged asserts "this commit is sound" rather than "the tree is quiet":
|
|
274
|
+
# the checks read the index of every staged file instead of the working tree
|
|
275
|
+
# copy, and a finding about a file this commit does not touch is somebody
|
|
276
|
+
# else's in-flight edit, which the unscoped fleet run still reports.
|
|
277
|
+
staged, staged_files = None, {}
|
|
278
|
+
if args.staged:
|
|
279
|
+
_, staged_files = rigops_core.staged_index()
|
|
280
|
+
staged = set(staged_files)
|
|
281
|
+
# Set either way: the overlay belongs to this run, not to the process.
|
|
282
|
+
rigops_core.set_overlay(staged_files)
|
|
283
|
+
findings = config_checks.run_checks(cfg, only=set(args.check or []) or None)
|
|
284
|
+
if staged is not None:
|
|
285
|
+
findings = [f for f in findings if _finding_paths(f) & staged]
|
|
286
|
+
if args.json:
|
|
287
|
+
print(json.dumps(
|
|
288
|
+
{"version": 1, "findings": [
|
|
289
|
+
{"id": f.id, "check": f.check, "area": f.area, "severity": f.severity,
|
|
290
|
+
"symptom": f.symptom, "evidence": f.evidence, "fix": f.fix} for f in findings]},
|
|
291
|
+
indent=2,
|
|
292
|
+
))
|
|
293
|
+
else:
|
|
294
|
+
print(render_findings(findings), end="")
|
|
295
|
+
return exit_code(findings, bool(_failing(findings)), args.exit_zero)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _job_gate_entries(jobs: list) -> list:
|
|
299
|
+
return [
|
|
300
|
+
{"kind": "job", "name": j["id"], "status": j["status"], "detail": ""}
|
|
301
|
+
for j in jobs if j["status"] in ("failing", "hung", "stale")
|
|
302
|
+
]
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _check_gate_entries(checks: list) -> list:
|
|
306
|
+
return [
|
|
307
|
+
{"kind": "check", "name": c["name"], "status": c["status"],
|
|
308
|
+
"detail": c["detail"]}
|
|
309
|
+
for c in checks if c["status"] != "ok"
|
|
310
|
+
]
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _config_gate_entries(findings: list) -> list:
|
|
314
|
+
by_check: dict = {}
|
|
315
|
+
for f in findings:
|
|
316
|
+
by_check.setdefault(f.check, []).append(f)
|
|
317
|
+
return [
|
|
318
|
+
{"kind": "config", "name": check, "detail": f"{len(group)} findings",
|
|
319
|
+
"status": "fail" if any(f.severity != "warn" for f in group) else "warn"}
|
|
320
|
+
for check, group in sorted(by_check.items())
|
|
321
|
+
]
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _with_since(gates: list, previous, ts: str) -> list:
|
|
325
|
+
"""A gate keeps its first ts while it stays in the record at the same red-or-not level."""
|
|
326
|
+
known = {}
|
|
327
|
+
if isinstance(previous, dict) and isinstance(previous.get("gates"), list):
|
|
328
|
+
known = {(g.get("kind"), g.get("name"), g.get("status") in RED): g["since"]
|
|
329
|
+
for g in previous["gates"]
|
|
330
|
+
if isinstance(g, dict) and isinstance(g.get("since"), str)}
|
|
331
|
+
return [{**g, "since": known.get((g["kind"], g["name"], g["status"] in RED), ts)}
|
|
332
|
+
for g in gates]
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _red_for(since: str, ts: str) -> str:
|
|
336
|
+
start, end = rigops_core.parse_utc_stamp(since), rigops_core.parse_utc_stamp(ts)
|
|
337
|
+
if start is None or end is None:
|
|
338
|
+
return "?"
|
|
339
|
+
hours = max(0.0, (end - start).total_seconds() / 3600)
|
|
340
|
+
return f"{int(hours // 24)}d" if hours >= 24 else f"{int(hours)}h"
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def main(argv: list[str] | None = None) -> int:
|
|
344
|
+
ap = argparse.ArgumentParser(prog="rigops doctor", description=cli.COMMANDS["doctor"])
|
|
345
|
+
ap.add_argument("--report", action="store_true", help="print the full report to stdout")
|
|
346
|
+
ap.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
|
347
|
+
ap.add_argument("--list", action="store_true", help="list registry items and exit")
|
|
348
|
+
ap.add_argument(
|
|
349
|
+
"--heal", action="store_true",
|
|
350
|
+
help=(
|
|
351
|
+
"allow kill/kickstart side effects; default is report-only: no "
|
|
352
|
+
"kill/kickstart (custom checks and notify still execute their "
|
|
353
|
+
"configured commands)"
|
|
354
|
+
),
|
|
355
|
+
)
|
|
356
|
+
ap.add_argument(
|
|
357
|
+
"--exit-zero", action="store_true",
|
|
358
|
+
help="exit 0 even when a finding fails; output and findings are unchanged",
|
|
359
|
+
)
|
|
360
|
+
ap.add_argument(
|
|
361
|
+
"--supervisor", choices=["launchd", "none"], default=default_supervisor(),
|
|
362
|
+
help=(
|
|
363
|
+
"'none' skips launchctl entirely and judges from evidence file ages only "
|
|
364
|
+
"(default: launchd on macOS, none elsewhere)"
|
|
365
|
+
),
|
|
366
|
+
)
|
|
367
|
+
ap.add_argument("--registry", help="registry file path (default: config doctor.registry, else $XDG_CONFIG_HOME/rigops/registry.md)")
|
|
368
|
+
ap.add_argument(
|
|
369
|
+
"--config-only", action="store_true",
|
|
370
|
+
help=(
|
|
371
|
+
"run only the config checks (agents, budget, jobs, levers, mcp, memory, "
|
|
372
|
+
"pointers) and skip the fleet"
|
|
373
|
+
),
|
|
374
|
+
)
|
|
375
|
+
ap.add_argument(
|
|
376
|
+
"--no-config", action="store_true", help="skip the config checks",
|
|
377
|
+
)
|
|
378
|
+
ap.add_argument(
|
|
379
|
+
"--staged", action="store_true",
|
|
380
|
+
help=(
|
|
381
|
+
"judge the git index of the files staged in the current repository "
|
|
382
|
+
"instead of the working tree, and report only findings about them; "
|
|
383
|
+
"for a pre-commit hook. Requires --config-only"
|
|
384
|
+
),
|
|
385
|
+
)
|
|
386
|
+
# choices, not a free string: an unrecognised name would otherwise build an
|
|
387
|
+
# empty filter, run nothing and report a clean tree, so a typo in the name of
|
|
388
|
+
# a check would read as "all clear".
|
|
389
|
+
ap.add_argument(
|
|
390
|
+
"--check", action="append", metavar="NAME", choices=config_checks.names(),
|
|
391
|
+
help=f"limit config checks to NAME (repeatable); one of {', '.join(config_checks.names())}",
|
|
392
|
+
)
|
|
393
|
+
args = ap.parse_args(argv)
|
|
394
|
+
if args.staged and not args.config_only:
|
|
395
|
+
ap.error("--staged applies to the config checks only: add --config-only")
|
|
396
|
+
|
|
397
|
+
cfg = rigops_config.load()
|
|
398
|
+
|
|
399
|
+
if args.config_only:
|
|
400
|
+
return report_config_checks(cfg, args)
|
|
401
|
+
|
|
402
|
+
configured = rigops_config.get(cfg, "doctor.registry")
|
|
403
|
+
is_default = configured == rigops_config.DEFAULTS["doctor"]["registry"]
|
|
404
|
+
registry_path = rigops_config.expand(
|
|
405
|
+
args.registry or (default_registry() if is_default else configured))
|
|
406
|
+
if not args.registry and is_default and not registry_path.exists():
|
|
407
|
+
print(f"note: no job registry at {rigops_core.short(registry_path)}; "
|
|
408
|
+
"job checks skipped", file=sys.stderr)
|
|
409
|
+
items = []
|
|
410
|
+
else:
|
|
411
|
+
items = rigops_registry.load_registry(registry_path)
|
|
412
|
+
|
|
413
|
+
if args.list:
|
|
414
|
+
if args.json:
|
|
415
|
+
print(json.dumps({"version": 1, "items": items}, indent=2, default=str))
|
|
416
|
+
else:
|
|
417
|
+
rows = [
|
|
418
|
+
[it.get("id", ""), it.get("domain", ""), it.get("trigger", ""),
|
|
419
|
+
it.get("cadence", "")]
|
|
420
|
+
for it in items
|
|
421
|
+
]
|
|
422
|
+
print(fmt.table(rows, ["id", "domain", "trigger", "cadence"]))
|
|
423
|
+
return 0
|
|
424
|
+
|
|
425
|
+
rigops_config.require_private(rigops_config.config_path(), registry_path)
|
|
426
|
+
doctor_state_dir = state.state_dir() / "doctor"
|
|
427
|
+
with state.locked(doctor_state_dir / "doctor"):
|
|
428
|
+
return _fleet_run(args, cfg, items)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _fleet_run(args, cfg: dict, items: list) -> int:
|
|
432
|
+
doctor_state_dir = state.state_dir() / "doctor"
|
|
433
|
+
heal_stamps_path = doctor_state_dir / "heal-stamps.json"
|
|
434
|
+
events_path = doctor_state_dir / "events.jsonl"
|
|
435
|
+
heal_stamps, stamps_bad = guard_state.load_guard_state(heal_stamps_path, numeric_values=True)
|
|
436
|
+
guard_problems = [(heal_stamps_path, stamps_bad)] if stamps_bad else []
|
|
437
|
+
cooldown_h = rigops_config.get(cfg, "doctor.heal_cooldown_h", 12)
|
|
438
|
+
kill_grace_s = rigops_config.get(cfg, "doctor.kill_grace_s", 5)
|
|
439
|
+
prefixes = rigops_config.get(cfg, "doctor.label_prefix", ["local."])
|
|
440
|
+
|
|
441
|
+
now = time.time()
|
|
442
|
+
ts = datetime.now(timezone.utc).strftime(rigops_core.UTC_STAMP)
|
|
443
|
+
cause_policy = rigops_config.get(cfg, "doctor.cause_policy", "off")
|
|
444
|
+
holds_path = doctor_state_dir / "holds.json"
|
|
445
|
+
cause_ctx = None
|
|
446
|
+
probe_warnings = []
|
|
447
|
+
if cause_policy in ("shadow", "on") and args.supervisor == "launchd":
|
|
448
|
+
probe_command = rigops_config.get(cfg, "doctor.cause_probe_command", "")
|
|
449
|
+
if not isinstance(probe_command, str):
|
|
450
|
+
probe_warnings.append(
|
|
451
|
+
f"cause_probe_command ignored: not a string ({type(probe_command).__name__})"
|
|
452
|
+
)
|
|
453
|
+
probe_command = probe_command.strip() if isinstance(probe_command, str) else ""
|
|
454
|
+
# A run that cannot kick must not spend a hold's retry, and a shadow run must not
|
|
455
|
+
# run the probe: it would be work the unchanged supervisor never did.
|
|
456
|
+
holds_raw, holds_bad = guard_state.load_guard_state(holds_path)
|
|
457
|
+
if holds_bad:
|
|
458
|
+
guard_problems.append((holds_path, holds_bad))
|
|
459
|
+
cause_ctx = {
|
|
460
|
+
"policy": cause_policy, "now": now, "undo": {},
|
|
461
|
+
"holds": rigops_cause.clean_holds(holds_raw),
|
|
462
|
+
"probe": (
|
|
463
|
+
_run_probe(probe_command, probe_warnings)
|
|
464
|
+
if probe_command and cause_policy == "on" and args.heal else None
|
|
465
|
+
),
|
|
466
|
+
"heal_stamps": heal_stamps, "label_ids": {}, "labels": {},
|
|
467
|
+
"killed": {
|
|
468
|
+
k[len(KILL_PREFIX):] for k in heal_stamps
|
|
469
|
+
if k.startswith(KILL_PREFIX) and _cooldown_active(heal_stamps, k, cooldown_h, now)
|
|
470
|
+
},
|
|
471
|
+
}
|
|
472
|
+
for item in items:
|
|
473
|
+
label = cause_ctx["labels"][id(item)] = _label_for_item(item, prefixes)
|
|
474
|
+
if label:
|
|
475
|
+
cause_ctx["label_ids"].setdefault(label, []).append(item.get("id", "unknown"))
|
|
476
|
+
jobs = []
|
|
477
|
+
for item in items:
|
|
478
|
+
job_id = item.get("id", "unknown")
|
|
479
|
+
cooldown_active = _cooldown_active(heal_stamps, job_id, cooldown_h, now)
|
|
480
|
+
if args.supervisor == "none":
|
|
481
|
+
job = _judge_evidence_only_item(item, cooldown_active)
|
|
482
|
+
else:
|
|
483
|
+
job = _judge_launchd_item(item, prefixes, cooldown_active, cause_ctx)
|
|
484
|
+
jobs.append(job)
|
|
485
|
+
|
|
486
|
+
would_log = []
|
|
487
|
+
if cause_ctx and cause_policy == "shadow":
|
|
488
|
+
would_log = [
|
|
489
|
+
{"id": j["id"], "cause": j["cause"], "action": j["action"], "would": j["would"],
|
|
490
|
+
"exit": j["exit"], "tail_sha": j["tail_sha"], "log": j["log"]}
|
|
491
|
+
for j in jobs if "would" in j
|
|
492
|
+
]
|
|
493
|
+
|
|
494
|
+
fail_closed = bool(guard_problems) and args.heal and args.supervisor == "launchd"
|
|
495
|
+
guard_findings = []
|
|
496
|
+
stamps_pinned = False
|
|
497
|
+
for path, reason in guard_problems:
|
|
498
|
+
moved = guard_state.move_aside(path, ts) if fail_closed else None
|
|
499
|
+
if not fail_closed:
|
|
500
|
+
outcome = "file left in place; a --heal run under launchd restarts nothing and moves it aside"
|
|
501
|
+
elif moved:
|
|
502
|
+
outcome = f"no job restarted and no hold released this run; moved aside to {moved.name}"
|
|
503
|
+
else:
|
|
504
|
+
outcome = "no job restarted and no hold released this run; file still in place"
|
|
505
|
+
stamps_pinned = stamps_pinned or (path == heal_stamps_path and not moved)
|
|
506
|
+
guard_findings.append(_guard_finding(path, reason, outcome))
|
|
507
|
+
|
|
508
|
+
heal_log = []
|
|
509
|
+
kicked_labels = set()
|
|
510
|
+
kicked_ids = set()
|
|
511
|
+
if args.heal and args.supervisor == "launchd":
|
|
512
|
+
for job in jobs:
|
|
513
|
+
if job["action"] == "kill" and job["pid"]:
|
|
514
|
+
current_pid = launchd.job_pid(job["label"])
|
|
515
|
+
if current_pid != job["pid"]:
|
|
516
|
+
heal_log.append(f"pid changed for {job['id']}, skip kill")
|
|
517
|
+
elif launchd.terminate_process_group(job["pid"], kill_grace_s):
|
|
518
|
+
heal_stamps[job["id"]] = heal_stamps[KILL_PREFIX + job["id"]] = now
|
|
519
|
+
heal_log.append(f"terminated hung job {job['id']} (pid {job['pid']})")
|
|
520
|
+
if not stamps_pinned:
|
|
521
|
+
_save_entries(heal_stamps_path, heal_stamps)
|
|
522
|
+
elif job["action"] == "kickstart" and job["label"] and not fail_closed:
|
|
523
|
+
if job["label"] in kicked_labels:
|
|
524
|
+
# One launchd label runs every job sharing it: a second kick is a double run.
|
|
525
|
+
heal_stamps[job["id"]] = now
|
|
526
|
+
kicked_ids.add(job["id"])
|
|
527
|
+
_save_entries(heal_stamps_path, heal_stamps)
|
|
528
|
+
elif launchd.kickstart(job["label"]):
|
|
529
|
+
kicked_labels.add(job["label"])
|
|
530
|
+
sharing = [j["id"] for j in jobs if j["label"] == job["label"]]
|
|
531
|
+
kicked_ids.update(sharing)
|
|
532
|
+
for sibling in sharing:
|
|
533
|
+
hold = cause_ctx["holds"].get(sibling) if cause_ctx else None
|
|
534
|
+
if hold and now not in hold["releases"]:
|
|
535
|
+
hold["releases"].append(now)
|
|
536
|
+
heal_stamps[job["id"]] = now
|
|
537
|
+
heal_log.append(f"kickstarted {job['id']} ({job['label']})")
|
|
538
|
+
_save_entries(heal_stamps_path, heal_stamps)
|
|
539
|
+
|
|
540
|
+
if cause_ctx and args.heal and not fail_closed:
|
|
541
|
+
for job_id, previous in cause_ctx["undo"].items():
|
|
542
|
+
if job_id not in kicked_ids:
|
|
543
|
+
if previous is None:
|
|
544
|
+
cause_ctx["holds"].pop(job_id, None)
|
|
545
|
+
else:
|
|
546
|
+
cause_ctx["holds"][job_id] = previous
|
|
547
|
+
keep = {
|
|
548
|
+
j["id"]: j.get("cause") for j in jobs
|
|
549
|
+
if j["runtime_h"] is not None or j["status"] == "failing"
|
|
550
|
+
}
|
|
551
|
+
cause_ctx["holds"] = {
|
|
552
|
+
k: v for k, v in cause_ctx["holds"].items()
|
|
553
|
+
if k in keep and (keep[k] is None or keep[k] == v["cause"])
|
|
554
|
+
}
|
|
555
|
+
_save_entries(holds_path, cause_ctx["holds"])
|
|
556
|
+
|
|
557
|
+
checks = []
|
|
558
|
+
for check_cfg in rigops_config.get(cfg, "doctor.checks.custom", []) or []:
|
|
559
|
+
checks.append(run_custom_check(check_cfg))
|
|
560
|
+
disk_free_cfg = rigops_config.get(cfg, "doctor.checks.disk_free")
|
|
561
|
+
if disk_free_cfg:
|
|
562
|
+
checks.append(run_disk_free_check(disk_free_cfg))
|
|
563
|
+
only = set(args.check or []) or None
|
|
564
|
+
findings = guard_findings + ([] if args.no_config else config_checks.run_checks(cfg, only=only))
|
|
565
|
+
|
|
566
|
+
fail_count = sum(1 for j in jobs if j["status"] in ("failing", "hung"))
|
|
567
|
+
# Reported, never paged: a stale row is a trend to read in the events log,
|
|
568
|
+
# not a nightly interruption, so it stays out of the notify predicate.
|
|
569
|
+
stale_count = sum(1 for j in jobs if j["status"] == "stale")
|
|
570
|
+
gates_path = rigops_core.local_state_path(rigops_core.GATES_STATE_NAME)
|
|
571
|
+
gates = _with_since(
|
|
572
|
+
_job_gate_entries(jobs) + _check_gate_entries(checks) + _config_gate_entries(findings),
|
|
573
|
+
_load_json(gates_path, None), ts,
|
|
574
|
+
)
|
|
575
|
+
red_for = {(g["kind"], g["name"]): _red_for(g["since"], ts) for g in gates}
|
|
576
|
+
report_text = render_report(ts, jobs, checks, heal_log, args.supervisor, red_for)
|
|
577
|
+
|
|
578
|
+
notify_command = rigops_config.get(cfg, "doctor.notify_command", "")
|
|
579
|
+
notify_stamps_path = doctor_state_dir / "notified.json"
|
|
580
|
+
kicked_path = doctor_state_dir / "kicked.json"
|
|
581
|
+
marked = _load_entries(kicked_path, {})
|
|
582
|
+
if isinstance(marked, list): # the shape before kicks were timed
|
|
583
|
+
marked = dict.fromkeys([m for m in marked if isinstance(m, str)], now)
|
|
584
|
+
silenced, marked = rigops_notify.kick_suppressed(
|
|
585
|
+
{k: v for k, v in marked.items() if isinstance(k, str)} if isinstance(marked, dict) else {},
|
|
586
|
+
kicked_ids, now,
|
|
587
|
+
)
|
|
588
|
+
notify_keys = (
|
|
589
|
+
rigops_notify.notify_keys(
|
|
590
|
+
jobs, checks, cause_ctx["holds"] if cause_policy == "on" and cause_ctx else None, now,
|
|
591
|
+
frozenset(silenced),
|
|
592
|
+
)
|
|
593
|
+
if notify_command else set()
|
|
594
|
+
)
|
|
595
|
+
due, stamps, held = rigops_notify.notify_due(
|
|
596
|
+
_load_dict(notify_stamps_path), notify_keys, now,
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
event = {
|
|
600
|
+
"ts": ts, "jobs_checked": len(jobs), "fail_count": fail_count,
|
|
601
|
+
"stale_count": stale_count, "healed": heal_log,
|
|
602
|
+
"failing": sorted(j["id"] for j in jobs if j["status"] in ("failing", "hung")),
|
|
603
|
+
"notified": [k for k in sorted(notify_keys) if k not in held] if due else [],
|
|
604
|
+
}
|
|
605
|
+
if held:
|
|
606
|
+
event["held"] = held
|
|
607
|
+
if cause_policy == "shadow":
|
|
608
|
+
event["would"] = would_log
|
|
609
|
+
state.append_jsonl(events_path, event)
|
|
610
|
+
for finding in guard_findings:
|
|
611
|
+
state.append_jsonl(events_path, {"ts": ts, "event": f"{finding.symptom}; {finding.fix}"})
|
|
612
|
+
for message in probe_warnings:
|
|
613
|
+
state.append_jsonl(events_path, {"ts": ts, "event": message})
|
|
614
|
+
|
|
615
|
+
# Saved before the send: a failed send must not hand the next kick a free silence.
|
|
616
|
+
if notify_command:
|
|
617
|
+
_save_entries(kicked_path, marked)
|
|
618
|
+
|
|
619
|
+
notify_error = ""
|
|
620
|
+
if due:
|
|
621
|
+
report_path = doctor_state_dir / "report-latest.txt"
|
|
622
|
+
state.atomic_write(report_path, report_text)
|
|
623
|
+
notify_error = _notify(notify_command, report_path)
|
|
624
|
+
if notify_error:
|
|
625
|
+
state.append_jsonl(events_path, {"ts": ts, "event": notify_error})
|
|
626
|
+
# A failed send leaves the keys unstamped so the next tick tries again.
|
|
627
|
+
if notify_command and not notify_error:
|
|
628
|
+
_save_entries(notify_stamps_path, stamps)
|
|
629
|
+
|
|
630
|
+
# Written every run, gates or none: an empty list still proves the doctor ran,
|
|
631
|
+
# which is what the session-start hook reading it needs to tell "clean" from "never checked".
|
|
632
|
+
try:
|
|
633
|
+
_save_json(gates_path, {"version": 1, "ts": ts, "gates": gates})
|
|
634
|
+
except OSError as exc:
|
|
635
|
+
print(f"warning: gates record not written: {exc}", file=sys.stderr)
|
|
636
|
+
|
|
637
|
+
unknown_keys = [key for key, note in rigops_config.unknown_keys(cfg) if note is None]
|
|
638
|
+
if args.json:
|
|
639
|
+
payload = {
|
|
640
|
+
"version": 1, "ts": ts, "supervisor": args.supervisor, "jobs": jobs, "checks": checks,
|
|
641
|
+
"healed": heal_log, "fail_count": fail_count, "stale_count": stale_count,
|
|
642
|
+
"gates": gates,
|
|
643
|
+
"unknown_config_keys": unknown_keys,
|
|
644
|
+
"findings": [
|
|
645
|
+
{"id": f.id, "check": f.check, "area": f.area, "severity": f.severity,
|
|
646
|
+
"symptom": f.symptom, "evidence": f.evidence, "fix": f.fix}
|
|
647
|
+
for f in findings
|
|
648
|
+
],
|
|
649
|
+
}
|
|
650
|
+
print(json.dumps(payload, indent=2, default=str))
|
|
651
|
+
elif args.report:
|
|
652
|
+
print(report_text, end="")
|
|
653
|
+
print(render_findings(findings), end="")
|
|
654
|
+
print(render_unknown_keys(unknown_keys), end="")
|
|
655
|
+
else:
|
|
656
|
+
print(render_summary(jobs, checks, findings, gates, ts), end="")
|
|
657
|
+
print(render_findings(findings), end="")
|
|
658
|
+
print(render_unknown_keys(unknown_keys), end="")
|
|
659
|
+
|
|
660
|
+
# Scheduled runs pass --exit-zero so the supervisor does not read a verdict as a crash.
|
|
661
|
+
failed_checks = any(c["status"] == "fail" for c in checks)
|
|
662
|
+
verdict = bool(fail_count or failed_checks or _failing(findings))
|
|
663
|
+
if guard_findings:
|
|
664
|
+
return 2
|
|
665
|
+
return exit_code(findings, verdict, args.exit_zero)
|
|
666
|
+
|