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31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"""The VERA agent loop: bounded state instead of transcript replay.

The one structural difference from `bmb.agent`, and the reason this module exists: the
prompt is rebuilt each step from a **bounded rendering of the analysis graph** plus the
single most recent tool output, rather than from the whole transcript. Measured on
BioMysteryBench, transcript replay costs 9,267 tokens per step to deliver ~400 tokens of
new content; at a 4k state budget the same token spend buys roughly four times the steps.

Everything else is deliberately reused from the existing harness -- workspace staging,
`run_bash`, the `Attempt` record and its status taxonomy -- so a VERA row and a baseline
row differ in the loop and nothing else, and remain directly comparable.
"""

from __future__ import annotations

import json
import re
import time
import urllib.error
import urllib.request
from typing import Sequence
from pathlib import Path

from bmb.codex_backend import Attempt, emission_is_malformed, extract_answer, strip_reasoning
from bmb.problems import Problem, RULES
from bmb.sandbox import Workspace, run_bash
from vera.checks import rho
from vera.protocol import parse_emission, run_checks
from vera.state import AnalysisState, Node

PROTOCOL = """Work in your current directory. Each turn, emit exactly one block:

<command>SHELL COMMAND TO RUN</command>

When a command has established a finding, add a NODE line and its CHECK lines:

NODE kind=KIND summary="WHAT YOU ESTABLISHED" artifact=FILE parents=n1,n2
CHECK CHECKKIND "WHAT MUST BE TRUE" :: ONE-LINE COMMAND PRINTING True OR False

kind is one of: load, qc, transform, test, interpret, answer.
CHECKKIND is one of: conservation, range, invariance, type.

Everything after :: is your check command, taken verbatim to the end of the line, so
quotes, < and > inside it are safe. Each CHECK must be ONE line -- if you need a
multi-line script, write it to a file in <command> and have the CHECK run that file.

CHECKS ARE RUN BY THE HARNESS, NOT TAKEN ON YOUR WORD. A check must print exactly True
or False as its LAST line. Printing a number, a sequence or a path is malformed and will
be rejected -- write a comparison, not a measurement:

  WRONG   CHECK range "n reads" :: grep -c '^>' reads.fasta
  RIGHT   CHECK range "n reads" :: test $(grep -c '^>' reads.fasta) -eq 1042 && echo True || echo False

  WRONG   CHECK type "sequence" :: python3 -c "print(seq[:50])"
  RIGHT   CHECK type "starts with ATG" :: python3 -c "print(open('g.fa').readlines()[1].startswith('ATG'))"

Use REAL filenames from your working directory -- never the placeholder word "file".
A STRONG check states an invariant that would FAIL if your analysis were wrong: a total
preserved across a filter, an estimate stable across two subsamples, a value inside its
admissible range. A check that passes no matter what the data says (a file existing, a
tool being installed) is worth nothing and will be scored as worthless.

Your summary is the ONLY thing you will see about this step later -- state the finding
("14,203 of 34,460 cells pass QC"), not the activity ("ran QC"). Do not re-declare a
node you have already recorded.

When you are certain, end a turn with:
FINAL ANSWER: <answer>"""


_COMMANDISH = re.compile(
    r"^\s*(?:\$\s*)?(?:ls|cd|cat|head|tail|wc|awk|sed|grep|zcat|gzip|sort|uniq|cut|echo"
    r"|python3?|Rscript|conda|pip|samtools|bcftools|blastn|makeblastdb|find|for|while|if)\b"
    r"|[|>]\s*\S|&&|\$\(", re.I)


def looks_like_a_command(text: str) -> bool:
    """True if `text` is a shell command rather than an answer to the question.

    The forced-answer phase made this necessary. Asked to commit, the model sometimes
    replies with the next command it wanted to run, and a naive extractor files that as
    the final answer -- turning a run that would have been *excluded* into one that is
    *confidently wrong*, which is strictly worse. Observed verbatim:
    ``awk -F'\t' 'NR>1{print $2}' alcohol.txt | head -5``.
    """
    return bool(_COMMANDISH.search(text or ""))


# Fragments that are the scaffolding of an answer rather than an answer. Seen when a
# prefilled continuation comes back empty: the recorded answer was the literal string
# "FINAL ANSWER:", which passed a naive length check and would have been graded as a
# wrong answer instead of an honest exclusion.
_NON_ANSWERS = {"final answer", "final answer:", "answer", "answer:", "n/a", "na",
                "unknown", "none", "tbd", "...", "-"}


_TRAILING_MARKUP = re.compile(r"(?:</?(?:command|node|check|think|tool_call)\s*/?>|```+)\s*$",
                              re.I)


def strip_markup(text: str) -> str:
    """Remove protocol tags and fences the model leaves attached to an answer.

    Observed in a real run: the graded answer was ``'Norovirus GII</command>'``. That one
    happened to be judged correct, but only by luck -- an answer carrying a closing tag is
    a string the grader was never meant to see, and for an exact-match rubric it would
    fail. Applied repeatedly, since models stack them (``X</command>```).
    """
    out = (text or "").strip()
    for _ in range(4):
        new = _TRAILING_MARKUP.sub("", out).strip()
        if new == out:
            break
        out = new
    return out


def answer_is_usable(text: str) -> bool:
    """Whether an extracted answer may be recorded as the run's conclusion.

    Rejects three things, each observed in a real run: a shell command (the model replied
    with its next action), an empty or stub emission, and the answer *prefix* itself left
    over from a prefill whose continuation was empty.
    """
    text = strip_markup(text)
    if len(text) < 3 or emission_is_malformed(text):
        return False
    stripped = text.lower().strip().rstrip(":.").strip()
    if stripped in _NON_ANSWERS or not any(c.isalnum() for c in text):
        return False
    # A prefilled emission that only echoes the prefix carries no content.
    if stripped.startswith("final answer") and len(stripped) < len("final answer") + 3:
        return False
    return not looks_like_a_command(text)


ANSWER_PREFIX = "FINAL ANSWER:"


def _chat(base_url: str, model: str, prompt: str, *, timeout: int, max_tokens: int = 2048,
          prefill: str = "") -> str:
    """Call an OpenAI-compatible /chat/completions endpoint and return the message text.

    Args:
        base_url: Endpoint root, e.g. ``http://host:8404/v1``.
        model: Served model id.
        prompt: The user turn.
        timeout: Wall clock, seconds.
        max_tokens: Completion cap.
        prefill: If given, the assistant turn is *started* with this text and the model
            continues it. This is not a stylistic preference. Asked in plain language to
            reply with a single ``FINAL ANSWER:`` line, BigBang-v1 instead emitted
            ``I need to identify the bacterium ... <tool_call> </think>`` -- it kept
            trying to act, so nothing was extractable and the run was recorded as
            max_steps with no answer. Prefilling removes the need for compliance: the
            model has already "said" the prefix and can only continue it.

    Returns:
        The message text, with `prefill` prepended so callers see a complete emission.

    Raises:
        RuntimeError: On a transport error or a malformed response, so the caller can
            record a `provider` status rather than mistaking it for a bad answer.
    """
    messages = [{"role": "user", "content": prompt}]
    payload = {
        "model": model,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": 0.0,
    }
    if prefill:
        messages.append({"role": "assistant", "content": prefill})
        # vLLM extensions: continue the assistant turn rather than starting a new one.
        payload["continue_final_message"] = True
        payload["add_generation_prompt"] = False
    body = json.dumps(payload).encode()
    req = urllib.request.Request(
        base_url.rstrip("/") + "/chat/completions", data=body,
        headers={"Content-Type": "application/json", "Authorization": "Bearer local"},
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            payload_out = json.loads(resp.read().decode(errors="replace"))
    except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
        raise RuntimeError(f"chat call failed: {exc}") from exc
    try:
        text = payload_out["choices"][0]["message"]["content"] or ""
    except (KeyError, IndexError) as exc:
        raise RuntimeError(f"malformed chat response: {str(payload_out)[:200]}") from exc
    return (prefill + text) if prefill else text


FORCE_ANSWER_RESERVE = 3


def build_forced_prompt(problem: Problem, state: AnalysisState, *, state_budget: int,
                        reason: str) -> str:
    """Demand a final answer from the analysis so far, with no further commands.

    Exists because of the single largest measured loss: on the 73-problem baseline,
    **22 of 73 problems (30%) produced no usable answer at all** -- 12 excluded for
    exhausting the budget and 10 graded on an empty or stub emission. Those runs had done
    the analysis; they simply never committed to a conclusion. A budget that ends without
    asking for one converts work already done into a zero.
    """
    return "\n".join([
        problem.question, "",
        "=== YOUR ANALYSIS ===", state.render(state_budget), "",
        f"STOP INVESTIGATING. {reason}",
        "Give your single best answer from the analysis above, even if you are not "
        "certain -- an uncertain answer scores better than none, and no further commands "
        "will be run.",
        "",
        "Reply with exactly one line and nothing else:",
        "FINAL ANSWER: <answer>",
    ])


RECENT_WINDOW = 4
# Total characters the recent window may occupy. Without a cap the window carried four
# tool outputs at `sandbox.MAX_OUTPUT_CHARS` (20k) each, so a step prompt could reach
# ~324 KB -- large enough that the CLI shim returned HTTP 500 (the prompt is passed as a
# command-line argument) and 68 of 70 problems died as provider timeouts. A method whose
# claim is bounded context has no business sending unbounded prompts.
WINDOW_CHARS = 12_000


def _clip_middle(text: str, budget: int) -> str:
    """Trim to `budget` chars keeping both ends.

    The head carries what a command produced; the tail carries any traceback. Cutting
    either loses the reason the step happened.
    """
    text = text or ""
    if budget <= 0:
        return ""
    if len(text) <= budget:
        return text
    half = max(1, (budget - 40) // 2)
    return f"{text[:half]}\n...[{len(text) - 2 * half} chars elided]...\n{text[-half:]}"


def build_step_prompt(problem: Problem, workspace: Path, state: AnalysisState,
                      recent: Sequence[tuple[str, str]], *, state_budget: int,
                      nudge: str = "", window: int = RECENT_WINDOW) -> str:
    """Assemble one step's prompt: task, bounded state, and a window of recent history.

    Cost is still O(B + window) rather than O(T), so the quadratic blow-up is gone --
    but the window is not optional. A first version passed only the state graph plus the
    single latest tool output, and it scored 17.6% against the baseline's 37.7%: the
    model repeatedly answered "cannot determine from the provided analysis logs", because
    node summaries written by the model are lossy and drop the concrete handles
    (filenames, column labels, sample ids) the next step needs.

    The lesson is that summarisation is not free. Compressing *old* context is affordable;
    compressing recent context destroys the analysis.
    """
    listing = "\n".join(f"- {Path(n).name}" for n in problem.data_members)
    parts = [
        problem.question, "", RULES, "",
        f"Data files in {workspace}:\n{listing}", "",
        PROTOCOL, "",
        "=== ANALYSIS SO FAR ===", state.render(state_budget), "",
    ]
    tail = list(recent)[-window:]
    if tail:
        parts.append("=== YOUR LAST %d COMMANDS AND THEIR OUTPUT ===" % len(tail))
        # Spend the window budget newest-first: the latest output is what the next action
        # builds on, and older ones are already summarised in the analysis graph.
        rendered: list[str] = []
        left = WINDOW_CHARS
        for cmd, out in reversed(tail):
            share = max(600, left // 2) if len(rendered) < 2 * (len(tail) - 1) else left
            block = f"$ {cmd}\n{_clip_middle(out, min(share, left))}\n"
            if left <= 0:
                break
            rendered.append(block[:left])
            left -= len(block)
        parts += list(reversed(rendered))
    if nudge:
        parts += [f"NOTE: {nudge}", ""]
    parts.append("Emit your next block.")
    return "\n".join(parts)


def run_vera_attempt(
    problem: Problem,
    model: str,
    base_url: str,
    *,
    max_steps: int = 50,
    state_budget: int = 4000,
    step_timeout: int = 900,
    chat_timeout: int = 600,
    workspace_root: Path | None = None,
    transcript_dir: Path | None = None,
) -> Attempt:
    """Run one attempt under VERA and return it ungraded.

    Args:
        problem: The problem to pose.
        model: Model id served at `base_url`.
        base_url: OpenAI-compatible endpoint, e.g. ``http://host:8404/v1``.
        max_steps: Step ceiling. Defaults to 50 rather than 25 because the point of the
            bounded state is to make that affordable.
        state_budget: Tokens allowed for the rendered analysis graph.
        step_timeout: Per-shell-command wall clock, seconds.
        chat_timeout: Per-model-call wall clock, seconds.
        workspace_root: Parent for the scratch workspace.
        transcript_dir: Where to persist the run, including the final graph.

    Returns:
        An `Attempt` with the baseline status taxonomy, plus `extra` carrying the
        cumulative verification reward, the node count and the mean node rho.
    """
    started = time.time()
    att = Attempt(problem_id=problem.id, model=f"vera:{model}", status="ok",
                  human_solvable=problem.human_solvable)
    state = AnalysisState()
    total_reward = 0.0
    log: list[str] = []

    with Workspace(problem, root=workspace_root, keep=False) as ws:
        assert ws.path is not None
        out_dir = Path(transcript_dir).resolve() if transcript_dir else None
        if out_dir:
            out_dir.mkdir(parents=True, exist_ok=True)
            att.transcript_dir = str(out_dir)

        recent: list[tuple[str, str]] = []
        nudge, step = "", 0
        rejections: dict[str, int] = {}
        while step < max_steps:
            step += 1
            forcing = step > max_steps - FORCE_ANSWER_RESERVE
            if forcing:
                prompt = build_forced_prompt(
                    problem, state, state_budget=state_budget,
                    reason=f"You have used {step - 1} of {max_steps} steps.")
            else:
                prompt = build_step_prompt(problem, ws.path, state, recent,
                                           state_budget=state_budget, nudge=nudge)
            nudge = ""
            try:
                reply = _chat(base_url, model, prompt, timeout=chat_timeout,
                              prefill=ANSWER_PREFIX + " " if forcing else "")
            except RuntimeError as exc:
                att.status, att.error = "provider", str(exc)
                break
            log.append(f"--- step {step} ---\n{reply}\n")

            if forcing:
                # No commands, no nodes -- only a commitment. Reasoning is stripped first
                # because a model that writes "FINAL ANSWER:" inside a think block would
                # otherwise have its reasoning mined as the answer.
                candidate = extract_answer(strip_reasoning(reply))
                if answer_is_usable(candidate):
                    att.answer, att.status = strip_markup(candidate), "ok"
                    break
                nudge = ("your reply was not an answer. Do not emit a shell command. "
                         "Name the organism, gene, cell type or value the question asks for.")
                continue

            emission = parse_emission(reply)
            if emission.error:
                nudge = f"your last turn was rejected: {emission.error}"
                last_output = ""
                continue

            if emission.command:
                res = run_bash(ws.path, emission.command, timeout=step_timeout)
                out = res.as_tool_output()
                recent.append((emission.command, out))
                log.append(f"$ {emission.command}\n{out}\n")

            if emission.declares_node:
                results = run_checks(emission.checks, ws.path, run_bash)
                malformed = [r for r in results if "no boolean verdict" in r.detail]
                # A check that printed a measurement rather than a verdict is a protocol
                # error, not evidence about the analysis. Scoring it would make rho a
                # compliance metric. Ask once for a rewrite; if the model repeats itself,
                # accept the failure so a non-complying model cannot stall the run.
                if malformed and rejections.get(emission.summary, 0) < 1:
                    rejections[emission.summary] = rejections.get(emission.summary, 0) + 1
                    bad = malformed[0]
                    nudge = (f"check {bad.name!r} printed a measurement, not a verdict "
                             f"({bad.detail}). Rewrite it as a comparison ending in "
                             f"True or False, using real filenames, then re-declare the node.")
                    continue
                node = Node(
                    id=f"n{len(state) + 1}", kind=emission.kind,
                    summary=emission.summary or "(no summary given)",
                    artifact=emission.artifact,
                    parents=tuple(p for p in emission.parents if p in state),
                    command=emission.command, checks=results,
                )
                state.add(node)
                total_reward += state.reward([node])
                log.append(f"[node {node.id}] rho={node.rho:.2f} "
                           f"({sum(c.passed for c in results)}/{len(results)} checks)\n")

            if emission.answer:
                # Emission gate: 29% of baseline errors were emission failures, so an
                # answer is only released if the analysis behind it verified.
                leaves = state.leaves()
                gate = rho([c for n in leaves for c in n.checks]) if leaves else 0.0
                if gate == 0.0 and step <= max_steps - FORCE_ANSWER_RESERVE and state:
                    nudge = ("your answer was withheld: no leaf node has a passing check. "
                             "Add a check that verifies the result you are about to report.")
                    continue
                att.answer = strip_markup(emission.answer)
                att.status = "ok"
                break
        else:
            # The budget ran out without a commitment. Ask once more, outside the loop:
            # this is exactly the case that produced 12 of the 73 baseline exclusions.
            try:
                reply = _chat(base_url, model, build_forced_prompt(
                    problem, state, state_budget=state_budget,
                    reason="Your step budget is exhausted."), timeout=chat_timeout,
                    prefill=ANSWER_PREFIX + " ")
                candidate = extract_answer(strip_reasoning(reply))
            except RuntimeError:
                candidate = ""
            if answer_is_usable(candidate):
                att.answer, att.status = strip_markup(candidate), "ok"
                att.extra["answer_forced"] = True
            else:
                att.status = "max_steps"
                att.error = f"no answer within {max_steps} steps"

        att.n_steps = step
        nodes = state.nodes
        att.extra.update({
            "verification_reward": round(total_reward, 3),
            "n_nodes": len(nodes),
            "mean_rho": round(sum(n.rho for n in nodes) / len(nodes), 3) if nodes else 0.0,
            "n_checks": sum(len(n.checks) for n in nodes),
        })
        if out_dir:
            (out_dir / "transcript.txt").write_text("\n".join(log))
            (out_dir / "graph.txt").write_text(state.render(1_000_000))
            (out_dir / "final_answer.txt").write_text(att.answer or "")

    if att.status == "ok" and not att.answer:
        att.status, att.error = "format", "loop ended with no answer"
    att.wall_s = time.time() - started
    return att