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.
- compactlab/__init__.py +3 -0
- compactlab/adapters/__init__.py +2 -0
- compactlab/adapters/base.py +212 -0
- compactlab/adapters/cache.py +396 -0
- compactlab/adapters/claude_code.py +226 -0
- compactlab/adapters/codex.py +298 -0
- compactlab/adapters/dsh.py +287 -0
- compactlab/adapters/gemini_cli.py +259 -0
- compactlab/adapters/opencode.py +375 -0
- compactlab/apply/__init__.py +582 -0
- compactlab/cli/__init__.py +5 -0
- compactlab/cli/main.py +2436 -0
- compactlab/data/config_knobs.json +158 -0
- compactlab/data/harness_defaults.json +72 -0
- compactlab/data/harness_formats.json +300 -0
- compactlab/data/pricing.json +51 -0
- compactlab/engine/__init__.py +138 -0
- compactlab/engine/live.py +306 -0
- compactlab/engine/settings.py +175 -0
- compactlab/engine/watch.py +82 -0
- compactlab/eval/__init__.py +1 -0
- compactlab/eval/deep.py +390 -0
- compactlab/eval/executors.py +84 -0
- compactlab/eval/factcheck.py +75 -0
- compactlab/lens.py +80 -0
- compactlab/model/__init__.py +285 -0
- compactlab/pricing/__init__.py +211 -0
- compactlab/pricing/auto.py +118 -0
- compactlab/pricing/ids.py +148 -0
- compactlab/pricing/refresh.py +299 -0
- compactlab/publish.py +125 -0
- compactlab/py.typed +0 -0
- compactlab/recommend/__init__.py +201 -0
- compactlab/recommend/claude_code.py +172 -0
- compactlab/recommend/codex.py +104 -0
- compactlab/recommend/dsh.py +89 -0
- compactlab/recommend/gemini_cli.py +85 -0
- compactlab/recommend/opencode.py +117 -0
- compactlab/recommend/units.py +63 -0
- compactlab/report/__init__.py +3 -0
- compactlab/report/html.py +27 -0
- compactlab/report/template.html +1189 -0
- compactlab/service/__init__.py +1 -0
- compactlab/service/core.py +220 -0
- compactlab/service/http.py +133 -0
- compactlab/service/lock.py +92 -0
- compactlab/service/policy.py +258 -0
- compactlab/service/schedule.py +212 -0
- compactlab/share.py +553 -0
- compactlab/sim/__init__.py +1 -0
- compactlab/sim/baseline.py +214 -0
- compactlab/sim/calibrate.py +108 -0
- compactlab/sim/engine.py +1130 -0
- compactlab/sim/select.py +238 -0
- compactlab/sim/timing.py +134 -0
- compactlab/synth.py +416 -0
- compactlab/term/__init__.py +0 -0
- compactlab/term/style.py +134 -0
- compactlab/term/top.py +531 -0
- compactlab/term/views.py +598 -0
- compactlab/term/widgets.py +238 -0
- compactlab/verify.py +462 -0
- compactlab-0.2.0.dist-info/METADATA +243 -0
- compactlab-0.2.0.dist-info/RECORD +67 -0
- compactlab-0.2.0.dist-info/WHEEL +4 -0
- compactlab-0.2.0.dist-info/entry_points.txt +2 -0
- compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
compactlab/publish.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""The shared files other programs read hold the latest run of every harness.
|
|
2
|
+
|
|
3
|
+
Two files are read by programs other than the run that wrote them: the lens summary (`--lens-out`, default
|
|
4
|
+
`~/.compactlab/lens.json`, read by the compactlab-lens mod) and the calibrator's result (`<state-dir>/service/
|
|
5
|
+
result.json`, read by `engine result`, `serve` and `top`). A run replaces the harnesses it covered and keeps the
|
|
6
|
+
entries of every other harness from the file, so `simulate --harness dsh` no longer leaves a lens with dsh alone.
|
|
7
|
+
Everything a result holds per harness is merged that way: groups, sessions, the single-key decision (`global_keys`),
|
|
8
|
+
Claude Code's idle-compaction verdict and the model notes.
|
|
9
|
+
|
|
10
|
+
`harnesses` says, per harness, which run its entries come from: mode, newest turn, calibration and, in a result, the
|
|
11
|
+
options its groups were selected with. Kept groups keep their picks; re-selection (`--profile`) and the threshold cap
|
|
12
|
+
use each harness's own options (`sim.engine.harness_options`), since another run's options may not even be feasible
|
|
13
|
+
for them (a cap below their grid). The top-level fields (`options`, `mode`, `calibration`, ...) are the latest run's.
|
|
14
|
+
|
|
15
|
+
A run's own output (`simulate --out`, `demo`) is that run alone.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import contextlib
|
|
21
|
+
import fcntl
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import tempfile
|
|
25
|
+
from collections.abc import Iterable
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
IDLE_HARNESS = "claude-code" # `idle_compaction` is Claude Code's setting
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def harness_info(d: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
|
33
|
+
"""Per harness with groups in `d` (a result or a lens summary): its mode, the newest turn analysed, the
|
|
34
|
+
calibration that made it and, for a result, its options. Files written before `harnesses` existed get the whole
|
|
35
|
+
run's values."""
|
|
36
|
+
have = d.get("harnesses")
|
|
37
|
+
have = have if isinstance(have, dict) else {}
|
|
38
|
+
out: dict[str, dict[str, Any]] = {}
|
|
39
|
+
for g in d.get("groups") or []:
|
|
40
|
+
h = g["harness"]
|
|
41
|
+
if isinstance(have.get(h), dict):
|
|
42
|
+
out[h] = have[h]
|
|
43
|
+
continue
|
|
44
|
+
if h not in out:
|
|
45
|
+
out[h] = {"mode": d.get("mode"), "data_through": None, "calibration": d.get("calibration")}
|
|
46
|
+
if "options" in d:
|
|
47
|
+
out[h]["options"] = d["options"]
|
|
48
|
+
end = g["span"][1] if g.get("span") else d.get("data_through")
|
|
49
|
+
if end is not None and (out[h]["data_through"] is None or end > out[h]["data_through"]):
|
|
50
|
+
out[h]["data_through"] = end
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def merge(prev: Any, new: dict[str, Any], covered: Iterable[str] | None) -> dict[str, Any]:
|
|
55
|
+
"""`new` plus the entries of `prev` for the harnesses `new` did not cover (`covered` None: it covered all). A
|
|
56
|
+
previous file that is missing, of another schema, demo data against real or damaged in any way (any entry that
|
|
57
|
+
cannot be read as written) is replaced: results are made again by the next run, and a background service must not
|
|
58
|
+
stop on a bad file."""
|
|
59
|
+
out = dict(new)
|
|
60
|
+
out["harnesses"] = harness_info(new)
|
|
61
|
+
if covered is None or not isinstance(prev, dict) or prev.get("schema") != new.get("schema"):
|
|
62
|
+
return out
|
|
63
|
+
if bool(prev.get("demo")) != bool(new.get("demo")):
|
|
64
|
+
return out
|
|
65
|
+
try:
|
|
66
|
+
return _keep(prev, new, out, set(covered))
|
|
67
|
+
except (AttributeError, IndexError, KeyError, TypeError, ValueError):
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _keep(prev: dict[str, Any], new: dict[str, Any], out: dict[str, Any], cov: set[str]) -> dict[str, Any]:
|
|
72
|
+
out = dict(out) # `out` stays as it was if this raises
|
|
73
|
+
|
|
74
|
+
def kept(items: Any) -> list[Any]: # raises on anything not written by this code: the file is then replaced
|
|
75
|
+
if items is not None and not isinstance(items, list):
|
|
76
|
+
raise TypeError(f"not a list: {type(items).__name__}")
|
|
77
|
+
out = [x for x in items or [] if x["harness"] not in cov]
|
|
78
|
+
if not all(isinstance(x["harness"], str) for x in out):
|
|
79
|
+
raise TypeError("a harness that is not a name")
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
old = kept(prev["groups"])
|
|
83
|
+
if not old:
|
|
84
|
+
return out
|
|
85
|
+
for k in ("groups", "sessions"):
|
|
86
|
+
if k in new: # stable: each harness's entries keep their order; harnesses sorted, as analyze() emits them
|
|
87
|
+
out[k] = sorted([*new[k], *kept(prev.get(k))], key=lambda x: x["harness"])
|
|
88
|
+
info = harness_info(prev)
|
|
89
|
+
out["harnesses"] = dict(sorted({**{h: info[h] for h in {g["harness"] for g in old}}, **out["harnesses"]}.items()))
|
|
90
|
+
if "global_keys" in new:
|
|
91
|
+
gk = {h: v for h, v in (prev.get("global_keys") or {}).items() if h not in cov}
|
|
92
|
+
out["global_keys"] = dict(sorted({**gk, **new["global_keys"]}.items()))
|
|
93
|
+
if "idle_compaction" in new and IDLE_HARNESS not in cov:
|
|
94
|
+
out["idle_compaction"] = prev.get("idle_compaction")
|
|
95
|
+
if isinstance(new.get("model_notes"), dict): # per-harness lists merge; the rest (fallback prices, ...) is new
|
|
96
|
+
notes, was = dict(new["model_notes"]), prev.get("model_notes") or {}
|
|
97
|
+
for k, v in notes.items():
|
|
98
|
+
w = was.get(k)
|
|
99
|
+
if isinstance(v, list) and isinstance(w, list) and all("harness" in x for x in [*v, *w]):
|
|
100
|
+
notes[k] = sorted([*v, *kept(w)], key=lambda x: x["harness"])
|
|
101
|
+
out["model_notes"] = notes
|
|
102
|
+
return out
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def update(path: Path, new: dict[str, Any], covered: Iterable[str] | None) -> dict[str, Any]:
|
|
106
|
+
"""Merge `new` into the file at `path` and replace it atomically; returns what was written. A lock on a file
|
|
107
|
+
beside it (`<name>.lock`) keeps two writers (a `simulate` and the service) from losing each other's harnesses."""
|
|
108
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
with open(path.with_name(path.name + ".lock"), "a") as lock:
|
|
110
|
+
fcntl.flock(lock, fcntl.LOCK_EX) # held for one read and one write of a small file
|
|
111
|
+
try:
|
|
112
|
+
prev = json.loads(path.read_text()) if path.exists() else None
|
|
113
|
+
except (OSError, ValueError):
|
|
114
|
+
prev = None # unreadable: replaced
|
|
115
|
+
out = merge(prev, new, covered)
|
|
116
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp")
|
|
117
|
+
try:
|
|
118
|
+
with os.fdopen(fd, "w") as f:
|
|
119
|
+
f.write(json.dumps(out, sort_keys=True))
|
|
120
|
+
os.replace(tmp, path)
|
|
121
|
+
except BaseException:
|
|
122
|
+
with contextlib.suppress(OSError):
|
|
123
|
+
os.unlink(tmp)
|
|
124
|
+
raise
|
|
125
|
+
return out
|
compactlab/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Ready-to-paste configuration from a result: one Recommender per harness.
|
|
2
|
+
|
|
3
|
+
Recommenders only produce text. Writing files stays with `compactlab apply` (pre-authorized).
|
|
4
|
+
Every key a snippet uses must exist in data/config_knobs.json with a source and a verified-on date.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import abc
|
|
10
|
+
import json
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
12
|
+
from datetime import date
|
|
13
|
+
from importlib import resources
|
|
14
|
+
from typing import Any, ClassVar
|
|
15
|
+
|
|
16
|
+
from ..sim.engine import harness_options
|
|
17
|
+
from ..sim.select import DEFAULT_PROFILE, PROFILE_NAMES
|
|
18
|
+
|
|
19
|
+
SCOPES = ("global", "project", "agent")
|
|
20
|
+
FORMATS = ("json", "toml", "yaml", "env", "shell")
|
|
21
|
+
|
|
22
|
+
_REG: dict[str, type[Recommender]] = {}
|
|
23
|
+
_KNOBS: dict[str, Any] | None = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def knobs() -> dict[str, Any]:
|
|
27
|
+
global _KNOBS
|
|
28
|
+
if _KNOBS is None:
|
|
29
|
+
_KNOBS = json.loads(resources.files("compactlab").joinpath("data/config_knobs.json").read_text())
|
|
30
|
+
return _KNOBS
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Snippet:
|
|
35
|
+
harness: str
|
|
36
|
+
scope: str
|
|
37
|
+
profile: str
|
|
38
|
+
format: str
|
|
39
|
+
title: str
|
|
40
|
+
target: str
|
|
41
|
+
content: str
|
|
42
|
+
merge: str = ""
|
|
43
|
+
revert: str = ""
|
|
44
|
+
evidence: list[str] = field(default_factory=list)
|
|
45
|
+
notes: list[str] = field(default_factory=list)
|
|
46
|
+
warnings: list[str] = field(default_factory=list)
|
|
47
|
+
knobs: list[str] = field(default_factory=list)
|
|
48
|
+
|
|
49
|
+
def text(self) -> str:
|
|
50
|
+
"""Plain-text rendering used by --print / --copy."""
|
|
51
|
+
out = [f"# {self.title}", f"# target: {self.target}"]
|
|
52
|
+
out += [f"# evidence: {e}" for e in self.evidence]
|
|
53
|
+
out += [f"# WARNING: {w}" for w in self.warnings]
|
|
54
|
+
out += [f"# note: {n}" for n in self.notes]
|
|
55
|
+
out += ["", self.content.rstrip()]
|
|
56
|
+
if self.merge:
|
|
57
|
+
out += ["", "# merge without touching other keys:", self.merge]
|
|
58
|
+
if self.revert:
|
|
59
|
+
out += ["", "# revert:", self.revert]
|
|
60
|
+
return "\n".join(out) + "\n"
|
|
61
|
+
|
|
62
|
+
def to_dict(self) -> dict[str, Any]:
|
|
63
|
+
return asdict(self) | {"text": self.text()}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Omitted:
|
|
68
|
+
harness: str
|
|
69
|
+
reason: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Recommender(abc.ABC):
|
|
73
|
+
harness: ClassVar[str] = ""
|
|
74
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {} # scope -> supported formats
|
|
75
|
+
|
|
76
|
+
@abc.abstractmethod
|
|
77
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
78
|
+
"""The bare setting for one group at one threshold, in this harness's own syntax (a quick copy)."""
|
|
79
|
+
|
|
80
|
+
@abc.abstractmethod
|
|
81
|
+
def generate(
|
|
82
|
+
self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str
|
|
83
|
+
) -> list[Snippet | Omitted]:
|
|
84
|
+
"""Snippets for this harness. fmt None = the scope's native format."""
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def register(cls: type[Recommender]) -> type[Recommender]:
|
|
88
|
+
_REG[cls.harness] = cls
|
|
89
|
+
return cls
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def recommenders() -> dict[str, type[Recommender]]:
|
|
93
|
+
from . import claude_code, codex, dsh, gemini_cli, opencode # noqa: F401 (register)
|
|
94
|
+
|
|
95
|
+
return dict(_REG)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
# ---------- shared helpers ----------
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def k(v: int | None) -> str:
|
|
102
|
+
return "-" if v is None else f"{v // 1000}k"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def evidence(g: dict[str, Any], profile: str) -> str:
|
|
106
|
+
cmp = g["comparison"][profile]
|
|
107
|
+
vd = cmp["vs_default"]
|
|
108
|
+
t = g["profiles"][profile]
|
|
109
|
+
d = g["default"]
|
|
110
|
+
tm = g.get("time_model", {})
|
|
111
|
+
sign = "+" if vd["d_cost"] >= 0 else "-"
|
|
112
|
+
return (
|
|
113
|
+
f"{g['model']} · {g['role']}: {g['n_sessions']} sessions, {g['n_turns']} turns, {g['days']:.0f} days; "
|
|
114
|
+
f"default {k(d['threshold'])} -> {profile} (${t['value_of_time']:g}/h) {k(t['threshold'])}: "
|
|
115
|
+
f"list-price cost {sign}${abs(vd['d_cost']):,.0f} ({vd['d_cost_pct'] * 100:+.0f}%), "
|
|
116
|
+
f"time {vd['d_time_s'] / 3600:+.1f}h ({vd['d_time_min_per_day']:+.0f} min/day), "
|
|
117
|
+
f"compactions/day {vd['compactions_per_day']:.1f} vs {vd['ref_compactions_per_day']:.1f}, "
|
|
118
|
+
f"recall {t['recall']:.3f} vs {d['recall']:.3f} (lite proxy); "
|
|
119
|
+
f"time model {tm.get('turn_source', '?')}/{tm.get('compact_source', '?')}"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def resolve_profile(result: dict[str, Any], profile: str | None) -> str:
|
|
124
|
+
return profile or (result.get("options") or {}).get("profile") or DEFAULT_PROFILE
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def safe_value(g: dict[str, Any], profile: str, result: dict[str, Any], lo: int, hi: int) -> tuple[int | None, str]:
|
|
128
|
+
"""Value to emit, or (None, reason). Never outside [lo, hi], the window/effective max, or the configured cap."""
|
|
129
|
+
cmp = g["comparison"][profile]
|
|
130
|
+
if cmp["action"] != "set":
|
|
131
|
+
return None, f"{g['model']} · {g['role']}: {cmp['action']}"
|
|
132
|
+
v = int(g["profiles"][profile]["threshold"])
|
|
133
|
+
cap = harness_options(result, g["harness"]).get("max_threshold") # the cap its run was selected under
|
|
134
|
+
limit = min(x for x in (hi, g.get("effective_max"), g.get("max_window"), cap) if x)
|
|
135
|
+
if v < lo or v > limit:
|
|
136
|
+
return None, f"{g['model']} · {g['role']}: {v} outside allowed range [{lo}, {limit}]; not emitted"
|
|
137
|
+
return v, ""
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def setting(g: dict[str, Any], threshold: int) -> str:
|
|
141
|
+
"""The setting for one group at any threshold, from its harness's recommender (terminal `c`, report Copy)."""
|
|
142
|
+
cls = recommenders().get(g["harness"])
|
|
143
|
+
if cls is None:
|
|
144
|
+
return f"# no recommender for harness {g['harness']}; set the threshold to {threshold} by hand"
|
|
145
|
+
return cls().setting(g, threshold)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def generate(
|
|
149
|
+
result: dict[str, Any],
|
|
150
|
+
harness: str | None = None,
|
|
151
|
+
scope: str = "global",
|
|
152
|
+
profile: str | None = None,
|
|
153
|
+
fmt: str | None = None,
|
|
154
|
+
provider: str = "default",
|
|
155
|
+
) -> list[Snippet | Omitted]:
|
|
156
|
+
"""Snippets for one profile (default: the result's selected profile)."""
|
|
157
|
+
profile = resolve_profile(result, profile)
|
|
158
|
+
out: list[Snippet | Omitted] = []
|
|
159
|
+
for name, cls in sorted(recommenders().items()):
|
|
160
|
+
if harness and name != harness:
|
|
161
|
+
continue
|
|
162
|
+
if not any(g["harness"] == name for g in result["groups"]):
|
|
163
|
+
continue
|
|
164
|
+
out += cls().generate(result, scope, profile, fmt, provider)
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def generate_all(result: dict[str, Any]) -> list[dict[str, Any]]:
|
|
169
|
+
"""Every harness × scope × profile × native/alternative format, for the report's copy panel."""
|
|
170
|
+
rows: list[dict[str, Any]] = []
|
|
171
|
+
for name, cls in sorted(recommenders().items()):
|
|
172
|
+
if not any(g["harness"] == name for g in result["groups"]):
|
|
173
|
+
continue
|
|
174
|
+
for scope in SCOPES:
|
|
175
|
+
for profile in PROFILE_NAMES:
|
|
176
|
+
for fmt in cls.formats.get(scope, ()):
|
|
177
|
+
for item in cls().generate(result, scope, profile, fmt, "default"):
|
|
178
|
+
if isinstance(item, Snippet):
|
|
179
|
+
rows.append(item.to_dict())
|
|
180
|
+
else:
|
|
181
|
+
rows.append({"harness": item.harness, "scope": scope, "profile": profile, "format": fmt,
|
|
182
|
+
"omitted": item.reason}) # fmt: skip
|
|
183
|
+
return rows
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def check(snippets: list[Snippet], max_age_days: int = 90, today: date | None = None) -> list[str]:
|
|
187
|
+
"""Problems with the knobs a set of snippets relies on: unverified, missing, or verified too long ago."""
|
|
188
|
+
today = today or date.today()
|
|
189
|
+
data = knobs()["knobs"]
|
|
190
|
+
problems = []
|
|
191
|
+
for key in sorted({kk for s in snippets for kk in s.knobs}):
|
|
192
|
+
kn = data.get(key)
|
|
193
|
+
if kn is None:
|
|
194
|
+
problems.append(f"{key}: not in config_knobs.json")
|
|
195
|
+
continue
|
|
196
|
+
if kn["status"] not in ("documented", "public-source"):
|
|
197
|
+
problems.append(f"{key}: status {kn['status']} ({kn.get('note', '')})")
|
|
198
|
+
age = (today - date.fromisoformat(kn["verified_on"])).days
|
|
199
|
+
if age > max_age_days:
|
|
200
|
+
problems.append(f"{key}: verified {age} days ago (> {max_age_days}); re-check {kn['source']}")
|
|
201
|
+
return problems
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""Claude Code recommender: settings.json (global / project), subagent frontmatter, env var, CLI flag."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
|
|
8
|
+
from ..pricing.ids import claude_settings_key as settings_key
|
|
9
|
+
from . import Omitted, Recommender, Snippet, evidence, k, knobs, register, safe_value
|
|
10
|
+
|
|
11
|
+
LO, HI = 100_000, 1_000_000
|
|
12
|
+
KN_MODEL = "claude.settings.modelSettings.autoCompactWindow"
|
|
13
|
+
KN_AGENT = "claude.agent.autoCompactWindow"
|
|
14
|
+
KN_ENV = "claude.env.CLAUDE_CODE_AUTO_COMPACT_WINDOW"
|
|
15
|
+
KN_FLAG = "claude.flag.--autocompact"
|
|
16
|
+
KN_IDLE = "claude.settings.idleCompaction"
|
|
17
|
+
TARGETS = {
|
|
18
|
+
"global": "~/.claude/settings.json",
|
|
19
|
+
"project": ".claude/settings.local.json (personal) or .claude/settings.json (shared, commit it)",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _merge_py(path: str, values: dict[str, int]) -> str:
|
|
24
|
+
code = (
|
|
25
|
+
"import json,os,sys;p=os.path.expanduser(sys.argv[1]);"
|
|
26
|
+
"d=json.load(open(p)) if os.path.exists(p) and open(p).read().strip() else {};"
|
|
27
|
+
"[d.setdefault('modelSettings',{}).setdefault(m,{}).update(autoCompactWindow=v) "
|
|
28
|
+
"for m,v in json.loads(sys.argv[2]).items()];"
|
|
29
|
+
"open(p,'w').write(json.dumps(d,indent=2)+'\\n')"
|
|
30
|
+
)
|
|
31
|
+
return f"cp {path} {path}.bak 2>/dev/null; python3 -c \"{code}\" {path} '{json.dumps(values)}'"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _idle_py(path: str, value: bool | None) -> str:
|
|
35
|
+
"""Set (or, with None, remove) the top-level idleCompaction key, leaving the rest of the file alone."""
|
|
36
|
+
code = (
|
|
37
|
+
"import json,os,sys;p=os.path.expanduser(sys.argv[1]);"
|
|
38
|
+
"d=json.load(open(p)) if os.path.exists(p) and open(p).read().strip() else {};v=json.loads(sys.argv[2]);"
|
|
39
|
+
"d.pop('idleCompaction',None) if v is None else d.update(idleCompaction=v);"
|
|
40
|
+
"open(p,'w').write(json.dumps(d,indent=2)+'\\n')"
|
|
41
|
+
)
|
|
42
|
+
return f'python3 -c "{code}" {path} {json.dumps(value)}'
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def idle_note(result: dict[str, Any], profile: str) -> tuple[dict[str, Any] | None, str]:
|
|
46
|
+
"""The idle-compaction verdict for a profile and one line about it ('' when it applies to no group)."""
|
|
47
|
+
adv = result.get("idle_compaction")
|
|
48
|
+
if not adv:
|
|
49
|
+
return None, ""
|
|
50
|
+
v = adv["profiles"][profile]
|
|
51
|
+
on = adv["enabled"]
|
|
52
|
+
flip = "turning it off" if on else "turning it on"
|
|
53
|
+
act = ("turn it off" if on else "turn it on") if v["switch"] else ("keep it on" if on else "keep it off")
|
|
54
|
+
sign = "+" if v["d_usd_per_day"] >= 0 else "-"
|
|
55
|
+
return v, (
|
|
56
|
+
f"Idle compaction (idleCompaction, now {'on' if on else 'off'}): {act}. With these picks, {flip} changes "
|
|
57
|
+
f"list-price cost by {sign}${abs(v['d_usd_per_day']):,.1f}/day, wall-clock by "
|
|
58
|
+
f"{v['d_min_per_day']:+.1f} min/day and compactions by {v['d_compactions_per_day']:+.1f}/day "
|
|
59
|
+
f"({', '.join(adv['groups'])})."
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _revert_py(path: str, models: list[str]) -> str:
|
|
64
|
+
code = (
|
|
65
|
+
"import json,os,sys;p=os.path.expanduser(sys.argv[1]);d=json.load(open(p));"
|
|
66
|
+
"[d.get('modelSettings',{}).get(m,{}).pop('autoCompactWindow',None) for m in sys.argv[2:]];"
|
|
67
|
+
"open(p,'w').write(json.dumps(d,indent=2)+'\\n')"
|
|
68
|
+
)
|
|
69
|
+
return (
|
|
70
|
+
f'python3 -c "{code}" {path} {" ".join(models)} # or run /autocompact auto in Claude Code for the user scope'
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@register
|
|
75
|
+
class ClaudeCodeRecommender(Recommender):
|
|
76
|
+
harness = "claude-code"
|
|
77
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {
|
|
78
|
+
"global": ("json", "env", "shell"),
|
|
79
|
+
"project": ("json",),
|
|
80
|
+
"agent": ("yaml",),
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
84
|
+
return json.dumps({"modelSettings": {settings_key(g["model"]): {"autoCompactWindow": threshold}}})
|
|
85
|
+
|
|
86
|
+
def generate(self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str) -> list:
|
|
87
|
+
fmt = fmt or self.formats[scope][0]
|
|
88
|
+
if fmt not in self.formats.get(scope, ()):
|
|
89
|
+
return [Omitted(self.harness, f"format {fmt} is not available for scope {scope}; "
|
|
90
|
+
f"use one of {', '.join(self.formats[scope])}")] # fmt: skip
|
|
91
|
+
role = "subagent" if scope == "agent" else "main"
|
|
92
|
+
groups = [g for g in result["groups"] if g["harness"] == self.harness and g["role"] == role]
|
|
93
|
+
values: dict[str, int] = {}
|
|
94
|
+
out: list[Snippet | Omitted] = []
|
|
95
|
+
ev = []
|
|
96
|
+
for g in groups:
|
|
97
|
+
v, why = safe_value(g, profile, result, LO, HI)
|
|
98
|
+
if v is None:
|
|
99
|
+
out.append(Omitted(self.harness, why))
|
|
100
|
+
continue
|
|
101
|
+
values[settings_key(g["model"])] = v
|
|
102
|
+
ev.append(evidence(g, profile))
|
|
103
|
+
idle_snip = self._idle_snippet(result, scope, profile, fmt)
|
|
104
|
+
if not values: # no window to change; the idle-compaction setting may still be worth flipping
|
|
105
|
+
return [
|
|
106
|
+
*([idle_snip] if idle_snip else []),
|
|
107
|
+
*(out or [Omitted(self.harness, f"no {role} groups for Claude Code")]),
|
|
108
|
+
]
|
|
109
|
+
prov = knobs()["providers"]["claude-code"]
|
|
110
|
+
pnote = prov.get(provider, prov["anthropic"]) if provider != "default" else prov["anthropic"]
|
|
111
|
+
notes = [pnote, "Gateway or custom model IDs: " + prov["gateway"]]
|
|
112
|
+
if scope in ("global", "project") and fmt == "json":
|
|
113
|
+
frag = {"modelSettings": {m: {"autoCompactWindow": v} for m, v in values.items()}}
|
|
114
|
+
path = "~/.claude/settings.json" if scope == "global" else ".claude/settings.local.json"
|
|
115
|
+
notes.insert(0, "Needs Claude Code v2.1.288+. Merge into the existing file; do not replace it.")
|
|
116
|
+
if scope == "project":
|
|
117
|
+
notes.insert(1, "Use .claude/settings.json instead to share with your team (commit it).")
|
|
118
|
+
idle, line = idle_note(result, profile) if scope == "global" else (None, "")
|
|
119
|
+
if line and not (idle and idle["switch"]):
|
|
120
|
+
notes.append(line)
|
|
121
|
+
out.insert(0, Snippet(
|
|
122
|
+
self.harness, scope, profile, fmt, f"Claude Code · {scope} · {profile}: per-model auto-compact window",
|
|
123
|
+
TARGETS[scope], json.dumps(frag, indent=2), _merge_py(path, values), _revert_py(path, list(values)),
|
|
124
|
+
ev, notes, [], [KN_MODEL])) # fmt: skip
|
|
125
|
+
if idle_snip:
|
|
126
|
+
out.insert(1, idle_snip)
|
|
127
|
+
elif fmt == "env":
|
|
128
|
+
lines = [f"# {m}: export only when this model is the one you run (applies to every model in the session)\n"
|
|
129
|
+
f"export CLAUDE_CODE_AUTO_COMPACT_WINDOW={v}" for m, v in values.items()] # fmt: skip
|
|
130
|
+
notes.insert(0, "Precedence: the env var beats --autocompact, /autocompact and settings files.")
|
|
131
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Claude Code · env var · {profile}",
|
|
132
|
+
"shell profile or CI environment", "\n".join(lines), "",
|
|
133
|
+
"unset CLAUDE_CODE_AUTO_COMPACT_WINDOW", ev, notes, [], [KN_ENV])) # fmt: skip
|
|
134
|
+
elif fmt == "shell":
|
|
135
|
+
lines = [f"claude --model {m} --autocompact {v // 1000}k" for m, v in values.items()]
|
|
136
|
+
notes.insert(0, "One launch only; saved settings are unchanged. The env var still wins if set.")
|
|
137
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Claude Code · CLI flag · {profile}",
|
|
138
|
+
"command line",
|
|
139
|
+
"\n".join(lines), "", "launch without --autocompact (or --autocompact auto)",
|
|
140
|
+
ev, notes, [], [KN_FLAG])) # fmt: skip
|
|
141
|
+
elif scope == "agent":
|
|
142
|
+
blocks = [f"# subagents whose model is {m}:\nautoCompactWindow: {v}" for m, v in values.items()]
|
|
143
|
+
notes.insert(0, "Add the line to the YAML frontmatter of each subagent file using that model "
|
|
144
|
+
"(~/.claude/agents/*.md or .claude/agents/*.md). "
|
|
145
|
+
"Needs v2.1.296+. It can only lower the window.") # fmt: skip
|
|
146
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Claude Code · subagents · {profile}",
|
|
147
|
+
"~/.claude/agents/<name>.md or .claude/agents/<name>.md (frontmatter)",
|
|
148
|
+
"\n\n".join(blocks), "", "delete the autoCompactWindow line from the frontmatter",
|
|
149
|
+
ev, notes, [], [KN_AGENT])) # fmt: skip
|
|
150
|
+
return out
|
|
151
|
+
|
|
152
|
+
def _idle_snippet(self, result: dict[str, Any], scope: str, profile: str, fmt: str) -> Snippet | None:
|
|
153
|
+
"""`idleCompaction` for the global settings file, only when flipping it wins by more than the tolerance."""
|
|
154
|
+
if scope != "global" or fmt != "json":
|
|
155
|
+
return None
|
|
156
|
+
idle, line = idle_note(result, profile)
|
|
157
|
+
if not (idle and idle["switch"]):
|
|
158
|
+
return None
|
|
159
|
+
adv = result["idle_compaction"]
|
|
160
|
+
want = not adv["enabled"]
|
|
161
|
+
path = "~/.claude/settings.json"
|
|
162
|
+
# revert to the value the file had; remove the key only when it was unset (absent means on)
|
|
163
|
+
undo = (_idle_py(path, adv["enabled"]) + f" # back to {str(adv['enabled']).lower()}") if adv.get(
|
|
164
|
+
"configured") else (_idle_py(path, None) + " # back to unset (the default, on)") # fmt: skip
|
|
165
|
+
return Snippet(
|
|
166
|
+
self.harness, scope, profile, fmt, f"Claude Code · idle compaction · {profile}", TARGETS[scope],
|
|
167
|
+
json.dumps({"idleCompaction": want}, indent=2), _idle_py(path, want), undo, [line],
|
|
168
|
+
["One setting for every model and project (a project's settings file can override it). "
|
|
169
|
+
"Needs Claude Code v2.1.290+."], [], [KN_IDLE]) # fmt: skip
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
__all__ = ["ClaudeCodeRecommender", "k"]
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Codex recommender: config.toml (global / trusted project), -c flag, role layer (unverified)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, ClassVar
|
|
6
|
+
|
|
7
|
+
from . import Omitted, Recommender, Snippet, evidence, k, knobs, register, safe_value
|
|
8
|
+
|
|
9
|
+
KEY = "model_auto_compact_token_limit"
|
|
10
|
+
KN = "codex.config.model_auto_compact_token_limit"
|
|
11
|
+
KN_FLAG = "codex.flag.-c"
|
|
12
|
+
KN_AGENT = "codex.agent.model_auto_compact_token_limit"
|
|
13
|
+
|
|
14
|
+
MERGE = (
|
|
15
|
+
'cp {p} {p}.bak 2>/dev/null; python3 -c "import os,re,sys;p=os.path.expanduser(sys.argv[1]);'
|
|
16
|
+
"t=open(p).read() if os.path.exists(p) else '';m=re.search(r'^[ \\t]*\\[',t,re.M);i=m.start() if m else len(t);"
|
|
17
|
+
"top,rest=t[:i],t[i:];line='{k} = '+sys.argv[2];"
|
|
18
|
+
"top=re.sub(r'^[ \\t]*{k}[ \\t]*=.*$',line,top,flags=re.M) if re.search(r'^[ \\t]*{k}[ \\t]*=',top,re.M) "
|
|
19
|
+
"else (top.rstrip('\\n')+'\\n' if top.strip() else '')+line+'\\n'+('\\n' if rest else '');"
|
|
20
|
+
"open(p,'w').write(top+rest)\" {p} {v}"
|
|
21
|
+
)
|
|
22
|
+
REVERT = "remove the `{k} = ...` line above the first [table] in {p} (or restore {p}.bak)"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@register
|
|
26
|
+
class CodexRecommender(Recommender):
|
|
27
|
+
harness = "codex"
|
|
28
|
+
formats: ClassVar[dict[str, tuple[str, ...]]] = {
|
|
29
|
+
"global": ("toml", "shell", "env"),
|
|
30
|
+
"project": ("toml",),
|
|
31
|
+
"agent": ("toml",),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
def setting(self, g: dict[str, Any], threshold: int) -> str:
|
|
35
|
+
return f"{KEY} = {threshold}"
|
|
36
|
+
|
|
37
|
+
def generate(self, result: dict[str, Any], scope: str, profile: str, fmt: str | None, provider: str) -> list:
|
|
38
|
+
fmt = fmt or self.formats[scope][0]
|
|
39
|
+
if fmt not in self.formats.get(scope, ()):
|
|
40
|
+
return [Omitted(self.harness, f"format {fmt} is not available for scope {scope}; "
|
|
41
|
+
f"use one of {', '.join(self.formats[scope])}")] # fmt: skip
|
|
42
|
+
if fmt == "env":
|
|
43
|
+
return [Omitted(self.harness, knobs()["knobs"]["codex.env"]["note"] + " Use config.toml or -c instead.")]
|
|
44
|
+
role = "subagent" if scope == "agent" else "main"
|
|
45
|
+
groups = [g for g in result["groups"] if g["harness"] == self.harness and g["role"] == role]
|
|
46
|
+
out: list[Snippet | Omitted] = []
|
|
47
|
+
prov = knobs()["providers"]["codex"]
|
|
48
|
+
pnote = prov.get(provider, prov["openai"]) if provider != "default" else prov["openai"]
|
|
49
|
+
glob = (result.get("global_keys") or {}).get(self.harness)
|
|
50
|
+
if glob and role == "main":
|
|
51
|
+
# one limit for every model: the value chosen across the models in use (compactlab.sim.engine.global_keys)
|
|
52
|
+
gp = glob["profiles"][profile]
|
|
53
|
+
gone = ", ".join(f"{a} (replaced by {b})" for a, b in glob["superseded"].items())
|
|
54
|
+
across = "Codex has one limit for every model; chosen across " + ", ".join(glob["models"]) + (
|
|
55
|
+
f"; not counted: {gone}" if gone else "") # fmt: skip
|
|
56
|
+
if gp["action"] != "set":
|
|
57
|
+
what = {
|
|
58
|
+
"keep current": f"keep current ({k(gp.get('current'))} is within the selection tolerance)",
|
|
59
|
+
"keep default": "keep default (no single value beats it by more than the selection tolerance)",
|
|
60
|
+
"no action needed": "no action needed (the default never compacts in these sessions)",
|
|
61
|
+
}.get(gp["action"], gp["action"])
|
|
62
|
+
return [Omitted(self.harness, f"Codex: {what}. {across}.")]
|
|
63
|
+
used = [g for g in groups if f"{g['model']} · {g['role']}" in glob["models"]] or groups
|
|
64
|
+
g, v = max(used, key=lambda x: x["n_turns"]), int(gp["threshold"])
|
|
65
|
+
notes = [across + ".", pnote]
|
|
66
|
+
notes += [
|
|
67
|
+
f"{m}: {k(t) if t else 'unchanged (its own default is lower)'}" for m, t in gp["per_model"].items()
|
|
68
|
+
]
|
|
69
|
+
else:
|
|
70
|
+
picks = []
|
|
71
|
+
for x in sorted(groups, key=lambda x: -x["n_turns"]):
|
|
72
|
+
xv, why = safe_value(x, profile, result, 1, 10**9)
|
|
73
|
+
if xv is None:
|
|
74
|
+
out.append(Omitted(self.harness, why))
|
|
75
|
+
else:
|
|
76
|
+
picks.append((x, xv))
|
|
77
|
+
if not picks:
|
|
78
|
+
return out or [Omitted(self.harness, f"no Codex {role} sessions in this history")]
|
|
79
|
+
g, v = picks[0]
|
|
80
|
+
notes = [f"Codex has one global limit, not one per model: this value follows {g['model']} (most turns).",
|
|
81
|
+
pnote] # fmt: skip
|
|
82
|
+
notes += [f"Also seen: {o['model']} would get {o_v // 1000}k." for o, o_v in picks[1:]]
|
|
83
|
+
ev = [evidence(g, profile)]
|
|
84
|
+
if scope in ("global", "project"):
|
|
85
|
+
path = "~/.codex/config.toml" if scope == "global" else ".codex/config.toml"
|
|
86
|
+
if scope == "project":
|
|
87
|
+
notes.insert(0, "Project config is loaded only for trusted projects.")
|
|
88
|
+
if fmt == "shell":
|
|
89
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Codex · -c flag · {profile}", "command line",
|
|
90
|
+
f"codex -c {KEY}={v}", "", "run without -c", ev,
|
|
91
|
+
["One run; highest precedence.", *notes], [], [KN_FLAG])) # fmt: skip
|
|
92
|
+
else:
|
|
93
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt,
|
|
94
|
+
f"Codex · {scope} · {profile}: auto-compact limit",
|
|
95
|
+
path + " (top level, above any [table])", f"{KEY} = {v}",
|
|
96
|
+
MERGE.format(p=path, k=KEY, v=v), REVERT.format(k=KEY, p=path),
|
|
97
|
+
ev, notes, [], [KN])) # fmt: skip
|
|
98
|
+
else:
|
|
99
|
+
content = (f"# ~/.codex/config.toml\n[agents.<role>]\nconfig_file = \"<role>.toml\"\n\n"
|
|
100
|
+
f"# <role>.toml (config layer for that role)\n{KEY} = {v}") # fmt: skip
|
|
101
|
+
out.insert(0, Snippet(self.harness, scope, profile, fmt, f"Codex · agent role · {profile}",
|
|
102
|
+
"~/.codex/config.toml + <role>.toml", content, "", "remove the key from <role>.toml",
|
|
103
|
+
ev, notes, [knobs()["knobs"][KN_AGENT]["note"]], [KN_AGENT])) # fmt: skip
|
|
104
|
+
return out
|