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.
Files changed (86) hide show
  1. rigops/__init__.py +3 -0
  2. rigops/__main__.py +7 -0
  3. rigops/authprobe.py +106 -0
  4. rigops/backlog.py +107 -0
  5. rigops/cause.py +151 -0
  6. rigops/cli/__init__.py +66 -0
  7. rigops/cli/authprobe.py +47 -0
  8. rigops/cli/backlog.py +93 -0
  9. rigops/cli/config.py +61 -0
  10. rigops/cli/doctor.py +666 -0
  11. rigops/cli/eit.py +225 -0
  12. rigops/cli/eval.py +370 -0
  13. rigops/cli/hook.py +7 -0
  14. rigops/cli/janitor.py +88 -0
  15. rigops/cli/jobs.py +122 -0
  16. rigops/cli/ledger.py +350 -0
  17. rigops/cli/mine.py +7 -0
  18. rigops/cli/reap.py +110 -0
  19. rigops/cli/tax.py +238 -0
  20. rigops/cli/version.py +12 -0
  21. rigops/config.py +83 -0
  22. rigops/config_spec.py +336 -0
  23. rigops/core/__init__.py +224 -0
  24. rigops/corpus.py +44 -0
  25. rigops/cost.py +37 -0
  26. rigops/detector.py +91 -0
  27. rigops/doctor/__init__.py +81 -0
  28. rigops/doctor/check_agents.py +85 -0
  29. rigops/doctor/check_budget.py +110 -0
  30. rigops/doctor/check_jobs.py +30 -0
  31. rigops/doctor/check_levers.py +328 -0
  32. rigops/doctor/check_mcp.py +104 -0
  33. rigops/doctor/check_memory.py +92 -0
  34. rigops/doctor/check_pointers.py +358 -0
  35. rigops/doctor/ids.py +32 -0
  36. rigops/doctor/pointer_grammar.py +147 -0
  37. rigops/errors.py +5 -0
  38. rigops/eval/__init__.py +35 -0
  39. rigops/eval/cases.py +188 -0
  40. rigops/eval/checks.py +117 -0
  41. rigops/eval/client.py +190 -0
  42. rigops/eval/diff.py +108 -0
  43. rigops/eval/score.py +90 -0
  44. rigops/fmt.py +62 -0
  45. rigops/frontmatter.py +36 -0
  46. rigops/guard_state.py +69 -0
  47. rigops/hook.py +245 -0
  48. rigops/janitor.py +384 -0
  49. rigops/jobs.py +203 -0
  50. rigops/judge.py +364 -0
  51. rigops/launchd.py +194 -0
  52. rigops/ledger_row.py +88 -0
  53. rigops/levers.py +397 -0
  54. rigops/mine.py +195 -0
  55. rigops/mine_group.py +111 -0
  56. rigops/mine_redact.py +192 -0
  57. rigops/modelmix.py +36 -0
  58. rigops/notify.py +114 -0
  59. rigops/procgroup.py +37 -0
  60. rigops/reap.py +917 -0
  61. rigops/reap_guards.py +70 -0
  62. rigops/reap_owned.py +44 -0
  63. rigops/reap_procs.py +382 -0
  64. rigops/reap_report.py +78 -0
  65. rigops/reap_selftest.py +94 -0
  66. rigops/rebuilds.py +163 -0
  67. rigops/redaction-patterns.public.txt +40 -0
  68. rigops/registry.py +137 -0
  69. rigops/sources/__init__.py +19 -0
  70. rigops/sources/ccusage.py +44 -0
  71. rigops/sources/command.py +50 -0
  72. rigops/starts.py +247 -0
  73. rigops/state.py +159 -0
  74. rigops/templates/cron/crontab.example +21 -0
  75. rigops/templates/launchd/doctor.plist.in +44 -0
  76. rigops/templates/launchd/janitor.plist.in +50 -0
  77. rigops/templates/launchd/ledger.plist.in +48 -0
  78. rigops/templates/launchd/reap.plist.in +48 -0
  79. rigops/transcripts.py +369 -0
  80. rigops/watermarks.py +116 -0
  81. rigops-0.13.0.dist-info/METADATA +300 -0
  82. rigops-0.13.0.dist-info/RECORD +86 -0
  83. rigops-0.13.0.dist-info/WHEEL +5 -0
  84. rigops-0.13.0.dist-info/entry_points.txt +2 -0
  85. rigops-0.13.0.dist-info/licenses/LICENSE +21 -0
  86. rigops-0.13.0.dist-info/top_level.txt +1 -0
rigops/cli/eit.py ADDED
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import datetime as dt
5
+ import json
6
+ import statistics
7
+ import sys
8
+ from collections import Counter, defaultdict
9
+
10
+ from rigops import cli
11
+ from rigops import config as rigops_config
12
+ from rigops import cost
13
+ from rigops import fmt
14
+ from rigops import rebuilds
15
+ from rigops import transcripts
16
+
17
+
18
+ def group_of(path: str, groups: dict, transcripts_dir) -> str:
19
+ rel = transcripts.relative_path(path, transcripts_dir)
20
+ return next((name for name, sub in groups.items() if sub and sub in rel), "other")
21
+
22
+
23
+ def _cost(turns) -> dict:
24
+ split = cost.split(turns)
25
+ total = sum(split.values())
26
+ return {
27
+ "cost": total,
28
+ "cost_pct": {k: (v / total * 100) if total else 0.0 for k, v in split.items()},
29
+ }
30
+
31
+
32
+ def build_report(turns, by, top_n, groups=None, transcripts_dir=None) -> dict:
33
+ n = len(turns)
34
+ eits = [transcripts.eit(t) for t in turns]
35
+ ctxs = [transcripts.ctx(t) for t in turns]
36
+ total_eit = sum(eits)
37
+ total_output = sum(t["output"] for t in turns)
38
+ total_input = sum(t["input"] for t in turns)
39
+ total_cache_creation = sum(t["cache_creation"] for t in turns)
40
+ total_cache_read = sum(t["cache_read"] for t in turns)
41
+ total_ctx = total_input + total_cache_creation + total_cache_read
42
+ cache_hit_pct = (total_cache_read / total_ctx * 100) if total_ctx else 0.0
43
+
44
+ ctx_sorted = sorted(ctxs)
45
+ mean_ctx = statistics.mean(ctxs) if ctxs else 0.0
46
+ p50 = transcripts.percentile(ctx_sorted, 0.50)
47
+ p90 = transcripts.percentile(ctx_sorted, 0.90)
48
+ max_ctx = max(ctxs) if ctxs else 0.0
49
+
50
+ over_300k_eit = sum(e for e, c in zip(eits, ctxs) if c > 300_000)
51
+ share_over_300k = (over_300k_eit / total_eit * 100) if total_eit else 0.0
52
+
53
+ histogram = {}
54
+ for label, lo, hi in transcripts.CTX_BUCKETS:
55
+ bucket = [e for e, c in zip(eits, ctxs) if lo <= c < hi]
56
+ b_eit = sum(bucket)
57
+ histogram[label] = {
58
+ "turns": len(bucket),
59
+ "eit_share_pct": (b_eit / total_eit * 100) if total_eit else 0.0,
60
+ }
61
+
62
+ tool_counter = Counter()
63
+ for t in turns:
64
+ tool_counter.update(t["tools"])
65
+ top_tools = tool_counter.most_common(10)
66
+
67
+ group_key_fn = {
68
+ "project": lambda t: t["project"],
69
+ "model": lambda t: t["model"],
70
+ "session": lambda t: t["session"],
71
+ "group": lambda t: group_of(t["path"], groups or {}, transcripts_dir),
72
+ "surface": lambda t: t["surface"],
73
+ "day": lambda t: t["ts"].astimezone().date().isoformat(),
74
+ }[by]
75
+ group_eit = defaultdict(float)
76
+ group_members = defaultdict(list)
77
+ for t, e in zip(turns, eits):
78
+ k = group_key_fn(t)
79
+ group_eit[k] += e
80
+ group_members[k].append(t)
81
+ if by == "day":
82
+ top_groups = sorted(group_eit.items())[-top_n:]
83
+ else:
84
+ top_groups = sorted(group_eit.items(), key=lambda kv: kv[1], reverse=True)[:top_n]
85
+ top_groups = [
86
+ {"key": k, "eit": v, "turns": len(group_members[k]), **_cost(group_members[k])}
87
+ for k, v in top_groups
88
+ ]
89
+
90
+ return {
91
+ "turns": n,
92
+ "eit_total": total_eit,
93
+ "eit_per_turn": (total_eit / n) if n else 0.0,
94
+ "output_tokens_total": total_output,
95
+ "cache_hit_pct": cache_hit_pct,
96
+ "ctx_mean": mean_ctx,
97
+ "ctx_p50": p50,
98
+ "ctx_p90": p90,
99
+ "ctx_max": max_ctx,
100
+ "eit_share_over_300k_pct": share_over_300k,
101
+ "top_tools": top_tools,
102
+ **_cost(turns),
103
+ "by": by,
104
+ "top_groups": top_groups,
105
+ "histogram": histogram,
106
+ }
107
+
108
+
109
+ def _split_str(r) -> str:
110
+ p = r["cost_pct"]
111
+ return (
112
+ f"read {p['cache_read']:.0f}% write {p['cache_write']:.0f}%"
113
+ f" out {p['output']:.0f}% in {p['input']:.0f}%"
114
+ )
115
+
116
+
117
+ def print_human(r) -> None:
118
+ out = []
119
+ out.append(f"Window: {r['window']['since']} -> {r['window']['until'] or 'now'}")
120
+ out.append(f"Turns: {r['turns']:,}")
121
+ out.append(f"EIT total: {r['eit_total']:,.0f}")
122
+ out.append(f"EIT/turn: {r['eit_per_turn']:,.0f}")
123
+ out.append(f"Output tokens total: {r['output_tokens_total']:,.0f}")
124
+ out.append(f"Cache hit %: {r['cache_hit_pct']:.1f}")
125
+ out.append(
126
+ "Context mean/p50/p90/max: "
127
+ f"{r['ctx_mean']:,.0f} / {r['ctx_p50']:,.0f} / {r['ctx_p90']:,.0f} / {r['ctx_max']:,.0f}"
128
+ )
129
+ out.append(f"EIT share from turns >300k ctx: {r['eit_share_over_300k_pct']:.1f}%")
130
+ out.append(f"Cost (input-equivalent, output x5): {r['cost']:,.0f} {_split_str(r)}")
131
+ out.append("")
132
+ out.append("Top tool calls:")
133
+ for name, count in r["top_tools"]:
134
+ out.append(f" {name}: {count:,}")
135
+ out.append("")
136
+ out.append(f"Top {len(r['top_groups'])} by {r['by']} (EIT):")
137
+ for g in r["top_groups"]:
138
+ out.append(
139
+ f" {g['key']}: EIT={g['eit']:,.0f} turns={g['turns']:,}"
140
+ f" cost={g['cost']:,.0f} ({g['cost'] / r['cost'] * 100 if r['cost'] else 0:.1f}%)"
141
+ f" {_split_str(g)}"
142
+ )
143
+ print("\n".join(out))
144
+
145
+
146
+ def print_rebuilds(summary: dict, found: list, since, top_n: int) -> None:
147
+ head = f"cache rebuilds since {since.astimezone().date().isoformat()}: " if since else "cache rebuilds: "
148
+ print(f"{head}{summary['count']} turns, {summary['eit_pct'] or 0:.1f}% of main-thread EIT")
149
+ if not found:
150
+ return
151
+ rows = [
152
+ [cls, str(c["count"]), f"{c['eit_pct']:.1f}%", f"{c['gap_p50_s']}s",
153
+ str(c["model_change"]), str(c["version_change"]), str(c["shape_change"]),
154
+ ", ".join(f"{name} {n}" for name, n in c["before"]) or "-"]
155
+ for cls, c in summary["classes"].items()
156
+ ]
157
+ print(fmt.table(rows, ["class", "turns", "EIT share", "gap p50", "model chg",
158
+ "version chg", "shape chg", "entries before"]))
159
+ worst = sorted(found, key=lambda h: -h["eit"])[:top_n]
160
+ if not worst:
161
+ return
162
+ print(f"largest {len(worst)}:")
163
+ print(fmt.table(
164
+ [[h["ts"].isoformat(timespec="seconds"), h["session"][:8], h["project"], h["class"],
165
+ f"{h['lost']:,}", f"{h['eit']:,.0f}"] for h in worst],
166
+ ["ts", "session", "project", "class", "lost", "EIT"],
167
+ ))
168
+
169
+
170
+ def main(argv: list[str] | None = None) -> int:
171
+ parser = argparse.ArgumentParser(prog="rigops eit", description=cli.COMMANDS["eit"])
172
+ parser.add_argument("--since", default="-7d", help="ISO date/time, 'today', or '-Nd'")
173
+ parser.add_argument("--until", default=None, help="ISO date/time")
174
+ parser.add_argument("--json", action="store_true")
175
+ parser.add_argument("--by", choices=["project", "model", "session", "group", "surface", "day"],
176
+ default="project",
177
+ help="group: ledger.watch_projects substrings, unmatched turns as other; "
178
+ "surface: desktop, cli or headless; day: last N local days in order")
179
+ parser.add_argument("--top", type=int, default=10)
180
+ parser.add_argument(
181
+ "--rebuilds", action="store_true",
182
+ help="main-thread turns that re-created a cached prefix, classed by cause",
183
+ )
184
+ parser.add_argument(
185
+ "--dir", dest="transcripts_dir", default=None,
186
+ help="transcripts root directory (default: config transcripts_dir)",
187
+ )
188
+ args = parser.parse_args(transcripts.attach_dash_values(sys.argv[1:] if argv is None else argv))
189
+
190
+ transcripts_dir = None
191
+ if args.transcripts_dir is not None:
192
+ transcripts_dir = rigops_config.expand(args.transcripts_dir)
193
+ if not transcripts_dir.is_dir():
194
+ print(f"error: --dir not found: {transcripts_dir}", file=sys.stderr)
195
+ return 2
196
+
197
+ now = dt.datetime.now(dt.timezone.utc)
198
+ since = transcripts.parse_bound(args.since, now)
199
+ until = transcripts.parse_bound(args.until, now) if args.until else None
200
+
201
+ if args.rebuilds:
202
+ found, main_eit = rebuilds.collect(since, until, transcripts_dir=transcripts_dir)
203
+ summary = rebuilds.summarize(found, main_eit)
204
+ if args.json:
205
+ worst = sorted(found, key=lambda h: -h["eit"])[:args.top]
206
+ print(json.dumps({"version": 1, **summary, "largest": worst}, indent=2, default=str))
207
+ else:
208
+ print_rebuilds(summary, found, since, args.top)
209
+ return 0
210
+
211
+ turns = transcripts.collect_turns(since, until, transcripts_dir=transcripts_dir)
212
+ groups = rigops_config.get(rigops_config.load(), "ledger.watch_projects", {}) or {}
213
+ report = build_report(turns, args.by, args.top, groups, transcripts_dir)
214
+ report["window"] = {
215
+ "since": since.isoformat() if since else None,
216
+ "until": until.isoformat() if until else None,
217
+ }
218
+
219
+ if args.json:
220
+ print(json.dumps({"version": 1, **report}, indent=2, default=str))
221
+ else:
222
+ print_human(report)
223
+
224
+ return 0
225
+
rigops/cli/eval.py ADDED
@@ -0,0 +1,370 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import datetime as dt
5
+ import json
6
+ import math
7
+ import os
8
+ import re
9
+ import sys
10
+ import urllib.parse
11
+ import uuid
12
+ from pathlib import Path
13
+
14
+ from rigops import cli
15
+ from rigops import config as rigops_config
16
+ from rigops import core, fmt, state
17
+ from rigops import eval as rigops_eval
18
+ from rigops.errors import RigopsError
19
+
20
+ SETTINGS = (
21
+ ("cases_dir", "cases"),
22
+ ("system_file", "system"),
23
+ ("endpoint", "endpoint"),
24
+ ("model", "model"),
25
+ ("api_key_env", "api_key_env"),
26
+ )
27
+ ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
28
+
29
+
30
+ def _results_path() -> Path:
31
+ return state.state_dir() / "eval.jsonl"
32
+
33
+
34
+ def _load_rows() -> list:
35
+ path = _results_path()
36
+ try:
37
+ rows = state.read_jsonl(path)
38
+ except state.MalformedJsonl as exc:
39
+ raise RigopsError(str(exc)) from exc
40
+ for row in rows:
41
+ problem = rigops_eval.row_problem(row)
42
+ if problem:
43
+ raise RigopsError(f"malformed eval row in {path}: {problem}")
44
+ return rows
45
+
46
+
47
+ def _pct(rate) -> str:
48
+ return "-" if rate is None else f"{rate * 100:.1f}%"
49
+
50
+
51
+ def _ms(value) -> str:
52
+ return "-" if value is None else str(value)
53
+
54
+
55
+ def _cells(s: dict) -> list:
56
+ return [
57
+ f"{s['passed']}/{s['total']}", _pct(s["pass_rate"]), _ms(s["p50_ms"]), _ms(s["p95_ms"]),
58
+ ]
59
+
60
+
61
+ def _clean(text: str) -> str:
62
+ # Reports carry model output and server text; a raw escape byte would drive the terminal.
63
+ return "\n".join(rigops_eval.printable(line) for line in str(text).split("\n"))
64
+
65
+
66
+ def _table(rows: list, headers: list) -> str:
67
+ return fmt.table([[rigops_eval.printable(str(cell)) for cell in row] for row in rows], headers)
68
+
69
+
70
+ def _fail(message: str) -> int:
71
+ print(_clean(f"error: {message}"), file=sys.stderr)
72
+ return 2
73
+
74
+
75
+ def _endpoint_problem(endpoint: str) -> str:
76
+ """Refuse anything but a plain http(s) URL: credentials in it would be written
77
+ to eval.jsonl verbatim, and urllib would not send them anyway."""
78
+ try:
79
+ parts = urllib.parse.urlsplit(endpoint)
80
+ _ = parts.port
81
+ except ValueError:
82
+ return "endpoint is not a valid URL"
83
+ if parts.scheme not in ("http", "https") or not parts.hostname:
84
+ return "endpoint must be an http(s) URL with a host"
85
+ if parts.username or parts.password or parts.query or parts.fragment:
86
+ return "endpoint must not carry credentials, a query or a fragment; use --api-key-env"
87
+ return ""
88
+
89
+
90
+ def _run_report(row: dict, dry_run: bool) -> str:
91
+ head = (
92
+ f"eval run {row['run_id']} label={row['label'] or '-'} model={row['model']} "
93
+ f"suite={row['suite']} cases={row['totals']['total']}"
94
+ )
95
+ if dry_run:
96
+ head += " (dry-run, not recorded)"
97
+ summaries = [*row["groups"].items(), ("total", row["totals"])]
98
+ lines = [
99
+ head, "", _table([[name, *_cells(s)] for name, s in summaries],
100
+ ["group", "pass", "rate", "p50 ms", "p95 ms"]),
101
+ ]
102
+ failing = [
103
+ [result["status"], case_id, result["group"], result["reason"]]
104
+ for case_id, result in row["cases"].items() if result["status"] != "pass"
105
+ ]
106
+ if failing:
107
+ lines += ["", "not passing:", _table(failing, ["status", "case", "group", "reason"])]
108
+ return _clean("\n".join(lines))
109
+
110
+
111
+ def cmd_run(args) -> int:
112
+ cfg = rigops_config.load()
113
+ settings = {}
114
+ for key, flag in SETTINGS:
115
+ value = getattr(args, flag)
116
+ if value is None:
117
+ value = core.cfg_get(cfg, f"eval.{key}", "")
118
+ if not isinstance(value, str):
119
+ return _fail(f"eval.{key} in config must be a string")
120
+ settings[key] = value
121
+
122
+ for flag, key in (("--cases", "cases_dir"), ("--endpoint", "endpoint"), ("--model", "model")):
123
+ if not settings[key]:
124
+ return _fail(f"no {flag[2:]}: pass {flag} or set eval.{key} in config")
125
+ endpoint = settings["endpoint"]
126
+ problem = _endpoint_problem(endpoint)
127
+ if problem:
128
+ return _fail(problem)
129
+ api_key = None
130
+ key_env = settings["api_key_env"]
131
+ if key_env:
132
+ if not ENV_NAME.fullmatch(key_env):
133
+ return _fail("--api-key-env and eval.api_key_env take an environment variable name")
134
+ api_key = os.environ.get(key_env)
135
+ if not api_key:
136
+ return _fail(f"{key_env} is not set (named by --api-key-env or eval.api_key_env)")
137
+ if not (api_key.isascii() and api_key.isprintable()) or any(c.isspace() for c in api_key):
138
+ return _fail(f"{key_env} holds whitespace or control characters")
139
+
140
+ cases_path = core.expand(settings["cases_dir"])
141
+ try:
142
+ suite = rigops_eval.load_suite(cases_path)
143
+ except rigops_eval.CaseError as exc:
144
+ return _fail(f"invalid eval cases\n{exc}")
145
+
146
+ if not math.isfinite(args.temperature) or args.temperature < 0:
147
+ return _fail("--temperature must be a finite number, zero or more")
148
+
149
+ system = system_hash = None
150
+ if settings["system_file"]:
151
+ # Not core.expand: it resolves symlinks, and read_text_file must see the link.
152
+ system_path = rigops_config.expand(settings["system_file"])
153
+ try:
154
+ system = rigops_eval.read_text_file(system_path)
155
+ except (OSError, ValueError) as exc:
156
+ return _fail(f"cannot read system prompt {system_path}: {exc}")
157
+ system_hash = rigops_eval.digest(system)
158
+
159
+ now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
160
+ run_id = f"{now:%Y%m%d-%H%M%S}-{uuid.uuid4().hex[:4]}"
161
+ git_sha = core.run(["git", "-C", str(cases_path), "rev-parse", "--short", "HEAD"]).strip()
162
+
163
+ results = {}
164
+ total = len(suite.cases)
165
+ for n, case in enumerate(suite.cases, start=1):
166
+ messages = [{"role": "user", "content": case.prompt}]
167
+ if system is not None:
168
+ messages.insert(0, {"role": "system", "content": system})
169
+ reply = rigops_eval.complete(
170
+ endpoint, settings["model"], messages, max_tokens=case.max_tokens,
171
+ temperature=args.temperature, timeout_s=case.timeout_s, api_key=api_key,
172
+ )
173
+ if reply["error"]:
174
+ status, reason = "error", reply["error"]
175
+ else:
176
+ passed, reason = rigops_eval.evaluate(case.expect, reply["content"])
177
+ status = "pass" if passed else "fail"
178
+ results[case.id] = {
179
+ "group": case.group, "status": status, "ms": reply["ms"],
180
+ "reason": reason, "hash": case.hash,
181
+ }
182
+ progress = f"[{n}/{total}] {status:<5} {reply['ms']:>6} ms {case.id}"
183
+ print(_clean(progress), file=sys.stderr)
184
+
185
+ row = rigops_eval.build_row(
186
+ run_id=run_id, ts=now.isoformat(), label=args.label, endpoint=endpoint,
187
+ model=settings["model"], temperature=args.temperature, suite=suite.hash,
188
+ system=system_hash, git_sha=git_sha or None, cases=results,
189
+ )
190
+ row = {"version": state.VERSION, **row}
191
+ if not args.dry_run:
192
+ state.append_jsonl(_results_path(), row)
193
+ print(json.dumps(row, indent=2) if args.json else _run_report(row, args.dry_run))
194
+ return 0
195
+
196
+
197
+ def _name(meta: dict) -> str:
198
+ return f"{meta['label']} ({meta['run_id']})" if meta.get("label") else meta["run_id"]
199
+
200
+
201
+ def _regression_line(r: dict) -> str:
202
+ if r["metric"] == "newly_failing":
203
+ return (
204
+ f"REGRESSION {r['group']}: {len(r['cases'])} newly failing, "
205
+ f"{r['base']}/{r['total']} -> {r['head']}/{r['total']} passing"
206
+ )
207
+ growth = f" (+{r['pct']}%)" if r["pct"] is not None else ""
208
+ return f"REGRESSION {r['group']}: p95 {r['base']} -> {r['head']} ms{growth}"
209
+
210
+
211
+ def _diff_report(report: dict) -> str:
212
+ base, head = report["base"], report["head"]
213
+ meta_rows = [
214
+ [key, base[key] or "-", head[key] or "-"] for key in ("model", "system", "suite", "git_sha")
215
+ ]
216
+ lines = [
217
+ f"eval diff: {_name(base)} -> {_name(head)}",
218
+ _table(meta_rows, ["", "base", "head"]),
219
+ "",
220
+ f"compared {report['shared']} unchanged cases",
221
+ ]
222
+ for key, what in (
223
+ ("added", "added (no baseline)"),
224
+ ("removed", "removed"),
225
+ ("changed", "changed (not compared)"),
226
+ ):
227
+ if report[key]:
228
+ lines.append(f"{what}: {', '.join(report[key])}")
229
+ group_rows = [
230
+ [
231
+ name,
232
+ f"{g['base']['passed']}/{g['base']['total']}",
233
+ f"{g['head']['passed']}/{g['head']['total']}",
234
+ _ms(g["base"]["p95_ms"]),
235
+ _ms(g["head"]["p95_ms"]),
236
+ ]
237
+ for name, g in report["groups"].items()
238
+ ]
239
+ lines += ["", _table(group_rows, ["group", "base", "head", "p95 base", "p95 head"])]
240
+ if report["newly_failing"]:
241
+ failing = [
242
+ [f["status"], f["case"], f["group"], f["reason"]] for f in report["newly_failing"]
243
+ ]
244
+ lines += ["", "newly failing:", _table(failing, ["status", "case", "group", "reason"])]
245
+ if report["newly_passing"]:
246
+ lines += ["", "newly passing: " + ", ".join(p["case"] for p in report["newly_passing"])]
247
+ lines.append("")
248
+ lines += [_regression_line(r) for r in report["regressions"]]
249
+ if report["unverified"]:
250
+ lines.append(
251
+ f"UNVERIFIED {len(report['unverified'])} cases errored in the base run and do not "
252
+ f"pass now: {', '.join(report['unverified'])}; re-run the baseline"
253
+ )
254
+ if report["dropped"]:
255
+ lines.append(
256
+ f"DROPPED {len(report['dropped'])} cases passed in the base run and are missing or "
257
+ f"changed now: {', '.join(report['dropped'])}; judge the change against the base cases"
258
+ )
259
+ if not (report["regressions"] or report["unverified"] or report["dropped"]):
260
+ lines.append("no regressions")
261
+ return _clean("\n".join(lines))
262
+
263
+
264
+ def cmd_diff(args) -> int:
265
+ tolerance = args.latency_tolerance
266
+ if tolerance is not None and not (math.isfinite(tolerance) and tolerance >= 0):
267
+ return _fail("--latency-tolerance must be zero or more")
268
+ for flag, ref in (("--base", args.base), ("--head", args.head)):
269
+ if ref is not None and not ref.strip():
270
+ return _fail(f"{flag} must name a run id or a label")
271
+ rows = _load_rows()
272
+ if not rows:
273
+ return _fail("no eval runs recorded yet")
274
+ head = rows[-1] if args.head is None else rigops_eval.resolve(rows, args.head)
275
+ if head is None:
276
+ return _fail(f"no eval run matches --head {args.head}")
277
+ if args.base is not None:
278
+ base = rigops_eval.resolve(rows, args.base)
279
+ if base is None:
280
+ return _fail(f"no eval run matches --base {args.base}")
281
+ else:
282
+ index = next(i for i, row in enumerate(rows) if row is head)
283
+ if index == 0:
284
+ return _fail(f"no run before {head['run_id']} to diff against; pass --base")
285
+ base = rows[index - 1]
286
+ if base["run_id"] == head["run_id"]:
287
+ return _fail("--base and --head select the same run")
288
+
289
+ report = rigops_eval.compare(base, head, tolerance)
290
+ if not report["shared"]:
291
+ return _fail("the two runs share no unchanged cases, so there is nothing to compare")
292
+ print(json.dumps({"version": 1, **report}, indent=2) if args.json else _diff_report(report))
293
+ if report["unverified"] or report["dropped"]:
294
+ return 2
295
+ return 1 if report["regressions"] else 0
296
+
297
+
298
+ def cmd_list(args) -> int:
299
+ rows = _load_rows()
300
+ if args.json:
301
+ print(json.dumps({"version": 1, "rows": rows}, indent=2))
302
+ return 0
303
+ if not rows:
304
+ print("no eval runs recorded yet")
305
+ return 0
306
+ table_rows = [
307
+ [
308
+ row["run_id"],
309
+ row.get("label") or "-",
310
+ row.get("model") or "-",
311
+ row.get("suite") or "-",
312
+ *_cells(row["totals"]),
313
+ ]
314
+ for row in rows
315
+ ]
316
+ headers = ["run", "label", "model", "suite", "pass", "rate", "p50 ms", "p95 ms"]
317
+ print(_table(table_rows, headers))
318
+ return 0
319
+
320
+
321
+ def main(argv: list[str] | None = None) -> int:
322
+ ap = argparse.ArgumentParser(
323
+ prog="rigops eval",
324
+ description=cli.COMMANDS["eval"],
325
+ )
326
+ sub = ap.add_subparsers(dest="cmd", required=True)
327
+
328
+ run_p = sub.add_parser("run", help="run every case once and append one results row")
329
+ run_p.add_argument("--cases", help="case directory (default: config eval.cases_dir)")
330
+ run_p.add_argument(
331
+ "--system", help="system prompt file sent before every case (default: eval.system_file)"
332
+ )
333
+ run_p.add_argument(
334
+ "--endpoint", help="OpenAI-compatible base URL, e.g. http://127.0.0.1:1234/v1"
335
+ )
336
+ run_p.add_argument("--model", help="model id sent with every request")
337
+ run_p.add_argument("--api-key-env", help="env var holding a bearer token for the endpoint")
338
+ run_p.add_argument("--temperature", type=float, default=0.0, help="default 0")
339
+ run_p.add_argument("--label", default="", help="tag for the run, e.g. main or proposal")
340
+ run_p.add_argument("--dry-run", action="store_true", help="run and print, record nothing")
341
+ run_p.add_argument("--json", action="store_true")
342
+
343
+ diff_p = sub.add_parser("diff", help="compare two runs; exit 1 on any regression")
344
+ diff_p.add_argument("--base", help="run id or label (default: the run before --head)")
345
+ diff_p.add_argument("--head", help="run id or label (default: the latest run)")
346
+ diff_p.add_argument(
347
+ "--latency-tolerance", type=float, metavar="PCT",
348
+ help="also fail a group whose p95 grew by more than PCT percent",
349
+ )
350
+ diff_p.add_argument("--json", action="store_true")
351
+
352
+ list_p = sub.add_parser("list", help="every recorded run, oldest first")
353
+ list_p.add_argument("--json", action="store_true")
354
+
355
+ args = ap.parse_args(argv)
356
+ try:
357
+ if args.cmd == "run":
358
+ return cmd_run(args)
359
+ if args.cmd == "diff":
360
+ return cmd_diff(args)
361
+ return cmd_list(args)
362
+ except KeyboardInterrupt:
363
+ print("interrupted: nothing recorded", file=sys.stderr)
364
+ return 130
365
+ except RigopsError as exc:
366
+ # A load error (config, results file) must not exit 1, which means regression.
367
+ return _fail(str(exc))
368
+ except Exception as exc: # noqa: BLE001 - exit 1 is reserved for a real regression
369
+ return _fail(f"{type(exc).__name__}: {exc}")
370
+
rigops/cli/hook.py ADDED
@@ -0,0 +1,7 @@
1
+ from __future__ import annotations
2
+
3
+ from rigops import hook
4
+
5
+
6
+ def main(argv: list[str] | None = None) -> int:
7
+ return hook.main(argv)