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,82 @@
|
|
|
1
|
+
"""`compactlab engine watch`: a resident process that prints the active sessions as JSON Lines.
|
|
2
|
+
|
|
3
|
+
stdout: a `hello` line, then a `sessions` line at start and whenever the sessions change. stdin, one command per line:
|
|
4
|
+
`refresh` (files changed: rescan, print only if something changed), `snapshot` (rescan and print regardless),
|
|
5
|
+
`ping` (answers `pong`), `quit`. End of input also ends it, so the process never outlives the app that started it.
|
|
6
|
+
Scans are at least `min_interval` seconds apart (requests in between are merged into one), and every `interval`
|
|
7
|
+
seconds without a request (0: never) a scan runs anyway, so sessions that went quiet drop out. A closed stdout
|
|
8
|
+
raises BrokenPipeError to the caller.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import queue
|
|
14
|
+
import threading
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Any, TextIO
|
|
18
|
+
|
|
19
|
+
from . import dumps, error, message
|
|
20
|
+
|
|
21
|
+
COMMANDS = ("refresh", "snapshot", "ping", "quit")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def run(
|
|
25
|
+
scan: Callable[[], dict[str, Any]],
|
|
26
|
+
hello: dict[str, Any],
|
|
27
|
+
inp: TextIO,
|
|
28
|
+
out: TextIO,
|
|
29
|
+
min_interval: float = 5.0,
|
|
30
|
+
interval: float = 60.0,
|
|
31
|
+
clock: Callable[[], float] = time.monotonic,
|
|
32
|
+
) -> int:
|
|
33
|
+
q: queue.Queue[str | None] = queue.Queue()
|
|
34
|
+
|
|
35
|
+
def read() -> None:
|
|
36
|
+
try:
|
|
37
|
+
for line in inp:
|
|
38
|
+
q.put(line.strip())
|
|
39
|
+
finally:
|
|
40
|
+
q.put(None)
|
|
41
|
+
|
|
42
|
+
threading.Thread(target=read, name="engine-watch-stdin", daemon=True).start()
|
|
43
|
+
|
|
44
|
+
def emit(msg: dict[str, Any]) -> None:
|
|
45
|
+
out.write(dumps(msg) + "\n")
|
|
46
|
+
out.flush()
|
|
47
|
+
|
|
48
|
+
last_rows: str | None = None
|
|
49
|
+
last_scan = -float("inf")
|
|
50
|
+
due: float | None = clock() # the first scan runs at once and is always printed
|
|
51
|
+
force = True
|
|
52
|
+
emit(hello)
|
|
53
|
+
while True:
|
|
54
|
+
now = clock()
|
|
55
|
+
if due is None and interval > 0:
|
|
56
|
+
due = last_scan + interval
|
|
57
|
+
if due is not None and now >= due:
|
|
58
|
+
try:
|
|
59
|
+
snap = scan()
|
|
60
|
+
except Exception as e: # keep running; the next request or interval retries
|
|
61
|
+
emit(error("scan_failed", f"{type(e).__name__}: {e}"[:500]))
|
|
62
|
+
else:
|
|
63
|
+
rows = dumps({k: v for k, v in snap.items() if k != "at"})
|
|
64
|
+
if force or rows != last_rows:
|
|
65
|
+
emit(snap)
|
|
66
|
+
last_rows = rows
|
|
67
|
+
last_scan, due, force = clock(), None, False
|
|
68
|
+
continue
|
|
69
|
+
try:
|
|
70
|
+
cmd = q.get(timeout=None if due is None else max(due - now, 0.0))
|
|
71
|
+
except queue.Empty:
|
|
72
|
+
continue
|
|
73
|
+
if cmd is None or cmd == "quit":
|
|
74
|
+
return 0
|
|
75
|
+
if cmd == "ping":
|
|
76
|
+
emit(message("pong"))
|
|
77
|
+
elif cmd in ("refresh", "snapshot"):
|
|
78
|
+
at = max(clock(), last_scan + min_interval)
|
|
79
|
+
due = at if due is None else min(due, at)
|
|
80
|
+
force = force or cmd == "snapshot"
|
|
81
|
+
elif cmd:
|
|
82
|
+
emit(error("bad_command", f"unknown command {cmd[:80]!r}; expected one of {', '.join(COMMANDS)}"))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Summary evaluation: offline fact-check heuristics and the opt-in deep (LLM) layer."""
|
compactlab/eval/deep.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"""Deep mode: opt-in, agent-driven evaluation layered on top of lite.
|
|
2
|
+
|
|
3
|
+
Never runs by default. The CLI prints an estimated cost, requires `--yes`, and enforces `--budget`:
|
|
4
|
+
a call is refused when its estimate would cross the cap, and the run stops as soon as the measured spend
|
|
5
|
+
after a call exceeds it. A single call can still overshoot by what the executor actually used, since a
|
|
6
|
+
CLI that exposes no output limit (Codex) cannot be capped provider-side. Network or harness access happens
|
|
7
|
+
only inside an `LLMClient` (see executors.py).
|
|
8
|
+
|
|
9
|
+
Two pieces:
|
|
10
|
+
run_eval() probes + LLM judge on summaries that already exist in your history.
|
|
11
|
+
deep_analyze() re-summarizes sampled sessions at candidate thresholds, probes the summaries for
|
|
12
|
+
ground-truth facts, and reports measured recall next to lite's assumed recall.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import importlib
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any, Protocol
|
|
23
|
+
|
|
24
|
+
from ..model import Compaction, Session
|
|
25
|
+
from ..pricing import PricingTable
|
|
26
|
+
from .factcheck import Flag, check_summary
|
|
27
|
+
|
|
28
|
+
CONFIRM_FLAG = "--yes"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class EvalError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class BudgetExceeded(EvalError):
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Completion:
|
|
41
|
+
text: str
|
|
42
|
+
input_tokens: int
|
|
43
|
+
output_tokens: int
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LLMClient(Protocol):
|
|
47
|
+
def complete(self, model: str, prompt: str, max_tokens: int) -> Completion: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class Probe:
|
|
52
|
+
kind: str
|
|
53
|
+
question: str
|
|
54
|
+
truth: list[str]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class ProbeResult:
|
|
59
|
+
probe: Probe
|
|
60
|
+
answer: str
|
|
61
|
+
exact: bool
|
|
62
|
+
judge_votes: list[bool]
|
|
63
|
+
judged: bool
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def ok(self) -> bool:
|
|
67
|
+
return self.judged if self.judge_votes else self.exact
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class EvalReport:
|
|
72
|
+
results: list[ProbeResult] = field(default_factory=list)
|
|
73
|
+
flags: list[Flag] = field(default_factory=list)
|
|
74
|
+
spent_usd: float = 0.0
|
|
75
|
+
calls: int = 0
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def exact_rate(self) -> float:
|
|
79
|
+
return sum(r.exact for r in self.results) / max(len(self.results), 1)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def judged_rate(self) -> float:
|
|
83
|
+
return sum(r.ok for r in self.results) / max(len(self.results), 1)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class BudgetGuard:
|
|
87
|
+
def __init__(self, cap_usd: float, pricing: PricingTable):
|
|
88
|
+
if cap_usd <= 0:
|
|
89
|
+
raise EvalError("budget cap must be > 0")
|
|
90
|
+
self.cap, self.pricing, self.spent, self.calls = cap_usd, pricing, 0.0, 0
|
|
91
|
+
|
|
92
|
+
def cost(self, model: str, in_tok: int, out_tok: int) -> float:
|
|
93
|
+
ri, ro, _, _ = self.pricing.lookup(model).rates(in_tok)
|
|
94
|
+
return in_tok * ri + out_tok * ro
|
|
95
|
+
|
|
96
|
+
def call(self, client: LLMClient, model: str, prompt: str, max_tokens: int) -> Completion:
|
|
97
|
+
est = self.cost(model, len(prompt) // 4 + 1, max_tokens)
|
|
98
|
+
if self.spent + est > self.cap:
|
|
99
|
+
raise BudgetExceeded(f"next call (~${est:.4f}) would exceed cap ${self.cap:.2f} (spent ${self.spent:.4f})")
|
|
100
|
+
out = client.complete(model, prompt, max_tokens)
|
|
101
|
+
self.spent += self.cost(model, out.input_tokens, out.output_tokens)
|
|
102
|
+
self.calls += 1
|
|
103
|
+
if self.spent > self.cap: # the estimate was wrong (or the executor ignored max_tokens): stop here
|
|
104
|
+
raise BudgetExceeded(f"spent ${self.spent:.4f}, over cap ${self.cap:.2f}; stopped after {self.calls} calls")
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
FILE_QUESTION = (
|
|
109
|
+
"List the exact file paths that were being worked on before the context was compacted, "
|
|
110
|
+
"one per line, as far as this summary lets you tell. Say 'unknown' if it does not say."
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def make_probes(s: Session, c: Compaction, limit: int = 5) -> list[Probe]:
|
|
115
|
+
"""Ground-truth probes from facts that are verifiably in the pre-compaction transcript."""
|
|
116
|
+
seen: list[str] = []
|
|
117
|
+
for t in reversed(s.turns[max(0, c.turn_index - 60) : c.turn_index]):
|
|
118
|
+
for k in t.tool_keys:
|
|
119
|
+
_name, _, arg = k.partition(":")
|
|
120
|
+
if arg.startswith("/") and arg not in seen:
|
|
121
|
+
seen.append(arg)
|
|
122
|
+
# The question must not contain the answer: every probe asks the same open question and is scored
|
|
123
|
+
# against its own file, so a summary that dropped the path scores 0.
|
|
124
|
+
return [Probe("file", FILE_QUESTION, [p]) for p in seen[:limit]]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def estimate_cost(
|
|
128
|
+
n_probes: int,
|
|
129
|
+
summary_chars: int,
|
|
130
|
+
answer_model: str,
|
|
131
|
+
judge_model: str,
|
|
132
|
+
repeats: int,
|
|
133
|
+
pricing: PricingTable,
|
|
134
|
+
max_tokens: int = 200,
|
|
135
|
+
) -> float:
|
|
136
|
+
in_a = summary_chars // 4 + 150
|
|
137
|
+
a = BudgetGuard(1.0, pricing).cost(answer_model, in_a, max_tokens)
|
|
138
|
+
j = BudgetGuard(1.0, pricing).cost(judge_model, in_a // 2 + 300, max_tokens) * repeats
|
|
139
|
+
return n_probes * (a + j)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _answer(
|
|
143
|
+
guard: BudgetGuard, client: LLMClient, model: str, summary: str, question: str, cache: dict[str, str]
|
|
144
|
+
) -> str:
|
|
145
|
+
"""Probes that share a question share one answer call."""
|
|
146
|
+
if question not in cache:
|
|
147
|
+
cache[question] = guard.call(client, model, f"Context summary:\n{summary}\n\nQuestion: {question}", 200).text
|
|
148
|
+
return cache[question]
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _norm(x: str) -> str:
|
|
152
|
+
return re.sub(r"\s+", " ", x.strip().lower())
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def run_eval(
|
|
156
|
+
s: Session,
|
|
157
|
+
c: Compaction,
|
|
158
|
+
client: LLMClient,
|
|
159
|
+
*,
|
|
160
|
+
answer_model: str,
|
|
161
|
+
judge_model: str,
|
|
162
|
+
pricing: PricingTable,
|
|
163
|
+
budget_usd: float,
|
|
164
|
+
repeats: int = 3,
|
|
165
|
+
confirm: bool = False,
|
|
166
|
+
probes: list[Probe] | None = None,
|
|
167
|
+
) -> EvalReport:
|
|
168
|
+
if not confirm:
|
|
169
|
+
raise EvalError(f"AI evaluation calls an LLM and costs money; pass {CONFIRM_FLAG} to run it")
|
|
170
|
+
if answer_model == judge_model:
|
|
171
|
+
raise EvalError("judge model must differ from the answering model")
|
|
172
|
+
guard = BudgetGuard(budget_usd, pricing)
|
|
173
|
+
rep = EvalReport()
|
|
174
|
+
rep.flags = check_summary(s, c)
|
|
175
|
+
answers: dict[str, str] = {}
|
|
176
|
+
try:
|
|
177
|
+
for p in probes if probes is not None else make_probes(s, c):
|
|
178
|
+
ans = _answer(guard, client, answer_model, c.summary_text, p.question, answers)
|
|
179
|
+
exact = any(_norm(t) in _norm(ans) for t in p.truth)
|
|
180
|
+
votes = []
|
|
181
|
+
for _ in range(max(repeats, 1)):
|
|
182
|
+
jp = f'Ground truth: {p.truth}\nAnswer: {ans}\nReply with JSON {{"correct": true|false}} only.'
|
|
183
|
+
raw = guard.call(client, judge_model, jp, 50).text
|
|
184
|
+
try:
|
|
185
|
+
votes.append(bool(json.loads(raw).get("correct")))
|
|
186
|
+
except (ValueError, AttributeError):
|
|
187
|
+
votes.append(False)
|
|
188
|
+
rep.results.append(ProbeResult(p, ans, exact, votes, sum(votes) * 2 > len(votes)))
|
|
189
|
+
finally:
|
|
190
|
+
rep.spent_usd, rep.calls = guard.spent, guard.calls
|
|
191
|
+
return rep
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class MockClient:
|
|
195
|
+
"""Deterministic offline client for tests and dry demos."""
|
|
196
|
+
|
|
197
|
+
def __init__(self, known: set[str] | None = None):
|
|
198
|
+
self.known: set[str] = known or set()
|
|
199
|
+
self.log: Counter[str] = Counter()
|
|
200
|
+
|
|
201
|
+
def complete(self, model: str, prompt: str, max_tokens: int) -> Completion:
|
|
202
|
+
self.log[model] += 1
|
|
203
|
+
if prompt.startswith("Ground truth"):
|
|
204
|
+
truth, _, ans = prompt.partition("Answer:")
|
|
205
|
+
paths = re.findall(r"'(/[^']+)'", truth)
|
|
206
|
+
ok = any(p in ans for p in paths) if not self.known else any(k in ans for k in self.known)
|
|
207
|
+
text = json.dumps({"correct": ok})
|
|
208
|
+
else:
|
|
209
|
+
summary = prompt.partition("Question:")[0] # answer only from the summary, never from the question
|
|
210
|
+
paths = [p for p in re.findall(r"(?<![\w.])(/[\w./-]*\w)", summary) if not self.known or p in self.known]
|
|
211
|
+
text = "\n".join(dict.fromkeys(paths)) or "unknown"
|
|
212
|
+
return Completion(text, len(prompt) // 4 + 1, max(len(text) // 4, 1))
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def load_client(spec: str) -> LLMClient:
|
|
216
|
+
if spec == "mock":
|
|
217
|
+
return MockClient()
|
|
218
|
+
mod, _, cls = spec.partition(":")
|
|
219
|
+
if not cls:
|
|
220
|
+
raise EvalError("--client must be 'mock' or 'package.module:ClassName'")
|
|
221
|
+
return getattr(importlib.import_module(mod), cls)()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
# ---------------- deep_analyze: re-summarize at candidate thresholds ----------------
|
|
225
|
+
|
|
226
|
+
SUMMARY_PROMPT = (
|
|
227
|
+
"You are compacting an agent session. Write a faithful summary that preserves file paths, "
|
|
228
|
+
"decisions, open tasks, errors and test results. Do not claim anything not shown.\n\n"
|
|
229
|
+
)
|
|
230
|
+
MAX_TRANSCRIPT_CHARS = 60_000
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def transcript_text(s: Session, end: int, max_chars: int = MAX_TRANSCRIPT_CHARS) -> str:
|
|
234
|
+
"""Reconstruct what compactlab kept of turns [0, end): user text, tool calls, output snippets.
|
|
235
|
+
This is an excerpt, not the full transcript (compactlab never stores full tool outputs)."""
|
|
236
|
+
parts = []
|
|
237
|
+
for _i, t in enumerate(s.turns[:end]):
|
|
238
|
+
if t.user_text:
|
|
239
|
+
parts.append(f"[user] {t.user_text[:500]}")
|
|
240
|
+
for k in t.tool_keys:
|
|
241
|
+
parts.append(f"[tool] {k}")
|
|
242
|
+
for sn in t.snippets[:2]:
|
|
243
|
+
parts.append(f"[out] {sn[:300]}")
|
|
244
|
+
text = "\n".join(parts)
|
|
245
|
+
return text[-max_chars:]
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def cut_index(s: Session, threshold: int, base: int) -> int | None:
|
|
249
|
+
from ..sim.engine import make_trace
|
|
250
|
+
|
|
251
|
+
ctx = base
|
|
252
|
+
for i, g in enumerate(make_trace(s, base).g):
|
|
253
|
+
ctx += g
|
|
254
|
+
if ctx > threshold:
|
|
255
|
+
return i + 1
|
|
256
|
+
return None
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
@dataclass
|
|
260
|
+
class DeepPlan:
|
|
261
|
+
pairs: list[tuple[str, str, Session, int, int]] # (model, role, session, threshold, cut)
|
|
262
|
+
est_usd: float
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def plan_deep(
|
|
266
|
+
sessions: list[Session],
|
|
267
|
+
result: dict,
|
|
268
|
+
pricing: PricingTable,
|
|
269
|
+
model: str,
|
|
270
|
+
judge_model: str,
|
|
271
|
+
repeats: int = 3,
|
|
272
|
+
sessions_per_group: int = 3,
|
|
273
|
+
probes: int = 5,
|
|
274
|
+
) -> DeepPlan:
|
|
275
|
+
pairs = []
|
|
276
|
+
est = 0.0
|
|
277
|
+
g_by = {(g["harness"], g["model"], g["role"]): g for g in result["groups"]}
|
|
278
|
+
for (h, m, role), g in sorted(g_by.items()):
|
|
279
|
+
cands = sorted({p["threshold"] for p in g["profiles"].values()})
|
|
280
|
+
ss = sorted((s for s in sessions if (s.harness, s.model, s.role) == (h, m, role)), key=lambda s: -s.peak)
|
|
281
|
+
for s in ss[:sessions_per_group]:
|
|
282
|
+
for T in cands:
|
|
283
|
+
cut = cut_index(s, T, g["base_tokens"])
|
|
284
|
+
if cut is None or cut < 10:
|
|
285
|
+
continue
|
|
286
|
+
pairs.append((m, role, s, T, cut))
|
|
287
|
+
chars = len(transcript_text(s, cut))
|
|
288
|
+
guard = BudgetGuard(1.0, pricing)
|
|
289
|
+
est += guard.cost(model, chars // 4 + 100, 2000)
|
|
290
|
+
est += estimate_cost(probes, 8000, model, judge_model, repeats, pricing)
|
|
291
|
+
return DeepPlan(pairs, est)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def deep_analyze(
|
|
295
|
+
plan: DeepPlan,
|
|
296
|
+
result: dict,
|
|
297
|
+
client: LLMClient,
|
|
298
|
+
*,
|
|
299
|
+
model: str,
|
|
300
|
+
judge_model: str,
|
|
301
|
+
pricing: PricingTable,
|
|
302
|
+
budget_usd: float,
|
|
303
|
+
repeats: int = 3,
|
|
304
|
+
confirm: bool = False,
|
|
305
|
+
) -> dict:
|
|
306
|
+
if not confirm:
|
|
307
|
+
raise EvalError(f"deep mode calls an LLM and costs money; pass {CONFIRM_FLAG} after reviewing the estimate")
|
|
308
|
+
if model == judge_model:
|
|
309
|
+
raise EvalError("judge model must differ from the summarizing/answering model")
|
|
310
|
+
from ..sim.engine import apply_measured
|
|
311
|
+
|
|
312
|
+
guard = BudgetGuard(budget_usd, pricing)
|
|
313
|
+
measured: dict[tuple[str, str, str, int], list[float]] = {}
|
|
314
|
+
stopped = ""
|
|
315
|
+
try:
|
|
316
|
+
for m, role, s, T, cut in plan.pairs:
|
|
317
|
+
summ = guard.call(client, model, SUMMARY_PROMPT + transcript_text(s, cut), 2000).text
|
|
318
|
+
comp = Compaction(turn_index=cut, summary_text=summ)
|
|
319
|
+
ps = make_probes(s, comp)
|
|
320
|
+
if not ps:
|
|
321
|
+
continue
|
|
322
|
+
ok = 0
|
|
323
|
+
answers: dict[str, str] = {}
|
|
324
|
+
for p in ps:
|
|
325
|
+
ans = _answer(guard, client, model, summ, p.question, answers)
|
|
326
|
+
votes = []
|
|
327
|
+
for _ in range(max(repeats, 1)):
|
|
328
|
+
raw = guard.call(
|
|
329
|
+
client,
|
|
330
|
+
judge_model,
|
|
331
|
+
f'Ground truth: {p.truth}\nAnswer: {ans}\nReply with JSON {{"correct": true|false}} only.',
|
|
332
|
+
50,
|
|
333
|
+
).text
|
|
334
|
+
try:
|
|
335
|
+
votes.append(bool(json.loads(raw).get("correct")))
|
|
336
|
+
except (ValueError, AttributeError):
|
|
337
|
+
votes.append(False)
|
|
338
|
+
ok += sum(votes) * 2 > len(votes)
|
|
339
|
+
measured.setdefault((s.harness, m, role, T), []).append(ok / len(ps))
|
|
340
|
+
except BudgetExceeded as e:
|
|
341
|
+
stopped = str(e)
|
|
342
|
+
out_groups = []
|
|
343
|
+
for g in result["groups"]:
|
|
344
|
+
pts: list[dict[str, Any]] = []
|
|
345
|
+
for (h, m, role, T), vals in sorted(measured.items()):
|
|
346
|
+
if (h, m, role) != (g["harness"], g["model"], g["role"]):
|
|
347
|
+
continue
|
|
348
|
+
assumed = g["recall"][g["grid"].index(T)] if T in g["grid"] else None
|
|
349
|
+
pts.append(
|
|
350
|
+
{
|
|
351
|
+
"threshold": T,
|
|
352
|
+
"measured_recall": sum(vals) / len(vals),
|
|
353
|
+
"samples": len(vals),
|
|
354
|
+
"assumed_recall": assumed,
|
|
355
|
+
}
|
|
356
|
+
)
|
|
357
|
+
if not pts:
|
|
358
|
+
continue
|
|
359
|
+
dis = [
|
|
360
|
+
p for p in pts if p["assumed_recall"] is not None and abs(p["measured_recall"] - p["assumed_recall"]) > 0.1
|
|
361
|
+
]
|
|
362
|
+
g["measured"] = pts # kept on the group: a later reselect applies the same guardrail
|
|
363
|
+
adjusted = apply_measured(g)
|
|
364
|
+
out_groups.append(
|
|
365
|
+
{
|
|
366
|
+
"harness": g["harness"],
|
|
367
|
+
"model": g["model"],
|
|
368
|
+
"role": g["role"],
|
|
369
|
+
"points": pts,
|
|
370
|
+
"disagreements": dis,
|
|
371
|
+
"adjusted": adjusted,
|
|
372
|
+
}
|
|
373
|
+
)
|
|
374
|
+
# a harness with one setting for every model (Codex) decides it across its groups: redo that with the measured
|
|
375
|
+
# recall now on them, or it keeps the lite-mode value the measurement just ruled out
|
|
376
|
+
from ..sim.engine import global_keys
|
|
377
|
+
|
|
378
|
+
result["global_keys"] = global_keys(result["groups"], result.get("options") or {})
|
|
379
|
+
result["mode"] = "deep"
|
|
380
|
+
result["deep"] = {
|
|
381
|
+
"model": model,
|
|
382
|
+
"judge_model": judge_model,
|
|
383
|
+
"repeats": repeats,
|
|
384
|
+
"spent_usd": guard.spent,
|
|
385
|
+
"calls": guard.calls,
|
|
386
|
+
"budget_usd": budget_usd,
|
|
387
|
+
"stopped": stopped,
|
|
388
|
+
"groups": out_groups,
|
|
389
|
+
}
|
|
390
|
+
return result
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""LLM clients that run through a local agent harness (for deep mode).
|
|
2
|
+
|
|
3
|
+
They shell out to the harness CLI in an empty temporary directory, send the prompt on stdin, and parse
|
|
4
|
+
the reply. Flags are the documented non-interactive modes; check them against your installed version
|
|
5
|
+
(`claude --help`, `codex exec --help`). Token counts come from the CLI's JSON when present, else are
|
|
6
|
+
estimated from text length (marked `estimated`).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from .deep import Completion, EvalError
|
|
19
|
+
|
|
20
|
+
Runner = Callable[..., str] # (cmd, prompt, cwd) -> stdout; also takes env= when the executor sets one
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _run(cmd: Sequence[str], prompt: str, cwd: str, env: Mapping[str, str] | None = None) -> str:
|
|
24
|
+
try:
|
|
25
|
+
r = subprocess.run(
|
|
26
|
+
list(cmd),
|
|
27
|
+
input=prompt,
|
|
28
|
+
capture_output=True,
|
|
29
|
+
text=True,
|
|
30
|
+
cwd=cwd,
|
|
31
|
+
timeout=600,
|
|
32
|
+
env={**os.environ, **env} if env else None,
|
|
33
|
+
)
|
|
34
|
+
except FileNotFoundError as e:
|
|
35
|
+
raise EvalError(f"executor not found: {cmd[0]} (is it installed and on PATH?)") from e
|
|
36
|
+
except subprocess.TimeoutExpired as e:
|
|
37
|
+
raise EvalError(f"executor timed out: {cmd[0]}") from e
|
|
38
|
+
if r.returncode != 0:
|
|
39
|
+
raise EvalError(f"{cmd[0]} exited {r.returncode}: {r.stderr.strip()[:300]}")
|
|
40
|
+
return r.stdout
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ClaudeCodeExecutor:
|
|
44
|
+
"""`claude -p --model M --output-format json` (print mode, no interactive session)."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, runner: Runner = _run, binary: str = "claude"):
|
|
47
|
+
self.runner, self.binary = runner, binary
|
|
48
|
+
|
|
49
|
+
def complete(self, model: str, prompt: str, max_tokens: int) -> Completion:
|
|
50
|
+
with tempfile.TemporaryDirectory(prefix="compactlab-deep-") as d:
|
|
51
|
+
out = self.runner(
|
|
52
|
+
[self.binary, "-p", "--model", model, "--output-format", "json"],
|
|
53
|
+
prompt,
|
|
54
|
+
d,
|
|
55
|
+
env={"CLAUDE_CODE_MAX_OUTPUT_TOKENS": str(max(int(max_tokens), 1))},
|
|
56
|
+
)
|
|
57
|
+
try:
|
|
58
|
+
j: dict[str, Any] = json.loads(out)
|
|
59
|
+
except ValueError:
|
|
60
|
+
return Completion(out.strip(), len(prompt) // 4 + 1, len(out) // 4 + 1)
|
|
61
|
+
u = j.get("usage") or {}
|
|
62
|
+
inp = (
|
|
63
|
+
int(u.get("input_tokens") or 0)
|
|
64
|
+
+ int(u.get("cache_read_input_tokens") or 0)
|
|
65
|
+
+ int(u.get("cache_creation_input_tokens") or 0)
|
|
66
|
+
)
|
|
67
|
+
text = str(j.get("result", ""))
|
|
68
|
+
return Completion(text, inp or len(prompt) // 4 + 1, int(u.get("output_tokens") or len(text) // 4 + 1))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CodexExecutor:
|
|
72
|
+
"""`codex exec -m M -` (non-interactive; prompt on stdin). Token usage is estimated."""
|
|
73
|
+
|
|
74
|
+
def __init__(self, runner: Runner = _run, binary: str = "codex"):
|
|
75
|
+
self.runner, self.binary = runner, binary
|
|
76
|
+
|
|
77
|
+
def complete(self, model: str, prompt: str, max_tokens: int) -> Completion:
|
|
78
|
+
with tempfile.TemporaryDirectory(prefix="compactlab-deep-") as d:
|
|
79
|
+
out = self.runner([self.binary, "exec", "-m", model, "--skip-git-repo-check", "-"], prompt, d)
|
|
80
|
+
text = out.strip()
|
|
81
|
+
return Completion(text, len(prompt) // 4 + 1, len(text) // 4 + 1)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
EXECUTORS: dict[str, type] = {"claude-code": ClaudeCodeExecutor, "codex": CodexExecutor}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Heuristic fact-checks for compaction summaries (offline; no LLM)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from ..model import Compaction, Session
|
|
9
|
+
|
|
10
|
+
CLAIM_RE = re.compile(
|
|
11
|
+
r"(all )?(unit |integration )?tests? (now )?(pass|passed|passing|green)|"
|
|
12
|
+
r"build (succeed|succeeded|passes|passed|is green)|"
|
|
13
|
+
r"\b(verified|confirmed|validated)\b|\b(fixed|resolved)\b|lint(ing)? (clean|passes)",
|
|
14
|
+
re.I,
|
|
15
|
+
)
|
|
16
|
+
RUN_RE = re.compile(
|
|
17
|
+
r"(pytest|npm (run )?test|yarn test|cargo test|go test|make test|jest|vitest|xcodebuild|swift test|"
|
|
18
|
+
r"tsc\b|npm run build|cargo build|make\b|ruff|eslint)",
|
|
19
|
+
re.I,
|
|
20
|
+
)
|
|
21
|
+
FAIL_RE = re.compile(r"(FAILED|\bfailed\b|\berror\b|Traceback|AssertionError|\b[1-9]\d* failed)", re.I)
|
|
22
|
+
PATH_RE = re.compile(r"(?<![\w.])(/[\w.\-]+(?:/[\w.\-]+)+|[\w.\-]+(?:/[\w.\-]+)+\.\w{1,5})")
|
|
23
|
+
TICK_RE = re.compile(r"`([^`\n]{3,60})`")
|
|
24
|
+
LOOKBACK = 200
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Flag:
|
|
29
|
+
kind: str # unsupported_claim | contradicted_claim | unknown_path | unknown_identifier
|
|
30
|
+
text: str
|
|
31
|
+
detail: str = ""
|
|
32
|
+
|
|
33
|
+
def to_dict(self) -> dict:
|
|
34
|
+
return {"kind": self.kind, "text": self.text, "detail": self.detail}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _evidence(s: Session, c: Compaction) -> tuple[str, list[str]]:
|
|
38
|
+
turns = s.turns[max(0, c.turn_index - LOOKBACK) : c.turn_index]
|
|
39
|
+
blob = " ".join(" ".join(t.tool_keys) + " " + " ".join(t.snippets) + " " + t.user_text for t in turns)
|
|
40
|
+
cmds = [sn for t in turns for sn in t.snippets if sn.startswith("$ ")]
|
|
41
|
+
# include tool keys such as "Bash:pytest -q" or "shell:pytest" as commands
|
|
42
|
+
cmds += [k for t in turns for k in t.tool_keys if ":" in k and RUN_RE.search(k)]
|
|
43
|
+
return blob, cmds
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def check_summary(s: Session, c: Compaction) -> list[Flag]:
|
|
47
|
+
text = c.summary_text
|
|
48
|
+
if not text:
|
|
49
|
+
return []
|
|
50
|
+
blob, cmds = _evidence(s, c)
|
|
51
|
+
flags: list[Flag] = []
|
|
52
|
+
ran = [x for x in cmds if RUN_RE.search(x)]
|
|
53
|
+
last_failed = False
|
|
54
|
+
if ran:
|
|
55
|
+
# crude: look at result snippets after the last run command
|
|
56
|
+
tail = " ".join(sn for t in s.turns[max(0, c.turn_index - 15) : c.turn_index] for sn in t.snippets)
|
|
57
|
+
last_failed = bool(FAIL_RE.search(tail))
|
|
58
|
+
for sent in re.split(r"(?<=[.;\n])\s+", text):
|
|
59
|
+
if not CLAIM_RE.search(sent):
|
|
60
|
+
continue
|
|
61
|
+
if not ran:
|
|
62
|
+
flags.append(
|
|
63
|
+
Flag("unsupported_claim", sent.strip()[:160], "no test/build command found before the compaction")
|
|
64
|
+
)
|
|
65
|
+
elif last_failed:
|
|
66
|
+
flags.append(Flag("contradicted_claim", sent.strip()[:160], "failure markers in recent tool output"))
|
|
67
|
+
for m in sorted(set(PATH_RE.findall(text))):
|
|
68
|
+
if m not in blob and m.split("/")[-1] not in blob:
|
|
69
|
+
flags.append(Flag("unknown_path", m, "path never appears in pre-compaction tool calls or output"))
|
|
70
|
+
for m in sorted(set(TICK_RE.findall(text))):
|
|
71
|
+
if "/" in m or " " in m:
|
|
72
|
+
continue
|
|
73
|
+
if m not in blob:
|
|
74
|
+
flags.append(Flag("unknown_identifier", m, "identifier never appears before the compaction"))
|
|
75
|
+
return flags
|