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/tax.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import datetime as dt
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from rigops import cli
|
|
9
|
+
from rigops import config as rigops_config
|
|
10
|
+
from rigops import fmt
|
|
11
|
+
from rigops import levers
|
|
12
|
+
from rigops import starts
|
|
13
|
+
from rigops import state
|
|
14
|
+
from rigops import transcripts
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def cmd_current(cfg, as_json: bool) -> int:
|
|
18
|
+
paths_cfg = rigops_config.get(cfg, "fixed_tax.paths", []) or []
|
|
19
|
+
globs_cfg = rigops_config.get(cfg, "fixed_tax.globs", []) or []
|
|
20
|
+
if not paths_cfg and not globs_cfg:
|
|
21
|
+
if as_json:
|
|
22
|
+
print(json.dumps({"version": 1, "files": [], "total_bytes": 0}, indent=2))
|
|
23
|
+
else:
|
|
24
|
+
print("fixed_tax not configured (fixed_tax.paths and fixed_tax.globs both empty)")
|
|
25
|
+
return 0
|
|
26
|
+
|
|
27
|
+
entries = levers.fixed_tax_entries(cfg)
|
|
28
|
+
if not entries:
|
|
29
|
+
if as_json:
|
|
30
|
+
print(json.dumps({"version": 1, "files": [], "total_bytes": 0}, indent=2))
|
|
31
|
+
else:
|
|
32
|
+
print("fixed_tax configured but no matching files found")
|
|
33
|
+
return 0
|
|
34
|
+
|
|
35
|
+
entries = sorted(entries, key=lambda e: e[1], reverse=True)
|
|
36
|
+
total = sum(size for _, size in entries)
|
|
37
|
+
|
|
38
|
+
if as_json:
|
|
39
|
+
payload = {
|
|
40
|
+
"version": 1,
|
|
41
|
+
"files": [{"path": str(p), "bytes": size} for p, size in entries],
|
|
42
|
+
"total_bytes": total,
|
|
43
|
+
}
|
|
44
|
+
print(json.dumps(payload, indent=2))
|
|
45
|
+
return 0
|
|
46
|
+
|
|
47
|
+
rows = [[str(p), fmt.human_bytes(size)] for p, size in entries]
|
|
48
|
+
print(fmt.table(rows, ["file", "size"]))
|
|
49
|
+
print(f"total: {fmt.human_bytes(total)}")
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def cmd_history(as_json: bool) -> int:
|
|
54
|
+
jsonl_path = state.state_dir() / "ledger.jsonl"
|
|
55
|
+
rows, skipped = state.read_rows(jsonl_path, lambda r: isinstance(r.get("date"), str))
|
|
56
|
+
if skipped:
|
|
57
|
+
print(f"warning: skipped {skipped} unreadable ledger row(s)", file=sys.stderr)
|
|
58
|
+
if not rows:
|
|
59
|
+
if as_json:
|
|
60
|
+
print(json.dumps({"version": 1, "rows": [], "skipped": skipped}, indent=2))
|
|
61
|
+
else:
|
|
62
|
+
print("no ledger rows yet")
|
|
63
|
+
return 0
|
|
64
|
+
|
|
65
|
+
series = [(r.get("date"), r.get("fixed_tax_b")) for r in rows]
|
|
66
|
+
|
|
67
|
+
if as_json:
|
|
68
|
+
print(json.dumps({"version": 1, "skipped": skipped,
|
|
69
|
+
"rows": [{"date": d, "fixed_tax_b": v} for d, v in series]}, indent=2))
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
print(fmt.sparkline(v for _, v in series))
|
|
73
|
+
non_none = [(d, v) for d, v in series if v is not None]
|
|
74
|
+
if not non_none:
|
|
75
|
+
print("no fixed_tax_b data in ledger")
|
|
76
|
+
return 0
|
|
77
|
+
first_date, first_val = non_none[0]
|
|
78
|
+
last_date, last_val = non_none[-1]
|
|
79
|
+
delta = last_val - first_val
|
|
80
|
+
print(f"first {first_date}: {fmt.human_bytes(first_val)}")
|
|
81
|
+
print(f"last {last_date}: {fmt.human_bytes(last_val)}")
|
|
82
|
+
if first_val:
|
|
83
|
+
print(f"delta: {delta:+d} B ({delta / first_val * 100:+.1f}%)")
|
|
84
|
+
else:
|
|
85
|
+
print(f"delta: {delta:+d} B")
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _k(chars) -> str:
|
|
90
|
+
return f"{chars / 1000:.1f}k"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _print_session(start: dict, top: int) -> None:
|
|
94
|
+
print(
|
|
95
|
+
f"{start['session']} {start['ts'].isoformat()} {start['surface']} "
|
|
96
|
+
f"project {start['project']}"
|
|
97
|
+
)
|
|
98
|
+
print(
|
|
99
|
+
f"tools {start['tools']}, tool schemas {_k(start['tool_chars'])} chars, "
|
|
100
|
+
f"system {_k(start['system_chars'])} chars"
|
|
101
|
+
)
|
|
102
|
+
groups = sorted(start["groups"].items(), key=lambda kv: (-kv[1]["chars"], kv[0]))
|
|
103
|
+
print(fmt.table(
|
|
104
|
+
[[g, str(v["tools"]), _k(v["chars"])] for g, v in groups], ["group", "tools", "chars"],
|
|
105
|
+
))
|
|
106
|
+
largest = sorted(start["tool_sizes"].items(), key=lambda kv: (-kv[1], kv[0]))[:top]
|
|
107
|
+
print(f"largest {len(largest)} tools:")
|
|
108
|
+
print(fmt.table([[n, _k(c)] for n, c in largest], ["tool", "chars"]))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _jsonable(start: dict) -> dict:
|
|
112
|
+
return {**start, "ts": start["ts"].isoformat()}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def cmd_starts(args) -> int:
|
|
116
|
+
now = dt.datetime.now(dt.timezone.utc)
|
|
117
|
+
since_raw = args.since or (None if args.session else "-7d")
|
|
118
|
+
since = transcripts.parse_bound(since_raw, now)
|
|
119
|
+
until = transcripts.parse_bound(args.until, now) if args.until else None
|
|
120
|
+
tdir = rigops_config.expand(args.transcripts_dir) if args.transcripts_dir else None
|
|
121
|
+
found = starts.collect_starts(
|
|
122
|
+
since, until, transcripts_dir=tdir, subagents=args.subagents, session=args.session,
|
|
123
|
+
)
|
|
124
|
+
if args.session:
|
|
125
|
+
if not found:
|
|
126
|
+
print(f"no session start matching {args.session} in the window", file=sys.stderr)
|
|
127
|
+
return 1
|
|
128
|
+
if args.json:
|
|
129
|
+
print(json.dumps({"version": 1, "rows": [_jsonable(s) for s in found]}, indent=2))
|
|
130
|
+
return 0
|
|
131
|
+
for i, start in enumerate(found):
|
|
132
|
+
if i:
|
|
133
|
+
print()
|
|
134
|
+
_print_session(start, args.top)
|
|
135
|
+
return 0
|
|
136
|
+
summary = starts.summarize(found)
|
|
137
|
+
if args.json:
|
|
138
|
+
print(json.dumps({"version": 1, **summary}, indent=2))
|
|
139
|
+
return 0
|
|
140
|
+
if not found:
|
|
141
|
+
print("no session starts with a recorded request shape in the window")
|
|
142
|
+
return 0
|
|
143
|
+
print(f"session starts since {since.astimezone().date().isoformat()}: {summary['starts']}")
|
|
144
|
+
print(fmt.table(
|
|
145
|
+
[
|
|
146
|
+
[name, str(v["starts"]), f"{v['tools_p50']:g}", _k(v["tool_chars_p50"]),
|
|
147
|
+
_k(v["system_chars_p50"])]
|
|
148
|
+
for name, v in summary["surfaces"].items()
|
|
149
|
+
],
|
|
150
|
+
["surface", "starts", "tools p50", "tool chars p50", "system chars p50"],
|
|
151
|
+
))
|
|
152
|
+
print("tool groups, ranked by chars x starts:")
|
|
153
|
+
print(fmt.table(
|
|
154
|
+
[[g["group"], str(g["starts"]), _k(g["chars_p50"])] for g in summary["groups"][:args.top]],
|
|
155
|
+
["group", "starts", "chars p50"],
|
|
156
|
+
))
|
|
157
|
+
return 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def cmd_dead(args) -> int:
|
|
161
|
+
now = dt.datetime.now(dt.timezone.utc)
|
|
162
|
+
since = transcripts.parse_bound(args.since or "-30d", now)
|
|
163
|
+
until = transcripts.parse_bound(args.until, now) if args.until else None
|
|
164
|
+
tdir = rigops_config.expand(args.transcripts_dir) if args.transcripts_dir else None
|
|
165
|
+
found = starts.collect_starts(since, until, transcripts_dir=tdir, subagents=args.subagents)
|
|
166
|
+
calls = starts.count_calls(since, until, transcripts_dir=tdir)
|
|
167
|
+
report = starts.dead_weight(found, calls, args.max_per_100)
|
|
168
|
+
if args.json:
|
|
169
|
+
print(json.dumps({"version": 1, **report}, indent=2))
|
|
170
|
+
return 0
|
|
171
|
+
if not found:
|
|
172
|
+
print("no session starts with a recorded request shape in the window")
|
|
173
|
+
return 0
|
|
174
|
+
print(
|
|
175
|
+
f"session starts since {since.astimezone().date().isoformat()}: {report['starts']}; "
|
|
176
|
+
f"loaded but called at most {args.max_per_100:g} times per 100 loads:"
|
|
177
|
+
)
|
|
178
|
+
head = ["sessions", "calls", "chars p50", "carried"]
|
|
179
|
+
|
|
180
|
+
def cells(r):
|
|
181
|
+
return [str(r["sessions"]), str(r["calls"]), _k(r["chars_p50"]), _k(r["carried"])]
|
|
182
|
+
|
|
183
|
+
groups = report["groups"][:args.top]
|
|
184
|
+
print(fmt.table([[g["name"], str(g["tools"]), *cells(g)] for g in groups],
|
|
185
|
+
["group", "tools", *head]) if groups else "groups: none")
|
|
186
|
+
tools = report["tools"][:args.top]
|
|
187
|
+
print(fmt.table([[t["name"], *cells(t)] for t in tools], ["tool", *head])
|
|
188
|
+
if tools else "tools: none")
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def main(argv: list[str] | None = None) -> int:
|
|
193
|
+
ap = argparse.ArgumentParser(prog="rigops tax", description=cli.COMMANDS["tax"])
|
|
194
|
+
ap.add_argument("--history", action="store_true", help="fixed_tax_b trend across the ledger")
|
|
195
|
+
ap.add_argument(
|
|
196
|
+
"--starts", action="store_true",
|
|
197
|
+
help="what session starts load: tool schemas and system prompt, per surface",
|
|
198
|
+
)
|
|
199
|
+
ap.add_argument(
|
|
200
|
+
"--dead", action="store_true",
|
|
201
|
+
help="tools and tool groups loaded at session start but rarely or never called",
|
|
202
|
+
)
|
|
203
|
+
ap.add_argument(
|
|
204
|
+
"--max-per-100", type=float, default=1.0,
|
|
205
|
+
help="with --dead: most calls per 100 loading sessions still counted as dead (default 1)",
|
|
206
|
+
)
|
|
207
|
+
ap.add_argument(
|
|
208
|
+
"--since", default=None,
|
|
209
|
+
help="ISO date, 'today' or '-Nd' (--starts default -7d, unbounded with --session; "
|
|
210
|
+
"--dead default -30d)",
|
|
211
|
+
)
|
|
212
|
+
ap.add_argument("--until", default=None, help="with --starts or --dead: ISO date")
|
|
213
|
+
ap.add_argument("--session", default=None, help="with --starts: one session id (prefix)")
|
|
214
|
+
ap.add_argument("--subagents", action="store_true", help="with --starts: count subagents too")
|
|
215
|
+
ap.add_argument("--top", type=int, default=15, help="rows per ranked table")
|
|
216
|
+
ap.add_argument("--dir", dest="transcripts_dir", default=None, help="transcripts root")
|
|
217
|
+
ap.add_argument("--json", action="store_true")
|
|
218
|
+
args = ap.parse_args(transcripts.attach_dash_values(sys.argv[1:] if argv is None else argv))
|
|
219
|
+
|
|
220
|
+
if args.transcripts_dir is not None:
|
|
221
|
+
resolved = rigops_config.expand(args.transcripts_dir)
|
|
222
|
+
if not resolved.is_dir():
|
|
223
|
+
print(f"error: --dir not found: {resolved}", file=sys.stderr)
|
|
224
|
+
return 2
|
|
225
|
+
|
|
226
|
+
cfg = rigops_config.load()
|
|
227
|
+
if args.dead:
|
|
228
|
+
return cmd_dead(args)
|
|
229
|
+
if args.starts:
|
|
230
|
+
return cmd_starts(args)
|
|
231
|
+
if args.history:
|
|
232
|
+
try:
|
|
233
|
+
return cmd_history(args.json)
|
|
234
|
+
except state.MalformedJsonl as exc:
|
|
235
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
236
|
+
return 2
|
|
237
|
+
return cmd_current(cfg, args.json)
|
|
238
|
+
|
rigops/cli/version.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
|
|
5
|
+
from rigops import __version__, cli
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv: list[str] | None = None) -> int:
|
|
9
|
+
parser = argparse.ArgumentParser(prog="rigops version", description=cli.COMMANDS["version"])
|
|
10
|
+
parser.parse_args(argv)
|
|
11
|
+
print(__version__)
|
|
12
|
+
return 0
|
rigops/config.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from rigops import config_spec
|
|
9
|
+
from rigops.errors import RigopsError
|
|
10
|
+
|
|
11
|
+
DEFAULTS = config_spec.DEFAULTS
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def config_path() -> Path:
|
|
15
|
+
env_path = os.environ.get("RIGOPS_CONFIG")
|
|
16
|
+
if env_path:
|
|
17
|
+
return expand(env_path)
|
|
18
|
+
xdg = os.environ.get("XDG_CONFIG_HOME") or "~/.config"
|
|
19
|
+
return expand(Path(xdg) / "rigops" / "config.json")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def require_private(*paths) -> None:
|
|
23
|
+
"""Refuse a file that exists and, symlinks followed, group or others can write.
|
|
24
|
+
|
|
25
|
+
Config and registry name the commands rigops runs and the paths it deletes,
|
|
26
|
+
so whoever can write them can run code as this user.
|
|
27
|
+
"""
|
|
28
|
+
for path in paths:
|
|
29
|
+
try:
|
|
30
|
+
mode = os.stat(path).st_mode
|
|
31
|
+
except OSError:
|
|
32
|
+
continue
|
|
33
|
+
if mode & 0o022:
|
|
34
|
+
raise RigopsError(
|
|
35
|
+
f"{path} is writable by group or others; refusing to run commands "
|
|
36
|
+
f"from it (chmod go-w {path})"
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _deep_merge(base, overlay):
|
|
41
|
+
merged = dict(base)
|
|
42
|
+
for key, value in overlay.items():
|
|
43
|
+
if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
|
|
44
|
+
merged[key] = _deep_merge(merged[key], value)
|
|
45
|
+
else:
|
|
46
|
+
merged[key] = value
|
|
47
|
+
return merged
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def load(path=None) -> dict:
|
|
51
|
+
cfg_path = Path(path) if path is not None else config_path()
|
|
52
|
+
if not cfg_path.exists():
|
|
53
|
+
return copy.deepcopy(DEFAULTS)
|
|
54
|
+
try:
|
|
55
|
+
text = cfg_path.read_text(encoding="utf-8")
|
|
56
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
57
|
+
raise RigopsError(f"cannot read config {cfg_path}: {exc}") from exc
|
|
58
|
+
try:
|
|
59
|
+
overlay = json.loads(text)
|
|
60
|
+
except json.JSONDecodeError as exc:
|
|
61
|
+
raise RigopsError(f"invalid JSON in config {cfg_path}: {exc}") from exc
|
|
62
|
+
if not isinstance(overlay, dict):
|
|
63
|
+
raise RigopsError(f"config {cfg_path} must be a JSON object")
|
|
64
|
+
merged = _deep_merge(DEFAULTS, overlay)
|
|
65
|
+
config_spec.validate(merged)
|
|
66
|
+
return merged
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def unknown_keys(cfg) -> list:
|
|
70
|
+
return config_spec.audit(cfg)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def get(cfg, dotted, default=None):
|
|
74
|
+
node = cfg
|
|
75
|
+
for part in dotted.split("."):
|
|
76
|
+
if not isinstance(node, dict) or part not in node:
|
|
77
|
+
return default
|
|
78
|
+
node = node[part]
|
|
79
|
+
return node
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def expand(p) -> Path:
|
|
83
|
+
return Path(os.path.expanduser(os.path.expandvars(str(p))))
|
rigops/config_spec.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from rigops.errors import RigopsError
|
|
9
|
+
|
|
10
|
+
UNSET = object()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class Type:
|
|
15
|
+
label: str
|
|
16
|
+
check: Callable[[Any, str], None]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _kind(value: Any) -> str:
|
|
20
|
+
if value is None:
|
|
21
|
+
return "null"
|
|
22
|
+
if isinstance(value, bool):
|
|
23
|
+
return "boolean"
|
|
24
|
+
if isinstance(value, int):
|
|
25
|
+
return "integer"
|
|
26
|
+
if isinstance(value, float):
|
|
27
|
+
return "number"
|
|
28
|
+
if isinstance(value, str):
|
|
29
|
+
return "string"
|
|
30
|
+
return "array" if isinstance(value, list) else "object"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _fail(path: str, want: str, value: Any) -> None:
|
|
34
|
+
raise RigopsError(f"config key {path}: expected {want}, got {_kind(value)}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _scalar(label: str, accepts: Callable[[Any], bool]) -> Type:
|
|
38
|
+
def check(value: Any, path: str) -> None:
|
|
39
|
+
if not accepts(value):
|
|
40
|
+
_fail(path, label, value)
|
|
41
|
+
return Type(label, check)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _is_int(value: Any) -> bool:
|
|
45
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
BOOL = _scalar("boolean", lambda v: isinstance(v, bool))
|
|
49
|
+
INT = _scalar("integer", _is_int)
|
|
50
|
+
NUMBER = _scalar("number", lambda v: _is_int(v) or isinstance(v, float))
|
|
51
|
+
STRING = _scalar("string", lambda v: isinstance(v, str))
|
|
52
|
+
ANY = Type("any value", lambda value, path: None)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def list_of(item: Type) -> Type:
|
|
56
|
+
def check(value: Any, path: str) -> None:
|
|
57
|
+
if not isinstance(value, list):
|
|
58
|
+
_fail(path, f"array of {item.label}", value)
|
|
59
|
+
for index, entry in enumerate(value):
|
|
60
|
+
item.check(entry, f"{path}[{index}]")
|
|
61
|
+
return Type(f"array of {item.label}", check)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def open_map(item: Type = ANY) -> Type:
|
|
65
|
+
def check(value: Any, path: str) -> None:
|
|
66
|
+
if not isinstance(value, dict):
|
|
67
|
+
_fail(path, f"object of {item.label}", value)
|
|
68
|
+
for name, entry in value.items():
|
|
69
|
+
item.check(entry, f"{path}.{name}")
|
|
70
|
+
return Type(f"object of {item.label}", check)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def nullable(inner: Type) -> Type:
|
|
74
|
+
def check(value: Any, path: str) -> None:
|
|
75
|
+
if value is not None:
|
|
76
|
+
inner.check(value, path)
|
|
77
|
+
return Type(f"{inner.label} or null", check)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def one_of(*options: Type) -> Type:
|
|
81
|
+
label = " or ".join(option.label for option in options)
|
|
82
|
+
|
|
83
|
+
def check(value: Any, path: str) -> None:
|
|
84
|
+
for option in options:
|
|
85
|
+
try:
|
|
86
|
+
option.check(value, path)
|
|
87
|
+
except RigopsError:
|
|
88
|
+
continue
|
|
89
|
+
return
|
|
90
|
+
_fail(path, label, value)
|
|
91
|
+
return Type(label, check)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def obj(**fields: Type) -> Type:
|
|
95
|
+
"""An object whose listed fields are typed; other fields are left alone."""
|
|
96
|
+
def check(value: Any, path: str) -> None:
|
|
97
|
+
if not isinstance(value, dict):
|
|
98
|
+
_fail(path, "object", value)
|
|
99
|
+
for name, field_type in fields.items():
|
|
100
|
+
if name in value:
|
|
101
|
+
field_type.check(value[name], f"{path}.{name}")
|
|
102
|
+
return Type("object", check)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
JANITOR_ACTIONS = {
|
|
106
|
+
"report": {},
|
|
107
|
+
"delete": {},
|
|
108
|
+
"keep_newest_n": {"keep": INT},
|
|
109
|
+
"truncate": {"keep_lines": INT, "archive": BOOL},
|
|
110
|
+
"command": {"command": STRING, "timeout_s": NUMBER},
|
|
111
|
+
}
|
|
112
|
+
_JANITOR_COMMON = {
|
|
113
|
+
"name": STRING, "path": STRING, "glob": STRING, "older_than_days": NUMBER,
|
|
114
|
+
"max_depth": INT, "dirs": BOOL, "only_empty": BOOL,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _janitor_rule(value: Any, path: str) -> None:
|
|
119
|
+
if not isinstance(value, dict):
|
|
120
|
+
_fail(path, "object", value)
|
|
121
|
+
action = value.get("action", "report")
|
|
122
|
+
if not isinstance(action, str) or action not in JANITOR_ACTIONS:
|
|
123
|
+
names = ", ".join(sorted(JANITOR_ACTIONS))
|
|
124
|
+
raise RigopsError(f"config key {path}.action: expected one of {names}, got {action!r}")
|
|
125
|
+
for name, field_type in {**_JANITOR_COMMON, **JANITOR_ACTIONS[action]}.items():
|
|
126
|
+
if name in value:
|
|
127
|
+
field_type.check(value[name], f"{path}.{name}")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
JANITOR_RULE = Type("janitor rule", _janitor_rule)
|
|
131
|
+
WATERMARK = obj(name=STRING, path=STRING, max_files=INT, max_kb=NUMBER, area=STRING)
|
|
132
|
+
CUSTOM_CHECK = obj(name=STRING, command=STRING, warn_exit=INT, fail_exit=INT, timeout_s=NUMBER)
|
|
133
|
+
DISK_FREE = obj(path=STRING, warn_gb=NUMBER, fail_gb=NUMBER)
|
|
134
|
+
CUSTOM_SOURCE = obj(name=STRING, argv=list_of(STRING), timeout_s=NUMBER)
|
|
135
|
+
DERIVED_REPO = one_of(STRING, obj(repo=STRING, paths=list_of(STRING)))
|
|
136
|
+
STRINGS = list_of(STRING)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@dataclass(frozen=True)
|
|
140
|
+
class Key:
|
|
141
|
+
path: str
|
|
142
|
+
type: Type
|
|
143
|
+
default: Any
|
|
144
|
+
doc: str
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _k(path: str, type_: Type, default: Any, doc: str) -> Key:
|
|
148
|
+
return Key(path, type_, default, doc)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
SPEC: tuple[Key, ...] = (
|
|
152
|
+
_k("transcripts_dir", STRING, "~/.claude/projects",
|
|
153
|
+
"Root of the Claude Code project transcripts."),
|
|
154
|
+
_k("ledger.watch_projects", open_map(STRING), {}, "Column name to transcript-path substring."),
|
|
155
|
+
_k("ledger.derive_interventions", list_of(DERIVED_REPO), [],
|
|
156
|
+
"Repos whose commits count as interventions."),
|
|
157
|
+
_k("ledger.extra_correction_patterns", STRINGS, [],
|
|
158
|
+
"Regexes that also count a prompt as a correction."),
|
|
159
|
+
_k("ledger.correction_exclude_patterns", STRINGS, [],
|
|
160
|
+
"Regexes that stop a line counting as a correction."),
|
|
161
|
+
_k("ledger.extra_denial_patterns", STRINGS, [],
|
|
162
|
+
"Regexes that also count a tool error as a denial."),
|
|
163
|
+
_k("ledger.week_reports", STRING, UNSET, "Glob of weekly reports written by other tools."),
|
|
164
|
+
_k("fixed_tax.paths", STRINGS, [], "Files always counted toward the fixed tax."),
|
|
165
|
+
_k("fixed_tax.globs", STRINGS, [],
|
|
166
|
+
"Globs of always-loaded files counted toward the fixed tax."),
|
|
167
|
+
_k("friction.headless_projects", STRINGS, [],
|
|
168
|
+
"Transcript-path substrings counted as headless."),
|
|
169
|
+
_k("context.nudge_tiers", list_of(INT), [250000, 350000, 500000],
|
|
170
|
+
"Ascending token thresholds for the context nudge."),
|
|
171
|
+
_k("context.rearm_tokens", INT, 50000, "Token climb needed to re-fire the nudge."),
|
|
172
|
+
_k("context.card.doctor_max_age_h", NUMBER, 2,
|
|
173
|
+
"Hours before a doctor gate record counts as stale."),
|
|
174
|
+
_k("doctor.registry", STRING, "~/.config/rigops/registry.md", "Path of the job registry file."),
|
|
175
|
+
_k("doctor.label_prefix", STRINGS, ["local."],
|
|
176
|
+
"launchd label prefixes tried for a registry item."),
|
|
177
|
+
_k("doctor.kill_grace_s", NUMBER, 5, "Seconds between SIGTERM and SIGKILL for a hung job."),
|
|
178
|
+
_k("doctor.heal_cooldown_h", NUMBER, 12, "Hours a repeat heal of the same job is suppressed."),
|
|
179
|
+
_k("doctor.checks.custom", list_of(CUSTOM_CHECK), [], "Custom checks judged by exit code."),
|
|
180
|
+
_k("doctor.checks.disk_free", nullable(DISK_FREE), None, "Disk free check; null skips it."),
|
|
181
|
+
_k("doctor.notify_command", STRING, "", "Command run with the report path when a page is due."),
|
|
182
|
+
_k("doctor.cause_policy", STRING, "off", "Failure-cause policy: off, shadow or on."),
|
|
183
|
+
_k("doctor.cause_probe_command", STRING, "", "Command whose exit 0 releases one held kick."),
|
|
184
|
+
_k("doctor.budget.always_on_tokens", INT, 6000,
|
|
185
|
+
"Ceiling for the always-loaded instruction tokens."),
|
|
186
|
+
_k("doctor.levers.rules", open_map(ANY), {}, "Lever rules keyed by ledger column."),
|
|
187
|
+
_k("doctor.levers.defaults", BOOL, True, "False drops the built-in lever rules."),
|
|
188
|
+
_k("doctor.levers.max_age_days", INT, 10, "Days before the newest ledger row is stale."),
|
|
189
|
+
_k("doctor.memory.sources", STRINGS, ["~/.claude/projects/*/memory/*.md"],
|
|
190
|
+
"Globs of memory notes to check."),
|
|
191
|
+
_k("doctor.memory.index_max_lines", INT, 150, "Line cap for a memory index."),
|
|
192
|
+
_k("doctor.memory.index_max_bytes", INT, 20000, "Byte cap for a memory index."),
|
|
193
|
+
_k("doctor.mcp.stdio_allow", STRINGS, [], "stdio MCP server names the mcp check accepts."),
|
|
194
|
+
_k("doctor.pointers.sources", STRINGS, UNSET,
|
|
195
|
+
"Files the pointer check scans; unset uses a built-in list."),
|
|
196
|
+
_k("doctor.pointers.skill_roots", STRINGS, UNSET,
|
|
197
|
+
"Roots skills resolve against; unset uses a built-in list."),
|
|
198
|
+
_k("doctor.pointers.agent_roots", STRINGS, UNSET,
|
|
199
|
+
"Roots agents resolve against; unset uses a built-in list."),
|
|
200
|
+
_k("doctor.pointers.memory_roots", STRINGS, UNSET,
|
|
201
|
+
"Roots a memory note's paths must resolve under; unset uses a built-in list."),
|
|
202
|
+
_k("doctor.pointers.ignore_prefixes", STRINGS, UNSET,
|
|
203
|
+
"Path prefixes the pointer check skips; unset uses a built-in list."),
|
|
204
|
+
_k("doctor.pointers.ignore_segments", STRINGS, UNSET,
|
|
205
|
+
"Placeholder path segments to skip; unset uses a built-in list."),
|
|
206
|
+
_k("doctor.pointers.known_mcp", STRINGS, UNSET,
|
|
207
|
+
"Extra MCP server names the pointer check accepts."),
|
|
208
|
+
_k("doctor.pointers.known_agents", STRINGS, UNSET,
|
|
209
|
+
"Extra agent names the pointer check accepts."),
|
|
210
|
+
_k("doctor.pointers.known_skills", STRINGS, UNSET,
|
|
211
|
+
"Extra skill names the pointer check accepts."),
|
|
212
|
+
_k("doctor.pointers.known_models", STRINGS, UNSET,
|
|
213
|
+
"Model ids the pointer check accepts; unset uses a built-in list."),
|
|
214
|
+
_k("reaper.roots", STRINGS, [], "Trees scanned for repositories."),
|
|
215
|
+
_k("reaper.sessions_dir", STRING, "~/.claude/sessions",
|
|
216
|
+
"Directory of live-session JSON files."),
|
|
217
|
+
_k("reaper.grace_days", INT, 14, "Age of an unmerged branch tip before it is reapable."),
|
|
218
|
+
_k("reaper.max_kills_per_tree", INT, 20,
|
|
219
|
+
"More matched processes than this under one worktree stops the reap."),
|
|
220
|
+
_k("reaper.orphan_min_age_s", INT, 172800,
|
|
221
|
+
"Minimum runtime before a build daemon counts as orphaned."),
|
|
222
|
+
_k("reaper.orphan_sweep", BOOL, False, "Run the orphan-daemon sweep."),
|
|
223
|
+
_k("reaper.kill_grace_s", NUMBER, 5,
|
|
224
|
+
"Seconds between SIGTERM and SIGKILL when clearing a worktree."),
|
|
225
|
+
_k("reaper.max_worktrees", INT, 5,
|
|
226
|
+
"Linked worktrees per repo before it is flagged; 0 disables."),
|
|
227
|
+
_k("reaper.ignored_untracked_dirs", STRINGS, ["node_modules", "dist", ".turbo"],
|
|
228
|
+
"Directory names treated as regenerated output."),
|
|
229
|
+
_k("reaper.ignored_untracked_prefixes", STRINGS, ["coverage"],
|
|
230
|
+
"Directory-name prefixes treated as regenerated output."),
|
|
231
|
+
_k("reaper.precious", STRINGS,
|
|
232
|
+
[".env*", "*.pem", "*.key", "*.p12", "*.pfx", "id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"],
|
|
233
|
+
"File-name globs; a tree holding an ignored match is kept, not removed."),
|
|
234
|
+
_k("janitor.rules", list_of(JANITOR_RULE), [], "Cleanup rules applied in order."),
|
|
235
|
+
_k("janitor.watermarks", list_of(WATERMARK), [], "Size watermarks that append to the backlog."),
|
|
236
|
+
_k("janitor.max_delete", INT, 200, "Delete budget for one run."),
|
|
237
|
+
_k("backlog.path", STRING, "~/.config/rigops/backlog.md", "The backlog markdown file."),
|
|
238
|
+
_k("backlog.areas", STRINGS,
|
|
239
|
+
["hooks", "skills", "memory", "permissions", "metrics", "repos", "docs", "jobs"],
|
|
240
|
+
"Allowed area tags in backlog lines."),
|
|
241
|
+
_k("sources.ccusage.argv", STRINGS, ["ccusage", "daily", "--json"],
|
|
242
|
+
"Command line of the ccusage source."),
|
|
243
|
+
_k("sources.ccusage.timeout_s", NUMBER, 60, "Timeout of the ccusage source."),
|
|
244
|
+
_k("sources.custom", list_of(CUSTOM_SOURCE), [],
|
|
245
|
+
"Custom JSON-emitting sources run on every ledger write."),
|
|
246
|
+
_k("authprobe.enabled", BOOL, False, "Run the credential probe without --force."),
|
|
247
|
+
_k("authprobe.command", STRINGS, ["claude", "-p", "reply with exactly: ok", "--max-turns", "1"],
|
|
248
|
+
"Argv the probe runs."),
|
|
249
|
+
_k("authprobe.expect", STRING, "ok", "Exact stdout expected on success."),
|
|
250
|
+
_k("authprobe.timeout_s", NUMBER, 60, "Probe timeout."),
|
|
251
|
+
_k("authprobe.path", STRING, "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin",
|
|
252
|
+
"PATH of the scrubbed probe environment."),
|
|
253
|
+
_k("authprobe.keychain_service", STRING, "", "Keychain service holding the long-lived token."),
|
|
254
|
+
_k("eval.cases_dir", STRING, "", "Directory of eval case files."),
|
|
255
|
+
_k("eval.system_file", STRING, "", "System prompt file sent before every case."),
|
|
256
|
+
_k("eval.endpoint", STRING, "", "Base URL of the OpenAI-compatible API."),
|
|
257
|
+
_k("eval.model", STRING, "", "Model id sent with every request."),
|
|
258
|
+
_k("eval.api_key_env", STRING, "", "Name of the env var holding the bearer token."),
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
REMOVED: dict[str, str] = {
|
|
262
|
+
"context.preload": "the card left; nothing reads it",
|
|
263
|
+
"context.card": "the card left; only context.card.doctor_max_age_h is still read, by the hook",
|
|
264
|
+
"context.nudges_path": "the prompt nudge left",
|
|
265
|
+
"context.prompt_nudge": "the prompt nudge left",
|
|
266
|
+
"doctor.imports": "the imports check left",
|
|
267
|
+
"doctor.plans": "the plans check left",
|
|
268
|
+
"doctor.rtk": "the rtk check left; pin a version with a doctor.checks.custom entry",
|
|
269
|
+
"render": "the render command left",
|
|
270
|
+
"retrieval": "the retrieval subsystem left",
|
|
271
|
+
"sources.rtk": "the rtk source is not built in; add a sources.custom entry",
|
|
272
|
+
"sources.caveman": "the caveman source is not built in; add a sources.custom entry",
|
|
273
|
+
}
|
|
274
|
+
REMOVED_RELEASE = "0.11"
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _build_defaults() -> dict:
|
|
278
|
+
tree: dict = {}
|
|
279
|
+
for key in SPEC:
|
|
280
|
+
if key.default is UNSET:
|
|
281
|
+
continue
|
|
282
|
+
node = tree
|
|
283
|
+
*parents, leaf = key.path.split(".")
|
|
284
|
+
for part in parents:
|
|
285
|
+
node = node.setdefault(part, {})
|
|
286
|
+
node[leaf] = copy.deepcopy(key.default)
|
|
287
|
+
return tree
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
DEFAULTS = _build_defaults()
|
|
291
|
+
_LEAVES = {key.path for key in SPEC}
|
|
292
|
+
_BRANCHES = {".".join(parts[:i]) for key in SPEC for parts in [key.path.split(".")]
|
|
293
|
+
for i in range(1, len(parts))}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def removed_note(path: str) -> str | None:
|
|
297
|
+
for prefix, note in REMOVED.items():
|
|
298
|
+
if (path == prefix or path.startswith(prefix + ".")) and path not in _LEAVES:
|
|
299
|
+
return note
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def validate(cfg: dict) -> None:
|
|
304
|
+
for key in SPEC:
|
|
305
|
+
node: Any = cfg
|
|
306
|
+
parts = key.path.split(".")
|
|
307
|
+
for depth, part in enumerate(parts):
|
|
308
|
+
if not isinstance(node, dict):
|
|
309
|
+
parent = ".".join(parts[:depth])
|
|
310
|
+
if parent in REMOVED:
|
|
311
|
+
break
|
|
312
|
+
_fail(parent, "object", node)
|
|
313
|
+
if part not in node:
|
|
314
|
+
break
|
|
315
|
+
node = node[part]
|
|
316
|
+
else:
|
|
317
|
+
key.type.check(node, key.path)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def audit(cfg: dict) -> list[tuple[str, str | None]]:
|
|
321
|
+
"""Every key the spec does not know, with the removal note when it is a removed one."""
|
|
322
|
+
found: list[tuple[str, str | None]] = []
|
|
323
|
+
|
|
324
|
+
def walk(node: dict, prefix: str) -> None:
|
|
325
|
+
for name, value in node.items():
|
|
326
|
+
path = f"{prefix}{name}"
|
|
327
|
+
if path in _LEAVES:
|
|
328
|
+
continue
|
|
329
|
+
if path in _BRANCHES:
|
|
330
|
+
if isinstance(value, dict):
|
|
331
|
+
walk(value, f"{path}.")
|
|
332
|
+
continue
|
|
333
|
+
found.append((path, removed_note(path)))
|
|
334
|
+
|
|
335
|
+
walk(cfg, "")
|
|
336
|
+
return sorted(found)
|