rigops 0.13.0rc1__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.0rc1.dist-info/METADATA +300 -0
- rigops-0.13.0rc1.dist-info/RECORD +86 -0
- rigops-0.13.0rc1.dist-info/WHEEL +5 -0
- rigops-0.13.0rc1.dist-info/entry_points.txt +2 -0
- rigops-0.13.0rc1.dist-info/licenses/LICENSE +21 -0
- rigops-0.13.0rc1.dist-info/top_level.txt +1 -0
rigops/__init__.py
ADDED
rigops/__main__.py
ADDED
rigops/authprobe.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Probe whether the headless `claude -p` credential still works.
|
|
2
|
+
|
|
3
|
+
A headless (launchd/cron) credential expires independently of interactive
|
|
4
|
+
login: interactive sessions keep working while every unattended run fails
|
|
5
|
+
silently. This probe runs under a scrubbed environment, because an
|
|
6
|
+
interactive Claude Code session exports variables that route auth through
|
|
7
|
+
the host session and would produce a false ok.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import getpass
|
|
13
|
+
import math
|
|
14
|
+
import os
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
|
|
19
|
+
from rigops import config as rigops_config
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_env(path: str, token: str = "") -> dict:
|
|
23
|
+
"""Minimal env for the probe subprocess -- nothing else is inherited."""
|
|
24
|
+
home = os.environ.get("HOME") or os.path.expanduser("~")
|
|
25
|
+
user = os.environ.get("USER") or getpass.getuser()
|
|
26
|
+
env = {"HOME": home, "USER": user, "PATH": path, "SHELL": "/bin/sh", "TERM": "dumb"}
|
|
27
|
+
if token:
|
|
28
|
+
env["CLAUDE_CODE_OAUTH_TOKEN"] = token
|
|
29
|
+
return env
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def keychain_token(service: str, timeout_s: float = 5, runner=subprocess.run) -> str:
|
|
33
|
+
"""Reads a long-lived token from the macOS keychain. A keychain item
|
|
34
|
+
added without -T triggers a GUI consent dialog on first read; the
|
|
35
|
+
timeout keeps that from hanging an unattended probe."""
|
|
36
|
+
if not service:
|
|
37
|
+
return ""
|
|
38
|
+
if shutil.which("security") is None:
|
|
39
|
+
return ""
|
|
40
|
+
user = os.environ.get("USER") or getpass.getuser()
|
|
41
|
+
try:
|
|
42
|
+
proc = runner(
|
|
43
|
+
["security", "find-generic-password", "-a", user, "-s", service, "-w"],
|
|
44
|
+
capture_output=True, text=True, timeout=timeout_s,
|
|
45
|
+
)
|
|
46
|
+
except (subprocess.TimeoutExpired, OSError):
|
|
47
|
+
return ""
|
|
48
|
+
if proc.returncode != 0:
|
|
49
|
+
return ""
|
|
50
|
+
return proc.stdout.strip()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def probe(cfg, runner=subprocess.run) -> tuple:
|
|
54
|
+
defaults = rigops_config.DEFAULTS["authprobe"]
|
|
55
|
+
command = rigops_config.get(cfg, "authprobe.command", defaults["command"])
|
|
56
|
+
expect = rigops_config.get(cfg, "authprobe.expect", defaults["expect"])
|
|
57
|
+
timeout_s = rigops_config.get(cfg, "authprobe.timeout_s", defaults["timeout_s"])
|
|
58
|
+
path = rigops_config.get(cfg, "authprobe.path", defaults["path"])
|
|
59
|
+
keychain_service = rigops_config.get(
|
|
60
|
+
cfg, "authprobe.keychain_service", defaults["keychain_service"]
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
if (
|
|
64
|
+
not isinstance(command, list)
|
|
65
|
+
or not command
|
|
66
|
+
or not all(isinstance(a, str) for a in command)
|
|
67
|
+
):
|
|
68
|
+
return False, "invalid authprobe.command"
|
|
69
|
+
if not isinstance(path, str) or not path:
|
|
70
|
+
path = defaults["path"]
|
|
71
|
+
try:
|
|
72
|
+
# The coerced float is what reaches subprocess -- a quoted number in
|
|
73
|
+
# config must not pass validation and then arrive as a string.
|
|
74
|
+
timeout_s = float(timeout_s)
|
|
75
|
+
if timeout_s <= 0 or not math.isfinite(timeout_s):
|
|
76
|
+
timeout_s = 60.0
|
|
77
|
+
except (TypeError, ValueError):
|
|
78
|
+
# Bad timeout still bounds the subprocess rather than hanging or
|
|
79
|
+
# crashing the caller.
|
|
80
|
+
timeout_s = 60.0
|
|
81
|
+
|
|
82
|
+
token = keychain_token(keychain_service)
|
|
83
|
+
env = build_env(path, token)
|
|
84
|
+
|
|
85
|
+
try:
|
|
86
|
+
proc = runner(
|
|
87
|
+
command, env=env, capture_output=True, text=True, timeout=timeout_s,
|
|
88
|
+
cwd=tempfile.gettempdir(),
|
|
89
|
+
)
|
|
90
|
+
except subprocess.TimeoutExpired:
|
|
91
|
+
return False, f"timeout after {timeout_s:g}s"
|
|
92
|
+
except OSError as exc:
|
|
93
|
+
return False, str(exc)
|
|
94
|
+
|
|
95
|
+
output = proc.stdout or ""
|
|
96
|
+
lines = output.splitlines()
|
|
97
|
+
if proc.returncode != 0:
|
|
98
|
+
first_nonempty = next((ln for ln in lines if ln.strip()), "")
|
|
99
|
+
if first_nonempty:
|
|
100
|
+
return False, first_nonempty
|
|
101
|
+
err_lines = (getattr(proc, "stderr", "") or "").splitlines()
|
|
102
|
+
first_err_nonempty = next((ln for ln in err_lines if ln.strip()), "")
|
|
103
|
+
return False, first_err_nonempty or f"exit {proc.returncode}"
|
|
104
|
+
if output.strip() != expect:
|
|
105
|
+
return False, lines[0] if lines else ""
|
|
106
|
+
return True, "ok"
|
rigops/backlog.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from rigops import state
|
|
8
|
+
|
|
9
|
+
LINE_RE = re.compile(r"^- \[( |x)\] (\d{4}-\d{2}-\d{2}) ([a-z]+): (.+)$")
|
|
10
|
+
|
|
11
|
+
OPEN_HEADING = "## Open"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def parse(text: str) -> dict:
|
|
15
|
+
"""Walk a backlog file's lines, splitting them into items and malformed candidates.
|
|
16
|
+
|
|
17
|
+
A candidate is any line starting with "- [" (checkbox syntax). Non-candidate
|
|
18
|
+
lines (prose, indented text) are ignored entirely -- they're not part of the
|
|
19
|
+
machine grammar.
|
|
20
|
+
"""
|
|
21
|
+
items = []
|
|
22
|
+
malformed = []
|
|
23
|
+
for line_no, line in enumerate(text.splitlines(), start=1):
|
|
24
|
+
if not line.startswith("- ["):
|
|
25
|
+
continue
|
|
26
|
+
m = LINE_RE.match(line)
|
|
27
|
+
if not m:
|
|
28
|
+
reason = "does not match backlog grammar"
|
|
29
|
+
malformed.append({"line_no": line_no, "line": line, "reason": reason})
|
|
30
|
+
continue
|
|
31
|
+
checkbox, date_str, area, rest = m.groups()
|
|
32
|
+
try:
|
|
33
|
+
datetime.strptime(date_str, "%Y-%m-%d")
|
|
34
|
+
except ValueError:
|
|
35
|
+
malformed.append({"line_no": line_no, "line": line, "reason": "invalid date"})
|
|
36
|
+
continue
|
|
37
|
+
items.append({
|
|
38
|
+
"line_no": line_no, "done": checkbox == "x", "date": date_str,
|
|
39
|
+
"area": area, "rest": rest,
|
|
40
|
+
})
|
|
41
|
+
return {"items": items, "malformed": malformed}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def lint(text: str, areas: list) -> dict:
|
|
45
|
+
parsed = parse(text)
|
|
46
|
+
items = parsed["items"]
|
|
47
|
+
unknown_area = [
|
|
48
|
+
{"line_no": it["line_no"], "area": it["area"]} for it in items if it["area"] not in areas
|
|
49
|
+
]
|
|
50
|
+
return {
|
|
51
|
+
"open": sum(1 for it in items if not it["done"]),
|
|
52
|
+
"done": sum(1 for it in items if it["done"]),
|
|
53
|
+
"malformed": parsed["malformed"],
|
|
54
|
+
"unknown_area": unknown_area,
|
|
55
|
+
"ok": not parsed["malformed"] and not unknown_area,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def format_line(date: str, area: str, text: str) -> str:
|
|
60
|
+
"""Build one open-item line. area format/membership is the caller's job (add_line)."""
|
|
61
|
+
if not text:
|
|
62
|
+
raise ValueError("text must not be empty")
|
|
63
|
+
if any(ord(c) < 0x20 for c in text):
|
|
64
|
+
raise ValueError("text must not contain control characters")
|
|
65
|
+
try:
|
|
66
|
+
datetime.strptime(date, "%Y-%m-%d")
|
|
67
|
+
except ValueError as exc:
|
|
68
|
+
raise ValueError(f"invalid date: {date!r}") from exc
|
|
69
|
+
return f"- [ ] {date} {area}: {text}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def add_line(path, area: str, text: str, date: str, areas: list) -> str:
|
|
73
|
+
"""Append (newest-first, under the '## Open' heading) a new open item. Returns the line."""
|
|
74
|
+
if area not in areas:
|
|
75
|
+
raise ValueError(f"unknown area {area!r}; must be one of {areas}")
|
|
76
|
+
line = format_line(date, area, text)
|
|
77
|
+
p = Path(path)
|
|
78
|
+
if not p.exists():
|
|
79
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
content = f"# Backlog\n\n{OPEN_HEADING}\n\n{line}\n\n## Done\n"
|
|
81
|
+
else:
|
|
82
|
+
lines = p.read_text(encoding="utf-8").splitlines()
|
|
83
|
+
try:
|
|
84
|
+
heading_idx = lines.index(OPEN_HEADING)
|
|
85
|
+
except ValueError as exc:
|
|
86
|
+
raise ValueError("no '## Open' heading") from exc
|
|
87
|
+
insert_at = heading_idx + 1
|
|
88
|
+
if insert_at < len(lines) and lines[insert_at] == "":
|
|
89
|
+
insert_at += 1
|
|
90
|
+
lines.insert(insert_at, line)
|
|
91
|
+
content = "\n".join(lines) + "\n"
|
|
92
|
+
state.atomic_write(p, content)
|
|
93
|
+
return line
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def has_open_line(text: str, needle: str) -> bool:
|
|
97
|
+
"""True when an OPEN item's raw line contains needle (dedup hook for janitor watermarks)."""
|
|
98
|
+
for line in text.splitlines():
|
|
99
|
+
if not line.startswith("- ["):
|
|
100
|
+
continue
|
|
101
|
+
m = LINE_RE.match(line)
|
|
102
|
+
if not m:
|
|
103
|
+
continue
|
|
104
|
+
checkbox = m.group(1)
|
|
105
|
+
if checkbox == " " and needle in line:
|
|
106
|
+
return True
|
|
107
|
+
return False
|
rigops/cause.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
CAUSES = ("auth", "quota", "network", "deterministic", "unknown")
|
|
7
|
+
|
|
8
|
+
_PROBE_FAIL_RE = re.compile(r"claude-auth-probe: FAIL \((auth|quota|network)\)")
|
|
9
|
+
_PROBE_EXIT_RE = re.compile(r"probe exit ([123])\b")
|
|
10
|
+
_PROBE_CODES = {"1": "auth", "2": "quota", "3": "network"}
|
|
11
|
+
_AUTH_RE = re.compile(r"Not logged in|Please run /login|auth-probe-failed", re.I)
|
|
12
|
+
_QUOTA_RE = re.compile(r"hit your|usage limit|\brate.?limit|\bquota\b", re.I)
|
|
13
|
+
_NETWORK_RE = re.compile(
|
|
14
|
+
r"nodename nor servname|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|Unable to connect|API Error: 5\d\d",
|
|
15
|
+
re.I,
|
|
16
|
+
)
|
|
17
|
+
_DETERMINISTIC_RE = re.compile(r"command not found|commit\.subject-type", re.I)
|
|
18
|
+
_DETERMINISTIC_EXITS = (126, 127)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def classify(exit_code, log_tail) -> str:
|
|
22
|
+
"""Name why a job failed from its exit status and the tail of its current run's log.
|
|
23
|
+
|
|
24
|
+
Pure. A cause that no signal names is "unknown", which keeps today's behaviour.
|
|
25
|
+
"""
|
|
26
|
+
if isinstance(exit_code, int) and exit_code > 255 and exit_code % 256 == 0:
|
|
27
|
+
exit_code //= 256 # launchctl reports the raw wait status
|
|
28
|
+
text = log_tail or ""
|
|
29
|
+
if exit_code in _DETERMINISTIC_EXITS or _DETERMINISTIC_RE.search(text):
|
|
30
|
+
return "deterministic"
|
|
31
|
+
last_probe = None
|
|
32
|
+
for m in _PROBE_FAIL_RE.finditer(text):
|
|
33
|
+
last_probe = (m.start(), m.group(1))
|
|
34
|
+
for m in _PROBE_EXIT_RE.finditer(text):
|
|
35
|
+
if last_probe is None or m.start() > last_probe[0]:
|
|
36
|
+
last_probe = (m.start(), _PROBE_CODES[m.group(1)])
|
|
37
|
+
if last_probe:
|
|
38
|
+
return last_probe[1]
|
|
39
|
+
if _AUTH_RE.search(text):
|
|
40
|
+
return "auth"
|
|
41
|
+
if _QUOTA_RE.search(text):
|
|
42
|
+
return "quota"
|
|
43
|
+
if _NETWORK_RE.search(text):
|
|
44
|
+
return "network"
|
|
45
|
+
return "unknown"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def tail_of(path, *, now: float, max_age_h: float, lines: int = 40, max_bytes: int = 16384) -> str:
|
|
49
|
+
"""Last lines of a job log, or "" when it is missing or older than max_age_h.
|
|
50
|
+
|
|
51
|
+
A log untouched for longer than the job's cadence cannot describe the run
|
|
52
|
+
that just failed, so it is ignored instead of misclassifying it.
|
|
53
|
+
"""
|
|
54
|
+
try:
|
|
55
|
+
p = Path(path)
|
|
56
|
+
st = p.stat()
|
|
57
|
+
if now - st.st_mtime > max_age_h * 3600:
|
|
58
|
+
return ""
|
|
59
|
+
with p.open("rb") as fh:
|
|
60
|
+
fh.seek(max(0, st.st_size - max_bytes))
|
|
61
|
+
data = fh.read()
|
|
62
|
+
except OSError:
|
|
63
|
+
return ""
|
|
64
|
+
kept = data.decode("utf-8", "replace").splitlines()[-lines:]
|
|
65
|
+
for i in range(len(kept) - 1, -1, -1):
|
|
66
|
+
if kept[i].startswith("====="):
|
|
67
|
+
kept = kept[i + 1:] or kept
|
|
68
|
+
break
|
|
69
|
+
return "\n".join(kept)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
HELD_CAUSES = ("auth", "quota", "network")
|
|
73
|
+
HOLD_RETRY_H = {"auth": 6.0, "quota": 4.0, "network": 1.0}
|
|
74
|
+
HOLD_NOTIFY_AFTER_H = {"auth": 0.0, "quota": 24.0, "network": 24.0}
|
|
75
|
+
NETWORK_MAX_RELEASES_PER_DAY = 3
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def clean_holds(raw) -> dict:
|
|
79
|
+
"""Keep only well-formed hold entries; anything else is dropped."""
|
|
80
|
+
if not isinstance(raw, dict):
|
|
81
|
+
return {}
|
|
82
|
+
num = (int, float)
|
|
83
|
+
out = {}
|
|
84
|
+
for k, v in raw.items():
|
|
85
|
+
if (
|
|
86
|
+
isinstance(v, dict) and v.get("cause") in HELD_CAUSES
|
|
87
|
+
and isinstance(v.get("since"), num) and isinstance(v.get("last_try"), num)
|
|
88
|
+
and isinstance(v.get("releases", []), list)
|
|
89
|
+
and all(isinstance(t, num) for t in v.get("releases", []))
|
|
90
|
+
):
|
|
91
|
+
out[k] = {**v, "releases": list(v.get("releases", []))}
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def log_paths(plist_path) -> list:
|
|
96
|
+
"""StandardErrorPath then StandardOutPath of a launchd plist; [] when unreadable."""
|
|
97
|
+
import plistlib
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
with Path(plist_path).expanduser().open("rb") as fh:
|
|
101
|
+
data = plistlib.load(fh)
|
|
102
|
+
if not isinstance(data, dict):
|
|
103
|
+
return []
|
|
104
|
+
except Exception:
|
|
105
|
+
return []
|
|
106
|
+
keys = ("StandardErrorPath", "StandardOutPath")
|
|
107
|
+
return [data[k] for k in keys if isinstance(data.get(k), str)]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def update_hold(
|
|
111
|
+
holds: dict, job_id: str, cause: str, now: float, probe=None, label_kicks=(),
|
|
112
|
+
) -> bool:
|
|
113
|
+
"""Advance one job's hold and say whether it may be kicked now.
|
|
114
|
+
|
|
115
|
+
Mutates holds. A new hold, or one for a different cause, starts held. After
|
|
116
|
+
the cause's retry interval the optional probe decides: a failing probe waits
|
|
117
|
+
a full interval again, a passing one (or none) releases a single kick.
|
|
118
|
+
A network hold with a probe skips the wait: the probe runs every call, a
|
|
119
|
+
failing one costs nothing, and the interval only spaces the kicks it releases.
|
|
120
|
+
Network releases are capped per day. label_kicks are the times the other jobs
|
|
121
|
+
on this launchd label were kicked: one label runs them all, so the spacing and
|
|
122
|
+
the cap count its kicks, not the job's own.
|
|
123
|
+
"""
|
|
124
|
+
entry = holds.get(job_id)
|
|
125
|
+
if not isinstance(entry, dict):
|
|
126
|
+
holds[job_id] = {"cause": cause, "since": now, "last_try": now, "releases": []}
|
|
127
|
+
return False
|
|
128
|
+
entry["cause"] = cause # a flapping cause keeps its clock, or the hold never expires
|
|
129
|
+
recent = [t for t in entry.get("releases", []) if now - t < 86400]
|
|
130
|
+
entry["releases"] = recent
|
|
131
|
+
kicks = recent + [t for t in label_kicks if now - t < 86400]
|
|
132
|
+
# A network hold with a probe asks it every run; the interval only spaces the kicks.
|
|
133
|
+
spaced_by_release = cause == "network" and probe is not None
|
|
134
|
+
last = max(kicks, default=None) if spaced_by_release else max([entry["last_try"], *kicks])
|
|
135
|
+
if last is not None and now - last < HOLD_RETRY_H[cause] * 3600:
|
|
136
|
+
return False
|
|
137
|
+
if cause == "network" and len(set(kicks)) >= NETWORK_MAX_RELEASES_PER_DAY:
|
|
138
|
+
return False
|
|
139
|
+
entry["last_try"] = now
|
|
140
|
+
if probe is not None and not probe():
|
|
141
|
+
return False
|
|
142
|
+
recent.append(now)
|
|
143
|
+
return True
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def hold_is_silent(holds: dict, job_id: str, cause: str, now: float) -> bool:
|
|
147
|
+
"""True while a held job is still inside its quiet period before it may page."""
|
|
148
|
+
entry = holds.get(job_id)
|
|
149
|
+
if not isinstance(entry, dict) or entry.get("cause") != cause:
|
|
150
|
+
return False
|
|
151
|
+
return now - entry["since"] < HOLD_NOTIFY_AFTER_H.get(cause, 0.0) * 3600
|
rigops/cli/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import sys
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
|
|
7
|
+
from rigops import state
|
|
8
|
+
from rigops.errors import RigopsError
|
|
9
|
+
|
|
10
|
+
COMMANDS: dict[str, str] = {
|
|
11
|
+
"authprobe": "Probe whether the headless claude credential still works.",
|
|
12
|
+
"backlog": "Lint or add to the governed one-line backlog.",
|
|
13
|
+
"config": "Get, locate or check the configuration.",
|
|
14
|
+
"doctor": "Health watchdog for the job fleet.",
|
|
15
|
+
"eit": "EIT usage report for session transcripts.",
|
|
16
|
+
"eval": "Run versioned eval cases and diff two runs.",
|
|
17
|
+
"janitor": "Declarative hygiene for rigops-managed state.",
|
|
18
|
+
"jobs": "Schedule, remove or check the launchd jobs.",
|
|
19
|
+
"ledger": "Write a ledger row, note an intervention, or diff two rows.",
|
|
20
|
+
"mine": "Mine repeated corrections.",
|
|
21
|
+
"reap": "Reap merged, unused git worktrees.",
|
|
22
|
+
"tax": "Fixed context tax: always-loaded config bytes.",
|
|
23
|
+
"version": "Print the installed version.",
|
|
24
|
+
}
|
|
25
|
+
EXPERIMENTAL = frozenset({"authprobe", "backlog", "eit", "mine"})
|
|
26
|
+
_DIRECT = frozenset({"hook"})
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def run(main: Callable[[], int]) -> int:
|
|
30
|
+
try:
|
|
31
|
+
return main()
|
|
32
|
+
except (RigopsError, state.MalformedJsonl) as exc:
|
|
33
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
34
|
+
return 2
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def usage() -> str:
|
|
38
|
+
width = max(map(len, COMMANDS))
|
|
39
|
+
rows = [f" {name.ljust(width)} {text}" for name, text in sorted(COMMANDS.items())]
|
|
40
|
+
experimental = ", ".join(sorted(EXPERIMENTAL))
|
|
41
|
+
return "\n".join([
|
|
42
|
+
"usage: rigops <command> [args...]",
|
|
43
|
+
"",
|
|
44
|
+
"commands:",
|
|
45
|
+
*rows,
|
|
46
|
+
"",
|
|
47
|
+
f"experimental (no compatibility promise): {experimental}",
|
|
48
|
+
"",
|
|
49
|
+
])
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def main(argv: list[str] | None = None) -> int:
|
|
53
|
+
args = sys.argv[1:] if argv is None else argv
|
|
54
|
+
if not args or args[0] in ("help", "-h", "--help"):
|
|
55
|
+
print(usage(), end="")
|
|
56
|
+
return 0
|
|
57
|
+
name, rest = args[0], args[1:]
|
|
58
|
+
if name == "--version":
|
|
59
|
+
name = "version"
|
|
60
|
+
if name not in COMMANDS and name not in _DIRECT:
|
|
61
|
+
print(f"error: unknown command '{name}'\n\n{usage()}", end="", file=sys.stderr)
|
|
62
|
+
return 2
|
|
63
|
+
module = importlib.import_module(f"rigops.cli.{name}")
|
|
64
|
+
if name in _DIRECT:
|
|
65
|
+
return module.main(rest)
|
|
66
|
+
return run(lambda: module.main(rest))
|
rigops/cli/authprobe.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from rigops import cli
|
|
8
|
+
from rigops import authprobe
|
|
9
|
+
from rigops import config as rigops_config
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv: list[str] | None = None) -> int:
|
|
13
|
+
ap = argparse.ArgumentParser(prog="rigops authprobe", description=cli.COMMANDS["authprobe"])
|
|
14
|
+
ap.add_argument("--json", action="store_true")
|
|
15
|
+
ap.add_argument(
|
|
16
|
+
"--force", action="store_true", help="run even when authprobe.enabled is false"
|
|
17
|
+
)
|
|
18
|
+
args = ap.parse_args(argv)
|
|
19
|
+
|
|
20
|
+
cfg = rigops_config.load()
|
|
21
|
+
defaults = rigops_config.DEFAULTS["authprobe"]
|
|
22
|
+
enabled = rigops_config.get(cfg, "authprobe.enabled", defaults["enabled"])
|
|
23
|
+
|
|
24
|
+
if not enabled and not args.force:
|
|
25
|
+
if args.json:
|
|
26
|
+
print(json.dumps({
|
|
27
|
+
"version": 1,
|
|
28
|
+
"ok": None,
|
|
29
|
+
"detail": "disabled (set authprobe.enabled true or pass --force)",
|
|
30
|
+
"enabled": False,
|
|
31
|
+
}))
|
|
32
|
+
else:
|
|
33
|
+
print("authprobe disabled (set authprobe.enabled true or pass --force)")
|
|
34
|
+
return 0
|
|
35
|
+
|
|
36
|
+
rigops_config.require_private(rigops_config.config_path())
|
|
37
|
+
ok, detail = authprobe.probe(cfg)
|
|
38
|
+
|
|
39
|
+
if args.json:
|
|
40
|
+
print(json.dumps({"version": 1, "ok": ok, "detail": detail, "enabled": enabled}))
|
|
41
|
+
elif ok:
|
|
42
|
+
print("authprobe: ok")
|
|
43
|
+
else:
|
|
44
|
+
print(f"authprobe: FAIL: {detail}", file=sys.stderr)
|
|
45
|
+
|
|
46
|
+
return 0 if ok else 1
|
|
47
|
+
|
rigops/cli/backlog.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from rigops import cli
|
|
10
|
+
from rigops import backlog as rigops_backlog
|
|
11
|
+
from rigops import config as rigops_config
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _backlog_path(cfg, arg_file) -> Path:
|
|
15
|
+
if arg_file:
|
|
16
|
+
return rigops_config.expand(arg_file)
|
|
17
|
+
return rigops_config.expand(rigops_config.get(cfg, "backlog.path"))
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def cmd_lint(args, cfg) -> int:
|
|
21
|
+
path = _backlog_path(cfg, args.file)
|
|
22
|
+
if not path.exists():
|
|
23
|
+
if args.json:
|
|
24
|
+
print(json.dumps({"version": 1, "open": 0, "done": 0, "malformed": [], "unknown_area": [],
|
|
25
|
+
"ok": True}, indent=2))
|
|
26
|
+
else:
|
|
27
|
+
print(f"no backlog file at {path}")
|
|
28
|
+
return 0
|
|
29
|
+
areas = rigops_config.get(cfg, "backlog.areas", [])
|
|
30
|
+
text = path.read_text(encoding="utf-8")
|
|
31
|
+
result = rigops_backlog.lint(text, areas)
|
|
32
|
+
|
|
33
|
+
if args.json:
|
|
34
|
+
print(json.dumps({"version": 1, **result}, indent=2))
|
|
35
|
+
return 0 if result["ok"] else 1
|
|
36
|
+
|
|
37
|
+
print(f"open={result['open']} done={result['done']}")
|
|
38
|
+
for m in result["malformed"]:
|
|
39
|
+
truncated = m["line"][:80]
|
|
40
|
+
print(f"line {m['line_no']}: {m['reason']}: {truncated}")
|
|
41
|
+
for u in result["unknown_area"]:
|
|
42
|
+
print(f"line {u['line_no']}: unknown area '{u['area']}'")
|
|
43
|
+
return 0 if result["ok"] else 1
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def cmd_add(args, cfg) -> int:
|
|
47
|
+
path = _backlog_path(cfg, args.file)
|
|
48
|
+
areas = rigops_config.get(cfg, "backlog.areas", [])
|
|
49
|
+
date = args.date or datetime.now().strftime("%Y-%m-%d")
|
|
50
|
+
|
|
51
|
+
area = args.area
|
|
52
|
+
text = args.text
|
|
53
|
+
if not area:
|
|
54
|
+
prefix, sep, rest = args.text.partition(": ")
|
|
55
|
+
if sep and prefix in areas:
|
|
56
|
+
area, text = prefix, rest
|
|
57
|
+
else:
|
|
58
|
+
print(
|
|
59
|
+
f"error: no --area given and no known area prefix found; areas: {areas}",
|
|
60
|
+
file=sys.stderr,
|
|
61
|
+
)
|
|
62
|
+
return 2
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
line = rigops_backlog.add_line(path, area, text, date, areas)
|
|
66
|
+
except ValueError as exc:
|
|
67
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
68
|
+
return 2
|
|
69
|
+
|
|
70
|
+
print(line)
|
|
71
|
+
return 0
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def main(argv: list[str] | None = None) -> int:
|
|
75
|
+
ap = argparse.ArgumentParser(prog="rigops backlog", description=cli.COMMANDS["backlog"])
|
|
76
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
77
|
+
|
|
78
|
+
lint_parser = sub.add_parser("lint", help="check backlog grammar and areas")
|
|
79
|
+
lint_parser.add_argument("--json", action="store_true")
|
|
80
|
+
lint_parser.add_argument("--file", help="backlog file path (default: config backlog.path)")
|
|
81
|
+
lint_parser.set_defaults(func=cmd_lint)
|
|
82
|
+
|
|
83
|
+
add_parser = sub.add_parser("add", help="append a new open backlog item")
|
|
84
|
+
add_parser.add_argument("text", help="symptom text, optionally prefixed 'area: '")
|
|
85
|
+
add_parser.add_argument("--area", help="backlog area (default: parsed from text prefix)")
|
|
86
|
+
add_parser.add_argument("--date", help="YYYY-MM-DD (default: today)")
|
|
87
|
+
add_parser.add_argument("--file", help="backlog file path (default: config backlog.path)")
|
|
88
|
+
add_parser.set_defaults(func=cmd_add)
|
|
89
|
+
|
|
90
|
+
args = ap.parse_args(argv)
|
|
91
|
+
cfg = rigops_config.load()
|
|
92
|
+
return args.func(args, cfg)
|
|
93
|
+
|
rigops/cli/config.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from rigops import cli
|
|
8
|
+
from rigops import config as rigops_config
|
|
9
|
+
from rigops import config_spec
|
|
10
|
+
from rigops.errors import RigopsError
|
|
11
|
+
|
|
12
|
+
_MISSING = object()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def cmd_get(args) -> int:
|
|
16
|
+
cfg = rigops_config.load()
|
|
17
|
+
value = rigops_config.get(cfg, args.key, _MISSING)
|
|
18
|
+
if value is _MISSING:
|
|
19
|
+
return 1
|
|
20
|
+
print(json.dumps(value, separators=(",", ":"), sort_keys=True))
|
|
21
|
+
return 0
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cmd_path(_args) -> int:
|
|
25
|
+
print(rigops_config.config_path())
|
|
26
|
+
return 0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def cmd_check(_args) -> int:
|
|
30
|
+
path = rigops_config.config_path()
|
|
31
|
+
try:
|
|
32
|
+
cfg = rigops_config.load()
|
|
33
|
+
except RigopsError as exc:
|
|
34
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
35
|
+
return 2
|
|
36
|
+
for key, note in rigops_config.unknown_keys(cfg):
|
|
37
|
+
if note is None:
|
|
38
|
+
print(f"warning: unknown config key: {key}", file=sys.stderr)
|
|
39
|
+
else:
|
|
40
|
+
print(f"removed in {config_spec.REMOVED_RELEASE}: {key} ({note})", file=sys.stderr)
|
|
41
|
+
print(f"config: OK ({path})")
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv: list[str] | None = None) -> int:
|
|
46
|
+
parser = argparse.ArgumentParser(prog="rigops config", description=cli.COMMANDS["config"])
|
|
47
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
48
|
+
|
|
49
|
+
get_parser = sub.add_parser("get", help="print a dotted config key")
|
|
50
|
+
get_parser.add_argument("key")
|
|
51
|
+
get_parser.set_defaults(func=cmd_get)
|
|
52
|
+
|
|
53
|
+
path_parser = sub.add_parser("path", help="print the resolved config file path")
|
|
54
|
+
path_parser.set_defaults(func=cmd_path)
|
|
55
|
+
|
|
56
|
+
check_parser = sub.add_parser("check", help="load config and report status")
|
|
57
|
+
check_parser.set_defaults(func=cmd_check)
|
|
58
|
+
|
|
59
|
+
args = parser.parse_args(argv)
|
|
60
|
+
return args.func(args)
|
|
61
|
+
|