compactlab 0.2.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 (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/cli/main.py ADDED
@@ -0,0 +1,2436 @@
1
+ """compactlab: measure where to auto-compact from your own agent history.
2
+
3
+ Modes: lite (default; offline, zero cost) and deep (opt-in; adds LLM-driven checks, needs --yes and --budget).
4
+ Profiles: cost ($10/h of agent time), balanced (default, $250/h), time ($600/h), each with guardrails.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import platform
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import time
18
+ import webbrowser
19
+ from collections.abc import Callable
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
+ from .. import __version__, synth
24
+ from .. import apply as ap
25
+ from ..adapters import adapter_names, get_adapter
26
+ from ..adapters.cache import ScanCache
27
+ from ..eval.deep import EvalError, MockClient, deep_analyze, load_client, plan_deep
28
+ from ..model import Session, drop_inherited, lean
29
+ from ..pricing import DEFAULT_REFRESHED, PricingTable
30
+ from ..pricing.refresh import SOURCES, recent_changes, refresh
31
+ from ..report.html import render_html
32
+ from ..sim.baseline import MAX_CONTEXT_ENV, read_current, read_env_int, read_idle
33
+ from ..sim.engine import SimOptions, analyze, price_drift, reselect
34
+ from ..sim.select import DEFAULT_PROFILE, PROFILE_NAMES, PROFILES, WAIT_CAP_MIN_PER_DAY
35
+
36
+ STATE = "~/.compactlab"
37
+ EX_BUSY = 75 # sysexits EX_TEMPFAIL: another calibration or config write holds the state dir's lock; try again later
38
+ EXAMPLES = """examples:
39
+ compactlab demo synthetic data -> report, opens it
40
+ compactlab doctor where are my logs and configs?
41
+ compactlab simulate --out result.json lite analysis of the last 30 days
42
+ compactlab report --result result.json HTML report from a saved result
43
+ compactlab apply --result result.json --claude-settings ~/.claude/settings.json dry-run diff
44
+ compactlab simulate --mode deep --budget 2 print the deep cost estimate (add --yes to run)
45
+ """
46
+
47
+
48
+ class CLIError(Exception):
49
+ pass
50
+
51
+
52
+ def _k(s: str) -> int:
53
+ s = s.strip().lower().replace("_", "")
54
+ try:
55
+ if s.endswith("k"):
56
+ return int(float(s[:-1]) * 1000)
57
+ if s.endswith("m"):
58
+ return int(float(s[:-1]) * 1_000_000)
59
+ return int(s)
60
+ except ValueError as e:
61
+ raise argparse.ArgumentTypeError(f"expected a token count like 250k, 1m or 300000, got {s!r}") from e
62
+
63
+
64
+ def _out(a: argparse.Namespace, obj: Any, text: str) -> None:
65
+ print(json.dumps(obj, indent=2, sort_keys=True, default=str) if getattr(a, "json", False) else text)
66
+
67
+
68
+ # ---------- shared option groups ----------
69
+
70
+
71
+ def _source(p: argparse.ArgumentParser) -> None:
72
+ g = p.add_argument_group("history source")
73
+ g.add_argument(
74
+ "--harness", action="append", choices=adapter_names(), help="limit to a harness (repeatable; default all)"
75
+ )
76
+ g.add_argument(
77
+ "--claude-root",
78
+ action="append",
79
+ help="Claude Code projects dir (default $CLAUDE_CONFIG_DIR/projects or ~/.claude/projects)",
80
+ )
81
+ g.add_argument(
82
+ "--codex-root", action="append", help="Codex sessions dir (default $CODEX_HOME/sessions or ~/.codex/sessions)"
83
+ )
84
+ g.add_argument(
85
+ "--dsh-root",
86
+ action="append",
87
+ help="DeepSeek Harness sessions dir (default $DSH_HOME/sessions or ~/.dsh/sessions)",
88
+ )
89
+ g.add_argument(
90
+ "--opencode-root",
91
+ action="append",
92
+ help="OpenCode data dir or opencode.db (default $XDG_DATA_HOME/opencode or ~/.local/share/opencode)",
93
+ )
94
+ g.add_argument(
95
+ "--gemini-root",
96
+ action="append",
97
+ help="Gemini CLI tmp dir (default $GEMINI_CLI_HOME/.gemini/tmp or ~/.gemini/tmp)",
98
+ )
99
+ g.add_argument(
100
+ "--since-days", type=float, default=30, help="only files modified in the last N days (0 = all; default 30)"
101
+ )
102
+ g.add_argument("--no-cache", action="store_true", help="do not read or write the scan cache")
103
+ g.add_argument("--cache-dir", default=f"{STATE}/cache", help="scan cache location (default ~/.compactlab/cache)")
104
+ p.add_argument("--json", action="store_true", help="machine-readable output")
105
+
106
+
107
+ def _sim(p: argparse.ArgumentParser) -> None:
108
+ _source(p)
109
+ g = p.add_argument_group("simulation")
110
+ g.add_argument("--pricing", help="pricing override JSON (same schema as the bundled data/pricing.json)")
111
+ g.add_argument(
112
+ "--offline-pricing", action="store_true", help="ignore refreshed prices; use bundled + --pricing only"
113
+ )
114
+ g.add_argument(
115
+ "--grid", default="100k:1m:25k", help="threshold sweep start:stop:step (stop capped per model window)"
116
+ )
117
+ g.add_argument(
118
+ "--recall-floor", type=float, default=0.90, help="minimum assumed (or measured) recall (default 0.90)"
119
+ )
120
+ g.add_argument("--max-threshold", type=_k, help="never recommend a threshold above this")
121
+ g.add_argument(
122
+ "--wait-cap",
123
+ type=float,
124
+ default=WAIT_CAP_MIN_PER_DAY,
125
+ help="guardrail: max added compaction wait vs default, minutes/day (default 30)",
126
+ )
127
+ g.add_argument("--cache-ttl", type=int, help="prompt-cache TTL in seconds (default from pricing file: 300)")
128
+ g.add_argument("--summary-tokens", type=_k, help="compaction summary size (default: observed median, else 12k)")
129
+ g.add_argument("--base-tokens", type=_k, help="post-compaction base context (default: observed, else 35k)")
130
+ _profile_args(g)
131
+ c = p.add_argument_group("current config (read-only, for comparison)")
132
+ _config_args(c)
133
+ c.add_argument("--no-current", action="store_true", help="do not read current harness config")
134
+ p.add_argument("--lang", choices=["both", "en", "zh"], default="both", help="output language (default: both 中英)")
135
+ h = p.add_argument_group("deep mode (opt-in, costs money)")
136
+ h.add_argument(
137
+ "--mode", choices=["lite", "deep"], default="lite", help="lite: offline (default); deep: adds LLM checks"
138
+ )
139
+ h.add_argument("--executor", default="claude-code", help="claude-code | codex | mock | package.module:Class")
140
+ h.add_argument("--model", default="claude-sonnet-5-5", help="model that re-summarizes and answers probes")
141
+ h.add_argument("--judge-model", default="claude-haiku-5-5", help="judge model (must differ from --model)")
142
+ h.add_argument("--repeats", type=int, default=3, help="judge repeats per probe (majority vote)")
143
+ h.add_argument("--sessions-per-group", type=int, default=3)
144
+ h.add_argument("--budget", type=float, help="hard USD cap for deep mode (required with --mode deep)")
145
+ h.add_argument("--yes", action="store_true", help="confirm deep-mode spending after reviewing the estimate")
146
+
147
+
148
+ def _profile_args(g: Any) -> None:
149
+ vots = ", ".join(f"{n} ${PROFILES[n]['value_of_time']:g}/h" for n in PROFILE_NAMES)
150
+ g.add_argument(
151
+ "--profile",
152
+ choices=PROFILE_NAMES,
153
+ help=f"which profile to use/apply (default {DEFAULT_PROFILE}; all three are always computed): {vots}",
154
+ )
155
+ g.add_argument(
156
+ "--value-of-time",
157
+ type=float,
158
+ help="USD per hour of agent wall-clock; overrides the selected profile's value (0 = cost only)",
159
+ )
160
+
161
+
162
+ def _reselect(a: argparse.Namespace, res: dict[str, Any]) -> dict[str, Any]:
163
+ """Apply --profile / --value-of-time to a saved result (selection only, no replay)."""
164
+ if getattr(a, "profile", None) or getattr(a, "value_of_time", None) is not None:
165
+ reselect(res, getattr(a, "profile", None), getattr(a, "value_of_time", None))
166
+ return res
167
+
168
+
169
+ def _config_args(g: Any) -> None:
170
+ g.add_argument("--claude-settings", help="Claude Code settings.json (default: ~/.claude/settings.json)")
171
+ g.add_argument("--codex-config", help="Codex config.toml (default: ~/.codex/config.toml)")
172
+ g.add_argument("--opencode-config", help="OpenCode opencode.json, read only (default: ~/.config/opencode/)")
173
+ g.add_argument("--gemini-settings", help="Gemini CLI settings.json, read only (default: ~/.gemini/settings.json)")
174
+
175
+
176
+ def _roots(a: argparse.Namespace) -> dict[str, list[str] | None]:
177
+ return {
178
+ "claude-code": a.claude_root,
179
+ "codex": a.codex_root,
180
+ "dsh": a.dsh_root,
181
+ "opencode": a.opencode_root,
182
+ "gemini-cli": a.gemini_root,
183
+ }
184
+
185
+
186
+ def _ttl_note(g: dict[str, Any], lang: str) -> str:
187
+ """The cache TTL a group was replayed with and where it came from, in one language."""
188
+ sec, src = int(g["cache_ttl"]), str(g.get("cache_ttl_source", ""))
189
+ if lang == "zh":
190
+ dur = f"{sec // 3600} 小时" if sec >= 3600 else f"{sec // 60} 分钟"
191
+ m = re.match(r"logs: (\d+%)", src)
192
+ why = (
193
+ f"日志:{m.group(1)} 的缓存写入是 1 小时档"
194
+ if m
195
+ else ("--cache-ttl" if src == "--cache-ttl" else "价格文件默认值")
196
+ )
197
+ return f"缓存时长:{dur}({why}),缓存写入按该档计价"
198
+ dur = f"{sec // 3600} h" if sec >= 3600 else f"{sec // 60} min"
199
+ return f"cache: {dur} ({src}); cache writes priced at that tier"
200
+
201
+
202
+ def _progress(msg: str) -> None:
203
+ """One in-place progress line on stderr, only when it is a terminal. The line is cut to the terminal width at a
204
+ space (never mid-field): a wrapped line would leave one stale row per update behind the carriage return."""
205
+ if not sys.stderr.isatty():
206
+ return
207
+ width = max(shutil.get_terminal_size((80, 24)).columns - 1, 10)
208
+ if len(msg) > width:
209
+ msg = msg[: msg.rfind(" ", 0, width) if " " in msg[:width] else width]
210
+ print(f"\r\033[K{msg}", end="", file=sys.stderr, flush=True)
211
+
212
+
213
+ def _cut(a: argparse.Namespace) -> float | None:
214
+ return time.time() - a.since_days * 86400 if a.since_days else None
215
+
216
+
217
+ def _warn(a: argparse.Namespace, msg: str) -> None:
218
+ """A warning on stderr; a service run's goes to its log too."""
219
+ if getattr(a, "service", False):
220
+ import logging
221
+
222
+ logging.getLogger("compactlab.service").warning("%s", msg)
223
+ else:
224
+ _progress("")
225
+ print(f"warning: {msg}", file=sys.stderr)
226
+
227
+
228
+ def load_sessions(a: argparse.Namespace, cut: float | None = None, text: bool = False) -> list[Session]:
229
+ """Sessions of the logs in the window, lean (`model.lean`: no transcript text, a fraction of the memory) unless
230
+ `text` (deep mode), which reads every log itself: the scan cache keeps no text."""
231
+ cache = None if a.no_cache or text else ScanCache(a.cache_dir)
232
+ out: list[Session] = []
233
+ cut = _cut(a) if cut is None else cut
234
+ quiet, total, errors = getattr(a, "service", False), 0, 0
235
+ failed: set[str] = set()
236
+ try:
237
+ for h in a.harness or adapter_names():
238
+ ad = get_adapter(h)(_roots(a).get(h))
239
+ files = list(ad.find_files())
240
+ total += len(files)
241
+ first = len(out)
242
+ for i, path in enumerate(files, 1):
243
+ if i % 20 == 0 or i == len(files):
244
+ stats = "" if quiet or not cache else f" · cached {cache.stats['hit'] + cache.stats['resumed']}"
245
+ _progress(f"scanning {h} {i}/{len(files)} files{stats}")
246
+ try:
247
+ found = ad.load(path, cache, cut)
248
+ except OSError:
249
+ errors += 1
250
+ failed.add(h)
251
+ continue
252
+ out += [s if text else lean(s) for s in found if s.turns]
253
+ if h == "claude-code": # a resumed or forked log repeats its parent's history
254
+ out[first:] = drop_inherited(out[first:])
255
+ if cache:
256
+ pr = cache.prune() # rows of deleted logs
257
+ if not pr.deleted:
258
+ _warn(
259
+ a,
260
+ f"the scan cache still holds {pr.stale} row(s) of deleted logs (the database was busy or "
261
+ "unwritable); the next scan tries again, `compactlab cache clear` removes them now",
262
+ )
263
+ elif not pr.erased:
264
+ _warn(
265
+ a,
266
+ f"dropped {pr.stale} row(s) of deleted logs from the scan cache; another compactlab run is "
267
+ "reading it, so their bytes stay in the cache files until the last run using it ends",
268
+ )
269
+ finally:
270
+ if cache:
271
+ cache.close()
272
+ _progress("")
273
+ st = cache.stats if cache else {"hit": 0, "resumed": 0, "parsed": total}
274
+ a.scan_stats = {"files": total, "cached": st["hit"] + st["resumed"], "parsed": st["parsed"]}
275
+ a.scan_errors, a.scan_failed = errors, failed
276
+ return out
277
+
278
+
279
+ def covered(a: argparse.Namespace, res: dict[str, Any]) -> list[str]:
280
+ """The harnesses a run speaks for in the shared files (publish.py): every one it scanned, so one with no logs
281
+ in the window loses its old entries, except one that came back empty because its logs could not be read."""
282
+ have = {g["harness"] for g in res["groups"]}
283
+ failed: set[str] = getattr(a, "scan_failed", set()) # a reused analysis comes from an error-free scan
284
+ return [h for h in dict.fromkeys(a.harness or adapter_names()) if h in have or h not in failed]
285
+
286
+
287
+ # ---------- reusing an analysis result (lite mode, with the scan cache) ----------
288
+
289
+
290
+ def _files_key(a: argparse.Namespace, cut: float | None) -> tuple[str, int]:
291
+ """Key of the logs `load_sessions(a)` would read, from each eligible file's identity in scan order (see
292
+ `Adapter.fingerprint`), and how many files were found (as `load_sessions` counts them). Taken before any is read:
293
+ a file that grows while the analysis runs then only makes the saved result's key stale, never a key that claims
294
+ data the result lacks."""
295
+ import hashlib
296
+
297
+ h, n = hashlib.sha256(), 0
298
+ for name in a.harness or adapter_names():
299
+ ad = get_adapter(name)(_roots(a).get(name))
300
+ for path in ad.find_files():
301
+ n += 1
302
+ try:
303
+ fp = ad.fingerprint(path, cut)
304
+ except OSError:
305
+ fp = [str(path), "unreadable"]
306
+ if fp is not None:
307
+ h.update(json.dumps([name, fp]).encode() + b"\n")
308
+ return h.hexdigest(), n
309
+
310
+
311
+ def _code_version() -> str:
312
+ """Hash of compactlab's own files (code, bundled data): any change to how a result is made changes the key."""
313
+ global _CODE
314
+ if _CODE is None:
315
+ import hashlib
316
+
317
+ h, root = hashlib.sha256(), Path(__file__).resolve().parents[1]
318
+ for p in sorted(root.rglob("*")):
319
+ if p.is_file() and "__pycache__" not in p.parts and p.suffix != ".pyc":
320
+ h.update(str(p.relative_to(root)).encode() + b"\0" + p.read_bytes() + b"\0")
321
+ _CODE = h.hexdigest()
322
+ return _CODE
323
+
324
+
325
+ _CODE: str | None = None
326
+
327
+
328
+ def _local_time() -> list[Any]:
329
+ """The local time rules (the analysis counts active days by local date): TZ, the zone file and its contents."""
330
+ import hashlib
331
+
332
+ zone = Path("/etc/localtime")
333
+ try:
334
+ data = hashlib.sha1(zone.read_bytes()).hexdigest() if zone.exists() else None
335
+ where = str(zone.resolve()) if zone.exists() else None
336
+ except OSError:
337
+ data = where = None
338
+ return [os.environ.get("TZ"), where, data, time.timezone, time.altzone, time.daylight, list(time.tzname)]
339
+
340
+
341
+ def _inputs_key(pricing: PricingTable, opts: SimOptions, current: dict[tuple[str, str], tuple[int | None, str]]) -> str:
342
+ """Key of everything besides the sessions that `analyze` reads: prices, options (with what was read from the
343
+ harness settings), the configured thresholds, compactlab's own files and the local time rules."""
344
+ import hashlib
345
+
346
+ inputs = {
347
+ "code": _code_version(),
348
+ "pricing": pricing.data,
349
+ "opts": {k: (v.to_dict() if hasattr(v, "to_dict") else v) for k, v in vars(opts).items()},
350
+ "current": sorted([h, m, thr, why] for (h, m), (thr, why) in current.items()),
351
+ "local_time": _local_time(),
352
+ }
353
+ return hashlib.sha256(json.dumps(inputs, sort_keys=True, default=repr).encode()).hexdigest()
354
+
355
+
356
+ def _opts(a: argparse.Namespace) -> SimOptions:
357
+ try:
358
+ lo, hi, st = (_k(x) for x in a.grid.split(":"))
359
+ except (ValueError, argparse.ArgumentTypeError) as e:
360
+ raise CLIError(f"--grid must look like 100k:1m:25k ({e})") from e
361
+ if a.max_threshold is not None and a.max_threshold < lo:
362
+ raise CLIError(
363
+ f"--max-threshold {a.max_threshold:,} is below the grid start {lo:,}: lower the grid start (--grid) or "
364
+ "raise the cap"
365
+ )
366
+ return SimOptions(
367
+ profile=a.profile or DEFAULT_PROFILE,
368
+ value_of_time=a.value_of_time,
369
+ wait_cap_min_per_day=a.wait_cap,
370
+ max_threshold=a.max_threshold,
371
+ grid_start=lo,
372
+ grid_stop=hi,
373
+ grid_step=st,
374
+ recall_floor=a.recall_floor,
375
+ ttl_seconds=a.cache_ttl,
376
+ summary_tokens=a.summary_tokens,
377
+ base_tokens=a.base_tokens,
378
+ )
379
+
380
+
381
+ def _pricing(a: argparse.Namespace) -> PricingTable:
382
+ return PricingTable.load(getattr(a, "pricing", None), offline=getattr(a, "offline_pricing", False))
383
+
384
+
385
+ def _claude_settings_path(a: argparse.Namespace) -> Path | None:
386
+ if getattr(a, "claude_settings", None):
387
+ return Path(a.claude_settings).expanduser()
388
+ return next((c for c in get_adapter("claude-code").config_paths() if c.exists()), None)
389
+
390
+
391
+ def _idle_opts(a: argparse.Namespace, opts: SimOptions) -> SimOptions:
392
+ """Claude Code settings the replay needs, read-only: idle compaction (on with a 200k minimum when nothing says
393
+ otherwise) and CLAUDE_CODE_MAX_CONTEXT_TOKENS (the window for model IDs Claude Code does not recognize)."""
394
+ if getattr(a, "no_current", False):
395
+ return opts
396
+ path = _claude_settings_path(a)
397
+ enabled, min_tokens, _ = read_idle(path)
398
+ if enabled is not None:
399
+ opts.idle_compaction = enabled
400
+ if min_tokens:
401
+ opts.idle_min_tokens = min_tokens
402
+ opts.claude_max_context = read_env_int(path, MAX_CONTEXT_ENV)
403
+ return opts
404
+
405
+
406
+ def _config_paths(a: argparse.Namespace) -> dict[str, Path | None]:
407
+ """Each harness's config file: the one named on the command line, else the first default that exists."""
408
+ paths: dict[str, Path | None] = {}
409
+ for h, arg in (
410
+ ("claude-code", a.claude_settings),
411
+ ("codex", a.codex_config),
412
+ ("opencode", getattr(a, "opencode_config", None)),
413
+ ("gemini-cli", getattr(a, "gemini_settings", None)),
414
+ ):
415
+ if arg:
416
+ paths[h] = Path(arg).expanduser()
417
+ else:
418
+ cands = get_adapter(h).config_paths() if h in adapter_names() else []
419
+ paths[h] = next((c for c in cands if c.exists()), None)
420
+ return paths
421
+
422
+
423
+ def _current(a: argparse.Namespace, pairs: set[tuple[str, str]]) -> dict[tuple[str, str], tuple[int | None, str]]:
424
+ """Read the configured threshold per (harness, model) from config files, read-only."""
425
+ if getattr(a, "no_current", False):
426
+ return {}
427
+ paths = _config_paths(a)
428
+ out = {}
429
+ for h, m in sorted(pairs):
430
+ try:
431
+ out[(h, m)] = read_current(h, m, paths.get(h))
432
+ except (OSError, ValueError) as e:
433
+ out[(h, m)] = (None, f"unreadable: {e}")
434
+ return out
435
+
436
+
437
+ def _load_result(path: str) -> dict[str, Any]:
438
+ p = Path(path).expanduser()
439
+ if not p.exists():
440
+ raise CLIError(f"{p} does not exist. Create it first with: compactlab simulate --out {path}")
441
+ res: dict[str, Any] = json.loads(p.read_text())
442
+ if res.get("schema", 0) < 4:
443
+ raise CLIError(f"{p} was made by an older compactlab (schema {res.get('schema')}); re-run compactlab simulate")
444
+ if any("impact" not in c["vs_default"] for g in res["groups"] for c in g.get("comparison", {}).values()):
445
+ reselect(res) # results saved before per-day impact existed: recompute selection (no replay)
446
+ drift = price_drift(res, PricingTable.load())
447
+ if drift:
448
+ what = "; ".join(f"{d['model']} {d['field']} {d['old']:g} -> {d['new']:g}" for d in drift[:6])
449
+ more = f" (+{len(drift) - 6} more)" if len(drift) > 6 else ""
450
+ print(f"note: prices or windows changed since {p.name} was made: {what}{more}. Its picks use the old figures; "
451
+ "re-run `compactlab simulate` for today's.", file=sys.stderr) # fmt: skip
452
+ return res
453
+
454
+
455
+ def run_analysis(a: argparse.Namespace) -> dict[str, Any] | None:
456
+ """Scan and analyse. A lite run with the scan cache first looks for a saved result made from the same files and
457
+ inputs and, when there is one, returns it without decoding a session; output is the same as a full run's."""
458
+ cut = _cut(a)
459
+ keep = None if a.no_cache or a.mode != "lite" else ScanCache(a.cache_dir)
460
+ try:
461
+ return _run_analysis(a, cut, keep)
462
+ finally:
463
+ if keep is not None:
464
+ keep.close()
465
+
466
+
467
+ def _run_analysis(a: argparse.Namespace, cut: float | None, keep: ScanCache | None) -> dict[str, Any] | None:
468
+ files, nfiles = _files_key(a, cut) if keep is not None else ("", 0)
469
+ priced: dict[frozenset[tuple[str, str]], PricingTable] = {}
470
+ facts = _facts(keep.facts(files)) if keep is not None else None
471
+ if keep is not None and facts is not None:
472
+ seen, pairs = facts
473
+ pricing = _prices(a, seen, priced)
474
+ opts = _idle_opts(a, _opts(a))
475
+ saved = keep.result(files, _inputs_key(pricing, opts, _current(a, pairs)))
476
+ try:
477
+ reused = _notes(saved) if saved is not None else None
478
+ except (KeyError, TypeError, AttributeError): # a damaged row: analyse again, which replaces it
479
+ reused = None
480
+ if reused is not None:
481
+ a.scan_stats = {"files": nfiles, "cached": 0, "parsed": 0, "reused": True} # no log was read
482
+ a.scan_failed = set() # not an earlier run's (the service reuses `a`)
483
+ return reused
484
+ sessions = load_sessions(a, cut, text=a.mode == "deep")
485
+ if not sessions:
486
+ roots = [str(r) for h in (a.harness or adapter_names()) for r in get_adapter(h)(_roots(a).get(h)).roots]
487
+ raise CLIError(
488
+ "no sessions with usage data found under:\n "
489
+ + "\n ".join(roots)
490
+ + "\nRun `compactlab doctor` to check locations, `--since-days 0` to include older files, "
491
+ "or `compactlab demo` to see a report built from synthetic data."
492
+ )
493
+ seen = {(t.model, s.platform) for s in sessions for t in s.turns}
494
+ pairs = {(x.harness, x.model) for x in sessions}
495
+ pricing = _prices(a, seen, priced)
496
+ quiet = getattr(a, "service", False)
497
+
498
+ def step(i: int, n: int, name: str) -> None:
499
+ _progress(f"simulating {i}/{n}" + ("" if quiet else f": {name}"))
500
+
501
+ opts = _idle_opts(a, _opts(a))
502
+ current = _current(a, pairs)
503
+ res = analyze(sessions, pricing, opts, current=current, progress=step)
504
+ _progress("")
505
+ if keep is not None and not a.scan_errors: # a log that could not be read this time must not be keyed as read
506
+ try:
507
+ text = json.dumps(res)
508
+ except (TypeError, ValueError):
509
+ text = ""
510
+ if text:
511
+ about = {"seen": sorted(seen, key=json.dumps), "pairs": sorted(pairs)}
512
+ keep.save_result(files, _inputs_key(pricing, opts, current), about, text, time.time())
513
+ res = json.loads(text) # the same object a run reusing it gets
514
+ res = _notes(res)
515
+ if a.mode == "deep":
516
+ return _deep(a, sessions, res, pricing)
517
+ return res
518
+
519
+
520
+ def _facts(d: Any) -> tuple[set[tuple[Any, Any]], set[tuple[str, str]]] | None:
521
+ """The models seen (model, platform or None) and harness/model pairs saved with a result; None if damaged."""
522
+ try:
523
+ return {(m, p) for m, p in d["seen"]}, {(str(h), str(m)) for h, m in d["pairs"]}
524
+ except (KeyError, TypeError, ValueError):
525
+ return None
526
+
527
+
528
+ def _prices(
529
+ a: argparse.Namespace, seen: set[tuple[str, str]], priced: dict[frozenset[tuple[str, str]], PricingTable]
530
+ ) -> PricingTable:
531
+ """The price table for these (model, platform) pairs: with automatic refresh on, a service run may download a
532
+ newer one first. Memoized in `priced`, so a run that looks for a saved result and then analyses refreshes once."""
533
+ if frozenset(seen) in priced:
534
+ return priced[frozenset(seen)]
535
+ pricing = _pricing(a)
536
+ quiet = getattr(a, "service", False)
537
+ if quiet and not getattr(a, "offline_pricing", False) and not getattr(a, "pricing", None):
538
+ from ..pricing.auto import maybe_refresh
539
+
540
+ pricing, info = maybe_refresh(pricing, seen, time.time(), lambda: _pricing(a))
541
+ if info:
542
+ import logging
543
+
544
+ moved = "; ".join(f"{c['model']} {c['field']} {c['old']} -> {c['new']}" for c in info["changes"])
545
+ logging.getLogger("compactlab.service").info(
546
+ "price refresh (%s%s): %s", info["reason"],
547
+ f": {', '.join(info['missing'])}" if info["missing"] else "",
548
+ f"from {info['source']}; changed for your models: {moved or 'nothing'}; "
549
+ f"still unpriced: {', '.join(info['still_missing']) or 'none'}"
550
+ if info["refreshed"] else f"failed ({info['error']})") # fmt: skip
551
+ priced[frozenset(seen)] = pricing
552
+ return pricing
553
+
554
+
555
+ def _notes(res: dict[str, Any]) -> dict[str, Any]:
556
+ """Notes that depend on today and on the price refresh state, not on the analysis: added to a saved result too."""
557
+ from ..pricing.auto import load_state
558
+
559
+ res["model_notes"]["auto_refresh"] = bool(load_state().get("enabled"))
560
+ # price and window changes the refreshes brought in the last 30 days, for the rows your models use
561
+ used = {g["price_key"] for g in res["groups"]}
562
+ since = time.strftime("%Y-%m-%d", time.localtime(time.time() - 30 * 86400))
563
+ res["model_notes"]["price_changes"] = [
564
+ c for c in recent_changes(DEFAULT_REFRESHED, used, limit=50) if str(c.get("date", "")) >= since
565
+ ]
566
+ return res
567
+
568
+
569
+ def _deep(
570
+ a: argparse.Namespace, sessions: list[Session], res: dict[str, Any], pricing: PricingTable
571
+ ) -> dict[str, Any] | None:
572
+ if a.budget is None:
573
+ raise CLIError("--mode deep needs --budget USD (a hard cap)")
574
+ plan = plan_deep(sessions, res, pricing, a.model, a.judge_model, a.repeats, a.sessions_per_group)
575
+ print(
576
+ f"deep plan: {len(plan.pairs)} re-summarizations via {a.executor} ({a.model}, judge {a.judge_model}); "
577
+ f"estimated ~${plan.est_usd:.2f}; hard cap ${a.budget:.2f}",
578
+ file=sys.stderr,
579
+ )
580
+ if not a.yes:
581
+ print(
582
+ "not running deep: review the estimate, then re-run with --yes (lite results are unaffected)",
583
+ file=sys.stderr,
584
+ )
585
+ return None
586
+ from ..eval.executors import EXECUTORS
587
+
588
+ client = (
589
+ MockClient()
590
+ if a.executor == "mock"
591
+ else (EXECUTORS[a.executor]() if a.executor in EXECUTORS else load_client(a.executor))
592
+ )
593
+ try:
594
+ return deep_analyze(
595
+ plan,
596
+ res,
597
+ client,
598
+ model=a.model,
599
+ judge_model=a.judge_model,
600
+ pricing=pricing,
601
+ budget_usd=a.budget,
602
+ repeats=a.repeats,
603
+ confirm=True,
604
+ )
605
+ except EvalError as e:
606
+ raise CLIError(str(e)) from e
607
+
608
+
609
+ def _k_(v: int | None) -> str:
610
+ return "-" if v is None else f"{v // 1000}k"
611
+
612
+
613
+ def _hrs(sec: float) -> str:
614
+ return f"{sec / 3600:+.1f}h" if abs(sec) >= 360 else f"{sec / 60:+.0f}m"
615
+
616
+
617
+ WIDTHS = ((16, "<"), (8, ">"), (22, "<"), (18, ">"), (16, ">"), (14, ">"), (16, ">"))
618
+
619
+
620
+ def _pad(text: str, width: int, align: str) -> str:
621
+ """Pad by display width (CJK characters take two columns)."""
622
+ import unicodedata
623
+
624
+ w = sum(2 if unicodedata.east_asian_width(ch) in "WF" else 1 for ch in text)
625
+ fill = " " * max(width - w, 0)
626
+ return (fill + text if align == ">" else text + fill) + " "
627
+
628
+
629
+ T: dict[str, dict[str, Any]] = {
630
+ "en": {
631
+ "cols": ("profile", "window", "action", "Δcost vs default", "Δtime (/day)", "compactions/d", "recall"),
632
+ "default": "default",
633
+ "current": "current",
634
+ "cost": "cost",
635
+ "balanced": "balanced",
636
+ "time": "time",
637
+ "vs_current": "vs current",
638
+ "no_action": "no action needed: the default never compacts in these sessions",
639
+ "time_src": "time model: turn latency from {t}, compaction latency from {c} ({n} own samples)",
640
+ "src": {"own": "this group's data", "pooled": "all {h} sessions (this group is thin)", "prior": "a prior"},
641
+ "flags": {
642
+ "below_quarter_window": "{p}: below 25% of the max window; expect frequent lossy compactions",
643
+ "wait_over_cap": "{p}: adds more than {cap:g} min/day of compaction wait vs default",
644
+ "guardrail_applied": "{p}: guardrail moved the pick from {u} to {t}",
645
+ "recall_floor_not_met": "{p}: no threshold met the recall floor",
646
+ "wait_cap_unreachable": "{p}: no threshold keeps added wait under {cap:g} min/day",
647
+ "min_window_unreachable": "{p}: the grid does not reach the profile's minimum window",
648
+ "deep_recall_below_floor": "{p}: deep mode measured recall below the floor; lowered to {t}",
649
+ },
650
+ "note": "Profile shown first is selected (--profile, default balanced). Δ vs the harness default. "
651
+ "Costs are list-price estimates; recall is an assumed proxy in lite mode.",
652
+ },
653
+ "zh": {
654
+ "cols": ("方案", "阈值", "建议", "成本差(对默认)", "时间差(每天)", "每天压缩", "召回"),
655
+ "default": "默认",
656
+ "current": "当前",
657
+ "cost": "省钱",
658
+ "balanced": "均衡",
659
+ "time": "省时",
660
+ "vs_current": "对当前",
661
+ "no_action": "无需调整:默认设置在这些会话里从未触发压缩",
662
+ "time_src": "时间模型:每轮耗时来自{t},压缩耗时来自{c}(本组 {n} 个样本)",
663
+ "src": {"own": "本组数据", "pooled": "全部 {h} 会话(本组样本太少)", "prior": "先验值"},
664
+ "flags": {
665
+ "below_quarter_window": "{p}:低于最大窗口的 25%,会频繁做有损压缩",
666
+ "wait_over_cap": "{p}:比默认每天多等压缩超过 {cap:g} 分钟",
667
+ "guardrail_applied": "{p}:护栏把选择从 {u} 调到 {t}",
668
+ "recall_floor_not_met": "{p}:没有阈值达到召回下限",
669
+ "wait_cap_unreachable": "{p}:没有阈值能把额外等待压到每天 {cap:g} 分钟以内",
670
+ "min_window_unreachable": "{p}:网格达不到该方案的最小窗口",
671
+ "deep_recall_below_floor": "{p}:deep 模式实测召回低于下限,已降到 {t}",
672
+ },
673
+ "note": "第一行方案是当前选择(--profile,默认均衡)。差值相对 harness 默认值。"
674
+ "成本按公开标价估算;lite 模式下召回率是假设代理值。",
675
+ },
676
+ }
677
+ ACTION_ZH = {"set": "设置", "keep default": "保持默认", "keep current": "保持当前", "no action needed": "无需调整",
678
+ "-": "-"} # fmt: skip
679
+
680
+
681
+ def _dtime(c: dict[str, Any]) -> str:
682
+ return f"{_hrs(c['d_time_s'])} ({c['d_time_min_per_day']:+.0f}m)"
683
+
684
+
685
+ def _term(a: argparse.Namespace, stream: Any = None) -> tuple[Any, int] | None:
686
+ """(style, columns) for the terminal views, or None for the plain tables: --plain, or --color auto off a TTY."""
687
+ from ..term.style import Style
688
+
689
+ stream = stream or sys.stdout
690
+ mode = getattr(a, "color", "auto")
691
+ if getattr(a, "plain", False) or (mode == "auto" and not stream.isatty()):
692
+ return None
693
+ return Style.detect(stream, mode), max(30, min(shutil.get_terminal_size((100, 30)).columns, 200))
694
+
695
+
696
+ def _lang1(a: argparse.Namespace) -> str:
697
+ return "zh" if getattr(a, "lang", "en") == "zh" else "en"
698
+
699
+
700
+ def _summary_out(a: argparse.Namespace, res: dict[str, Any]) -> str:
701
+ """The terminal view on a TTY, the full plain tables otherwise."""
702
+ t = _term(a)
703
+ if not t:
704
+ return _summary(res, getattr(a, "lang", "both"))
705
+ from ..term.views import summary_view
706
+
707
+ style, cols = t
708
+ return str(style.lines(summary_view(res, cols, _lang1(a), getattr(a, "unit", "pct"))))
709
+
710
+
711
+ def _summary(res: dict[str, Any], lang: str = "both") -> str:
712
+ from ..sim.select import compare
713
+
714
+ langs = ["en", "zh"] if lang == "both" else [lang]
715
+
716
+ def name(key: str) -> str:
717
+ return "/".join(T[x][key] for x in langs)
718
+
719
+ def act(action: str) -> str:
720
+ if action == "-" or lang == "en":
721
+ return action
722
+ return ACTION_ZH.get(action, action) if lang == "zh" else f"{action}/{ACTION_ZH.get(action, action)}"
723
+
724
+ head = f"mode: {res['mode']}" + (f" (deep spent ${res['deep']['spent_usd']:.2f})" if res.get("deep") else "")
725
+ from ..term.views import verdict
726
+
727
+ lines = [head]
728
+ for x in langs:
729
+ v = "".join(t for t, _ in verdict(res, x))
730
+ if v:
731
+ lines.append(v)
732
+ for g in res["groups"]:
733
+ d, days, sel = g["default"], g["days"], g["profile"]
734
+ lines.append(
735
+ f"\n{g['model']} · {g['role']} · {g['n_sessions']} sessions · {g['n_turns']} turns"
736
+ f" · {days:.0f} days · window {_k_(g['max_window'])}"
737
+ )
738
+ for hdr in [T[x]["cols"] for x in langs]:
739
+ lines.append(" " + "".join(_pad(h, w, al) for h, (w, al) in zip(hdr, WIDTHS, strict=True)))
740
+
741
+ def row(cells: tuple[str, ...]) -> str:
742
+ return " " + "".join(_pad(x, w, al) for x, (w, al) in zip(cells, WIDTHS, strict=True))
743
+
744
+ lines.append(row((name("default"), _k_(d["threshold"]), "-", f"${d['combined_cost']:,.0f} (base)", "0",
745
+ f"{d['compactions'] / days:.1f}", f"{d['recall']:.3f}"))) # fmt: skip
746
+ if g.get("current"):
747
+ c = g["current"]
748
+ cm = compare(c, d, days)
749
+ lines.append(row((name("current"), _k_(c["configured"]), "-", _dc(cm), _dtime(cm),
750
+ f"{cm['compactions_per_day']:.1f}", f"{c['recall']:.3f}"))) # fmt: skip
751
+ order = [sel] + [n for n in PROFILE_NAMES if n != sel]
752
+ for n in order:
753
+ cm, p = g["comparison"][n], g["profiles"][n]
754
+ v = cm["vs_default"]
755
+ label = name(n) + ("*" if n == sel else "")
756
+ if cm["action"] == "no action needed":
757
+ lines.append(row((label, "-", act(cm["action"]), "-", "-", f"{v['compactions_per_day']:.1f}",
758
+ f"{p['recall']:.3f}"))) # fmt: skip
759
+ continue
760
+ rc = f"{p['recall']:.3f} ({v['d_recall']:+.3f})"
761
+ lines.append(row((label, _k_(cm["threshold"]), act(cm["action"]), _dc(v), _dtime(v),
762
+ f"{v['compactions_per_day']:.1f}", rc))) # fmt: skip
763
+ notes = []
764
+ if g.get("current") and not g["no_action_needed"]:
765
+ vc = {n: g["comparison"][n]["vs_current"] for n in PROFILE_NAMES}
766
+ parts = [f"{name(n)} {_dc(v)} {_hrs(v['d_time_s'])}" for n, v in vc.items()]
767
+ notes.append(f"{name('vs_current')}: " + "; ".join(parts))
768
+ if g["no_action_needed"]:
769
+ notes += [T[x]["no_action"] for x in langs]
770
+ tmod = g["time_model"]
771
+ for x in langs:
772
+ src = T[x]["src"]
773
+ notes.append(T[x]["time_src"].format(t=src[tmod.get("turn_source", "prior")].format(h=g["harness"]),
774
+ c=src[tmod.get("compact_source", "prior")].format(h=g["harness"]),
775
+ n=tmod["n_compact_samples"])) # fmt: skip
776
+ if not g["no_action_needed"]:
777
+ for n in order:
778
+ p = g["profiles"][n]
779
+ fmt = {"cap": p["wait_cap_min_per_day"], "u": _k_(p["unconstrained_threshold"]),
780
+ "t": _k_(p["threshold"])} # fmt: skip
781
+ for f in p["flags"]:
782
+ notes += [T[x]["flags"][f].format(p=T[x][n], **fmt) for x in langs if f in T[x]["flags"]]
783
+ sel_cmp = g["comparison"][g.get("profile") or "balanced"]
784
+ if sel_cmp.get("global") and sel_cmp["action"] != "set":
785
+ from ..term.views import keep_reason
786
+
787
+ notes += [keep_reason(g, g.get("profile") or "balanced", x) for x in langs]
788
+ if g.get("cache_ttl"):
789
+ notes += [_ttl_note(g, x) for x in langs]
790
+ if "en" in langs:
791
+ notes.append(f"default: {d['note']}" + (f"; current: {g['current_note']}" if g.get("current_note") else ""))
792
+ if "zh" in langs:
793
+ notes.append(
794
+ f"默认依据:{d.get('note_zh', d['note'])}"
795
+ + (f";当前:{g['current_note']}" if g.get("current_note") else "")
796
+ )
797
+ lines += [f" · {n}" for n in notes]
798
+ from ..term.views import idle_lines, model_lines
799
+
800
+ for x in langs:
801
+ il = idle_lines(res, x)
802
+ if il:
803
+ lines += ["", *il]
804
+ ml = model_lines(res, x)
805
+ if ml:
806
+ lines += ["", *ml]
807
+ lines.append("")
808
+ lines += [T[x]["note"] for x in langs]
809
+ return "\n".join(ln.rstrip() for ln in lines)
810
+
811
+
812
+ def _dc(c: dict[str, Any]) -> str:
813
+ sign = "+" if c["d_cost"] >= 0 else "-"
814
+ return f"{sign}${abs(c['d_cost']):,.0f} ({c['d_cost_pct'] * 100:+.0f}%)"
815
+
816
+
817
+ IMPACT: dict[str, dict[str, Any]] = {
818
+ "en": {
819
+ "title": "Per-day impact · {m} · {r} · history {d:.1f} calendar days, {a} active days (with ≥1 turn)",
820
+ "vs": {"vs_default": "vs harness default {t}", "vs_current": "vs your current {t}"},
821
+ "cols": (
822
+ "profile",
823
+ "window",
824
+ "$/day",
825
+ "$/active d",
826
+ "$/month",
827
+ "min/day",
828
+ "wait",
829
+ "turns",
830
+ "min/active d",
831
+ "h/month",
832
+ "compact/d",
833
+ "/month",
834
+ ),
835
+ "legend": "Sign: -$ / -min = saves, + = adds. min/day = wait (compaction + re-discovery) - turns "
836
+ "(faster turns from a smaller context). Month = 30 days. List-price estimates; recall is a lite-mode proxy.",
837
+ "keep": "{p}: picks {t}, which is not better than the default: recommend keeps the default",
838
+ "keep_cur": "{p}: picks {t}, within the tolerance of your current {c}: recommend keeps your setting",
839
+ },
840
+ "zh": {
841
+ "title": "每日影响 · {m} · {r} · 历史覆盖 {d:.1f} 个自然日,其中 {a} 个活跃日(至少一轮)",
842
+ "vs": {"vs_default": "对 harness 默认 {t}", "vs_current": "对你当前的 {t}"},
843
+ "cols": (
844
+ "方案",
845
+ "阈值",
846
+ "$/天",
847
+ "$/活跃天",
848
+ "$/月",
849
+ "分钟/天",
850
+ "等待",
851
+ "每轮",
852
+ "分钟/活跃天",
853
+ "小时/月",
854
+ "压缩/天",
855
+ "/月",
856
+ ),
857
+ "legend": "符号:-$ / -分钟 = 节省,+ = 增加。分钟/天 = 等待(压缩 + 重新查找)- 每轮提速(上下文更小)。"
858
+ "一个月按 30 天。成本按公开标价估算;lite 模式下召回率是代理值。",
859
+ "keep": "{p}:选出 {t},不比默认值好,recommend 会保持默认",
860
+ "keep_cur": "{p}:选出 {t},与你当前的 {c} 相差在容差内,recommend 会保持你的设置",
861
+ },
862
+ }
863
+ IWIDTHS = ((14, "<"), (7, ">"), (10, ">"), (11, ">"), (11, ">"), (9, ">"), (8, ">"), (8, ">"), (13, ">"),
864
+ (9, ">"), (10, ">"), (7, ">")) # fmt: skip
865
+
866
+
867
+ def _usd(x: float | None) -> str:
868
+ if x is None:
869
+ return "-"
870
+ if abs(x) < 0.05:
871
+ return "$0"
872
+ return f"{'-' if x < 0 else '+'}${abs(x):,.1f}" if abs(x) < 1000 else f"{'-' if x < 0 else '+'}${abs(x):,.0f}"
873
+
874
+
875
+ def _mins(x: float | None) -> str:
876
+ return "-" if x is None else ("0.0" if abs(x) < 0.05 else f"{x:+.1f}")
877
+
878
+
879
+ def impact_text(res: dict[str, Any], lang: str = "both") -> str:
880
+ """Per-day / per-active-day / per-month table for every profile of every group, vs default and current."""
881
+ langs = ["en", "zh"] if lang == "both" else [lang]
882
+ lines: list[str] = []
883
+ for g in res["groups"]:
884
+ if g["no_action_needed"]:
885
+ continue
886
+ sel = g["profile"]
887
+ active = g.get("active_days")
888
+ act = f"{active:.3g}" if active is not None else "?"
889
+ lines.append("")
890
+ lines += [IMPACT[x]["title"].format(m=g["model"], r=g["role"], d=g["days"], a=act) for x in langs]
891
+ for ref in ("vs_default", "vs_current"):
892
+ refpt = g["default"] if ref == "vs_default" else g.get("current")
893
+ if not refpt:
894
+ continue
895
+ thr = _k_(refpt.get("configured", refpt["threshold"]))
896
+ lines.append(" " + " / ".join(IMPACT[x]["vs"][ref].format(t=thr) for x in langs))
897
+ for x in langs:
898
+ lines.append(
899
+ " " + "".join(_pad(h, w, al) for h, (w, al) in zip(IMPACT[x]["cols"], IWIDTHS, strict=True))
900
+ )
901
+ for n in [sel] + [n for n in PROFILE_NAMES if n != sel]:
902
+ cm = g["comparison"][n]
903
+ im = (cm.get(ref) or {}).get("impact")
904
+ if not im:
905
+ continue
906
+ u, m, w, tg, c = (
907
+ im["usd"],
908
+ im["minutes"],
909
+ im["wait_minutes"],
910
+ im["turn_gain_minutes"],
911
+ im["compactions"],
912
+ )
913
+ cells = ("/".join(T[x][n] for x in langs) + ("*" if n == sel else ""), _k_(cm["threshold"]),
914
+ _usd(u["per_day"]), _usd(u["per_active_day"]), _usd(u["per_month"]),
915
+ _mins(m["per_day"]), _mins(w["per_day"]), _mins(-tg["per_day"]),
916
+ _mins(m["per_active_day"]), _mins(m["per_month"] / 60), f"{c['per_day']:.1f}",
917
+ f"{c['per_month']:.0f}") # fmt: skip
918
+ lines.append(" " + "".join(_pad(v, w_, al) for v, (w_, al) in zip(cells, IWIDTHS, strict=True)))
919
+ for n in PROFILE_NAMES:
920
+ act_n = g["comparison"][n]["action"]
921
+ if act_n in ("keep default", "keep current") and g["comparison"][n].get("global"):
922
+ from ..term.views import keep_reason
923
+
924
+ lines += [f" · {T[x][n]}: {keep_reason(g, n, x)}" for x in langs]
925
+ elif act_n in ("keep default", "keep current"):
926
+ key = "keep" if act_n == "keep default" else "keep_cur"
927
+ lines += [" · " + IMPACT[x][key].format(p=T[x][n], t=_k_(g["profiles"][n]["threshold"]),
928
+ c=_k_((g.get("current") or {}).get("configured")))
929
+ for x in langs] # fmt: skip
930
+ if lines:
931
+ lines.append("")
932
+ lines += [IMPACT[x]["legend"] for x in langs]
933
+ return "\n".join(ln.rstrip() for ln in lines)
934
+
935
+
936
+ # ---------- commands ----------
937
+
938
+
939
+ def cmd_scan(a: argparse.Namespace) -> int:
940
+ ss = load_sessions(a)
941
+ rows: dict[tuple[str, str, str], dict[str, Any]] = {}
942
+ unknown: dict[str, int] = {}
943
+ for s in ss:
944
+ d = rows.setdefault((s.harness, s.role, s.model), {"sessions": 0, "turns": 0, "compactions": 0, "peak": 0})
945
+ d["sessions"] += 1
946
+ d["turns"] += len(s.turns)
947
+ d["compactions"] += len(s.compactions)
948
+ d["peak"] = max(d["peak"], s.peak)
949
+ for k, v in s.unknown_events.items():
950
+ unknown[f"{s.harness}:{k}"] = unknown.get(f"{s.harness}:{k}", 0) + v
951
+ obj = {
952
+ "sessions": len(ss),
953
+ "groups": [{"harness": h, "role": r, "model": m, **d} for (h, r, m), d in sorted(rows.items())],
954
+ "unknown_event_types": unknown,
955
+ }
956
+ text = [
957
+ f"{len(ss)} sessions",
958
+ f"{'harness':12} {'role':9} {'model':26} {'sess':>5} {'turns':>7} {'compact':>8} {'peak':>7}",
959
+ ]
960
+ text += [
961
+ f"{h:12} {r:9} {m[:26]:26} {d['sessions']:>5} {d['turns']:>7} {d['compactions']:>8} {d['peak'] // 1000:>6}k"
962
+ for (h, r, m), d in sorted(rows.items())
963
+ ]
964
+ if unknown:
965
+ text.append(
966
+ "unrecognized event types (ignored, counted): " + ", ".join(f"{k}={v}" for k, v in sorted(unknown.items()))
967
+ )
968
+ _out(a, obj, "\n".join(text))
969
+ return 0
970
+
971
+
972
+ def cmd_simulate(a: argparse.Namespace) -> int:
973
+ res = run_analysis(a)
974
+ if res is None:
975
+ return 2
976
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
977
+ Path(a.out).write_text(json.dumps(res, sort_keys=True))
978
+ if a.lens_out: # shared with the service and earlier runs: keeps the harnesses this run did not cover
979
+ from ..lens import summarize
980
+ from ..publish import update
981
+
982
+ update(Path(a.lens_out).expanduser(), summarize(res), covered(a, res))
983
+ _out(
984
+ a,
985
+ {
986
+ "result": a.out,
987
+ "mode": res["mode"],
988
+ "groups": [
989
+ {k: g[k] for k in ("harness", "model", "role", "profile", "profiles", "comparison")}
990
+ for g in res["groups"]
991
+ ],
992
+ },
993
+ _summary_out(a, res) + f"\n\nwrote {a.out}",
994
+ )
995
+ return 0
996
+
997
+
998
+ def cmd_report(a: argparse.Namespace) -> int:
999
+ res = _reselect(a, _load_result(a.result)) if a.result else run_analysis(a)
1000
+ if res is None:
1001
+ return 2
1002
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
1003
+ Path(a.out).write_text(render_html(res, redact=a.redact))
1004
+ print(f"wrote {a.out}")
1005
+ if a.open:
1006
+ _open(Path(a.out))
1007
+ return 0
1008
+
1009
+
1010
+ def _open(p: Path) -> None:
1011
+ if platform.system() == "Darwin" and shutil.which("open"):
1012
+ subprocess.run(["open", str(p)], check=False)
1013
+ else:
1014
+ webbrowser.open(p.resolve().as_uri())
1015
+
1016
+
1017
+ def _apply_opts(p: argparse.ArgumentParser) -> None:
1018
+ g = p.add_argument_group("apply")
1019
+ g.add_argument(
1020
+ "--preauth", help="pre-authorization JSON: allowed files, key patterns, models, bounds (docs/SAFETY.md)"
1021
+ )
1022
+ g.add_argument(
1023
+ "--i-authorize", action="store_true", help="explicit one-off authorization instead of a preauth file"
1024
+ )
1025
+ g.add_argument("--models", nargs="*", help="models allowed with --i-authorize")
1026
+ g.add_argument("--min", type=_k, default=100_000, help="lower bound with --i-authorize (default 100k)")
1027
+ g.add_argument("--max", type=_k, default=1_000_000, help="upper bound with --i-authorize (default 1m)")
1028
+ g.add_argument("--write", action="store_true", help="actually write; without it apply is a dry-run")
1029
+ g.add_argument(
1030
+ "--expect-plan",
1031
+ metavar="HASH",
1032
+ help="refuse (exit 2, write nothing) unless the plan is the one a dry-run printed with this hash",
1033
+ )
1034
+ g.add_argument("--state-dir", default=STATE, help="backups, manifests and the lock (default ~/.compactlab)")
1035
+
1036
+
1037
+ def _preauth(a: argparse.Namespace) -> ap.Preauth:
1038
+ if a.preauth:
1039
+ return ap.load_preauth(a.preauth)
1040
+ if not a.i_authorize:
1041
+ raise ap.ApplyError(
1042
+ "writing needs --preauth FILE, or --i-authorize with explicit --claude-settings/--codex-config and --models"
1043
+ )
1044
+ files = {h: Path(f) for h, f in (("claude-code", a.claude_settings), ("codex", a.codex_config)) if f}
1045
+ if not files or not a.models:
1046
+ raise ap.ApplyError("--i-authorize needs explicit config file paths and --models")
1047
+ return ap.explicit_preauth(files, a.models, a.min, a.max)
1048
+
1049
+
1050
+ def _recs(res: dict[str, Any]) -> list[dict[str, Any]]:
1051
+ """The selected profile's threshold per main-session model; groups where the default is fine are left alone. A
1052
+ harness with one setting for every model (Codex) gets one entry: the value chosen across its models."""
1053
+ out = []
1054
+ seen: set[str] = set()
1055
+ for g in res["groups"]:
1056
+ if g["role"] != "main" or g["comparison"][g["profile"]]["action"] in (
1057
+ "no action needed", "keep default", "keep current"): # fmt: skip
1058
+ continue
1059
+ glob = (res.get("global_keys") or {}).get(g["harness"])
1060
+ if glob:
1061
+ if g["harness"] in seen:
1062
+ continue
1063
+ seen.add(g["harness"])
1064
+ out.append({"harness": g["harness"], "model": g["model"],
1065
+ "value": glob["profiles"][g["profile"]]["threshold"]}) # fmt: skip
1066
+ continue
1067
+ out.append({"harness": g["harness"], "model": ap.model_key(g["harness"], g["model"]),
1068
+ "value": g["profiles"][g["profile"]]["threshold"]}) # fmt: skip
1069
+ return out
1070
+
1071
+
1072
+ def _apply_error(a: argparse.Namespace, code: str, text: str, plan: dict[str, Any] | None = None) -> None:
1073
+ """A refusal: the reason on stderr and, with --json, an `error` object ({code, message}) on stdout, next to the
1074
+ plan when there is one, so a caller never has to parse stderr. Codes: refused, plan_changed, busy."""
1075
+ print(f"{'busy' if code == 'busy' else 'refused'}: {text}", file=sys.stderr)
1076
+ if getattr(a, "json", False):
1077
+ _out(a, {**(plan or {}), "error": {"code": code, "message": text}}, "")
1078
+
1079
+
1080
+ def _single_flight(a: argparse.Namespace, job: str, fn: Callable[[], int]) -> int:
1081
+ """Run `fn` holding the state dir's lock (service/lock.py). While another calibration or config write holds it,
1082
+ run nothing and exit EX_BUSY."""
1083
+ from ..service.lock import Busy, LockError, single_flight
1084
+
1085
+ try:
1086
+ with single_flight(Path(a.state_dir).expanduser(), job):
1087
+ return fn()
1088
+ except Busy as e:
1089
+ _apply_error(a, "busy", str(e))
1090
+ return EX_BUSY
1091
+ except LockError as e:
1092
+ _apply_error(a, "refused", str(e))
1093
+ return 2
1094
+
1095
+
1096
+ def _do_apply(a: argparse.Namespace, res: dict[str, Any], retune: bool = False) -> int:
1097
+ """Plan, show and (with --write) write. A write runs under the state dir's lock (the caller holds it), so the
1098
+ plan it checks against --expect-plan is the one it writes."""
1099
+ try:
1100
+ if a.write or retune:
1101
+ pre = _preauth(a)
1102
+ if retune and not pre.allow_retune:
1103
+ raise ap.ApplyError('retune needs a --preauth file with "allow_retune": true')
1104
+ elif a.preauth:
1105
+ pre = ap.load_preauth(a.preauth)
1106
+ else:
1107
+ files = {h: Path(f) for h, f in (("claude-code", a.claude_settings), ("codex", a.codex_config)) if f}
1108
+ pre = ap.explicit_preauth(files, a.models or [g["model"] for g in res["groups"]], a.min, a.max)
1109
+ changes, rejected = ap.plan_changes(_recs(res), pre)
1110
+ rendered = ap.render(changes)
1111
+ except ap.ApplyError as e:
1112
+ _apply_error(a, "refused", str(e))
1113
+ return 2
1114
+ h = ap.plan_hash(changes)
1115
+ plan = {
1116
+ "profile": res["groups"][0]["profile"] if res["groups"] else (a.profile or DEFAULT_PROFILE),
1117
+ "dry_run": not a.write,
1118
+ "changes": [
1119
+ {"harness": c.harness, "file": str(c.file), "key": c.key, "old": c.old, "new": c.new} for c in changes
1120
+ ],
1121
+ "skipped": rejected,
1122
+ "plan_hash": h,
1123
+ }
1124
+ text = [f"skip: {r}" for r in rejected]
1125
+ text += [f"{c.harness}: {c.key}: {c.old!r} -> {c.new} ({c.file})" for c in changes]
1126
+ if changes:
1127
+ text.append(ap.diff_text(rendered))
1128
+ text += [f"note: {n}" for n in ap.formatting_note(rendered, changes)]
1129
+ else:
1130
+ text.append("nothing to change")
1131
+ text.append(f"plan {h}")
1132
+ want = None if a.expect_plan is None else a.expect_plan.strip().lower()
1133
+ if want is not None and want != h: # an empty hash never matches
1134
+ if not a.json:
1135
+ print("\n".join(text))
1136
+ why = f"the plan is not the reviewed one (expected {want or '(empty)'}, now {h})"
1137
+ _apply_error(a, "plan_changed", f"{why}; nothing written: review this plan, then pass its hash", plan)
1138
+ return 2
1139
+ if changes and not a.write:
1140
+ text.append("dry-run: nothing written (add --write with authorization to apply)")
1141
+ if changes and a.write:
1142
+ m = ap.write_changes(changes, Path(a.state_dir).expanduser(), pre)
1143
+ plan["manifest"] = str(m)
1144
+ text.append(f"applied; manifest {m}\nundo with: compactlab revert --state-dir {a.state_dir}")
1145
+ _out(a, plan, "\n".join(text))
1146
+ return 0
1147
+
1148
+
1149
+ def cmd_apply(a: argparse.Namespace) -> int:
1150
+ res = _reselect(a, _load_result(a.result))
1151
+ if not a.write:
1152
+ return _do_apply(a, res) # a dry-run only reads: no lock
1153
+ return _single_flight(a, "apply --write", lambda: _do_apply(a, res))
1154
+
1155
+
1156
+ def cmd_retune(a: argparse.Namespace) -> int:
1157
+ if not a.preauth:
1158
+ _apply_error(a, "refused", 'retune needs --preauth (with "allow_retune": true)')
1159
+ return 2
1160
+
1161
+ def run() -> int: # a calibration, then maybe a write: one job under the lock
1162
+ res = run_analysis(a)
1163
+ return 2 if res is None else _do_apply(a, res, retune=True)
1164
+
1165
+ return _single_flight(a, "retune", run)
1166
+
1167
+
1168
+ def _forget_applied(state: Path, manifest_id: str) -> None:
1169
+ """A reverted auto-apply is no longer what compactlab last wrote: drop it so the next run does not read the
1170
+ restored value as a manual edit."""
1171
+ from ..service.policy import journal, load_applied
1172
+
1173
+ p = state / "service" / "applied.json"
1174
+ applied = load_applied(p)
1175
+ keep = {k: v for k, v in applied.items() if v.get("manifest") != manifest_id}
1176
+ if keep != applied:
1177
+ p.write_text(json.dumps(keep, indent=2))
1178
+ journal(state / "service" / "journal.jsonl", {"reverted": manifest_id})
1179
+
1180
+
1181
+ def cmd_revert(a: argparse.Namespace) -> int:
1182
+ sd = Path(a.state_dir).expanduser()
1183
+
1184
+ def run() -> int:
1185
+ try:
1186
+ m = sd / "manifests" / f"{a.id}.json" if a.id else ap.latest_manifest(sd)
1187
+ for line in ap.revert(m, a.force):
1188
+ print(line)
1189
+ _forget_applied(sd, m.stem)
1190
+ except (ap.ApplyError, FileNotFoundError) as e:
1191
+ print(f"error: {e}", file=sys.stderr)
1192
+ return 2
1193
+ return 0
1194
+
1195
+ return _single_flight(a, "revert", run)
1196
+
1197
+
1198
+ def _version(binary: str) -> str | None:
1199
+ path = shutil.which(binary)
1200
+ if not path:
1201
+ return None
1202
+ try:
1203
+ r = subprocess.run([path, "--version"], capture_output=True, text=True, timeout=5)
1204
+ return (r.stdout or r.stderr).strip().splitlines()[0] if (r.stdout or r.stderr) else "installed"
1205
+ except (OSError, subprocess.TimeoutExpired):
1206
+ return "installed (version unknown)"
1207
+
1208
+
1209
+ def cmd_doctor(a: argparse.Namespace) -> int:
1210
+ report: dict[str, Any] = {
1211
+ "compactlab": __version__,
1212
+ "python": platform.python_version(),
1213
+ "platform": platform.platform(),
1214
+ "harnesses": [],
1215
+ "pricing": {},
1216
+ "cache": {},
1217
+ }
1218
+ bins = {"claude-code": "claude", "codex": "codex", "dsh": "dsh", "opencode": "opencode", "gemini-cli": "gemini"}
1219
+ for name in adapter_names():
1220
+ ad = get_adapter(name)
1221
+ roots = ad.default_roots()
1222
+ report["harnesses"].append(
1223
+ {
1224
+ "name": name,
1225
+ "cli": _version(bins.get(name, name)),
1226
+ "log_roots": [
1227
+ {
1228
+ "path": str(r),
1229
+ "exists": r.exists(),
1230
+ "jsonl_files": sum(1 for _ in ad(r).find_files()) if r.exists() else 0,
1231
+ }
1232
+ for r in roots
1233
+ ],
1234
+ "config": [{"path": str(c), "exists": c.exists()} for c in ad.config_paths()],
1235
+ "checks": ad().doctor_checks(),
1236
+ }
1237
+ )
1238
+ if name == "dsh":
1239
+ from ..adapters.dsh import zstd_available
1240
+
1241
+ report["harnesses"][-1]["zstd"] = zstd_available()
1242
+ rp = DEFAULT_REFRESHED.expanduser()
1243
+ report["pricing"] = {
1244
+ "bundled": PricingTable.bundled().get("retrieved"),
1245
+ "refreshed_file": str(rp),
1246
+ "refreshed": rp.exists(),
1247
+ }
1248
+ sc = ScanCache(f"{STATE}/cache")
1249
+ report["cache"] = sc.info()
1250
+ sc.close()
1251
+ lines = [f"compactlab {__version__} · Python {report['python']} · {platform.system()}"]
1252
+ for h in report["harnesses"]:
1253
+ lines.append(f"\n{h['name']}: CLI {h['cli'] or 'not found'}")
1254
+ lines += [
1255
+ f" logs {'ok ' if r['exists'] else '-- '} {r['path']} ({r['jsonl_files']} files)"
1256
+ for r in h["log_roots"]
1257
+ ]
1258
+ lines += [f" config {'ok ' if c['exists'] else '-- '} {c['path']}" for c in h["config"]]
1259
+ if h["name"] == "dsh":
1260
+ zs = "decoder available" if h["zstd"] else "no decoder: Python 3.14+ or the zstd command"
1261
+ lines.append(f" zstd {'ok ' if h['zstd'] else '-- '} {zs}")
1262
+ lines += [f" {c['label']:6} {'ok ' if c['ok'] else '-- '} {c['text']}" for c in h["checks"]]
1263
+ lines.append(
1264
+ f"\npricing: bundled snapshot {report['pricing']['bundled']}; "
1265
+ f"refreshed: {'yes' if report['pricing']['refreshed'] else 'no'}"
1266
+ )
1267
+ lines.append(f"scan cache {_cache_line(report['cache'])}")
1268
+ t = _term(a)
1269
+ if t and not a.json:
1270
+ from ..term.views import doctor_view
1271
+
1272
+ print(t[0].lines(doctor_view(report, t[1])))
1273
+ return 0
1274
+ _out(a, report, "\n".join(lines))
1275
+ return 0
1276
+
1277
+
1278
+ def cmd_pricing(a: argparse.Namespace) -> int:
1279
+ if a.action == "auto":
1280
+ from ..pricing.auto import AUTO_FILE, load_state, set_enabled
1281
+
1282
+ st = set_enabled(a.state == "on") if a.state in ("on", "off") else load_state()
1283
+
1284
+ def when(k: str) -> str:
1285
+ return time.strftime("%Y-%m-%d %H:%M", time.localtime(st[k])) if st.get(k) else "never"
1286
+
1287
+ text = [
1288
+ f"automatic price refresh: {'on' if st.get('enabled') else 'off'} ({AUTO_FILE})",
1289
+ " when on, `serve` and scheduled runs download models.dev (then LiteLLM) when the logs show a model "
1290
+ "with no price row of its own; at most once a day; nothing about you is sent",
1291
+ f" last attempt: {when('last_attempt')}; last success: {when('last_ok')}"
1292
+ + (f" from {st['last_source']}" if st.get("last_source") else ""),
1293
+ ]
1294
+ if st.get("still_missing"):
1295
+ text.append(" still not in the public data: " + ", ".join(st["still_missing"]))
1296
+ for c in recent_changes(DEFAULT_REFRESHED, limit=10):
1297
+ text.append(f" changed {c['date']}: {c['model']} {c['field']} {c['old']} -> {c['new']}")
1298
+ if st.get("last_error"):
1299
+ text.append(f" last error: {st['last_error']}")
1300
+ _out(a, st, "\n".join(text))
1301
+ return 0
1302
+ if a.action == "refresh":
1303
+ try:
1304
+ n = refresh(a.source, DEFAULT_REFRESHED, a.url)
1305
+ except Exception as e: # network/parse errors: keep bundled pricing
1306
+ print(f"refresh failed, bundled pricing still in use: {e}", file=sys.stderr)
1307
+ return 2
1308
+ print(f"stored {n} model rows from {a.source} in {DEFAULT_REFRESHED}")
1309
+ return 0
1310
+ t = PricingTable.load(a.pricing, offline=a.offline_pricing)
1311
+ keys = a.model or sorted(k for k in t.data["models"] if ":" not in k) # platform rows: ask with --platform
1312
+ rows = []
1313
+ for k in keys:
1314
+ p = t.lookup(k, a.platform)
1315
+ rows.append(
1316
+ {
1317
+ "model": k,
1318
+ "row": p.key,
1319
+ "match": p.kind,
1320
+ "platform": p.platform,
1321
+ "input": p.input,
1322
+ "output": p.output,
1323
+ "cache_write": p.cache_write,
1324
+ "cache_read": p.cache_read,
1325
+ "window": p.max_window,
1326
+ "long_above": p.long_above,
1327
+ "source": p.source,
1328
+ }
1329
+ )
1330
+ text = [f"{'model':24} {'row':24} {'match':8} {'in':>6} {'out':>6} {'cw':>6} {'cr':>6} {'window':>8} source"]
1331
+ text += [
1332
+ f"{r['model'][:24]:24} {r['row'][:24]:24} {r['match']:8} {r['input']:>6g} {r['output']:>6g} "
1333
+ f"{r['cache_write']:>6g} {r['cache_read']:>6g} {r['window'] // 1000:>7}k {r['source']}"
1334
+ for r in rows
1335
+ ]
1336
+ legend = (
1337
+ "USD per million tokens. match: exact = the model's own row; vendor = the vendor's list price for a platform "
1338
+ "with no row of its own; family = borrowed from the closest model of the same family; fallback = unknown."
1339
+ )
1340
+ _out(a, rows, "\n".join(text) + "\n" + legend)
1341
+ return 0
1342
+
1343
+
1344
+ def _cache_line(info: dict[str, Any]) -> str:
1345
+ text = f"{info['path']}: " + (
1346
+ f"{info['files']} files, {info['results']} saved results, {info['bytes'] / 1e6:.1f} MB"
1347
+ if info["exists"]
1348
+ else "none"
1349
+ )
1350
+ if info["stale"]:
1351
+ text += f"; {info['stale']} rows of deleted logs (dropped by the next scan)"
1352
+ if info["old_bytes"]:
1353
+ text += f"; older cache versions {info['old_bytes'] / 1e6:.1f} MB (deleted by the next scan)"
1354
+ if info["newer_bytes"]:
1355
+ text += f"; a newer compactlab's cache {info['newer_bytes'] / 1e6:.1f} MB (left alone)"
1356
+ return text
1357
+
1358
+
1359
+ def cmd_cache(a: argparse.Namespace) -> int:
1360
+ c = ScanCache(a.cache_dir)
1361
+ if a.action == "clear":
1362
+ gone = c.clear()
1363
+ text = f"removed {len(gone)} cache files from {c.dir}" if gone else f"no cache files in {c.dir}"
1364
+ _out(a, {"removed": [str(p) for p in gone]}, text)
1365
+ else:
1366
+ info = c.info()
1367
+ c.close()
1368
+ _out(a, info, f"scan cache {_cache_line(info)}")
1369
+ return 0
1370
+
1371
+
1372
+ def cmd_recommend(a: argparse.Namespace) -> int:
1373
+ from ..recommend import Snippet, check, generate
1374
+
1375
+ res = _reselect(a, _load_result(a.result)) if a.result else run_analysis(a)
1376
+ if res is None:
1377
+ return 2
1378
+ harness = a.harness[0] if a.harness and len(a.harness) == 1 else None
1379
+ profiles = PROFILE_NAMES if a.all_profiles else (None,)
1380
+ items = [x for pr in profiles for x in generate(res, harness, a.scope, pr, a.format, a.provider)]
1381
+ snippets = [x for x in items if isinstance(x, Snippet)]
1382
+ omitted = [x for x in items if not isinstance(x, Snippet)]
1383
+ if a.check:
1384
+ problems = check(snippets, a.max_age_days)
1385
+ _out(a, {"problems": problems}, "\n".join(problems) or f"all {len(snippets)} snippet(s) use verified keys")
1386
+ return 1 if problems else 0
1387
+ text = "\n".join(s.text() for s in snippets)
1388
+ notes = [f"# omitted: {o.harness}: {o.reason}" for o in omitted]
1389
+ if a.json:
1390
+ imp = [{"harness": g["harness"], "model": g["model"], "role": g["role"], "days": g["days"],
1391
+ "active_days": g.get("active_days"),
1392
+ "profiles": {n: {"threshold": c["threshold"], "action": c["action"],
1393
+ "vs_default": c["vs_default"]["impact"],
1394
+ "vs_current": (c["vs_current"] or {}).get("impact")}
1395
+ for n, c in g["comparison"].items()}}
1396
+ for g in res["groups"]] # fmt: skip
1397
+ print(json.dumps({"snippets": [s.to_dict() for s in snippets], "omitted": [vars(o) for o in omitted],
1398
+ "impact": imp}, indent=2, ensure_ascii=False)) # fmt: skip
1399
+ else:
1400
+ print(text + ("\n" + "\n".join(notes) if notes else ""))
1401
+ t = _term(a)
1402
+ if t:
1403
+ from ..term.views import recs_table
1404
+
1405
+ print("\n" + t[0].lines(recs_table(res, min(t[1], 120), _lang1(a), getattr(a, "unit", "pct"))))
1406
+ else:
1407
+ table = impact_text(res, a.lang)
1408
+ if table:
1409
+ print(table)
1410
+ if a.copy:
1411
+ if not snippets:
1412
+ print("nothing to copy", file=sys.stderr)
1413
+ return 1
1414
+ if not shutil.which("pbcopy"):
1415
+ raise CLIError("--copy needs pbcopy (macOS); use --print and copy manually")
1416
+ subprocess.run(["pbcopy"], input=text, text=True, check=True)
1417
+ print(f"copied {len(snippets)} snippet(s) to the clipboard", file=sys.stderr)
1418
+ return 0
1419
+
1420
+
1421
+ # ---------- service: serve / recalibrate / schedule / consent ----------
1422
+
1423
+
1424
+ def _service_args(p: argparse.ArgumentParser) -> None:
1425
+ g = p.add_argument_group("calibration")
1426
+ g.add_argument("--every", default="1d", help="recalibrate interval: 30m, 6h, 1d, 2w ... or off (default 1d)")
1427
+ g.add_argument("--state-dir", default=STATE, help="service state, logs, backups (default ~/.compactlab)")
1428
+ g.add_argument("--lens-out", default=f"{STATE}/lens.json", help="summary for the compactlab-lens mod ('' to skip)")
1429
+ g.add_argument(
1430
+ "--auto-apply", action="store_true", help="apply the consented profile after each run (needs consent)"
1431
+ )
1432
+ g.add_argument("--dry-run", action="store_true", help="with --auto-apply: decide and show the diff, write nothing")
1433
+ g.add_argument("--min-days", type=float, default=7.0, help="auto-apply: minimum history days (default 7)")
1434
+ g.add_argument("--min-turns", type=int, default=500, help="auto-apply: minimum turns (default 500)")
1435
+ g.add_argument("--max-step", type=_k, default=100_000, help="auto-apply: largest move per run (default 100k)")
1436
+ g.add_argument("--cooldown", default="7d", help="auto-apply: minimum time between changes (default 7d)")
1437
+
1438
+
1439
+ def _calibrator(a: argparse.Namespace):
1440
+ from ..service.core import Calibrator
1441
+ from ..service.policy import Rules, load_consent
1442
+ from ..service.schedule import parse_every
1443
+
1444
+ try:
1445
+ every = parse_every(a.every)
1446
+ cooldown = parse_every(a.cooldown) or 0.0
1447
+ except ValueError as e:
1448
+ raise CLIError(str(e)) from e
1449
+ a.mode = "lite" # the service never runs deep mode
1450
+ a.service = True # short progress line, scan counts for the summary log
1451
+ state = Path(a.state_dir).expanduser()
1452
+ consent = None
1453
+ if a.auto_apply:
1454
+ try:
1455
+ consent = load_consent(state / "consent.json")
1456
+ except ap.ApplyError as e:
1457
+ raise CLIError(f"--auto-apply: {e}") from e
1458
+
1459
+ def analyze() -> dict[str, Any]:
1460
+ res = run_analysis(a)
1461
+ if res is None:
1462
+ raise RuntimeError("analysis returned nothing")
1463
+ res["scan"] = getattr(a, "scan_stats", None) # popped by the calibrator for its log line
1464
+ res["covered"] = covered(a, res) # popped too: what its result and lens replace (publish.py)
1465
+ return res
1466
+
1467
+ rules = Rules(min_days=a.min_days, min_turns=a.min_turns, max_step=a.max_step, cooldown_s=cooldown)
1468
+ lens = Path(a.lens_out).expanduser() if a.lens_out else None
1469
+ return Calibrator(
1470
+ analyze,
1471
+ state,
1472
+ every,
1473
+ lens_out=lens,
1474
+ consent=consent,
1475
+ rules=rules,
1476
+ dry_run=a.dry_run,
1477
+ consent_path=state / "consent.json" if a.auto_apply else None,
1478
+ )
1479
+
1480
+
1481
+ def _service_logging(state: Path) -> None:
1482
+ import logging
1483
+ from logging.handlers import RotatingFileHandler
1484
+
1485
+ (state / "service").mkdir(parents=True, exist_ok=True)
1486
+ lg = logging.getLogger("compactlab.service")
1487
+ lg.setLevel(logging.INFO)
1488
+ fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
1489
+
1490
+ class Console(logging.StreamHandler):
1491
+ """Clears the in-place progress line before a log line, so the two never share a row."""
1492
+
1493
+ def emit(self, record: logging.LogRecord) -> None:
1494
+ self.stream = sys.stderr # stderr as it is now, not when logging was set up
1495
+ if self.stream.isatty():
1496
+ self.stream.write("\r\033[K")
1497
+ super().emit(record)
1498
+
1499
+ for old in [h for h in lg.handlers if h.get_name() == "compactlab"]: # set up once per process
1500
+ lg.removeHandler(old)
1501
+ old.close()
1502
+ for h in (RotatingFileHandler(state / "service" / "service.log", maxBytes=1_000_000, backupCount=3),
1503
+ Console(sys.stderr)): # fmt: skip
1504
+ h.setFormatter(fmt)
1505
+ h.set_name("compactlab")
1506
+ lg.addHandler(h)
1507
+
1508
+
1509
+ def cmd_serve(a: argparse.Namespace) -> int:
1510
+ import logging
1511
+ import threading
1512
+
1513
+ from ..service.http import load_token, make_server
1514
+
1515
+ cal = _calibrator(a)
1516
+ state = Path(a.state_dir).expanduser()
1517
+ _service_logging(state)
1518
+ if a.nice and hasattr(os, "nice"):
1519
+ os.nice(a.nice)
1520
+ token = load_token(state / "service" / "token")
1521
+ try:
1522
+ srv = make_server(cal, a.host, a.port, token, unsafe_bind=a.unsafe_bind)
1523
+ except PermissionError as e:
1524
+ raise CLIError(str(e)) from e
1525
+ host, port = str(srv.server_address[0]), int(srv.server_address[1])
1526
+ t = _term(a, sys.stderr)
1527
+ if t:
1528
+ from ..term.views import serve_view
1529
+
1530
+ print(t[0].lines(serve_view(f"http://{host}:{port}/", str(state / "service" / "token"), cal.next_text(),
1531
+ str(state), bool(a.auto_apply), t[1])), file=sys.stderr) # fmt: skip
1532
+ else:
1533
+ print(f"compactlab serving http://{host}:{port}/ (token in {state / 'service' / 'token'}; Ctrl-C stops)",
1534
+ file=sys.stderr) # fmt: skip
1535
+ logging.getLogger("compactlab.service").info("next calibration: %s", cal.next_text())
1536
+ # where `compactlab top` finds this service (loopback address only; removed on exit)
1537
+ endpoint = state / "service" / "endpoint.json"
1538
+ endpoint.write_text(json.dumps({"host": host, "port": port, "pid": os.getpid()}))
1539
+ stop = threading.Event()
1540
+ threading.Thread(target=cal.loop, args=(stop,), daemon=True).start()
1541
+ try:
1542
+ srv.serve_forever()
1543
+ except KeyboardInterrupt:
1544
+ pass
1545
+ finally:
1546
+ stop.set()
1547
+ srv.server_close()
1548
+ endpoint.unlink(missing_ok=True)
1549
+ return 0
1550
+
1551
+
1552
+ def cmd_recalibrate(a: argparse.Namespace) -> int:
1553
+ """One calibration (what a scheduler runs), with the same auto-apply rules as the service."""
1554
+ cal = _calibrator(a)
1555
+ _service_logging(Path(a.state_dir).expanduser())
1556
+ out = cal.recalibrate("cli")
1557
+ if out["status"] == "busy":
1558
+ text = [f"recalibration: busy: {out.get('message') or 'a run is already in flight'}"]
1559
+ else:
1560
+ text = [f"recalibration: {out['status']}" + (f" ({out.get('error')})" if out.get("error") else "")]
1561
+ for d in (out.get("auto_apply") or {}).get("decisions", []):
1562
+ text.append(f" {d['model']}: {d['action']}: {d['reason']}")
1563
+ aa = out.get("auto_apply") or {}
1564
+ if aa.get("diff"):
1565
+ text.append(aa["diff"])
1566
+ if aa.get("manifest"):
1567
+ text.append(f"applied; undo with: compactlab revert --state-dir {a.state_dir}")
1568
+ elif aa.get("dry_run") and aa.get("diff"):
1569
+ text.append("dry-run: nothing written")
1570
+ _out(a, out, "\n".join(text))
1571
+ return 0 if out["status"] == "ok" else EX_BUSY if out["status"] == "busy" else 1
1572
+
1573
+
1574
+ # ---------- engine: the JSON interface the app talks to (docs/ENGINE_API.md) ----------
1575
+
1576
+
1577
+ def _engine(fn: Any) -> Any:
1578
+ """Every engine command prints one JSON object; failures are an `error` object on stdout too, so a caller never
1579
+ has to parse stderr (which keeps the log and tracebacks)."""
1580
+
1581
+ def run(a: argparse.Namespace) -> int:
1582
+ from .. import engine as en
1583
+
1584
+ try:
1585
+ msg, rc = fn(a)
1586
+ except Exception as e:
1587
+ msg, rc = _engine_failure(e)
1588
+ print(en.dumps(msg), flush=True)
1589
+ return rc
1590
+
1591
+ return run
1592
+
1593
+
1594
+ def _engine_failure(e: Exception) -> tuple[dict[str, Any], int]:
1595
+ from .. import engine as en
1596
+
1597
+ if isinstance(e, EngineError):
1598
+ return en.error(e.code, str(e)), 1
1599
+ if isinstance(e, CLIError): # a bad option
1600
+ return en.error("bad_args", str(e)), 2
1601
+ import traceback
1602
+
1603
+ traceback.print_exc(file=sys.stderr)
1604
+ return en.error("internal", f"{type(e).__name__}: {e}"[:500]), 1
1605
+
1606
+
1607
+ class EngineError(CLIError):
1608
+ def __init__(self, code: str, text: str) -> None:
1609
+ super().__init__(text)
1610
+ self.code = code
1611
+
1612
+
1613
+ def _engine_hello(a: argparse.Namespace) -> dict[str, Any]:
1614
+ from ..engine import LIVE_HARNESSES, hello
1615
+
1616
+ roots, cfg = _roots(a), _config_paths(a)
1617
+ harnesses = []
1618
+ for name in adapter_names():
1619
+ ad = get_adapter(name)(roots.get(name))
1620
+ c = cfg.get(name) or next(iter(ad.config_paths()), None)
1621
+ harnesses.append({
1622
+ "name": name,
1623
+ "live": name in LIVE_HARNESSES,
1624
+ "roots": [{"path": str(r), "exists": r.exists()} for r in ad.roots],
1625
+ "config": {"path": str(c), "exists": c.exists()} if c else None,
1626
+ }) # fmt: skip
1627
+ return hello(harnesses, Path(a.state_dir).expanduser())
1628
+
1629
+
1630
+ def _live(a: argparse.Namespace) -> Any:
1631
+ from ..engine import LIVE_HARNESSES
1632
+ from ..engine.live import LiveSessions
1633
+
1634
+ # a config file that does not exist yet is still watched: `apply` may create it while this runs
1635
+ cfg = {h: p or next(iter(get_adapter(h).config_paths()), None) for h, p in _config_paths(a).items()}
1636
+ return LiveSessions(
1637
+ _roots(a),
1638
+ cfg,
1639
+ _pricing(a),
1640
+ time.time,
1641
+ active_s=a.active_hours * 3600,
1642
+ project_names=not a.no_project_names,
1643
+ harnesses=tuple(h for h in LIVE_HARNESSES if not a.harness or h in a.harness),
1644
+ )
1645
+
1646
+
1647
+ @_engine
1648
+ def cmd_engine_hello(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1649
+ return _engine_hello(a), 0
1650
+
1651
+
1652
+ @_engine
1653
+ def cmd_engine_sessions(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1654
+ return _live(a).snapshot(), 0
1655
+
1656
+
1657
+ def cmd_engine_watch(a: argparse.Namespace) -> int:
1658
+ from ..engine import dumps
1659
+ from ..engine.watch import run
1660
+
1661
+ try:
1662
+ live, hello = _live(a), _engine_hello(a)
1663
+ except Exception as e: # e.g. an unreadable --pricing file: say so in JSON like the one-shot commands
1664
+ msg, rc = _engine_failure(e)
1665
+ print(dumps(msg), flush=True)
1666
+ return rc
1667
+ try:
1668
+ return run(live.snapshot, hello, sys.stdin, sys.stdout, a.min_interval, a.interval)
1669
+ except BrokenPipeError: # the app went away; keep the interpreter's final flush from failing too
1670
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
1671
+ return 0
1672
+
1673
+
1674
+ def _engine_result(a: argparse.Namespace) -> dict[str, Any]:
1675
+ """The calibrator's result (or --result), re-selected for --profile."""
1676
+ from ..engine import result_path
1677
+
1678
+ path = Path(a.result).expanduser() if a.result else result_path(Path(a.state_dir).expanduser())
1679
+ if not path.exists():
1680
+ raise EngineError("no_result", f"no calibration yet ({path}); run: compactlab engine calibrate")
1681
+ try:
1682
+ res = _load_result(str(path))
1683
+ except (CLIError, ValueError, KeyError) as e:
1684
+ raise EngineError("bad_result", str(e)) from e
1685
+ if a.profile:
1686
+ reselect(res, a.profile)
1687
+ return res
1688
+
1689
+
1690
+ @_engine
1691
+ def cmd_engine_result(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1692
+ from ..engine import result_message
1693
+
1694
+ return result_message(_engine_result(a), Path(a.state_dir).expanduser()), 0
1695
+
1696
+
1697
+ @_engine
1698
+ def cmd_engine_calibrate(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1699
+ from ..engine import result_message
1700
+
1701
+ cal = _calibrator(a)
1702
+ state = Path(a.state_dir).expanduser()
1703
+ _service_logging(state)
1704
+ out = cal.recalibrate(a.reason)
1705
+ if out["status"] == "busy":
1706
+ raise EngineError("busy", str(out.get("message") or "a calibration is already running"))
1707
+ if out["status"] != "ok" or cal.result is None:
1708
+ raise EngineError("calibration_failed", str(out.get("error") or "no result"))
1709
+ return result_message(cal.result, state, out.get("auto_apply")), 0
1710
+
1711
+
1712
+ # the settings commands: plan, apply, revert, history, verify, consent (engine/settings.py)
1713
+
1714
+
1715
+ def _engine_configs(a: argparse.Namespace) -> dict[str, Path]:
1716
+ """The config file `apply` writes per harness: the one named, else the first that exists, else the default."""
1717
+ named = _config_paths(a)
1718
+ out: dict[str, Path] = {}
1719
+ for h in ("claude-code", "codex"):
1720
+ p = named.get(h) or next(iter(get_adapter(h).config_paths()), None)
1721
+ if p is not None:
1722
+ out[h] = p
1723
+ return out
1724
+
1725
+
1726
+ def _engine_plan(a: argparse.Namespace) -> tuple[dict[str, Any], ap.Preauth, list[ap.Change], list[str], str]:
1727
+ from ..engine.settings import preauth
1728
+
1729
+ res = _engine_result(a)
1730
+ pre = preauth(_engine_configs(a), res)
1731
+ try:
1732
+ recs, seen, dup = [], set(), []
1733
+ for r in _recs(res):
1734
+ sel = f"{r['harness']}:{r['model']}"
1735
+ if sel in seen: # two groups on one key (a dated and an alias ID): ambiguous, so neither value is used
1736
+ dup.append(sel)
1737
+ seen.add(sel)
1738
+ if not a.only or sel in a.only:
1739
+ recs.append(r)
1740
+ recs = [r for r in recs if f"{r['harness']}:{r['model']}" not in dup]
1741
+ changes, rejected = ap.plan_changes(recs, pre)
1742
+ rejected += [f"{d}: two calibrated groups map to this setting; set it by hand" for d in sorted(set(dup))]
1743
+ except (ap.ApplyError, ValueError) as e: # a config file that cannot be read safely
1744
+ raise EngineError("refused", str(e)) from e
1745
+ return res, pre, changes, rejected, (res.get("options") or {}).get("profile") or DEFAULT_PROFILE
1746
+
1747
+
1748
+ def _locked(
1749
+ a: argparse.Namespace, job: str, fn: Callable[[], tuple[dict[str, Any], int]]
1750
+ ) -> tuple[dict[str, Any], int]:
1751
+ from ..service.lock import Busy, LockError, single_flight
1752
+
1753
+ try:
1754
+ with single_flight(Path(a.state_dir).expanduser(), job):
1755
+ return fn()
1756
+ except Busy as e:
1757
+ raise EngineError("busy", str(e)) from e
1758
+ except LockError as e:
1759
+ raise EngineError("refused", str(e)) from e
1760
+
1761
+
1762
+ @_engine
1763
+ def cmd_engine_plan(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1764
+ from ..engine.settings import plan_message
1765
+
1766
+ res, _, changes, rejected, profile = _engine_plan(a)
1767
+ try:
1768
+ return plan_message(res, changes, rejected, profile), 0
1769
+ except (ap.ApplyError, ValueError) as e:
1770
+ raise EngineError("refused", str(e)) from e
1771
+
1772
+
1773
+ @_engine
1774
+ def cmd_engine_apply(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1775
+ from ..engine.settings import applied_message, record_applied
1776
+
1777
+ state = Path(a.state_dir).expanduser()
1778
+
1779
+ def run() -> tuple[dict[str, Any], int]: # planned again under the lock: what is written is what was reviewed
1780
+ _, pre, changes, _, profile = _engine_plan(a)
1781
+ h, want = ap.plan_hash(changes), a.expect_plan.strip().lower()
1782
+ if h != want:
1783
+ raise EngineError("plan_changed", f"the plan is not the reviewed one (expected {want}, now {h}); "
1784
+ "nothing written: review the new plan") # fmt: skip
1785
+ if not changes:
1786
+ raise EngineError("refused", "nothing to change")
1787
+ try:
1788
+ m = ap.write_changes(changes, state, pre)
1789
+ except (ap.ApplyError, OSError, ValueError) as e:
1790
+ raise EngineError("refused", str(e)) from e
1791
+ record_applied(state, m, changes, profile)
1792
+ return applied_message(m, changes), 0
1793
+
1794
+ return _locked(a, "app apply", run)
1795
+
1796
+
1797
+ def _engine_manifest(a: argparse.Namespace) -> Path:
1798
+ sd = Path(a.state_dir).expanduser()
1799
+ try:
1800
+ m = sd / "manifests" / f"{a.id}.json" if a.id else ap.latest_manifest(sd)
1801
+ except ap.ApplyError as e:
1802
+ raise EngineError("no_apply", str(e)) from e
1803
+ if not m.exists():
1804
+ raise EngineError("no_apply", f"no apply manifest {m}")
1805
+ return m
1806
+
1807
+
1808
+ @_engine
1809
+ def cmd_engine_revert(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1810
+ from ..engine.settings import reverted_message
1811
+
1812
+ def run() -> tuple[dict[str, Any], int]:
1813
+ m = _engine_manifest(a)
1814
+ try:
1815
+ log = ap.revert(m)
1816
+ except (ap.ApplyError, OSError, ValueError) as e:
1817
+ raise EngineError("refused", str(e)) from e
1818
+ _forget_applied(Path(a.state_dir).expanduser(), m.stem)
1819
+ return reverted_message(m, log), 0
1820
+
1821
+ return _locked(a, "app revert", run)
1822
+
1823
+
1824
+ @_engine
1825
+ def cmd_engine_history(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1826
+ from ..engine.settings import history_message
1827
+
1828
+ return history_message(Path(a.state_dir).expanduser(), a.limit), 0
1829
+
1830
+
1831
+ @_engine
1832
+ def cmd_engine_verify(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1833
+ from .. import verify as vf
1834
+ from ..engine.settings import verification_message
1835
+
1836
+ m = _engine_manifest(a)
1837
+ try:
1838
+ manifest = json.loads(m.read_text())
1839
+ except (OSError, ValueError) as e:
1840
+ raise EngineError("no_apply", f"{m}: {e}") from e
1841
+ sessions = load_sessions(a)
1842
+ if not sessions:
1843
+ raise EngineError("no_sessions", "no sessions in the window")
1844
+ res = vf.verify(sessions, manifest, _pricing(a), min_sessions=a.min_sessions, min_days=a.min_days,
1845
+ opts=_idle_opts(a, SimOptions())) # fmt: skip
1846
+ return verification_message(m.stem, res), 0
1847
+
1848
+
1849
+ @_engine
1850
+ def cmd_engine_consent(a: argparse.Namespace) -> tuple[dict[str, Any], int]:
1851
+ from ..engine.settings import consent_message
1852
+ from ..service.policy import Consent, load_consent, save_consent
1853
+
1854
+ path = Path(a.state_dir).expanduser() / "consent.json"
1855
+ if a.action == "clear":
1856
+ path.unlink(missing_ok=True)
1857
+ return consent_message(None), 0
1858
+ if a.action == "set": # Claude Code only (docs/MENUBAR_APP.zh-CN.md §7 item 3)
1859
+ file = _engine_configs(a).get("claude-code")
1860
+ if file is None:
1861
+ raise EngineError("refused", "no Claude Code settings file")
1862
+ try:
1863
+ save_consent(path, Consent("claude-code", str(file), a.models, a.profile))
1864
+ except ap.ApplyError as e:
1865
+ raise EngineError("refused", str(e)) from e
1866
+ try:
1867
+ return consent_message(load_consent(path)), 0
1868
+ except ap.ApplyError:
1869
+ return consent_message(None), 0
1870
+
1871
+
1872
+ def cmd_schedule(a: argparse.Namespace) -> int:
1873
+ from ..service import schedule as sc
1874
+
1875
+ home = Path.home()
1876
+ plat = a.platform if a.platform != "auto" else ("launchd" if platform.system() == "Darwin" else "systemd")
1877
+ if a.action == "status":
1878
+ found = sc.installed(plat, home)
1879
+ print("\n".join(f"installed: {p}" for p in found) or f"not installed ({plat})")
1880
+ return 0
1881
+ if a.action == "uninstall":
1882
+ if not a.yes:
1883
+ print("refused: uninstall needs --yes", file=sys.stderr)
1884
+ return 2
1885
+ gone = sc.uninstall(plat, home)
1886
+ print("\n".join(f"removed: {p}" for p in gone) or "nothing to remove")
1887
+ if gone:
1888
+ print("unload it yourself if it is loaded (launchctl bootout / systemctl --user disable --now)")
1889
+ return 0
1890
+ try:
1891
+ every = sc.parse_every(a.every)
1892
+ units = sc.units(plat, a.mode, every, ["--state-dir", a.state_dir] + (["--auto-apply"] if a.auto_apply else []),
1893
+ home) # fmt: skip
1894
+ except ValueError as e:
1895
+ raise CLIError(str(e)) from e
1896
+ if a.action == "print":
1897
+ for u in units:
1898
+ print(f"# {u.path}\n{u.text}")
1899
+ return 0
1900
+ print(sc.diff(units))
1901
+ if not a.yes and (not sys.stdin.isatty() or input("write these files? [y/N] ").strip().lower() != "y"):
1902
+ print("not installed", file=sys.stderr)
1903
+ return 2
1904
+ try:
1905
+ for p in sc.install(units):
1906
+ print(f"wrote {p}")
1907
+ except PermissionError as e:
1908
+ raise CLIError(str(e)) from e
1909
+ print(sc.activation_hint(plat))
1910
+ return 0
1911
+
1912
+
1913
+ def cmd_consent(a: argparse.Namespace) -> int:
1914
+ from dataclasses import asdict
1915
+
1916
+ from ..service.policy import Consent, load_consent, save_consent
1917
+
1918
+ path = Path(a.state_dir).expanduser() / "consent.json"
1919
+ if a.action == "show":
1920
+ try:
1921
+ print(json.dumps(asdict(load_consent(path)), indent=2))
1922
+ except ap.ApplyError as e:
1923
+ print(str(e), file=sys.stderr)
1924
+ return 1
1925
+ return 0
1926
+ if a.action == "clear":
1927
+ if path.exists():
1928
+ path.unlink()
1929
+ print("consent removed; auto-apply is off")
1930
+ return 0
1931
+ if not (a.file and a.models):
1932
+ raise CLIError("consent set needs --file and --models")
1933
+ c = Consent(a.harness, str(ap._p(a.file)), list(a.models), a.profile, expires=a.expires)
1934
+ print(json.dumps(asdict(c), indent=2))
1935
+ if not a.yes and (not sys.stdin.isatty() or input("allow compactlab to change these keys unattended? [y/N] ")
1936
+ .strip().lower() != "y"): # fmt: skip
1937
+ print("no consent stored", file=sys.stderr)
1938
+ return 2
1939
+ try:
1940
+ save_consent(path, c)
1941
+ except ap.ApplyError as e:
1942
+ raise CLIError(str(e)) from e
1943
+ print(f"stored {path}")
1944
+ return 0
1945
+
1946
+
1947
+ def cmd_share(a: argparse.Namespace) -> int:
1948
+ """Write an anonymous record of the estimated savings for people to post; never sends anything itself."""
1949
+ from .. import share
1950
+
1951
+ if a.check:
1952
+ try:
1953
+ rec = share.parse_issue_body(Path(a.check).expanduser().read_text())
1954
+ except (OSError, share.ShareError) as e:
1955
+ raise CLIError(str(e)) from e
1956
+ bad = share.validate(rec)
1957
+ if bad:
1958
+ print("not acceptable:\n " + "\n ".join(bad), file=sys.stderr)
1959
+ return 1
1960
+ print("ok: " + share.preview(rec))
1961
+ return 0
1962
+ res = _load_result(a.result) if a.result else run_analysis(a)
1963
+ if res is None:
1964
+ return 2
1965
+ verification = None
1966
+ if a.verify:
1967
+ from .. import verify as vf
1968
+
1969
+ sessions = load_sessions(a)
1970
+ try:
1971
+ m = (
1972
+ Path(a.state_dir).expanduser() / "manifests" / f"{a.id}.json"
1973
+ if a.id
1974
+ else ap.latest_manifest(Path(a.state_dir).expanduser())
1975
+ )
1976
+ manifest = json.loads(m.read_text())
1977
+ except (ap.ApplyError, OSError, ValueError) as e:
1978
+ raise CLIError(f"--verify needs a change made with compactlab apply: {e}") from e
1979
+ verification = vf.verify(sessions, manifest, _pricing(a), opts=_idle_opts(a, SimOptions()))
1980
+ if not any(g["verdict"] != "no_data" for g in verification["groups"]):
1981
+ raise CLIError("--verify: no sessions on both sides of the change yet; share without --verify")
1982
+ try:
1983
+ rec = share.build(res, verification=verification)
1984
+ except share.ShareError as e:
1985
+ raise CLIError(str(e)) from e
1986
+ if verification and not any(g["verification"] for g in rec["groups"]):
1987
+ raise CLIError("--verify: the verified models are not among the shared groups; share without --verify")
1988
+ text = json.dumps(rec, indent=2, sort_keys=True)
1989
+ out = Path(a.out).expanduser()
1990
+ out.parent.mkdir(parents=True, exist_ok=True)
1991
+ out.write_text(text + "\n")
1992
+ if a.json:
1993
+ print(text)
1994
+ else:
1995
+ print(share.preview(rec))
1996
+ print(f"\nwrote {out}: numbers and model names only; read it before you post it.")
1997
+ print(f"It holds no session ids, paths, project names, timestamps or text. Post it at:\n {share.ISSUE_URL}")
1998
+ if a.copy:
1999
+ if not shutil.which("pbcopy"):
2000
+ raise CLIError("--copy needs pbcopy (macOS); open the file and copy it by hand")
2001
+ subprocess.run(["pbcopy"], input=text, text=True, check=True)
2002
+ print("copied the record to the clipboard", file=sys.stderr)
2003
+ return 0
2004
+
2005
+
2006
+ def cmd_verify(a: argparse.Namespace) -> int:
2007
+ """Compare what a change was predicted to do with what the logs show since it was applied."""
2008
+ from .. import verify as vf
2009
+
2010
+ note = None
2011
+ if a.applied_at:
2012
+ if a.id or a.new is None:
2013
+ raise CLIError(
2014
+ "--applied-at describes a change made by hand: give --new (and --model for Claude Code), not --id"
2015
+ )
2016
+ harness = a.harness[0] if a.harness and len(a.harness) == 1 else "claude-code"
2017
+ if harness in ("claude-code", "opencode", "gemini-cli") and not a.model:
2018
+ raise CLIError(
2019
+ "--model is needed for a Claude Code, OpenCode or Gemini CLI change (the threshold is per model; "
2020
+ "OpenCode models are named provider/model, as `compactlab scan` lists them)"
2021
+ )
2022
+ try:
2023
+ manifest = vf.manual_manifest(vf.parse_when(a.applied_at), harness, a.model or "", a.new, a.old)
2024
+ except ValueError as e:
2025
+ raise CLIError(str(e)) from e
2026
+ m = Path("manual")
2027
+ note = (
2028
+ "Change made by hand: the time and the old value are as given"
2029
+ + (
2030
+ f" (old {a.old // 1000}k)"
2031
+ if a.old
2032
+ else " (old = the harness default; pass --old if it was something else)"
2033
+ )
2034
+ + "."
2035
+ )
2036
+ else:
2037
+ sd = Path(a.state_dir).expanduser()
2038
+ try:
2039
+ m = sd / "manifests" / f"{a.id}.json" if a.id else ap.latest_manifest(sd)
2040
+ manifest = json.loads(m.read_text())
2041
+ except (ap.ApplyError, OSError, ValueError) as e:
2042
+ raise CLIError(
2043
+ f"no usable apply manifest: {e}. Verify needs a change made with compactlab apply, "
2044
+ "or describe a manual one with --applied-at, --model and --new."
2045
+ ) from e
2046
+ sessions = load_sessions(a)
2047
+ if not sessions:
2048
+ raise CLIError("no sessions found; check `compactlab doctor`, or widen --since-days (0 = all)")
2049
+ res = vf.verify(sessions, manifest, _pricing(a), min_sessions=a.min_sessions, min_days=a.min_days,
2050
+ opts=_idle_opts(a, SimOptions())) # fmt: skip
2051
+ res["manifest"] = m.stem
2052
+ if note:
2053
+ res["note"] = note
2054
+ _out(a, res, vf.render(res))
2055
+ return 0
2056
+
2057
+
2058
+ def cmd_top(a: argparse.Namespace) -> int:
2059
+ """Live view of the latest result; one static frame when stdout is not a terminal (or with --once)."""
2060
+ import tempfile
2061
+
2062
+ from ..term import top as tp
2063
+ from ..term.style import Style
2064
+
2065
+ state = Path(a.state_dir).expanduser()
2066
+ tmp = None
2067
+ if a.demo:
2068
+ tmp = tempfile.mkdtemp(prefix="compactlab-top-")
2069
+ res: dict[str, Any] | None = _demo_result(Path(tmp), "en")
2070
+ src: Path | None = None
2071
+ else:
2072
+ cands = (
2073
+ [Path(a.result).expanduser()]
2074
+ if a.result
2075
+ else [state / "service" / "result.json", Path("compactlab-result.json"), state / "result.json"]
2076
+ )
2077
+ src = next((c for c in cands if c.exists()), None)
2078
+ if src is None:
2079
+ raise CLIError(
2080
+ "no result found; run `compactlab simulate` (or `compactlab serve`), or try `compactlab top --demo`"
2081
+ )
2082
+ res = _load_result(str(src))
2083
+ assert res is not None
2084
+ mtime = [src.stat().st_mtime if src else 0.0]
2085
+
2086
+ def reload() -> dict[str, Any] | None:
2087
+ if src and src.exists() and src.stat().st_mtime != mtime[0]:
2088
+ mtime[0] = src.stat().st_mtime
2089
+ return _load_result(str(src))
2090
+ return None
2091
+
2092
+ def recalibrate() -> dict[str, Any] | None:
2093
+ if a.demo:
2094
+ return _demo_result(Path(tempfile.mkdtemp(prefix="compactlab-top-")), "en")
2095
+ ns = build_parser().parse_args(["simulate", "--out", str(src or "compactlab-result.json"), "--lang", "en"])
2096
+ ns.lens_out = ""
2097
+ return run_analysis(ns)
2098
+
2099
+ # --demo never looks at the real service; open on the first model, not its harness row
2100
+ st = tp.TopState(res=res, unit=a.unit, profile=a.profile, service={} if a.demo else tp.service_state(state), sel=1)
2101
+ if a.once or not (sys.stdout.isatty() and sys.stdin.isatty()):
2102
+ size = shutil.get_terminal_size((120, 36))
2103
+ cols, rows = a.width or size.columns, a.height or size.lines
2104
+ style = Style.detect(sys.stdout, a.color) if not a.plain else Style(0)
2105
+ print(tp.static(st, style, max(30, min(cols, 200)), max(10, rows)))
2106
+ return 0
2107
+ tp.run(st, state, reload, recalibrate, a.interval)
2108
+ return 0
2109
+
2110
+
2111
+ def _demo_result(out: Path, lang: str = "both") -> dict[str, Any]:
2112
+ """Synthetic history under `out` analysed like `simulate` (never reads real data)."""
2113
+ synth.write_claude_code(out / "claude" / "projects", n_main=12, n_sub=6)
2114
+ synth.write_codex(out / "codex" / "sessions", n=6)
2115
+ demo_settings = out / "claude" / "settings.json" # synthetic "current" config to show the comparison
2116
+ demo_settings.write_text(
2117
+ json.dumps({"modelSettings": {"claude-opus-5-5": {"autoCompactWindow": 600000}}}, indent=2)
2118
+ )
2119
+ ns = build_parser().parse_args(
2120
+ ["simulate", "--claude-root", str(out / "claude" / "projects"), "--codex-root", str(out / "codex" / "sessions"),
2121
+ "--harness", "claude-code", "--harness", "codex", # the other harnesses' default roots are real logs
2122
+ "--since-days", "0", "--no-cache", "--offline-pricing", "--claude-settings", str(demo_settings),
2123
+ "--codex-config", str(out / "codex" / "config.toml"), "--lang", lang]
2124
+ ) # fmt: skip
2125
+ res = run_analysis(ns)
2126
+ assert res is not None
2127
+ res["demo"] = True
2128
+ return res
2129
+
2130
+
2131
+ def cmd_demo(a: argparse.Namespace) -> int:
2132
+ from ..lens import summarize
2133
+
2134
+ out = Path(a.out)
2135
+ res = _demo_result(out, a.lang)
2136
+ (out / "result.json").write_text(json.dumps(res, sort_keys=True))
2137
+ (out / "lens.json").write_text(json.dumps(summarize(res), sort_keys=True))
2138
+ (out / "report.html").write_text(render_html(res))
2139
+ print(_summary_out(a, res))
2140
+ print(f"\nSYNTHETIC DEMO DATA (not your history). Report: {out / 'report.html'}")
2141
+ print(f"Copy the settings / 复制推荐设置: compactlab recommend --result {out / 'result.json'} [--copy]")
2142
+ if not a.no_open:
2143
+ _open(out / "report.html")
2144
+ return 0
2145
+
2146
+
2147
+ def build_parser() -> argparse.ArgumentParser:
2148
+ fmt = argparse.RawDescriptionHelpFormatter
2149
+ p = argparse.ArgumentParser(prog="compactlab", description=__doc__, epilog=EXAMPLES, formatter_class=fmt)
2150
+ p.add_argument("--version", action="version", version=f"compactlab {__version__}")
2151
+ sub = p.add_subparsers(dest="cmd", required=True, metavar="command")
2152
+ _commands(sub, fmt)
2153
+ for sp in sub.choices.values(): # every command: terminal look
2154
+ g = sp.add_argument_group("terminal output")
2155
+ g.add_argument("--plain", action="store_true", help="plain text tables, no colour or boxes")
2156
+ g.add_argument("--color", choices=["auto", "always", "never"], default="auto",
2157
+ help="colour: auto (TTY, honours NO_COLOR), always, never") # fmt: skip
2158
+ g.add_argument("--unit", choices=["pct", "usd"], default="pct", help="lead with %% of the default or $ / day")
2159
+ return p
2160
+
2161
+
2162
+ def _commands(sub: Any, fmt: Any) -> None:
2163
+ s = sub.add_parser("demo", help="build and open a report from bundled synthetic data", formatter_class=fmt)
2164
+ s.add_argument("--out", default="compactlab-demo")
2165
+ s.add_argument("--no-open", action="store_true", help="do not open the report")
2166
+ s.add_argument("--lang", choices=["both", "en", "zh"], default="both", help="summary language (default: both 中英)")
2167
+ s.set_defaults(f=cmd_demo)
2168
+
2169
+ s = sub.add_parser("top", help="live terminal view of the latest result (htop-like; keys: ? for help)")
2170
+ s.add_argument("--result", help="result.json (default: the service's, ./compactlab-result.json, ~/.compactlab)")
2171
+ s.add_argument("--demo", action="store_true", help="synthetic data instead of your history")
2172
+ s.add_argument("--state-dir", default=STATE, help="service state, to show and reach a running service")
2173
+ s.add_argument("--profile", choices=list(PROFILE_NAMES), help="show this profile for every model")
2174
+ s.add_argument("--interval", type=float, default=5.0, help="seconds between reloads (default 5)")
2175
+ s.add_argument("--once", action="store_true", help="print one frame and exit")
2176
+ s.add_argument("--width", type=int, help="frame width for --once (default: the terminal's)")
2177
+ s.add_argument("--height", type=int, help="frame height for --once")
2178
+ s.set_defaults(f=cmd_top)
2179
+
2180
+ s = sub.add_parser("doctor", help="detect harnesses, log locations, config paths, versions")
2181
+ s.add_argument("--json", action="store_true")
2182
+ s.set_defaults(f=cmd_doctor)
2183
+
2184
+ s = sub.add_parser("scan", help="list sessions found, per harness/role/model")
2185
+ _source(s)
2186
+ s.set_defaults(f=cmd_scan)
2187
+
2188
+ s = sub.add_parser("simulate", help="threshold sweep -> result.json + summary (lite or deep)")
2189
+ _sim(s)
2190
+ s.add_argument("--out", default="compactlab-result.json")
2191
+ s.add_argument(
2192
+ "--lens-out",
2193
+ default=f"{STATE}/lens.json",
2194
+ help="small per-model summary the compactlab-lens mod reads (default ~/.compactlab/lens.json; '' to skip)",
2195
+ )
2196
+ s.set_defaults(f=cmd_simulate)
2197
+
2198
+ s = sub.add_parser("report", help="self-contained offline HTML report")
2199
+ _sim(s)
2200
+ s.add_argument("--result", help="render a saved result.json instead of re-running")
2201
+ s.add_argument("--out", default="compactlab-report.html")
2202
+ s.add_argument("--redact", action="store_true", help="replace session ids with short hashes")
2203
+ s.add_argument("--open", action="store_true", help="open the report when done")
2204
+ s.set_defaults(f=cmd_report)
2205
+
2206
+ s = sub.add_parser("apply", help="write a profile to harness config (dry-run unless --write + authorization)")
2207
+ s.add_argument("--result", required=True)
2208
+ s.add_argument("--json", action="store_true")
2209
+ _profile_args(s)
2210
+ _config_args(s)
2211
+ _apply_opts(s)
2212
+ s.set_defaults(f=cmd_apply)
2213
+
2214
+ s = sub.add_parser("retune", help="re-analyze and apply under an existing pre-authorization")
2215
+ _sim(s)
2216
+ _apply_opts(s)
2217
+ s.set_defaults(f=cmd_retune)
2218
+
2219
+ s = sub.add_parser(
2220
+ "recommend", help="ready-to-paste settings per harness/scope/profile (prints or copies; never writes)"
2221
+ )
2222
+ _sim(s)
2223
+ s.add_argument("--result", help="use a saved result.json instead of re-running")
2224
+ s.add_argument(
2225
+ "--scope",
2226
+ choices=["global", "project", "agent"],
2227
+ default="global",
2228
+ help="user-level config, project config, or per-agent/subagent (default global)",
2229
+ )
2230
+ s.add_argument("--all-profiles", action="store_true", help="print cost, balanced and time side by side")
2231
+ s.add_argument(
2232
+ "--format",
2233
+ choices=["json", "toml", "yaml", "env", "shell"],
2234
+ help="default: the scope's native format (json for Claude Code, toml for Codex, yaml for subagents)",
2235
+ )
2236
+ s.add_argument(
2237
+ "--provider",
2238
+ default="default",
2239
+ help="provider: anthropic|bedrock|vertex|foundry|gateway (Claude Code); openai|amazon-bedrock|custom (Codex)",
2240
+ )
2241
+ s.add_argument("--copy", action="store_true", help="copy the snippet(s) to the macOS clipboard (pbcopy)")
2242
+ s.add_argument("--print", action="store_true", help="print the snippet(s) (default)")
2243
+ s.add_argument("--check", action="store_true", help="flag snippets whose config keys are unverified or stale")
2244
+ s.add_argument("--max-age-days", type=int, default=90, help="with --check: max age of a key's verification")
2245
+ s.set_defaults(f=cmd_recommend)
2246
+
2247
+ s = sub.add_parser(
2248
+ "verify", help="after apply: compare the predicted cost and compactions with what the logs show since"
2249
+ )
2250
+ _source(s)
2251
+ s.set_defaults(since_days=60)
2252
+ s.add_argument("--id", help="manifest id (default: the latest apply)")
2253
+ s.add_argument("--state-dir", default=STATE, help="backups and manifests (default ~/.compactlab)")
2254
+ h = s.add_argument_group("a change made by hand (instead of an apply manifest)")
2255
+ h.add_argument(
2256
+ "--applied-at", metavar="WHEN", help="when it took effect: 2026-10-29 or 2026-10-29T21:05 (local time)"
2257
+ )
2258
+ h.add_argument(
2259
+ "--model",
2260
+ help="the model the change is checked for (Claude Code: its modelSettings key; OpenCode: provider/model; "
2261
+ "Gemini CLI: --new is that model's token threshold)",
2262
+ )
2263
+ h.add_argument("--new", type=_k, help="the threshold you set, e.g. 625k")
2264
+ h.add_argument("--old", type=_k, help="the threshold before (default: the harness default)")
2265
+ s.add_argument("--pricing", help="pricing override JSON")
2266
+ s.add_argument("--offline-pricing", action="store_true", help="ignore refreshed prices")
2267
+ s.add_argument("--min-sessions", type=int, default=3, help="sessions needed on each side (default 3)")
2268
+ s.add_argument("--min-days", type=int, default=2, help="active days needed on each side (default 2)")
2269
+ s.set_defaults(f=cmd_verify)
2270
+
2271
+ s = sub.add_parser(
2272
+ "share", help="anonymous record of your estimated savings to post for research (writes a file; sends nothing)"
2273
+ )
2274
+ _sim(s)
2275
+ s.add_argument("--result", help="use a saved result.json instead of re-running")
2276
+ s.add_argument("--out", default="compactlab-share.json", help="where to write the record")
2277
+ s.add_argument("--copy", action="store_true", help="also copy the record to the macOS clipboard (pbcopy)")
2278
+ s.add_argument("--check", metavar="FILE", help="validate a record (or an issue body) instead of building one")
2279
+ s.add_argument("--verify", action="store_true",
2280
+ help="add what `compactlab verify` found since the last apply (predicted vs logged)") # fmt: skip
2281
+ s.add_argument("--id", help="with --verify: manifest id (default: the latest apply)")
2282
+ s.add_argument("--state-dir", default=STATE, help="with --verify: backups and manifests (default ~/.compactlab)")
2283
+ s.set_defaults(f=cmd_share)
2284
+
2285
+ s = sub.add_parser("serve", help="localhost service: live report + JSON API, recalibrates on a schedule (lite)")
2286
+ _sim(s)
2287
+ _service_args(s)
2288
+ s.add_argument("--host", default="127.0.0.1", help="bind address (loopback only unless --unsafe-bind)")
2289
+ s.add_argument("--port", type=int, default=0, help="port (default: a free one)")
2290
+ s.add_argument("--unsafe-bind", action="store_true", help="allow a non-loopback bind (not recommended)")
2291
+ s.add_argument("--nice", type=int, default=10, help="lower the process priority by this much (default 10)")
2292
+ s.set_defaults(f=cmd_serve)
2293
+
2294
+ s = sub.add_parser("recalibrate", help="one lite recalibration (what a scheduler runs), optional auto-apply")
2295
+ _sim(s)
2296
+ _service_args(s)
2297
+ s.set_defaults(f=cmd_recalibrate)
2298
+
2299
+ s = sub.add_parser("engine", help="JSON interface for the compactlab app and other tools (docs/ENGINE_API.md)")
2300
+ es = s.add_subparsers(dest="engine_cmd", required=True, metavar="engine-command")
2301
+ e = es.add_parser("hello", help="engine and contract version, harness log and config locations")
2302
+ _source(e)
2303
+ _config_args(e)
2304
+ e.add_argument("--state-dir", default=STATE)
2305
+ e.set_defaults(f=cmd_engine_hello)
2306
+ for name, text in (
2307
+ ("sessions", "the active sessions now: context, model, threshold in force, cache expiry"),
2308
+ ("watch", "active sessions as JSON Lines on stdout while running; commands on stdin"),
2309
+ ):
2310
+ e = es.add_parser(name, help=text)
2311
+ _source(e)
2312
+ _config_args(e)
2313
+ e.add_argument("--state-dir", default=STATE)
2314
+ e.add_argument("--active-hours", type=float, default=6.0, help="sessions written in the last N hours (6)")
2315
+ e.add_argument("--no-project-names", action="store_true", help="leave out the working directory's name")
2316
+ e.add_argument("--pricing", help="pricing override JSON (windows of models the logs do not size)")
2317
+ e.add_argument("--offline-pricing", action="store_true", help="ignore refreshed prices and windows")
2318
+ e.set_defaults(f=cmd_engine_watch)
2319
+ e.add_argument("--min-interval", type=float, default=5.0, help="seconds between scans at most (default 5)")
2320
+ e.add_argument("--interval", type=float, default=60.0, help="scan anyway after N quiet seconds (0 = never)")
2321
+ es.choices["sessions"].set_defaults(f=cmd_engine_sessions)
2322
+ e = es.add_parser("result", help="the last calibration, summarized for the threshold table")
2323
+ e.add_argument("--state-dir", default=STATE)
2324
+ e.add_argument("--result", help="a result.json (default: the calibrator's, <state-dir>/service/result.json)")
2325
+ e.add_argument("--profile", choices=PROFILE_NAMES, help="select this profile (no replay)")
2326
+ e.set_defaults(f=cmd_engine_result)
2327
+ e = es.add_parser("calibrate", help="one lite calibration (like recalibrate), then its summary")
2328
+ _sim(e)
2329
+ _service_args(e)
2330
+ e.add_argument("--reason", default="engine", help="recorded with the calibration (e.g. app, schedule)")
2331
+ e.set_defaults(f=cmd_engine_calibrate)
2332
+ for name, text, fn in (
2333
+ ("plan", "what `apply` would change for the calibrated (or --profile) pick, with its hash", cmd_engine_plan),
2334
+ ("apply", "write the plan, only if its hash is still --expect-plan", cmd_engine_apply),
2335
+ ):
2336
+ e = es.add_parser(name, help=text)
2337
+ _config_args(e)
2338
+ e.add_argument("--state-dir", default=STATE)
2339
+ e.add_argument("--result", help="a result.json (default: the calibrator's)")
2340
+ e.add_argument("--profile", choices=PROFILE_NAMES, help="select this profile (no replay)")
2341
+ e.add_argument("--only", action="append", metavar="HARNESS:MODEL", help="just this change (repeatable)")
2342
+ e.set_defaults(f=fn)
2343
+ es.choices["apply"].add_argument("--expect-plan", required=True, metavar="HASH", help="the reviewed plan's hash")
2344
+ e = es.add_parser("revert", help="undo an apply (default: the latest) from its manifest")
2345
+ e.add_argument("--state-dir", default=STATE)
2346
+ e.add_argument("--id", help="manifest id (default: the latest)")
2347
+ e.set_defaults(f=cmd_engine_revert)
2348
+ e = es.add_parser("history", help="the latest applies and what each key holds now")
2349
+ e.add_argument("--state-dir", default=STATE)
2350
+ e.add_argument("--limit", type=int, default=10)
2351
+ e.set_defaults(f=cmd_engine_history)
2352
+ e = es.add_parser("verify", help="an apply's predicted effect against the logs since")
2353
+ _source(e)
2354
+ _config_args(e)
2355
+ e.set_defaults(since_days=60)
2356
+ e.add_argument("--state-dir", default=STATE)
2357
+ e.add_argument("--id", help="manifest id (default: the latest)")
2358
+ e.add_argument("--pricing", help="pricing override JSON")
2359
+ e.add_argument("--offline-pricing", action="store_true", help="ignore refreshed prices")
2360
+ e.add_argument("--min-sessions", type=int, default=3, help="sessions needed on each side (default 3)")
2361
+ e.add_argument("--min-days", type=int, default=2, help="active days needed on each side (default 2)")
2362
+ e.set_defaults(f=cmd_engine_verify)
2363
+ e = es.add_parser("consent", help="show, set or clear the auto-apply consent (Claude Code)")
2364
+ e.add_argument("action", choices=["show", "set", "clear"])
2365
+ _config_args(e)
2366
+ e.add_argument("--state-dir", default=STATE)
2367
+ e.add_argument("--models", nargs="+", default=["*"], help="models whose key may change (default: all)")
2368
+ e.add_argument("--profile", choices=PROFILE_NAMES, default=DEFAULT_PROFILE)
2369
+ e.set_defaults(f=cmd_engine_consent)
2370
+
2371
+ s = sub.add_parser("schedule", help="print / install a launchd or systemd user schedule (never auto-loaded)")
2372
+ s.add_argument("action", choices=["print", "install", "status", "uninstall"])
2373
+ s.add_argument("--platform", choices=["auto", "launchd", "systemd"], default="auto")
2374
+ s.add_argument("--mode", choices=["serve", "recalibrate"], default="recalibrate")
2375
+ s.add_argument("--every", default="1d")
2376
+ s.add_argument("--state-dir", default=STATE)
2377
+ s.add_argument("--auto-apply", action="store_true", help="scheduled runs auto-apply (needs consent)")
2378
+ s.add_argument("--yes", action="store_true", help="install/uninstall without the prompt (the diff still prints)")
2379
+ s.set_defaults(f=cmd_schedule)
2380
+
2381
+ s = sub.add_parser("consent", help="store, show or clear the auto-apply consent (scope: file, models, profile)")
2382
+ s.add_argument("action", choices=["set", "show", "clear"])
2383
+ s.add_argument("--harness", choices=["claude-code", "codex"], default="claude-code")
2384
+ s.add_argument("--file", help="the one settings file auto-apply may change")
2385
+ s.add_argument("--models", nargs="*", help="models whose key may change")
2386
+ s.add_argument("--profile", choices=PROFILE_NAMES, default=DEFAULT_PROFILE)
2387
+ s.add_argument("--expires", help="YYYY-MM-DD after which the consent lapses")
2388
+ s.add_argument("--state-dir", default=STATE)
2389
+ s.add_argument("--yes", action="store_true")
2390
+ s.set_defaults(f=cmd_consent)
2391
+
2392
+ s = sub.add_parser("revert", help="undo an apply using its manifest")
2393
+ s.add_argument("--state-dir", default=STATE)
2394
+ s.add_argument("--id", help="manifest id (default: latest)")
2395
+ s.add_argument("--force", action="store_true", help="also revert keys edited after apply")
2396
+ s.set_defaults(f=cmd_revert)
2397
+
2398
+ s = sub.add_parser(
2399
+ "pricing",
2400
+ help="show effective prices, refresh from a public dataset, or turn on automatic refresh for new models",
2401
+ )
2402
+ s.add_argument("action", choices=["show", "refresh", "auto"])
2403
+ s.add_argument("state", nargs="?", choices=["on", "off", "status"], help="for `auto`: on, off or status (default)")
2404
+ s.add_argument("--model", action="append")
2405
+ s.add_argument(
2406
+ "--platform", help="price on this platform: amazon-bedrock, google-vertex-anthropic, azure, openrouter"
2407
+ )
2408
+ s.add_argument("--source", choices=sorted(SOURCES), default="models.dev")
2409
+ s.add_argument("--url", help="override the dataset URL (https only)")
2410
+ s.add_argument("--pricing")
2411
+ s.add_argument("--offline-pricing", action="store_true")
2412
+ s.add_argument("--json", action="store_true")
2413
+ s.set_defaults(f=cmd_pricing)
2414
+
2415
+ s = sub.add_parser("cache", help="inspect or clear the scan cache")
2416
+ s.add_argument("action", choices=["info", "clear"])
2417
+ s.add_argument("--cache-dir", default=f"{STATE}/cache")
2418
+ s.add_argument("--json", action="store_true")
2419
+ s.set_defaults(f=cmd_cache)
2420
+
2421
+
2422
+ def main(argv: list[str] | None = None) -> int:
2423
+ a = build_parser().parse_args(argv)
2424
+ try:
2425
+ rc: int = a.f(a)
2426
+ return rc
2427
+ except CLIError as e:
2428
+ print(f"compactlab: {e}", file=sys.stderr)
2429
+ return 2
2430
+ except KeyboardInterrupt:
2431
+ return 130
2432
+
2433
+
2434
+ if __name__ == "__main__":
2435
+ os.environ.setdefault("PYTHONUTF8", "1")
2436
+ sys.exit(main())