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
@@ -0,0 +1,138 @@
1
+ """What `compactlab engine ...` prints: the contract between the engine and the compactlab app (or any other tool).
2
+
3
+ Every JSON object the engine writes has `engine_api` (this contract's version) and `kind`. Within one version fields
4
+ and kinds are only added; a consumer ignores what it does not know. Removing, renaming or retyping a field bumps
5
+ ENGINE_API. Every kind has an example in tests/contract/ (the app's tests decode the same files), and
6
+ docs/ENGINE_API.md describes them.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import platform
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from .. import __version__
17
+ from ..lens import summarize
18
+ from ..sim.select import DEFAULT_PROFILE
19
+
20
+ ENGINE_API = 1
21
+ COMMANDS = (
22
+ "hello",
23
+ "sessions",
24
+ "watch",
25
+ "result",
26
+ "calibrate",
27
+ "plan",
28
+ "apply",
29
+ "revert",
30
+ "history",
31
+ "verify",
32
+ "consent",
33
+ )
34
+ LIVE_HARNESSES = ("claude-code", "codex") # harnesses `sessions` / `watch` read
35
+
36
+
37
+ def message(kind: str, **body: Any) -> dict[str, Any]:
38
+ return {"engine_api": ENGINE_API, "kind": kind, **body}
39
+
40
+
41
+ def error(code: str, text: str) -> dict[str, Any]:
42
+ """codes: no_result, bad_result, calibration_failed, busy, bad_command, scan_failed, internal; plan_changed,
43
+ refused, no_apply, no_sessions (the settings commands)"""
44
+ return message("error", error={"code": code, "message": text})
45
+
46
+
47
+ def dumps(msg: dict[str, Any]) -> str:
48
+ """One line of JSON (what `watch` writes per message; the one-shot commands print the same)."""
49
+ return json.dumps(msg, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
50
+
51
+
52
+ def _read_json(p: Path) -> Any:
53
+ try:
54
+ return json.loads(p.read_text()) if p.exists() else None
55
+ except (OSError, ValueError):
56
+ return None
57
+
58
+
59
+ def result_path(state_dir: Path) -> Path:
60
+ return state_dir / "service" / "result.json"
61
+
62
+
63
+ def service_state(state_dir: Path) -> dict[str, Any]:
64
+ """The background calibrator's bookkeeping (`serve`, `recalibrate`, `engine calibrate` all keep it)."""
65
+ st = _read_json(state_dir / "service" / "state.json")
66
+ st = st if isinstance(st, dict) else {}
67
+ return {
68
+ "last_calibrated": st.get("last_ok"),
69
+ "last_attempt": st.get("last_attempt"),
70
+ "failures": int(st.get("failures") or 0),
71
+ "last_error": st.get("last_error"),
72
+ }
73
+
74
+
75
+ def hello(harnesses: list[dict[str, Any]], state_dir: Path) -> dict[str, Any]:
76
+ res = result_path(state_dir)
77
+ return message(
78
+ "hello",
79
+ version=__version__,
80
+ python=platform.python_version(),
81
+ commands=list(COMMANDS),
82
+ live_harnesses=list(LIVE_HARNESSES),
83
+ harnesses=harnesses,
84
+ state_dir=str(state_dir),
85
+ result={"path": str(res), "exists": res.exists()},
86
+ service=service_state(state_dir),
87
+ consent=consent_state(state_dir),
88
+ )
89
+
90
+
91
+ def consent_state(state_dir: Path) -> dict[str, Any] | None:
92
+ """The stored auto-apply consent (`compactlab consent`, `engine consent`), or null when there is none or it no
93
+ longer holds (expired, unreadable)."""
94
+ from dataclasses import asdict
95
+
96
+ from ..apply import ApplyError
97
+ from ..service.policy import load_consent
98
+
99
+ try:
100
+ return asdict(load_consent(state_dir / "consent.json"))
101
+ except ApplyError:
102
+ return None
103
+
104
+
105
+ def result_message(
106
+ res: dict[str, Any], state_dir: Path | None = None, auto_apply: dict[str, Any] | None = None
107
+ ) -> dict[str, Any]:
108
+ """The last calibration for the app's threshold table: per group the pick of every profile and what it would
109
+ change against the current setting and the harness default, plus the idle-compaction verdict, the Codex
110
+ single-key decision and the model notes (unpriced, unset, window or default changes)."""
111
+ lens = summarize(res)
112
+ groups = [
113
+ {
114
+ **s,
115
+ "platform": g.get("platform"),
116
+ "current_note": g.get("current_note") or None,
117
+ "window_source": g.get("window_source"),
118
+ "n_sessions": g.get("n_sessions"),
119
+ "n_turns": g.get("n_turns"),
120
+ "superseded_by": g.get("superseded_by"),
121
+ }
122
+ for g, s in zip(res["groups"], lens["groups"], strict=True)
123
+ ]
124
+ return message(
125
+ "result",
126
+ calibration=res.get("calibration"),
127
+ mode=res.get("mode"),
128
+ data_through=res.get("data_through"),
129
+ demo=bool(res.get("demo")),
130
+ profile=(res.get("options") or {}).get("profile") or DEFAULT_PROFILE,
131
+ harnesses=lens["harnesses"], # per harness: the run its groups come from (the result keeps each one's latest)
132
+ groups=groups,
133
+ idle_compaction=res.get("idle_compaction"),
134
+ global_keys=res.get("global_keys") or {},
135
+ model_notes=res.get("model_notes") or {},
136
+ service=service_state(state_dir) if state_dir else None,
137
+ auto_apply=auto_apply, # what `engine calibrate --auto-apply` decided; null otherwise
138
+ )
@@ -0,0 +1,306 @@
1
+ """Active sessions, read from the end of their log files: context size, model, threshold in force, cache expiry.
2
+
3
+ The same parsers as the full analysis read the records (format knowledge stays in one place), but only the last
4
+ 256 KiB of each recently written file, plus the records a parser needs from the top of the file. More is read when
5
+ that holds no complete request, or when the harness re-writes earlier history at the end of a log (Claude Code
6
+ appends copies of old messages with their original times; the full parse drops them as already seen) and the
7
+ newest record is well after the latest request found. The latest request is the newest by time, not the last line.
8
+ Finding the files is incremental: a full walk every 10 minutes; in between, only directories whose mtime moved (a
9
+ file was added or removed) are listed again, and only files written in the last two days are stat'ed. A file whose
10
+ size and mtime did not change is not read again.
11
+
12
+ Project names (the last part of the logged working directory) are only ever printed, never written to a file.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import os
19
+ from collections.abc import Callable
20
+ from dataclasses import dataclass, replace
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ from ..adapters import get_adapter
25
+ from ..adapters.base import Adapter, Parser, parse_lines, parse_ts
26
+ from ..model import Compaction, Session, Turn
27
+ from ..pricing import PricingTable
28
+ from ..sim.baseline import (
29
+ MAX_CONTEXT_ENV,
30
+ default_threshold,
31
+ effective_max,
32
+ read_current,
33
+ read_env_int,
34
+ read_idle,
35
+ )
36
+ from ..sim.engine import SimOptions, group_window
37
+ from . import LIVE_HARNESSES, message
38
+
39
+ TAIL = 256 << 10
40
+ TAIL_MAX = 32 << 20
41
+ REWRITE_GAP_S = 600 # newest record this much after the latest request: maybe a re-written copy, read further back
42
+ HEAD_MAX = 4 << 20 # a Codex session_meta line carries the base instructions
43
+ HOT_S = 2 * 86400 # files written this recently are stat'ed on every update; older ones only on the full walk
44
+ RESCAN_S = 600.0
45
+ ACTIVE_S = 6 * 3600
46
+ CACHE_1H, CACHE_5M = 3600, 300
47
+
48
+
49
+ class Files:
50
+ """`*.jsonl` files under some roots, kept current without walking the whole tree every time."""
51
+
52
+ def __init__(self, roots: list[Path], clock: Callable[[], float]) -> None:
53
+ self.roots = roots
54
+ self.clock = clock
55
+ self.dirs: dict[str, int] = {} # directory -> mtime_ns when last listed
56
+ self.files: dict[str, float] = {} # file -> mtime when last seen
57
+ self.walked = -math.inf
58
+
59
+ def _list(self, d: str, deep: bool) -> None:
60
+ try:
61
+ mtime = os.stat(d).st_mtime_ns
62
+ with os.scandir(d) as it:
63
+ entries = list(it)
64
+ except OSError:
65
+ self._drop(d)
66
+ return
67
+ self.dirs[d] = mtime
68
+ here = set()
69
+ for e in entries:
70
+ try:
71
+ if e.is_dir(follow_symlinks=False):
72
+ if deep or e.path not in self.dirs:
73
+ self._list(e.path, True)
74
+ elif e.name.endswith(".jsonl"):
75
+ here.add(e.path)
76
+ if e.path not in self.files:
77
+ self.files[e.path] = e.stat().st_mtime
78
+ except OSError:
79
+ continue
80
+ pre = d + os.sep
81
+ for p in [p for p in self.files if p.startswith(pre) and os.sep not in p[len(pre) :] and p not in here]:
82
+ del self.files[p]
83
+
84
+ def _drop(self, d: str) -> None:
85
+ pre = d + os.sep
86
+ for k in [k for k in self.dirs if k == d or k.startswith(pre)]:
87
+ del self.dirs[k]
88
+ for p in [p for p in self.files if p.startswith(pre)]:
89
+ del self.files[p]
90
+
91
+ def recent(self, within: float) -> list[tuple[str, os.stat_result]]:
92
+ """Files written in the last `within` seconds, with their stat."""
93
+ now = self.clock()
94
+ if now - self.walked >= RESCAN_S:
95
+ self.dirs, self.files = {}, {}
96
+ for r in self.roots:
97
+ if r.is_dir():
98
+ self._list(str(r), True)
99
+ self.walked = now
100
+ else:
101
+ for d, listed in list(self.dirs.items()):
102
+ if d not in self.dirs: # dropped with its parent in this loop
103
+ continue
104
+ try:
105
+ changed = os.stat(d).st_mtime_ns != listed
106
+ except OSError:
107
+ self._drop(d)
108
+ continue
109
+ if changed:
110
+ self._list(d, False)
111
+ out = []
112
+ hot = max(HOT_S, within)
113
+ for p, m in list(self.files.items()):
114
+ if now - m > hot:
115
+ continue
116
+ try:
117
+ st = os.stat(p)
118
+ except OSError:
119
+ del self.files[p]
120
+ continue
121
+ self.files[p] = st.st_mtime
122
+ if now - st.st_mtime <= within:
123
+ out.append((p, st))
124
+ return out
125
+
126
+
127
+ def read_tail(ad: Adapter, path: str, size: int) -> tuple[Session, Parser, float | None]:
128
+ """The session as far as the end of the file shows it: its last requests, any compaction after them, what the
129
+ parser takes from the file's first records, and the newest record time (None when no record is dated)."""
130
+ tail = TAIL
131
+ while True:
132
+ p = ad.new_parser(Path(path))
133
+ start = max(0, size - tail)
134
+ newest = 0.0
135
+ with open(path, "rb") as f: # line by line: a deep read must not hold the whole region at once
136
+ if start and p.head_records:
137
+ head = [f.readline(HEAD_MAX) for _ in range(p.head_records)]
138
+ for d in parse_lines(iter(head), p):
139
+ p.feed(d)
140
+ f.seek(start)
141
+ if start:
142
+ f.readline() # a tail starts mid-line
143
+ for d in parse_lines(iter(f), p):
144
+ newest = max(newest, parse_ts(d.get("timestamp")) or 0.0)
145
+ p.feed(d)
146
+ s: Session = p.session # type: ignore[attr-defined] # live state, with compactions after the last turn
147
+ if not start or tail >= TAIL_MAX:
148
+ return s, p, newest or None
149
+ if s.turns:
150
+ last = latest(s)[1]
151
+ copied = p.rewrites_history and last.ts is not None and newest - last.ts > REWRITE_GAP_S
152
+ if last.model != "unknown" and not copied:
153
+ return s, p, newest or None
154
+ tail *= 4
155
+
156
+
157
+ def latest(s: Session) -> tuple[int, Turn]:
158
+ """The newest request by time (a later line can be a copy of an older one), with its index."""
159
+ i = max(range(len(s.turns)), key=lambda k: (s.turns[k].ts or 0.0, k))
160
+ return i, s.turns[i]
161
+
162
+
163
+ def _after(s: Session, i: int, t: Turn) -> Compaction | None:
164
+ """A compaction after request `i`: by time when both are dated, else by position."""
165
+ for c in reversed(s.compactions):
166
+ if (c.ts > t.ts) if (c.ts and t.ts) else c.turn_index > i:
167
+ return c
168
+ return None
169
+
170
+
171
+ @dataclass
172
+ class _Entry:
173
+ sig: tuple[int, int]
174
+ session: Session | None
175
+ cwd: str | None
176
+ newest: float | None = None # the newest record time: last activity (mtime also moves when a file is touched)
177
+ failed: bool = False
178
+
179
+
180
+ def _slim(s: Session) -> Session:
181
+ for t in s.turns: # the live view needs sizes and times, not text
182
+ t.snippets, t.tool_keys, t.tool_result_tokens, t.user_text = [], [], [], ""
183
+ for c in s.compactions:
184
+ c.summary_text = ""
185
+ return s
186
+
187
+
188
+ def _cache_ttl(s: Session) -> int | None:
189
+ """The prompt-cache tier of the latest request that wrote cache (Claude Code logs it per request)."""
190
+ if s.harness != "claude-code":
191
+ return None
192
+ for t in sorted(s.turns, key=lambda t: t.ts or 0.0, reverse=True):
193
+ if t.cache_write:
194
+ return CACHE_1H if t.cache_write_1h else CACHE_5M
195
+ return None
196
+
197
+
198
+ def _parent(s: Session) -> str | None:
199
+ # a Claude Code subagent's file lives under <parent session id>/subagents/
200
+ if s.parent_id or s.harness != "claude-code" or s.role != "subagent":
201
+ return s.parent_id
202
+ return Path(s.path).parent.parent.name or None
203
+
204
+
205
+ class LiveSessions:
206
+ """Snapshots of the sessions written to in the last `active_s` seconds."""
207
+
208
+ def __init__(
209
+ self,
210
+ roots: dict[str, list[str] | None],
211
+ configs: dict[str, Path | None],
212
+ pricing: PricingTable,
213
+ clock: Callable[[], float],
214
+ active_s: float = ACTIVE_S,
215
+ project_names: bool = True,
216
+ harnesses: tuple[str, ...] = LIVE_HARNESSES,
217
+ ) -> None:
218
+ self.adapters = {h: get_adapter(h)(roots.get(h)) for h in harnesses}
219
+ self.files = {h: Files(ad.roots, clock) for h, ad in self.adapters.items()}
220
+ self.configs, self.pricing, self.clock = configs, pricing, clock
221
+ self.active_s, self.project_names = active_s, project_names
222
+ self.entries: dict[str, _Entry] = {}
223
+
224
+ def snapshot(self) -> dict[str, Any]:
225
+ now = self.clock()
226
+ claude_cfg = self.configs.get("claude-code")
227
+ opts = SimOptions(claude_max_context=read_env_int(claude_cfg, MAX_CONTEXT_ENV))
228
+ idle_on, idle_min, _ = read_idle(claude_cfg)
229
+ current: dict[tuple[str, str], tuple[int | None, str]] = {}
230
+ rows, seen = [], set()
231
+ for h, ad in self.adapters.items():
232
+ for path, st in self.files[h].recent(self.active_s):
233
+ seen.add(path)
234
+ sig = (st.st_size, st.st_mtime_ns)
235
+ e = self.entries.get(path)
236
+ if e is None or e.sig != sig:
237
+ try:
238
+ s, p, newest = read_tail(ad, path, st.st_size)
239
+ e = _Entry(sig, _slim(s) if s.turns else None, p.cwd, newest)
240
+ except (OSError, ValueError):
241
+ e = _Entry(sig, None, None, failed=True)
242
+ self.entries[path] = e
243
+ active = e.newest or st.st_mtime
244
+ if e.session is not None and now - active <= self.active_s:
245
+ rows.append(self._row(e, active, opts, current))
246
+ for gone in set(self.entries) - seen:
247
+ del self.entries[gone]
248
+ unreadable = sum(e.failed for e in self.entries.values())
249
+ rows.sort(key=lambda r: (-r["last_activity_at"], r["harness"], r["id"]))
250
+ return message(
251
+ "sessions",
252
+ at=now,
253
+ active_s=self.active_s,
254
+ sessions=rows,
255
+ unreadable=unreadable,
256
+ # Claude Code raises a smaller minimum to 100k, as the analysis does
257
+ idle_compaction={"enabled": idle_on, "min_tokens": max(idle_min or SimOptions().idle_min_tokens, 100_000)},
258
+ )
259
+
260
+ def _row(
261
+ self, e: _Entry, active: float, opts: SimOptions, current: dict[tuple[str, str], tuple[int | None, str]]
262
+ ) -> dict[str, Any]:
263
+ s = e.session
264
+ assert s is not None
265
+ i, last = latest(s)
266
+ h, model = s.harness, last.model
267
+ # only this model's requests: another model's larger contexts must not raise its window
268
+ mine = replace(s, turns=[x for x in s.turns if x.model == model], compactions=[])
269
+ table_window = self.pricing.lookup(model, s.platform).max_window
270
+ window, window_source, _ = group_window(h, model, [mine], table_window, opts)
271
+ if s.context_window and window == s.context_window:
272
+ window_source = "logged by the session"
273
+ if (h, model) not in current:
274
+ try:
275
+ current[(h, model)] = read_current(h, model, self.configs.get(h))
276
+ except (OSError, ValueError) as err:
277
+ current[(h, model)] = (None, f"unreadable: {err}")
278
+ configured, note = current[(h, model)]
279
+ if configured is not None:
280
+ threshold, source = min(configured, effective_max(h, window)), "configured"
281
+ else:
282
+ threshold, note = default_threshold(h, model, window)
283
+ source = "default"
284
+ after = _after(s, i, last)
285
+ ttl = _cache_ttl(s)
286
+ return {
287
+ "harness": h,
288
+ "id": s.id,
289
+ "role": s.role,
290
+ "parent_id": _parent(s),
291
+ "project": (Path(e.cwd).name or None) if e.cwd and self.project_names else None,
292
+ "model": model,
293
+ "platform": s.platform,
294
+ # null right after a compaction: the next request shows the compacted size
295
+ "ctx": None if after else last.ctx,
296
+ "compacted_at": (after.ts or active) if after else None,
297
+ "window": window,
298
+ "window_source": window_source,
299
+ "threshold": threshold,
300
+ "threshold_source": source,
301
+ "threshold_note": note,
302
+ "last_request_at": last.ts,
303
+ "last_activity_at": active,
304
+ "cache_ttl_s": ttl,
305
+ "cache_expires_at": last.ts + ttl if ttl and last.ts else None,
306
+ }
@@ -0,0 +1,175 @@
1
+ """The engine's settings commands: `plan`, `apply`, `revert`, `history`, `verify` and `consent` (docs/ENGINE_API.md).
2
+
3
+ Writing goes through compactlab.apply as everywhere else (backup, atomic write, manifest, revert); these functions
4
+ only choose the targets and shape the messages. The person clicking Apply on a reviewed plan is the authorization:
5
+ the targets are the harnesses' own config files, the models the result has groups for, and the usual bounds.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from .. import apply as ap
16
+ from . import message, result_message
17
+
18
+ APPLY_BOUNDS = (100_000, 1_000_000) # the CLI's --i-authorize defaults
19
+ WRITABLE = ("claude-code", "codex")
20
+
21
+
22
+ def preauth(configs: dict[str, Path], res: dict[str, Any]) -> ap.Preauth:
23
+ """Every main-session model of the result, in the harness's config file, within the usual bounds."""
24
+ files = {h: p for h, p in configs.items() if h in WRITABLE}
25
+ models = sorted({ap.model_key(g["harness"], g["model"]) for g in res["groups"] if g["role"] == "main"})
26
+ pre = ap.explicit_preauth(files, models or ["-"], *APPLY_BOUNDS)
27
+ pre.source = "app"
28
+ return pre
29
+
30
+
31
+ def _impact(summary: dict[str, Any], ch: ap.Change) -> dict[str, Any]:
32
+ """What the change does per day, against the setting in force (negative: cheaper / faster), and its evidence."""
33
+ gk = (summary.get("global_keys") or {}).get(ch.harness)
34
+ mains = [g for g in summary["groups"] if g["harness"] == ch.harness and g["role"] == "main"]
35
+ if gk: # one key for every model: the decision across them, against the default
36
+ p = gk["profiles"].get(summary["profile"]) or {}
37
+ return {
38
+ "against": "default",
39
+ "usd_per_day": p.get("d_usd_per_day"),
40
+ "min_per_day": p.get("d_min_per_day"),
41
+ "cost_pct": None,
42
+ "time_pct": None,
43
+ "days": max((g.get("active_days") or g["days"] for g in mains), default=None),
44
+ "sessions": sum(g.get("n_sessions") or 0 for g in mains) or None,
45
+ }
46
+ g = next((g for g in mains if ap.model_key(g["harness"], g["model"]) == ch.model), None)
47
+ if g is None:
48
+ return {"against": None, "usd_per_day": None, "min_per_day": None, "cost_pct": None, "time_pct": None,
49
+ "days": None, "sessions": None} # fmt: skip
50
+ pick = g["profiles"][g["selected"]]
51
+ vs, against = (pick["vs_current"], "current") if pick.get("vs_current") else (pick.get("vs_default"), "default")
52
+ vs = vs or {}
53
+ return {
54
+ "against": against,
55
+ "usd_per_day": vs.get("usd_per_day"),
56
+ "min_per_day": vs.get("min_per_day"),
57
+ "cost_pct": vs.get("cost_pct"),
58
+ "time_pct": vs.get("time_pct"),
59
+ "days": g.get("active_days") or g["days"],
60
+ "sessions": g.get("n_sessions"),
61
+ }
62
+
63
+
64
+ def plan_message(res: dict[str, Any], changes: list[ap.Change], rejected: list[str], profile: str) -> dict[str, Any]:
65
+ summary = result_message(res)
66
+ rendered = ap.render(changes) if changes else {}
67
+ return message(
68
+ "plan",
69
+ profile=profile,
70
+ plan_hash=ap.plan_hash(changes),
71
+ changes=[
72
+ {
73
+ "harness": c.harness,
74
+ "model": c.model,
75
+ "file": str(c.file),
76
+ "key": c.key,
77
+ "old": c.old,
78
+ "new": c.new,
79
+ "impact": _impact(summary, c),
80
+ "plan_hash": ap.plan_hash([c]), # apply just this one: --only harness:model --expect-plan this
81
+ }
82
+ for c in changes
83
+ ],
84
+ skipped=rejected,
85
+ diff=ap.diff_text(rendered) if rendered else "",
86
+ notes=ap.formatting_note(rendered, changes) if rendered else [],
87
+ )
88
+
89
+
90
+ def applied_message(manifest: Path, changes: list[ap.Change]) -> dict[str, Any]:
91
+ return message(
92
+ "applied",
93
+ id=manifest.stem,
94
+ changes=[{"harness": c.harness, "model": c.model, "key": c.key, "old": c.old, "new": c.new} for c in changes],
95
+ )
96
+
97
+
98
+ def record_applied(state_dir: Path, manifest: Path, changes: list[ap.Change], profile: str) -> None:
99
+ """Remember what compactlab wrote, as auto-apply does: its manual-edit check and cooldown then see this change."""
100
+ import sys
101
+
102
+ from ..service.policy import journal, load_applied
103
+
104
+ p = state_dir / "service" / "applied.json"
105
+ try:
106
+ applied = load_applied(p)
107
+ except (OSError, ValueError) as e: # the write is done: a broken bookkeeping file must not report it as failed
108
+ print(f"warning: {p} is unreadable ({e}); starting it again", file=sys.stderr)
109
+ applied = {}
110
+ now = time.time()
111
+ for c in changes:
112
+ applied[f"{c.file}::{c.model}"] = {"value": c.new, "at": now, "manifest": manifest.stem}
113
+ journal(state_dir / "service" / "journal.jsonl",
114
+ {"model": c.model, "file": str(c.file), "key": c.key, "old": c.old, "new": c.new,
115
+ "manifest": manifest.stem, "profile": profile, "by": "app"}) # fmt: skip
116
+ p.parent.mkdir(parents=True, exist_ok=True)
117
+ p.write_text(json.dumps(applied, indent=2))
118
+
119
+
120
+ def _status(now: object, old: object, new: object) -> str:
121
+ if now == "unreadable": # half-written or malformed right now: not evidence of an edit
122
+ return "unreadable"
123
+ if now == new:
124
+ return "in_effect"
125
+ return "reverted" if now == old else "changed"
126
+
127
+
128
+ def history_message(state_dir: Path, limit: int) -> dict[str, Any]:
129
+ """The latest applies, newest first, each key with the value its file holds now: `in_effect`, `reverted` or
130
+ `changed` (edited since by someone else: drift), or `unreadable`."""
131
+ out = []
132
+ for m in sorted((state_dir / "manifests").glob("*.json"), reverse=True)[:limit]:
133
+ try:
134
+ d = json.loads(m.read_text())
135
+ except (OSError, ValueError):
136
+ continue
137
+ rows = []
138
+ for e in d.get("entries", []):
139
+ f = Path(e["file"])
140
+ for ch in e.get("changes", []):
141
+ try:
142
+ now = ap._read_current(f, ch["harness"], ch["model"])
143
+ except (ap.ApplyError, OSError, ValueError):
144
+ now = "unreadable"
145
+ rows.append({
146
+ "harness": ch["harness"], "model": ch["model"], "file": str(f), "key": ch["key"],
147
+ "old": ch["old"], "new": ch["new"], "now": now, "status": _status(now, ch["old"], ch["new"]),
148
+ }) # fmt: skip
149
+ out.append({"id": d.get("id", m.stem), "at": d.get("created"), "by": d.get("preauth"), "changes": rows})
150
+ return message("history", applies=out)
151
+
152
+
153
+ def reverted_message(manifest: Path, log: list[str]) -> dict[str, Any]:
154
+ return message("reverted", id=manifest.stem, log=log, complete=not any("skipped" in x for x in log))
155
+
156
+
157
+ def verification_message(manifest_id: str, res: dict[str, Any]) -> dict[str, Any]:
158
+ """verify's verdict per model, without the per-session detail."""
159
+ keep = ("harness", "model", "role", "old", "new", "verdict", "summary", "in_effect")
160
+ groups = []
161
+ for g in res["groups"]:
162
+ row = {k: g.get(k) for k in keep}
163
+ obs, pred = g.get("observed") or {}, g.get("predicted") or {}
164
+ row["cost_pct"] = obs.get("cost_pct")
165
+ row["cost_pct_predicted"] = pred.get("cost_pct")
166
+ row["sessions_before"] = (g.get("before") or {}).get("sessions")
167
+ row["sessions_after"] = (g.get("after") or {}).get("sessions")
168
+ groups.append(row)
169
+ return message("verification", id=manifest_id, applied_at=res["applied_at"], groups=groups)
170
+
171
+
172
+ def consent_message(consent: Any) -> dict[str, Any]:
173
+ from dataclasses import asdict
174
+
175
+ return message("consent", consent=asdict(consent) if consent is not None else None)