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
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
"""Pre-authorized config changes: dry-run by default, backup + manifest, key-level revert.
|
|
2
|
+
|
|
3
|
+
Targets (verified against vendor docs, 2026-10):
|
|
4
|
+
claude-code: modelSettings.<model>.autoCompactWindow in settings.json (int 100000..1000000 or "auto"; per model)
|
|
5
|
+
codex: top-level model_auto_compact_token_limit in config.toml (global; no per-model form)
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import difflib
|
|
11
|
+
import fnmatch
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
import tomllib
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from datetime import date
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from ..pricing.ids import claude_settings_key
|
|
25
|
+
|
|
26
|
+
CLAUDE_LIMITS = (100_000, 1_000_000)
|
|
27
|
+
CODEX_KEY = "model_auto_compact_token_limit"
|
|
28
|
+
CLAUDE_KEY_FMT = "modelSettings.{model}.autoCompactWindow"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ApplyError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Target:
|
|
37
|
+
harness: str
|
|
38
|
+
file: Path
|
|
39
|
+
keys: list[str]
|
|
40
|
+
models: list[str]
|
|
41
|
+
lo: int
|
|
42
|
+
hi: int
|
|
43
|
+
max_change_pct: float | None = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class Preauth:
|
|
48
|
+
targets: list[Target]
|
|
49
|
+
allow_retune: bool = False
|
|
50
|
+
source: str = "flag"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _p(x) -> Path:
|
|
54
|
+
return Path(os.path.expanduser(str(x))).resolve()
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _pct(x) -> float | None:
|
|
58
|
+
if x is None:
|
|
59
|
+
return None
|
|
60
|
+
if isinstance(x, bool) or not isinstance(x, (int, float)) or x < 0:
|
|
61
|
+
raise ApplyError(f"preauth max_change_pct must be a number >= 0, got {x!r}")
|
|
62
|
+
return float(x)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def load_preauth(path: str | Path) -> Preauth:
|
|
66
|
+
d = json.loads(Path(path).read_text())
|
|
67
|
+
if d.get("version") != 1:
|
|
68
|
+
raise ApplyError("preauth file: unsupported version")
|
|
69
|
+
if d.get("expires") and date.fromisoformat(d["expires"]) < date.today():
|
|
70
|
+
raise ApplyError("preauth file has expired")
|
|
71
|
+
ts = []
|
|
72
|
+
for t in d.get("targets", []):
|
|
73
|
+
for req in ("harness", "file", "keys", "models", "min", "max"):
|
|
74
|
+
if req not in t:
|
|
75
|
+
raise ApplyError(f"preauth target missing {req!r}")
|
|
76
|
+
ts.append(
|
|
77
|
+
Target(
|
|
78
|
+
t["harness"],
|
|
79
|
+
_p(t["file"]),
|
|
80
|
+
list(t["keys"]),
|
|
81
|
+
list(t["models"]),
|
|
82
|
+
int(t["min"]),
|
|
83
|
+
int(t["max"]),
|
|
84
|
+
_pct(t.get("max_change_pct")),
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
if not ts:
|
|
88
|
+
raise ApplyError("preauth file has no targets")
|
|
89
|
+
return Preauth(ts, bool(d.get("allow_retune", False)), str(path))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def explicit_preauth(files: dict[str, Path], models: list[str], lo: int, hi: int) -> Preauth:
|
|
93
|
+
keys = {"claude-code": ["modelSettings.*.autoCompactWindow"], "codex": [CODEX_KEY]}
|
|
94
|
+
return Preauth([Target(h, _p(f), keys[h], models, lo, hi) for h, f in files.items()], False, "flag")
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class Change:
|
|
99
|
+
harness: str
|
|
100
|
+
file: Path
|
|
101
|
+
key: str # dotted key (claude) or bare key (codex)
|
|
102
|
+
model: str
|
|
103
|
+
old: object # None => absent
|
|
104
|
+
new: int
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------- planning ----------
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def model_key(harness: str, model: str) -> str:
|
|
111
|
+
"""The name a harness's config uses for a logged model: Claude Code's canonical modelSettings key, else as
|
|
112
|
+
logged."""
|
|
113
|
+
return claude_settings_key(model) if harness == "claude-code" else model
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def model_allowed(harness: str, model: str, allowed: list[str]) -> bool:
|
|
117
|
+
"""`model` is in `allowed`, also when either side is a dated, platform or alias ID of the same Claude model.
|
|
118
|
+
`*` allows every model (a consent that should cover models that appear later)."""
|
|
119
|
+
return (
|
|
120
|
+
"*" in allowed or model in allowed or any(model_key(harness, m) == model_key(harness, model) for m in allowed)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def plan_changes(recs: list[dict], pre: Preauth) -> tuple[list[Change], list[str]]:
|
|
125
|
+
"""recs: [{harness, model, value}]. Returns allowed changes and human-readable rejections."""
|
|
126
|
+
changes, rejected = [], []
|
|
127
|
+
for r in recs:
|
|
128
|
+
tgt = next((t for t in pre.targets if t.harness == r["harness"]), None)
|
|
129
|
+
if not tgt:
|
|
130
|
+
rejected.append(f"{r['harness']}/{r['model']}: no pre-authorized target for this harness")
|
|
131
|
+
continue
|
|
132
|
+
if not model_allowed(r["harness"], r["model"], tgt.models):
|
|
133
|
+
rejected.append(f"{r['model']}: not in authorized models {tgt.models}")
|
|
134
|
+
continue
|
|
135
|
+
key = CLAUDE_KEY_FMT.format(model=r["model"]) if r["harness"] == "claude-code" else CODEX_KEY
|
|
136
|
+
if not any(fnmatch.fnmatchcase(key, pat) for pat in tgt.keys):
|
|
137
|
+
rejected.append(f"{key}: not in authorized keys {tgt.keys}")
|
|
138
|
+
continue
|
|
139
|
+
lo, hi = (
|
|
140
|
+
max(tgt.lo, CLAUDE_LIMITS[0]) if r["harness"] == "claude-code" else tgt.lo,
|
|
141
|
+
min(tgt.hi, CLAUDE_LIMITS[1]) if r["harness"] == "claude-code" else tgt.hi,
|
|
142
|
+
)
|
|
143
|
+
v = int(r["value"])
|
|
144
|
+
if not lo <= v <= hi:
|
|
145
|
+
rejected.append(f"{key}: value {v} outside authorized bounds [{lo}, {hi}]")
|
|
146
|
+
continue
|
|
147
|
+
old = _read_current(tgt.file, r["harness"], r["model"])
|
|
148
|
+
# the limit applies to what is in force now, which may be a top-level setting the model key inherits
|
|
149
|
+
prev = old if old is not None else _effective_value(tgt.file, r["harness"], r["model"])
|
|
150
|
+
if (
|
|
151
|
+
tgt.max_change_pct is not None
|
|
152
|
+
and isinstance(prev, int)
|
|
153
|
+
and prev > 0
|
|
154
|
+
and abs(v - prev) / prev * 100 > tgt.max_change_pct
|
|
155
|
+
):
|
|
156
|
+
rejected.append(f"{key}: change {prev}->{v} exceeds max_change_pct {tgt.max_change_pct:g}")
|
|
157
|
+
continue
|
|
158
|
+
if old == v:
|
|
159
|
+
continue
|
|
160
|
+
changes.append(Change(r["harness"], tgt.file, key, r["model"], old, v))
|
|
161
|
+
return changes, rejected
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def plan_hash(changes: list[Change]) -> str:
|
|
165
|
+
"""A short, stable fingerprint of what a write would do: per change the harness, the file, the key, the value the
|
|
166
|
+
key has now (None when absent) and the value it gets. Order, timestamps and the rest of the file do not count, so
|
|
167
|
+
the same plan hashes the same in any process at any time; a key edited since, a different pick or another file
|
|
168
|
+
gives another hash. `apply --expect-plan` compares it to refuse writing anything but the reviewed plan."""
|
|
169
|
+
rows = sorted(
|
|
170
|
+
json.dumps([c.harness, str(c.file), c.key, c.old, c.new], separators=(",", ":"), default=str) for c in changes
|
|
171
|
+
)
|
|
172
|
+
return hashlib.sha256(("plan-v1\n" + "\n".join(rows)).encode()).hexdigest()[:16]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def recs_from_result(result: dict, harness_of: dict[str, str] | None = None) -> list[dict]:
|
|
176
|
+
"""One recommendation per (harness, model) from the main-role group. Codex has a single global key."""
|
|
177
|
+
recs = []
|
|
178
|
+
for g in result["groups"]:
|
|
179
|
+
if g["role"] != "main":
|
|
180
|
+
continue
|
|
181
|
+
recs.append(
|
|
182
|
+
{
|
|
183
|
+
"harness": g.get("harness", "claude-code"),
|
|
184
|
+
"model": claude_settings_key(g["model"])
|
|
185
|
+
if g.get("harness", "claude-code") == "claude-code"
|
|
186
|
+
else g["model"],
|
|
187
|
+
"value": g["recommendation"]["threshold"],
|
|
188
|
+
"n_turns": g["n_turns"],
|
|
189
|
+
}
|
|
190
|
+
)
|
|
191
|
+
return recs
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ---------- file access ----------
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _read_current(file: Path, harness: str, model: str):
|
|
198
|
+
if not file.exists():
|
|
199
|
+
return None
|
|
200
|
+
text = file.read_text()
|
|
201
|
+
if harness == "claude-code":
|
|
202
|
+
d = _load_json(text, file)
|
|
203
|
+
return (
|
|
204
|
+
d.get("modelSettings", {}).get(model, {}).get("autoCompactWindow")
|
|
205
|
+
if isinstance(d.get("modelSettings", {}).get(model, {}), dict)
|
|
206
|
+
else None
|
|
207
|
+
)
|
|
208
|
+
v = _load_toml(text, file).get(CODEX_KEY)
|
|
209
|
+
return v if isinstance(v, int) and not isinstance(v, bool) else None
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _load_json(text: str, file: Path) -> dict:
|
|
213
|
+
try:
|
|
214
|
+
d = json.loads(text) if text.strip() else {}
|
|
215
|
+
except ValueError as e:
|
|
216
|
+
raise ApplyError(f"{file} is not strict JSON ({e}); refusing to touch it") from e
|
|
217
|
+
if not isinstance(d, dict):
|
|
218
|
+
raise ApplyError(f"{file}: top level is not an object")
|
|
219
|
+
return d
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _dump_json(d: dict, original: str) -> str:
|
|
223
|
+
m = re.search(r"^( +|\t)\"", original, re.M)
|
|
224
|
+
indent = m.group(1) if m else 2
|
|
225
|
+
if isinstance(indent, str) and indent != "\t":
|
|
226
|
+
indent = len(indent)
|
|
227
|
+
s = json.dumps(d, indent=indent, ensure_ascii=False)
|
|
228
|
+
return s + ("\n" if original.endswith("\n") or not original else "")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _load_toml(text: str, file: Path | str = "config.toml") -> dict:
|
|
232
|
+
try:
|
|
233
|
+
return tomllib.loads(text)
|
|
234
|
+
except tomllib.TOMLDecodeError as e:
|
|
235
|
+
raise ApplyError(f"{file} is not valid TOML ({e}); refusing to touch it") from e
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _toml_string_end(text: str, i: int) -> int:
|
|
239
|
+
"""text[i] is a quote that opens a TOML string; the index just past its closing quote."""
|
|
240
|
+
q = text[i]
|
|
241
|
+
triple = text.startswith(q * 3, i)
|
|
242
|
+
j = i + (3 if triple else 1)
|
|
243
|
+
while j < len(text):
|
|
244
|
+
c = text[j]
|
|
245
|
+
if q == '"' and c == "\\":
|
|
246
|
+
j += 2
|
|
247
|
+
elif triple and text.startswith(q * 3, j):
|
|
248
|
+
j += 3
|
|
249
|
+
while j < len(text) and text[j] == q: # up to two quotes before the closer belong to the string
|
|
250
|
+
j += 1
|
|
251
|
+
return j
|
|
252
|
+
elif not triple and c == q:
|
|
253
|
+
return j + 1
|
|
254
|
+
elif not triple and c == "\n":
|
|
255
|
+
break
|
|
256
|
+
else:
|
|
257
|
+
j += 1
|
|
258
|
+
raise ApplyError("unterminated TOML string; refusing to edit")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
_BARE_KEY = re.compile(r"[A-Za-z0-9_-]+")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@dataclass
|
|
265
|
+
class _TomlStmt:
|
|
266
|
+
key: list[str]
|
|
267
|
+
start: int # start of the line
|
|
268
|
+
vstart: int
|
|
269
|
+
vend: int # value text is text[vstart:vend], no trailing space or comment
|
|
270
|
+
end: int # just past the line break that ends the statement
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _toml_top_statements(text: str) -> tuple[list[_TomlStmt], int]:
|
|
274
|
+
"""The `key = value` statements before the first [table], and where that table starts (len(text) if none).
|
|
275
|
+
Quoted keys, multi-line strings and multi-line arrays are skipped over, not mistaken for lines."""
|
|
276
|
+
n = len(text)
|
|
277
|
+
out: list[_TomlStmt] = []
|
|
278
|
+
|
|
279
|
+
def ws(i: int) -> int:
|
|
280
|
+
while i < n and text[i] in " \t":
|
|
281
|
+
i += 1
|
|
282
|
+
return i
|
|
283
|
+
|
|
284
|
+
i = 0
|
|
285
|
+
while i < n:
|
|
286
|
+
j = ws(i)
|
|
287
|
+
if j >= n:
|
|
288
|
+
break
|
|
289
|
+
if text[j] in "\r\n":
|
|
290
|
+
i = j + 1
|
|
291
|
+
continue
|
|
292
|
+
if text[j] == "#":
|
|
293
|
+
k = text.find("\n", j)
|
|
294
|
+
i = n if k < 0 else k + 1
|
|
295
|
+
continue
|
|
296
|
+
if text[j] == "[":
|
|
297
|
+
return out, i
|
|
298
|
+
key: list[str] = []
|
|
299
|
+
while True:
|
|
300
|
+
j = ws(j)
|
|
301
|
+
if j < n and text[j] in "\"'":
|
|
302
|
+
e = _toml_string_end(text, j)
|
|
303
|
+
try:
|
|
304
|
+
key.append(next(iter(tomllib.loads(f"{text[j:e]} = 0"))))
|
|
305
|
+
except (tomllib.TOMLDecodeError, StopIteration) as ex:
|
|
306
|
+
raise ApplyError("unreadable quoted TOML key; refusing to edit") from ex
|
|
307
|
+
j = e
|
|
308
|
+
else:
|
|
309
|
+
m = _BARE_KEY.match(text, j)
|
|
310
|
+
if not m:
|
|
311
|
+
raise ApplyError("unreadable TOML key; refusing to edit")
|
|
312
|
+
key.append(m.group())
|
|
313
|
+
j = m.end()
|
|
314
|
+
j = ws(j)
|
|
315
|
+
if j < n and text[j] == ".":
|
|
316
|
+
j += 1
|
|
317
|
+
continue
|
|
318
|
+
break
|
|
319
|
+
if j >= n or text[j] != "=":
|
|
320
|
+
raise ApplyError("unreadable TOML line; refusing to edit")
|
|
321
|
+
vstart = ws(j + 1)
|
|
322
|
+
k, depth, vend = vstart, 0, vstart
|
|
323
|
+
while k < n:
|
|
324
|
+
c = text[k]
|
|
325
|
+
if c in "\"'":
|
|
326
|
+
k = _toml_string_end(text, k)
|
|
327
|
+
vend = k
|
|
328
|
+
continue
|
|
329
|
+
if c == "#":
|
|
330
|
+
e = text.find("\n", k)
|
|
331
|
+
k = n if e < 0 else e
|
|
332
|
+
continue
|
|
333
|
+
if c in "[{":
|
|
334
|
+
depth += 1
|
|
335
|
+
elif c in "]}":
|
|
336
|
+
depth -= 1
|
|
337
|
+
elif c == "\n" and depth <= 0:
|
|
338
|
+
break
|
|
339
|
+
if c not in " \t\r\n":
|
|
340
|
+
vend = k + 1
|
|
341
|
+
k += 1
|
|
342
|
+
out.append(_TomlStmt(key, i, vstart, vend, min(k + 1, n)))
|
|
343
|
+
i = min(k + 1, n)
|
|
344
|
+
return out, n
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _set_toml(text: str, value: int | None) -> str:
|
|
348
|
+
"""Set (or, with None, remove) the top-level Codex key. Parses before and after and refuses on any surprise."""
|
|
349
|
+
before = _load_toml(text)
|
|
350
|
+
stmts, top_end = _toml_top_statements(text)
|
|
351
|
+
hit = [s for s in stmts if s.key == [CODEX_KEY]]
|
|
352
|
+
if hit:
|
|
353
|
+
s = hit[0]
|
|
354
|
+
if not re.fullmatch(r"[+-]?\d[\d_]*", text[s.vstart : s.vend]):
|
|
355
|
+
raise ApplyError(f"{CODEX_KEY} is not a plain integer in the file; refusing to edit it")
|
|
356
|
+
if value is None:
|
|
357
|
+
new = text[: s.start] + text[s.end :]
|
|
358
|
+
else:
|
|
359
|
+
new = text[: s.vstart] + str(value) + text[s.vend :]
|
|
360
|
+
elif value is None:
|
|
361
|
+
new = text
|
|
362
|
+
else:
|
|
363
|
+
top, rest = text[:top_end], text[top_end:]
|
|
364
|
+
body = top.rstrip("\n")
|
|
365
|
+
trailing = top[len(body) :]
|
|
366
|
+
top = (body + "\n" if body else "") + f"{CODEX_KEY} = {value}" + (trailing or "\n")
|
|
367
|
+
if rest and not trailing:
|
|
368
|
+
top += "\n"
|
|
369
|
+
new = top + rest
|
|
370
|
+
expect = {k: v for k, v in before.items() if k != CODEX_KEY or value is not None}
|
|
371
|
+
if value is not None:
|
|
372
|
+
expect[CODEX_KEY] = value
|
|
373
|
+
if _load_toml(new) != expect:
|
|
374
|
+
raise ApplyError("the TOML edit would change more than the one key; refusing to write it")
|
|
375
|
+
return new
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _set_path(d: dict, path: list[str], value) -> int:
|
|
379
|
+
"""Set nested key; returns number of path elements that did not exist before."""
|
|
380
|
+
created = 0
|
|
381
|
+
cur = d
|
|
382
|
+
for k in path[:-1]:
|
|
383
|
+
if not isinstance(cur.get(k), dict):
|
|
384
|
+
if k in cur:
|
|
385
|
+
raise ApplyError(f"{k!r} exists and is not an object")
|
|
386
|
+
cur[k] = {}
|
|
387
|
+
created += 1
|
|
388
|
+
cur = cur[k]
|
|
389
|
+
if path[-1] not in cur:
|
|
390
|
+
created += 1
|
|
391
|
+
cur[path[-1]] = value
|
|
392
|
+
return created
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _split_key(key: str, model: str) -> list[str]:
|
|
396
|
+
return ["modelSettings", model, "autoCompactWindow"]
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def render(change_set: list[Change]) -> dict[Path, tuple[str, str]]:
|
|
400
|
+
"""Compute (old_text, new_text) per file without writing."""
|
|
401
|
+
out: dict[Path, tuple[str, str]] = {}
|
|
402
|
+
for ch in change_set:
|
|
403
|
+
old_text = out[ch.file][1] if ch.file in out else (ch.file.read_text() if ch.file.exists() else "")
|
|
404
|
+
orig = out[ch.file][0] if ch.file in out else old_text
|
|
405
|
+
if ch.harness == "claude-code":
|
|
406
|
+
d = _load_json(old_text, ch.file)
|
|
407
|
+
_set_path(d, _split_key(ch.key, ch.model), ch.new)
|
|
408
|
+
new_text = _dump_json(d, orig)
|
|
409
|
+
else:
|
|
410
|
+
new_text = _set_toml(old_text, ch.new)
|
|
411
|
+
out[ch.file] = (orig, new_text)
|
|
412
|
+
return out
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def diff_text(rendered: dict[Path, tuple[str, str]]) -> str:
|
|
416
|
+
parts = []
|
|
417
|
+
for f, (a, b) in rendered.items():
|
|
418
|
+
parts.append("".join(difflib.unified_diff(a.splitlines(True), b.splitlines(True), f"a/{f}", f"b/{f}")))
|
|
419
|
+
return "\n".join(parts)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def formatting_note(rendered: dict[Path, tuple[str, str]], changes: list[Change]) -> list[str]:
|
|
423
|
+
notes = []
|
|
424
|
+
for f, (a, _) in rendered.items():
|
|
425
|
+
if f.suffix == ".json" and a.strip():
|
|
426
|
+
try:
|
|
427
|
+
if _dump_json(json.loads(a), a) != a:
|
|
428
|
+
notes.append(f"{f}: JSON formatting will be normalized (content of other keys is unchanged)")
|
|
429
|
+
except ValueError:
|
|
430
|
+
pass
|
|
431
|
+
return notes
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
# ---------- write / revert ----------
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _sha(text: str) -> str:
|
|
438
|
+
return hashlib.sha256(text.encode()).hexdigest()
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def _atomic_write(path: Path, text: str) -> None:
|
|
442
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
443
|
+
fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.")
|
|
444
|
+
try:
|
|
445
|
+
with os.fdopen(fd, "w") as f:
|
|
446
|
+
f.write(text)
|
|
447
|
+
if path.exists():
|
|
448
|
+
os.chmod(tmp, path.stat().st_mode & 0o777)
|
|
449
|
+
os.replace(tmp, path)
|
|
450
|
+
except BaseException:
|
|
451
|
+
if os.path.exists(tmp):
|
|
452
|
+
os.unlink(tmp)
|
|
453
|
+
raise
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _write_private(path: Path, text: str) -> None:
|
|
457
|
+
"""Create `path` readable by the owner only, whatever the umask."""
|
|
458
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
459
|
+
with os.fdopen(fd, "w") as f:
|
|
460
|
+
os.fchmod(f.fileno(), 0o600)
|
|
461
|
+
f.write(text)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _effective_value(file: Path, harness: str, model: str) -> int | None:
|
|
465
|
+
"""The threshold in force now, including a top-level setting the model key inherits."""
|
|
466
|
+
from ..sim.baseline import read_current
|
|
467
|
+
|
|
468
|
+
try:
|
|
469
|
+
return read_current(harness, model, file)[0]
|
|
470
|
+
except (OSError, ValueError):
|
|
471
|
+
return None
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _effective_old(ch: Change) -> int | None:
|
|
475
|
+
"""The threshold in force before this change."""
|
|
476
|
+
return _effective_value(ch.file, ch.harness, ch.model)
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
def write_changes(changes: list[Change], state_dir: Path, pre: Preauth) -> Path:
|
|
480
|
+
rendered = render(changes)
|
|
481
|
+
mid = time.strftime("%Y%m%dT%H%M%S") + f"-{os.getpid()}"
|
|
482
|
+
bdir = state_dir / "backups" / mid
|
|
483
|
+
bdir.mkdir(parents=True, exist_ok=True)
|
|
484
|
+
for d in (bdir.parent, bdir): # backups hold whole harness configs, which can contain secrets
|
|
485
|
+
d.chmod(0o700)
|
|
486
|
+
entries: list[dict[str, Any]] = []
|
|
487
|
+
for f, (old_text, new_text) in rendered.items():
|
|
488
|
+
bak = bdir / f"{len(entries)}-{f.name}.bak"
|
|
489
|
+
_write_private(bak, old_text)
|
|
490
|
+
ents = []
|
|
491
|
+
for ch in changes:
|
|
492
|
+
if ch.file != f:
|
|
493
|
+
continue
|
|
494
|
+
depth = 0
|
|
495
|
+
if ch.harness == "claude-code" and old_text.strip():
|
|
496
|
+
d = json.loads(old_text)
|
|
497
|
+
tmp = json.loads(json.dumps(d))
|
|
498
|
+
depth = _set_path(tmp, _split_key(ch.key, ch.model), ch.new)
|
|
499
|
+
elif ch.harness == "claude-code":
|
|
500
|
+
depth = 3
|
|
501
|
+
ents.append(
|
|
502
|
+
{
|
|
503
|
+
"harness": ch.harness,
|
|
504
|
+
"key": ch.key,
|
|
505
|
+
"model": ch.model,
|
|
506
|
+
"old": ch.old,
|
|
507
|
+
"old_effective": _effective_old(ch), # what applied before: the key, else an inherited setting
|
|
508
|
+
"new": ch.new,
|
|
509
|
+
"created_depth": depth,
|
|
510
|
+
}
|
|
511
|
+
)
|
|
512
|
+
entries.append(
|
|
513
|
+
{
|
|
514
|
+
"file": str(f),
|
|
515
|
+
"existed": f.exists(),
|
|
516
|
+
"backup": str(bak),
|
|
517
|
+
"sha_before": _sha(old_text),
|
|
518
|
+
"sha_after": _sha(new_text),
|
|
519
|
+
"changes": ents,
|
|
520
|
+
}
|
|
521
|
+
)
|
|
522
|
+
for f, (_, new_text) in rendered.items():
|
|
523
|
+
_atomic_write(f, new_text)
|
|
524
|
+
manifest = state_dir / "manifests" / f"{mid}.json"
|
|
525
|
+
manifest.parent.mkdir(parents=True, exist_ok=True)
|
|
526
|
+
manifest.write_text(
|
|
527
|
+
json.dumps({"id": mid, "created": time.time(), "preauth": pre.source, "entries": entries}, indent=2)
|
|
528
|
+
)
|
|
529
|
+
return manifest
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def latest_manifest(state_dir: Path) -> Path:
|
|
533
|
+
ms = sorted((state_dir / "manifests").glob("*.json"))
|
|
534
|
+
if not ms:
|
|
535
|
+
raise ApplyError("no manifests found; nothing to revert")
|
|
536
|
+
return ms[-1]
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def revert(manifest: Path, force: bool = False) -> list[str]:
|
|
540
|
+
"""Restore only the keys we changed. If the key was edited since, skip it unless force."""
|
|
541
|
+
m = json.loads(manifest.read_text())
|
|
542
|
+
log = []
|
|
543
|
+
for e in reversed(m["entries"]):
|
|
544
|
+
f = Path(e["file"])
|
|
545
|
+
text = f.read_text() if f.exists() else ""
|
|
546
|
+
if _sha(text) == e["sha_after"]:
|
|
547
|
+
# untouched since apply: exact restore from backup
|
|
548
|
+
bak = Path(e["backup"]).read_text()
|
|
549
|
+
if e["existed"]:
|
|
550
|
+
_atomic_write(f, bak)
|
|
551
|
+
else:
|
|
552
|
+
f.unlink()
|
|
553
|
+
log.append(f"{f}: restored from backup")
|
|
554
|
+
continue
|
|
555
|
+
for ch in e["changes"]:
|
|
556
|
+
cur = _read_current(f, ch["harness"], ch["model"])
|
|
557
|
+
if cur != ch["new"] and not force:
|
|
558
|
+
log.append(f"{f}: {ch['key']} changed since apply (now {cur!r}); skipped (use --force)")
|
|
559
|
+
continue
|
|
560
|
+
if ch["harness"] == "claude-code":
|
|
561
|
+
d = _load_json(text, f)
|
|
562
|
+
path = _split_key(ch["key"], ch["model"])
|
|
563
|
+
chain = [d]
|
|
564
|
+
for k in path[:-1]:
|
|
565
|
+
chain.append(chain[-1].get(k, {}))
|
|
566
|
+
if ch["old"] is None:
|
|
567
|
+
chain[-1].pop(path[-1], None)
|
|
568
|
+
pruned = 1
|
|
569
|
+
for i in range(len(path) - 2, -1, -1):
|
|
570
|
+
if pruned < ch["created_depth"] and chain[i + 1] == {}:
|
|
571
|
+
chain[i].pop(path[i], None)
|
|
572
|
+
pruned += 1
|
|
573
|
+
else:
|
|
574
|
+
break
|
|
575
|
+
else:
|
|
576
|
+
chain[-1][path[-1]] = ch["old"]
|
|
577
|
+
text = _dump_json(d, text)
|
|
578
|
+
else:
|
|
579
|
+
text = _set_toml(text, ch["old"])
|
|
580
|
+
log.append(f"{f}: {ch['key']} reverted to {ch['old']!r}")
|
|
581
|
+
_atomic_write(f, text)
|
|
582
|
+
return log
|