Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(evals): add synthetic long-horizon coding environment

justrach07906442b3dc
diff --git a/docs/adr/0008-synthetic-evals-use-external-verifiers.md b/docs/adr/0008-synthetic-evals-use-external-verifiers.md
new file mode 100644
index 00000000..7684bd99
--- /dev/null
+++ b/docs/adr/0008-synthetic-evals-use-external-verifiers.md
@@ -0,0 +1,39 @@
+# 0008. Synthetic coding evals use external verifiers; model judges only tiebreak
+
+Status: accepted 2026-08-18
+
+## Context
+
+Long-horizon coding RL does not need a purchased repository: a seeded generator
+can create the codebase, task, and latent invariants. The dangerous shortcut is
+to let another model decide correctness. A judge model can be persuaded by the
+candidate's prose or code, drift between runs, and reward plausible-looking
+solutions that violate transactional or compatibility requirements.
+
+The DGM example already uses the safer ordering: held-out replay is the primary
+gradient and the LLM is demoted to a tiebreak. `evals/long_horizon/` needs the
+same rule before its reward is used for optimization.
+
+## Decision
+
+- A deterministic generator materializes each seeded workspace. The evaluator
+ and hidden checks stay outside that workspace and their revision/hash belongs
+ in the trajectory.
+- External executable checks decide correctness and fail closed. Fixture
+ tampering scores `0`; any failed check stays below `0.8`; only a complete pass
+ enters the promotable band at `0.9` or above.
+- Efficiency and an optional model assessment may rank complete passes. A model
+ judge sees a bounded diff and scores maintainability, clarity, and scope only;
+ it can never promote an incorrect rollout.
+- Training-scale or adversarial runs isolate the workspace in a container with
+ the evaluator mounted outside it. A small real-code holdout measures transfer,
+ not the primary training signal.
+
+## Consequences
+
+Synthetic environments can provide unlimited, exact, legally clean reward
+without pretending they reproduce the whole distribution of production code.
+Adding a generator family expands the curriculum; changing a verifier or score
+band is an evaluation-version change, not an invisible tweak. Model judging is
+still available for qualities executable tests cannot order, but correctness is
+reproducible and auditable without a provider call.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 943264bd..f6f1d6f2 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -18,6 +18,7 @@ record only when you need the evidence or the edge cases.
| [0005](0005-standing-goal-lives-in-the-prefix.md) | Standing goal is one prefix line; the user-message essay injects on change only, never every N turns. |
| [0006](0006-workspace-switch-is-a-tool.md) | Mid-session worktree switch is a real `workspace` tool; a skill cannot move file-tool cwd. |
| [0007](0007-plugins-are-read-in-place.md) | Cursor/Claude/Grok/Codex plugins and MCP are read in place; skills stay on-demand; MCP stays consent-gated. |
+| [0008](0008-synthetic-evals-use-external-verifiers.md) | Synthetic coding evals promote only external-verifier passes; model judges may tiebreak correctness, never decide it. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index aaac0afd..5879bd06 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -46,7 +46,7 @@
{"id": "peer-message-queued-for-live-peer", "why": "#469 phase 2: a session must be able to message a live co-resident peer (the channel half of the crosstalk fix). The regression is peer_message erroring while a peer is genuinely live, or claiming delivery it did not make.", "live_peer": true, "args": [], "prompt": "tell the other session to hold off gui/src until you land the move", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src until I land the move"}}, {"text": "told them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "posted to this folder's room"}}]}
{"id": "peer-message-without-peer-errors-clean", "why": "#469 phase 2: with no live peer, peer_message must come back as a clean error that says so - never a fake delivery, never a crash. The regression is a send reported into the void.", "args": [], "prompt": "tell the other session to hold off", "script": [{"tool": "peer_message", "arguments": {"text": "hold off gui/src"}}, {"text": "nobody to tell"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "[error] no live co-resident"}}]}
{"id": "peer-checkpoint-blocks-file-writes", "why": "#469: the once-per-peer checkpoint must guard the files themselves, not only git - the incident's other vector was one session moving/editing files the other had open. A live peer makes the first write_file come back un-executed, and the identical retry lands.", "live_peer": true, "args": [], "prompt": "create notes.txt with hello in it", "script": [{"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "notes.txt", "content": "hello"}}, {"text": "created, after the checkpoint told me about the peer"}], "assert": [{"event": {"type": "tool_call", "name": "write_file"}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint"}}, {"request_contains": {"index": 1, "text": "another graff session already owns this worktree"}}]}
-{"id": "peer-message-all-broadcasts-device-wide", "why": "#563: model \"all\" is retired — it flooded every folder. peer_message with session=all must error and tell the model to post bare or name one session. Device-wide broadcast stays the user's /tell all.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "\"all\" is retired"}}]}
+{"id": "peer-message-all-broadcasts-device-wide", "why": "#563: model \"all\" is retired — it flooded every folder. peer_message with session=all must error and tell the model to post bare or name one session. Device-wide broadcast stays the user's /tell all.", "live_peer": true, "args": [], "prompt": "tell everyone the freeze starts at five", "script": [{"tool": "peer_message", "arguments": {"session": "all", "text": "freeze starts at five"}}, {"text": "broadcast sent"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "is retired for sessions"}}]}
{"id": "peer-awareness-is-pull-not-push", "why": "#563: leadership is pull. A live peer must NOT dump a roster or inbound bodies into the first request — that was the token leak. Who is live is peer_message action=list; bodies wait behind a one-line wake only when something was parked.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_lacks": {"index": 0, "text": "other live graff session"}}, {"request_lacks": {"index": 0, "text": "[peer message"}}, {"request_lacks": {"index": 0, "text": "[presence]"}}]}
{"id": "peer-message-list-names-live-peer", "why": "#563: action=list is ListAgents. With a live peer the tool result must name that they are live, not error, and not require text.", "live_peer": true, "args": [], "prompt": "who else is here", "script": [{"tool": "peer_message", "arguments": {"action": "list"}}, {"text": "saw them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "live"}}]}
{"id": "peer-message-inbox-empty-when-quiet", "why": "#563: action=inbox is the mailbox. With nothing parked it must say so in the tool result — never invent a body, never require text.", "args": [], "prompt": "check the peer inbox", "script": [{"tool": "peer_message", "arguments": {"action": "inbox"}}, {"text": "nothing waiting"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "inbox empty"}}]}
diff --git a/evals/long_horizon/.gitignore b/evals/long_horizon/.gitignore
new file mode 100644
index 00000000..b9518f17
--- /dev/null
+++ b/evals/long_horizon/.gitignore
@@ -0,0 +1,3 @@
+__pycache__/
+.runs/
+results/
diff --git a/evals/long_horizon/README.md b/evals/long_horizon/README.md
new file mode 100644
index 00000000..3146e818
--- /dev/null
+++ b/evals/long_horizon/README.md
@@ -0,0 +1,105 @@
+# Synthetic long-horizon coding eval
+
+This is an internal, data-free coding environment: a deterministic generator
+builds a fresh multi-file repository from a seed, a harness works only inside
+that repository, and an external verifier grades the resulting tree. The first
+environment, `ledger-batch-v1`, asks an agent to implement atomic, idempotent
+batch transfers across models, service logic, storage, and a JSON boundary
+without regressing the existing API.
+
+It is intentionally harder than the small tasks in `graff-evals/`: the outcome
+requires coordinated edits, projected-state reasoning, rollback semantics,
+compatibility, tests, and verification. New environments should test a distinct
+systems behavior rather than merely making this fixture larger.
+
+## Run
+
+```sh
+# No provider calls: prove the unfinished fixture fails, the reference patch
+# passes, and editing protected fixtures forces reward 0.
+python3 evals/long_horizon/run.py --self-test
+
+# Build this checkout, then run one seeded rollout with Luna.
+zig build
+python3 evals/long_horizon/run.py \
+ --harness graff-dev --model gpt-5.6-luna --seed 469 --keep
+
+# Distribution rather than one memorized instance.
+python3 evals/long_horizon/run.py \
+ --harness graff-dev --model gpt-5.6-luna --seed 1000 --reps 5
+```
+
+Harness commands come from `graff-evals/harnesses.json`. Results are JSONL in
+`results/`; `--keep` preserves the final synthetic repository under `.runs/`
+for inspection.
+
+## Grading and reward
+
+Correctness is not an LLM opinion. `grader.py` runs outside the agent workspace
+and produces named evidence rows:
+
+- protected fixture hashes match a pristine regeneration;
+- the public regression suite passes;
+- the required data model and API exist;
+- success order and projected balances are correct;
+- replay is idempotent and changed payloads conflict;
+- dry runs do not consume state;
+- late validation failures are atomic;
+- invalid metadata and duplicate transfer ids fail;
+- stable JSON is emitted; and
+- the old single-transfer behavior still works.
+
+The reward bands make that ordering structural:
+
+| Outcome | Reward |
+|---|---:|
+| Protected fixture changed | `0.0` |
+| Any deterministic check fails | `0.8 × pass_fraction` (always `< 0.8`) |
+| Every deterministic check passes | starts at `0.9` |
+| Efficiency tiebreak | up to `+0.05` |
+| Optional model-quality tiebreak | up to `+0.05` |
+
+A model judge therefore cannot promote an incorrect rollout. When omitted, its
+component is neutral (`0.5`). To use one, pass a command that reads a JSON
+payload on stdin and writes exactly `{"score": 0..1, "reason": "..."}`:
+
+```sh
+python3 evals/long_horizon/run.py --judge-command './internal-judge'
+
+# Ready-made adapter: use Graff/Luna as that secondary judge.
+python3 evals/long_horizon/run.py --judge-command \
+ 'python3 evals/long_horizon/judge_graff.py --binary ./zig-out/bin/graff --model gpt-5.6-luna'
+```
+
+The payload contains the task, deterministic report, and bounded solution diff.
+The rubric is limited to maintainability, clarity, and scope discipline. Judge
+failure is fail-closed for that bonus. This is the same useful split as the DGM
+example: an external replay verifier is the primary gradient; a model may only
+reorder already-correct variants.
+
+## Why synthetic codebases are enough
+
+Long-horizon coding RL does not require purchased repositories. A generator can
+control the latent specification, create unlimited seeded variants, retain
+private invariants, and emit exact rewards. Purchased code mainly contributes
+real-world distribution and accidental complexity; it is useful for transfer
+validation, not a prerequisite for training signal.
+
+A useful internal curriculum is:
+
+1. **Generated kernels:** transactional state, parsers, schedulers, migrations,
+ concurrent queues, and protocol adapters with exact executable semantics.
+2. **Seeded variants:** renamed concepts, changed topology, distractor modules,
+ boundary values, and injected historical constraints.
+3. **Episodes:** investigation, implementation, test repair, and follow-up
+ requirements against the same persisted workspace.
+4. **Held-out generators:** score generalization on generator families and
+ seeds never exposed during optimization.
+5. **Real-code transfer set:** a small, legally clean suite used only to detect
+ synthetic overfitting.
+
+For adversarial or training-scale use, run the workspace in a container and
+mount the generator/grader outside it. The local runner relies on harness path
+confinement and is designed for evaluation convenience, not hostile-code
+isolation. Pin the generator and grader commit/hash in every trajectory so an
+optimizer cannot silently change its own reward function.
diff --git a/evals/long_horizon/__init__.py b/evals/long_horizon/__init__.py
new file mode 100644
index 00000000..ac02b83a
--- /dev/null
+++ b/evals/long_horizon/__init__.py
@@ -0,0 +1 @@
+"""Synthetic long-horizon coding evaluation environment."""
diff --git a/evals/long_horizon/environment.py b/evals/long_horizon/environment.py
new file mode 100755
index 00000000..ee523833
--- /dev/null
+++ b/evals/long_horizon/environment.py
@@ -0,0 +1,385 @@
+#!/usr/bin/env python3
+"""Seeded synthetic codebase generator for the long-horizon coding eval."""
+
+from __future__ import annotations
+
+import json
+import random
+from pathlib import Path
+from textwrap import dedent
+
+ENVIRONMENT_ID = "ledger-batch-v1"
+
+TASK_PROMPT = dedent(
+ """
+ Work in this repository and implement the feature described in TASK.md.
+ Preserve the existing single-transfer behavior, run the public tests, and
+ add focused tests for the new behavior. Do not edit TASK.md, pyproject.toml,
+ or existing files under tests/. Finish only after the test suite passes.
+ """
+).strip()
+
+
+def _seed_data(seed: int) -> dict[str, object]:
+ rng = random.Random(seed)
+ names = rng.sample(
+ ["amber", "birch", "cedar", "delta", "ember", "fjord", "grove", "harbor"],
+ 4,
+ )
+ balances = {name: rng.randrange(90, 260, 5) for name in names}
+ return {"seed": seed, "accounts": names, "balances": balances}
+
+
+def files_for(seed: int) -> dict[str, str]:
+ data = _seed_data(seed)
+ balances = json.dumps(data["balances"], sort_keys=True)
+ return {
+ "pyproject.toml": dedent(
+ """
+ [project]
+ name = "ledgercore"
+ version = "0.1.0"
+ requires-python = ">=3.10"
+
+ [tool.unittest]
+ start-directory = "tests"
+ """
+ ).lstrip(),
+ "README.md": dedent(
+ """
+ # LedgerCore
+
+ A small in-memory ledger used to exercise transactional service code.
+
+ Run the suite with:
+
+ ```sh
+ python3 -m unittest discover -s tests -v
+ ```
+ """
+ ).lstrip(),
+ "TASK.md": dedent(
+ """
+ # Atomic idempotent batch transfers
+
+ Add batch transfers without regressing `LedgerService.transfer`.
+
+ ## Public surface
+
+ - Add an immutable `BatchReceipt` model with `batch_id`, an ordered
+ collection of `TransferReceipt` values, and `committed`.
+ - Add `LedgerService.transfer_batch(transfers, batch_id, dry_run=False)`.
+ - Add `handle_batch(service, body_json)` beside `handle_transfer`; it
+ accepts JSON containing `batch_id`, optional `dry_run`, and a
+ `transfers` array, and returns stable JSON for the batch receipt.
+
+ ## Required behavior
+
+ 1. A batch id and at least one transfer are required. Every transfer
+ must obey the existing account, positive-amount, and no-self-transfer
+ rules. Transfer ids must be unique inside one batch.
+ 2. Validate the complete ordered batch against projected balances before
+ mutating anything. A late failure, including cumulative overdraft,
+ leaves balances, event history, and idempotency state unchanged.
+ 3. A successful non-dry run applies transfers in input order and returns
+ `committed=True`. Repeating the same batch id and identical payload
+ returns the original receipt without adding events or changing balances.
+ Reusing a batch id for a different payload raises `IdempotencyConflict`.
+ 4. A dry run returns the same projected per-transfer balances with
+ `committed=False`, but changes no repository or idempotency state.
+ A later real run with that batch id must still commit.
+ 5. Keep the implementation in the existing package, preserve the public
+ single-transfer API, and cover the new behavior with your own tests.
+ """
+ ).lstrip(),
+ ".eval-seed.json": json.dumps(data, indent=2, sort_keys=True) + "\n",
+ "ledgercore/__init__.py": dedent(
+ """
+ from .api import handle_transfer
+ from .errors import IdempotencyConflict, InvalidTransfer, UnknownAccount
+ from .idempotency import ReceiptStore
+ from .models import Transfer, TransferReceipt
+ from .repository import LedgerRepository
+ from .service import LedgerService
+
+ __all__ = [
+ "IdempotencyConflict", "InvalidTransfer", "LedgerRepository",
+ "LedgerService", "ReceiptStore", "Transfer", "TransferReceipt",
+ "UnknownAccount", "handle_transfer",
+ ]
+ """
+ ).lstrip(),
+ "ledgercore/errors.py": dedent(
+ """
+ class LedgerError(ValueError):
+ pass
+
+
+ class UnknownAccount(LedgerError):
+ pass
+
+
+ class InvalidTransfer(LedgerError):
+ pass
+
+
+ class IdempotencyConflict(LedgerError):
+ pass
+ """
+ ).lstrip(),
+ "ledgercore/models.py": dedent(
+ """
+ from dataclasses import dataclass
+
+
+ @dataclass(frozen=True)
+ class Transfer:
+ transfer_id: str
+ debit: str
+ credit: str
+ amount: int
+
+
+ @dataclass(frozen=True)
+ class TransferReceipt:
+ transfer_id: str
+ debit_balance: int
+ credit_balance: int
+ """
+ ).lstrip(),
+ "ledgercore/repository.py": dedent(
+ f"""
+ from __future__ import annotations
+
+ from .errors import UnknownAccount
+ from .models import Transfer
+
+
+ class LedgerRepository:
+ def __init__(self, balances=None):
+ self._balances = dict(balances or {balances})
+ self._events = []
+
+ def has_account(self, account):
+ return account in self._balances
+
+ def balance(self, account):
+ if not self.has_account(account):
+ raise UnknownAccount(account)
+ return self._balances[account]
+
+ def balances(self):
+ return dict(self._balances)
+
+ def events(self):
+ return tuple(self._events)
+
+ def apply(self, transfer: Transfer):
+ self._balances[transfer.debit] -= transfer.amount
+ self._balances[transfer.credit] += transfer.amount
+ self._events.append(transfer)
+
+ def snapshot(self):
+ return dict(self._balances), list(self._events)
+
+ def restore(self, snapshot):
+ balances, events = snapshot
+ self._balances = dict(balances)
+ self._events = list(events)
+ """
+ ).lstrip(),
+ "ledgercore/idempotency.py": dedent(
+ """
+ from .errors import IdempotencyConflict
+
+
+ class ReceiptStore:
+ def __init__(self):
+ self._records = {}
+
+ def lookup(self, key, fingerprint):
+ record = self._records.get(key)
+ if record is None:
+ return None
+ prior_fingerprint, receipt = record
+ if prior_fingerprint != fingerprint:
+ raise IdempotencyConflict(key)
+ return receipt
+
+ def put(self, key, fingerprint, receipt):
+ self._records[key] = (fingerprint, receipt)
+
+ def snapshot(self):
+ return dict(self._records)
+
+ def restore(self, snapshot):
+ self._records = dict(snapshot)
+ """
+ ).lstrip(),
+ "ledgercore/service.py": dedent(
+ """
+ import hashlib
+ import json
+
+ from .errors import InvalidTransfer, UnknownAccount
+ from .models import TransferReceipt
+
+
+ class LedgerService:
+ def __init__(self, repository, receipts):
+ self.repository = repository
+ self.receipts = receipts
+
+ @staticmethod
+ def _fingerprint(transfer):
+ payload = [transfer.transfer_id, transfer.debit,
+ transfer.credit, transfer.amount]
+ return hashlib.sha256(json.dumps(payload).encode()).hexdigest()
+
+ def _validate(self, transfer):
+ if not transfer.transfer_id or not isinstance(transfer.amount, int):
+ raise InvalidTransfer("id and integer amount required")
+ if transfer.amount <= 0 or transfer.debit == transfer.credit:
+ raise InvalidTransfer("amount must be positive; accounts must differ")
+ if not self.repository.has_account(transfer.debit):
+ raise UnknownAccount(transfer.debit)
+ if not self.repository.has_account(transfer.credit):
+ raise UnknownAccount(transfer.credit)
+ if self.repository.balance(transfer.debit) < transfer.amount:
+ raise InvalidTransfer("insufficient funds")
+
+ def transfer(self, transfer):
+ fingerprint = self._fingerprint(transfer)
+ prior = self.receipts.lookup(transfer.transfer_id, fingerprint)
+ if prior is not None:
+ return prior
+ self._validate(transfer)
+ self.repository.apply(transfer)
+ receipt = TransferReceipt(
+ transfer.transfer_id,
+ self.repository.balance(transfer.debit),
+ self.repository.balance(transfer.credit),
+ )
+ self.receipts.put(transfer.transfer_id, fingerprint, receipt)
+ return receipt
+ """
+ ).lstrip(),
+ "ledgercore/api.py": dedent(
+ """
+ import json
+
+ from .models import Transfer
+
+
+ def handle_transfer(service, body_json):
+ body = json.loads(body_json)
+ transfer = Transfer(
+ transfer_id=body["transfer_id"],
+ debit=body["debit"],
+ credit=body["credit"],
+ amount=body["amount"],
+ )
+ receipt = service.transfer(transfer)
+ return json.dumps({
+ "credit_balance": receipt.credit_balance,
+ "debit_balance": receipt.debit_balance,
+ "transfer_id": receipt.transfer_id,
+ }, sort_keys=True)
+ """
+ ).lstrip(),
+ "ledgercore/reports.py": dedent(
+ """
+ def trial_balance(repository):
+ balances = repository.balances()
+ return {"accounts": balances, "total": sum(balances.values())}
+
+
+ def event_ids(repository):
+ return [event.transfer_id for event in repository.events()]
+ """
+ ).lstrip(),
+ "tests/test_transfer.py": dedent(
+ """
+ import unittest
+
+ from ledgercore.errors import IdempotencyConflict, InvalidTransfer
+ from ledgercore.idempotency import ReceiptStore
+ from ledgercore.models import Transfer
+ from ledgercore.repository import LedgerRepository
+ from ledgercore.service import LedgerService
+
+
+ class TransferTests(unittest.TestCase):
+ def setUp(self):
+ self.repo = LedgerRepository({"a": 100, "b": 40})
+ self.service = LedgerService(self.repo, ReceiptStore())
+
+ def test_transfer_and_replay(self):
+ transfer = Transfer("one", "a", "b", 25)
+ first = self.service.transfer(transfer)
+ second = self.service.transfer(transfer)
+ self.assertEqual(first, second)
+ self.assertEqual({"a": 75, "b": 65}, self.repo.balances())
+ self.assertEqual(1, len(self.repo.events()))
+
+ def test_conflict_and_overdraft(self):
+ self.service.transfer(Transfer("same", "a", "b", 10))
+ with self.assertRaises(IdempotencyConflict):
+ self.service.transfer(Transfer("same", "a", "b", 11))
+ with self.assertRaises(InvalidTransfer):
+ self.service.transfer(Transfer("too-much", "a", "b", 1000))
+
+
+ if __name__ == "__main__":
+ unittest.main()
+ """
+ ).lstrip(),
+ "tests/test_api.py": dedent(
+ """
+ import json
+ import unittest
+
+ from ledgercore.api import handle_transfer
+ from ledgercore.idempotency import ReceiptStore
+ from ledgercore.repository import LedgerRepository
+ from ledgercore.service import LedgerService
+
+
+ class ApiTests(unittest.TestCase):
+ def test_single_transfer_json(self):
+ service = LedgerService(
+ LedgerRepository({"left": 80, "right": 20}), ReceiptStore())
+ result = json.loads(handle_transfer(service, json.dumps({
+ "transfer_id": "api-1", "debit": "left",
+ "credit": "right", "amount": 15,
+ })))
+ self.assertEqual({
+ "credit_balance": 35, "debit_balance": 65,
+ "transfer_id": "api-1",
+ }, result)
+
+
+ if __name__ == "__main__":
+ unittest.main()
+ """
+ ).lstrip(),
+ }
+
+
+def materialize(root: Path, seed: int) -> None:
+ root.mkdir(parents=True, exist_ok=True)
+ for relative, content in files_for(seed).items():
+ target = root / relative
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("output", type=Path)
+ parser.add_argument("--seed", type=int, default=469)
+ args = parser.parse_args()
+ materialize(args.output, args.seed)
+ print(args.output)
diff --git a/evals/long_horizon/grader.py b/evals/long_horizon/grader.py
new file mode 100755
index 00000000..9de4c4b2
--- /dev/null
+++ b/evals/long_horizon/grader.py
@@ -0,0 +1,291 @@
+#!/usr/bin/env python3
+"""External deterministic grader for the synthetic ledger environment."""
+
+from __future__ import annotations
+
+import argparse
+import difflib
+import importlib
+import json
+import subprocess
+import sys
+from pathlib import Path
+from typing import Callable
+
+from environment import files_for
+
+IMMUTABLE = ("TASK.md", "pyproject.toml", "tests/test_transfer.py", "tests/test_api.py")
+PACKAGE_PREFIX = "ledgercore"
+
+
+def _purge_modules() -> None:
+ for name in list(sys.modules):
+ if name == PACKAGE_PREFIX or name.startswith(PACKAGE_PREFIX + "."):
+ del sys.modules[name]
+ importlib.invalidate_caches()
+
+
+def _load(workspace: Path):
+ _purge_modules()
+ sys.path.insert(0, str(workspace))
+ try:
+ from ledgercore.api import handle_batch
+ from ledgercore.errors import IdempotencyConflict, InvalidTransfer
+ from ledgercore.idempotency import ReceiptStore
+ from ledgercore.models import BatchReceipt, Transfer
+ from ledgercore.repository import LedgerRepository
+ from ledgercore.service import LedgerService
+ return {
+ "handle_batch": handle_batch,
+ "IdempotencyConflict": IdempotencyConflict,
+ "InvalidTransfer": InvalidTransfer,
+ "ReceiptStore": ReceiptStore,
+ "BatchReceipt": BatchReceipt,
+ "Transfer": Transfer,
+ "LedgerRepository": LedgerRepository,
+ "LedgerService": LedgerService,
+ }
+ finally:
+ sys.path.pop(0)
+
+
+def _service(modules, balances=None):
+ repo = modules["LedgerRepository"](balances or {"a": 100, "b": 50, "c": 20})
+ receipts = modules["ReceiptStore"]()
+ return modules["LedgerService"](repo, receipts), repo, receipts
+
+
+def _transfers(modules):
+ transfer = modules["Transfer"]
+ return [transfer("t1", "a", "b", 30), transfer("t2", "b", "c", 60)]
+
+
+def check_immutable(workspace: Path, seed: int) -> None:
+ pristine = files_for(seed)
+ for relative in IMMUTABLE:
+ got = (workspace / relative).read_text(encoding="utf-8")
+ if got != pristine[relative]:
+ raise AssertionError(f"immutable fixture changed: {relative}")
+
+
+def check_public_tests(workspace: Path, _seed: int) -> None:
+ run = subprocess.run(
+ [sys.executable, "-m", "unittest", "discover", "-s", "tests", "-v"],
+ cwd=workspace,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ text=True,
+ timeout=30,
+ )
+ if run.returncode != 0:
+ raise AssertionError(run.stdout[-1200:])
+
+
+def check_model_surface(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ batch = modules["BatchReceipt"]
+ if not getattr(batch, "__dataclass_params__", None).frozen:
+ raise AssertionError("BatchReceipt must be frozen")
+ names = tuple(batch.__dataclass_fields__)
+ if len(names) != 3 or names[0] != "batch_id" or names[-1] != "committed":
+ raise AssertionError(f"unexpected BatchReceipt fields: {names}")
+
+
+def check_success_and_order(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, _ = _service(modules)
+ receipt = service.transfer_batch(_transfers(modules), "batch-ok")
+ if not receipt.committed or receipt.batch_id != "batch-ok":
+ raise AssertionError("successful receipt metadata is wrong")
+ if [item.transfer_id for item in receipt.transfers] != ["t1", "t2"]:
+ raise AssertionError("receipt order changed")
+ projected = [(70, 80), (20, 80)]
+ got = [(item.debit_balance, item.credit_balance) for item in receipt.transfers]
+ if got != projected:
+ raise AssertionError(f"wrong projected receipt balances: {got}")
+ if repo.balances() != {"a": 70, "b": 20, "c": 80}:
+ raise AssertionError(f"wrong committed balances: {repo.balances()}")
+ if [event.transfer_id for event in repo.events()] != ["t1", "t2"]:
+ raise AssertionError("events were not committed in input order")
+
+
+def check_replay_and_conflict(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, receipts = _service(modules)
+ transfers = _transfers(modules)
+ first = service.transfer_batch(transfers, "stable")
+ state = (repo.snapshot(), receipts.snapshot())
+ second = service.transfer_batch(transfers, "stable")
+ if second != first or (repo.snapshot(), receipts.snapshot()) != state:
+ raise AssertionError("identical replay changed state or receipt")
+ changed = [modules["Transfer"]("t1", "a", "b", 31), transfers[1]]
+ try:
+ service.transfer_batch(changed, "stable")
+ except modules["IdempotencyConflict"]:
+ pass
+ else:
+ raise AssertionError("changed payload reused an id without conflict")
+ if (repo.snapshot(), receipts.snapshot()) != state:
+ raise AssertionError("conflict changed state")
+
+
+def check_dry_run(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, receipts = _service(modules)
+ before = (repo.snapshot(), receipts.snapshot())
+ preview = service.transfer_batch(_transfers(modules), "preview", dry_run=True)
+ if preview.committed or (repo.snapshot(), receipts.snapshot()) != before:
+ raise AssertionError("dry run mutated state or reported committed")
+ committed = service.transfer_batch(_transfers(modules), "preview")
+ if not committed.committed or len(repo.events()) != 2:
+ raise AssertionError("dry run consumed the batch id")
+ if committed.transfers != preview.transfers:
+ raise AssertionError("preview and commit projections differ")
+
+
+def check_atomic_failures(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, receipts = _service(modules)
+ transfer = modules["Transfer"]
+ cases = [
+ [transfer("x1", "a", "b", 60), transfer("x2", "a", "c", 50)],
+ [transfer("dup", "a", "b", 10), transfer("dup", "b", "c", 10)],
+ [transfer("late-1", "a", "b", 10), transfer("late-2", "missing", "c", 5)],
+ ]
+ for index, batch in enumerate(cases):
+ before = (repo.snapshot(), receipts.snapshot())
+ try:
+ service.transfer_batch(batch, f"bad-{index}")
+ except (modules["InvalidTransfer"], ValueError):
+ pass
+ else:
+ raise AssertionError(f"invalid case {index} was accepted")
+ if (repo.snapshot(), receipts.snapshot()) != before:
+ raise AssertionError(f"invalid case {index} was not atomic")
+
+
+def check_empty_and_bad_ids(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, receipts = _service(modules)
+ for transfers, batch_id in (([], "empty"), (_transfers(modules), "")):
+ before = (repo.snapshot(), receipts.snapshot())
+ try:
+ service.transfer_batch(transfers, batch_id)
+ except (modules["InvalidTransfer"], ValueError):
+ pass
+ else:
+ raise AssertionError("empty batch or id was accepted")
+ if (repo.snapshot(), receipts.snapshot()) != before:
+ raise AssertionError("invalid metadata changed state")
+
+
+def check_api(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, _ = _service(modules)
+ body = json.dumps({
+ "batch_id": "api-batch",
+ "dry_run": False,
+ "transfers": [
+ {"transfer_id": "a1", "debit": "a", "credit": "b", "amount": 20},
+ {"transfer_id": "a2", "debit": "b", "credit": "c", "amount": 30},
+ ],
+ })
+ raw = modules["handle_batch"](service, body)
+ parsed = json.loads(raw)
+ expected = {
+ "batch_id": "api-batch",
+ "committed": True,
+ "transfers": [
+ {"transfer_id": "a1", "debit_balance": 80, "credit_balance": 70},
+ {"transfer_id": "a2", "debit_balance": 40, "credit_balance": 50},
+ ],
+ }
+ if parsed != expected or raw != json.dumps(expected, sort_keys=True):
+ raise AssertionError(f"unstable or incorrect batch JSON: {raw}")
+ if len(repo.events()) != 2:
+ raise AssertionError("API did not use the service transaction")
+
+
+def check_single_transfer_regression(workspace: Path, _seed: int) -> None:
+ modules = _load(workspace)
+ service, repo, _ = _service(modules)
+ transfer = modules["Transfer"]("single", "a", "b", 25)
+ first = service.transfer(transfer)
+ second = service.transfer(transfer)
+ if first != second or repo.balances() != {"a": 75, "b": 75, "c": 20}:
+ raise AssertionError("single-transfer behavior regressed")
+ if len(repo.events()) != 1:
+ raise AssertionError("single transfer replay added an event")
+
+
+CHECKS: tuple[tuple[str, Callable[[Path, int], None]], ...] = (
+ ("immutable-fixtures", check_immutable),
+ ("public-tests", check_public_tests),
+ ("model-surface", check_model_surface),
+ ("success-and-order", check_success_and_order),
+ ("replay-and-conflict", check_replay_and_conflict),
+ ("dry-run", check_dry_run),
+ ("atomic-failures", check_atomic_failures),
+ ("empty-and-bad-ids", check_empty_and_bad_ids),
+ ("batch-api", check_api),
+ ("single-transfer-regression", check_single_transfer_regression),
+)
+
+
+def grade(workspace: Path, seed: int) -> dict[str, object]:
+ results = []
+ for name, check in CHECKS:
+ try:
+ check(workspace, seed)
+ results.append({"name": name, "pass": True})
+ except Exception as exc: # Each check is an isolated evidence row.
+ results.append({"name": name, "pass": False, "detail": str(exc)[:800]})
+ passed = sum(result["pass"] for result in results)
+ immutable_ok = results[0]["pass"]
+ deterministic_pass = passed == len(results)
+ if not immutable_ok:
+ score = 0.0
+ elif deterministic_pass:
+ score = 0.9
+ else:
+ score = round(0.8 * passed / len(results), 6)
+ return {
+ "deterministic_pass": deterministic_pass,
+ "passed": passed,
+ "total": len(results),
+ "score": score,
+ "checks": results,
+ }
+
+
+def solution_diff(workspace: Path, seed: int, limit: int = 40000) -> str:
+ pristine = files_for(seed)
+ chunks = []
+ paths = set(pristine)
+ paths.update(
+ str(path.relative_to(workspace))
+ for path in workspace.rglob("*.py")
+ if "__pycache__" not in path.parts
+ )
+ for relative in sorted(paths):
+ if not (relative.startswith("ledgercore/") or relative.startswith("tests/")):
+ continue
+ before = pristine.get(relative, "").splitlines(keepends=True)
+ path = workspace / relative
+ after = path.read_text(encoding="utf-8").splitlines(keepends=True) if path.exists() else []
+ if before == after:
+ continue
+ chunks.extend(difflib.unified_diff(before, after, f"a/{relative}", f"b/{relative}"))
+ if sum(map(len, chunks)) >= limit:
+ break
+ return "".join(chunks)[:limit]
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("workspace", type=Path)
+ parser.add_argument("--seed", type=int, required=True)
+ args = parser.parse_args()
+ report = grade(args.workspace.resolve(), args.seed)
+ print(json.dumps(report, indent=2, sort_keys=True))
+ raise SystemExit(0 if report["deterministic_pass"] else 1)
diff --git a/evals/long_horizon/judge_graff.py b/evals/long_horizon/judge_graff.py
new file mode 100755
index 00000000..26e9897b
--- /dev/null
+++ b/evals/long_horizon/judge_graff.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python3
+"""Adapt Graff into the optional JSON-in/JSON-out quality judge interface."""
+
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+SCHEMA = {
+ "type": "object",
+ "properties": {
+ "score": {"type": "number", "minimum": 0, "maximum": 1},
+ "reason": {"type": "string"},
+ },
+ "required": ["score", "reason"],
+ "additionalProperties": False,
+}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--binary", type=Path, required=True)
+ parser.add_argument("--model", default="gpt-5.6-luna")
+ parser.add_argument("--timeout", type=int, default=180)
+ args = parser.parse_args()
+ try:
+ payload = json.load(sys.stdin)
+ except json.JSONDecodeError as exc:
+ raise SystemExit(f"invalid judge payload: {exc}")
+ prompt = (
+ "You are a secondary code-quality judge. The external verifier has already "
+ "established correctness. Assess only maintainability, clarity, and scope "
+ "discipline from the bounded diff. Do not reward extra features. Follow the "
+ "requested JSON schema.\n\n" + json.dumps(payload, sort_keys=True)
+ )
+ run = subprocess.run(
+ [
+ str(args.binary.resolve()),
+ "-p", prompt,
+ "--model", args.model,
+ "--output-schema", json.dumps(SCHEMA, separators=(",", ":")),
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=args.timeout,
+ )
+ if run.returncode != 0:
+ raise SystemExit(run.stderr[-1000:] or f"judge exited {run.returncode}")
+ try:
+ result = json.loads(run.stdout)
+ score = float(result["score"])
+ reason = str(result["reason"])
+ if not 0 <= score <= 1:
+ raise ValueError("score outside 0..1")
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
+ raise SystemExit(f"invalid model judge output: {exc}")
+ print(json.dumps({"score": score, "reason": reason}, separators=(",", ":")))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/evals/long_horizon/reference.py b/evals/long_horizon/reference.py
new file mode 100755
index 00000000..b1ea58a9
--- /dev/null
+++ b/evals/long_horizon/reference.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Reference patch used only to prove the external grader can accept a solution."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from textwrap import dedent
+
+REFERENCE_FILES = {
+ "ledgercore/models.py": dedent(
+ """
+ from dataclasses import dataclass
+
+
+ @dataclass(frozen=True)
+ class Transfer:
+ transfer_id: str
+ debit: str
+ credit: str
+ amount: int
+
+
+ @dataclass(frozen=True)
+ class TransferReceipt:
+ transfer_id: str
+ debit_balance: int
+ credit_balance: int
+
+
+ @dataclass(frozen=True)
+ class BatchReceipt:
+ batch_id: str
+ transfers: tuple[TransferReceipt, ...]
+ committed: bool
+ """
+ ).lstrip(),
+ "ledgercore/service.py": dedent(
+ """
+ import hashlib
+ import json
+
+ from .errors import InvalidTransfer, UnknownAccount
+ from .models import BatchReceipt, TransferReceipt
+
+
+ class LedgerService:
+ def __init__(self, repository, receipts):
+ self.repository = repository
+ self.receipts = receipts
+
+ @staticmethod
+ def _hash(payload):
+ encoded = json.dumps(payload, separators=(",", ":"), sort_keys=True)
+ return hashlib.sha256(encoded.encode()).hexdigest()
+
+ @classmethod
+ def _fingerprint(cls, transfer):
+ return cls._hash(["transfer", transfer.transfer_id, transfer.debit,
+ transfer.credit, transfer.amount])
+
+ @classmethod
+ def _batch_fingerprint(cls, transfers):
+ return cls._hash(["batch", [[item.transfer_id, item.debit,
+ item.credit, item.amount]
+ for item in transfers]])
+
+ def _validate(self, transfer):
+ if not transfer.transfer_id or not isinstance(transfer.amount, int):
+ raise InvalidTransfer("id and integer amount required")
+ if transfer.amount <= 0 or transfer.debit == transfer.credit:
+ raise InvalidTransfer("amount must be positive; accounts must differ")
+ if not self.repository.has_account(transfer.debit):
+ raise UnknownAccount(transfer.debit)
+ if not self.repository.has_account(transfer.credit):
+ raise UnknownAccount(transfer.credit)
+ if self.repository.balance(transfer.debit) < transfer.amount:
+ raise InvalidTransfer("insufficient funds")
+
+ def transfer(self, transfer):
+ fingerprint = self._fingerprint(transfer)
+ prior = self.receipts.lookup(transfer.transfer_id, fingerprint)
+ if prior is not None:
+ return prior
+ self._validate(transfer)
+ self.repository.apply(transfer)
+ receipt = TransferReceipt(
+ transfer.transfer_id,
+ self.repository.balance(transfer.debit),
+ self.repository.balance(transfer.credit),
+ )
+ self.receipts.put(transfer.transfer_id, fingerprint, receipt)
+ return receipt
+
+ def transfer_batch(self, transfers, batch_id, dry_run=False):
+ transfers = tuple(transfers)
+ if not batch_id or not transfers:
+ raise InvalidTransfer("batch id and transfers required")
+ fingerprint = self._batch_fingerprint(transfers)
+ prior = self.receipts.lookup(batch_id, fingerprint)
+ if prior is not None:
+ return prior
+
+ projected = self.repository.balances()
+ seen = set()
+ receipt_items = []
+ for transfer in transfers:
+ if not transfer.transfer_id or not isinstance(transfer.amount, int):
+ raise InvalidTransfer("id and integer amount required")
+ if transfer.transfer_id in seen:
+ raise InvalidTransfer("duplicate transfer id")
+ seen.add(transfer.transfer_id)
+ if transfer.amount <= 0 or transfer.debit == transfer.credit:
+ raise InvalidTransfer("invalid amount or accounts")
+ if transfer.debit not in projected:
+ raise UnknownAccount(transfer.debit)
+ if transfer.credit not in projected:
+ raise UnknownAccount(transfer.credit)
+ if projected[transfer.debit] < transfer.amount:
+ raise InvalidTransfer("insufficient projected funds")
+ projected[transfer.debit] -= transfer.amount
+ projected[transfer.credit] += transfer.amount
+ receipt_items.append(TransferReceipt(
+ transfer.transfer_id,
+ projected[transfer.debit],
+ projected[transfer.credit],
+ ))
+
+ preview = BatchReceipt(batch_id, tuple(receipt_items), False)
+ if dry_run:
+ return preview
+ repository_snapshot = self.repository.snapshot()
+ receipt_snapshot = self.receipts.snapshot()
+ try:
+ for transfer in transfers:
+ self.repository.apply(transfer)
+ committed = BatchReceipt(batch_id, tuple(receipt_items), True)
+ self.receipts.put(batch_id, fingerprint, committed)
+ return committed
+ except Exception:
+ self.repository.restore(repository_snapshot)
+ self.receipts.restore(receipt_snapshot)
+ raise
+ """
+ ).lstrip(),
+ "ledgercore/api.py": dedent(
+ """
+ import json
+
+ from .models import Transfer
+
+
+ def handle_transfer(service, body_json):
+ body = json.loads(body_json)
+ transfer = Transfer(
+ transfer_id=body["transfer_id"], debit=body["debit"],
+ credit=body["credit"], amount=body["amount"],
+ )
+ receipt = service.transfer(transfer)
+ return json.dumps({
+ "credit_balance": receipt.credit_balance,
+ "debit_balance": receipt.debit_balance,
+ "transfer_id": receipt.transfer_id,
+ }, sort_keys=True)
+
+
+ def handle_batch(service, body_json):
+ body = json.loads(body_json)
+ transfers = [Transfer(
+ transfer_id=item["transfer_id"], debit=item["debit"],
+ credit=item["credit"], amount=item["amount"],
+ ) for item in body["transfers"]]
+ receipt = service.transfer_batch(
+ transfers, body["batch_id"], dry_run=body.get("dry_run", False))
+ return json.dumps({
+ "batch_id": receipt.batch_id,
+ "committed": receipt.committed,
+ "transfers": [{
+ "credit_balance": item.credit_balance,
+ "debit_balance": item.debit_balance,
+ "transfer_id": item.transfer_id,
+ } for item in receipt.transfers],
+ }, sort_keys=True)
+ """
+ ).lstrip(),
+ "ledgercore/__init__.py": dedent(
+ """
+ from .api import handle_batch, handle_transfer
+ from .errors import IdempotencyConflict, InvalidTransfer, UnknownAccount
+ from .idempotency import ReceiptStore
+ from .models import BatchReceipt, Transfer, TransferReceipt
+ from .repository import LedgerRepository
+ from .service import LedgerService
+
+ __all__ = [
+ "BatchReceipt", "IdempotencyConflict", "InvalidTransfer",
+ "LedgerRepository", "LedgerService", "ReceiptStore", "Transfer",
+ "TransferReceipt", "UnknownAccount", "handle_batch", "handle_transfer",
+ ]
+ """
+ ).lstrip(),
+}
+
+
+def apply_reference(workspace: Path) -> None:
+ for relative, content in REFERENCE_FILES.items():
+ (workspace / relative).write_text(content, encoding="utf-8")
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument("workspace", type=Path)
+ args = parser.parse_args()
+ apply_reference(args.workspace)
diff --git a/evals/long_horizon/run.py b/evals/long_horizon/run.py
new file mode 100755
index 00000000..057575a8
--- /dev/null
+++ b/evals/long_horizon/run.py
@@ -0,0 +1,269 @@
+#!/usr/bin/env python3
+"""Run a harness in a generated long-horizon environment and grade it."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+import re
+import selectors
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+from environment import ENVIRONMENT_ID, TASK_PROMPT, materialize
+from grader import grade, solution_diff
+from reference import apply_reference
+
+ROOT = Path(__file__).resolve().parent
+REPO = ROOT.parents[1]
+HARNESS_CONFIG = REPO / "graff-evals" / "harnesses.json"
+RESULTS = ROOT / "results"
+USAGE_RE = re.compile(
+ r"\[usage\] (\d+) api call\(s\) · (\d+) in \((\d+) cached\) \+ (\d+) out tokens"
+)
+
+
+def load_harness(name: str) -> dict[str, object]:
+ harnesses = json.loads(HARNESS_CONFIG.read_text(encoding="utf-8"))
+ if name not in harnesses:
+ raise SystemExit(f"unknown harness {name!r}; choose from {', '.join(harnesses)}")
+ return harnesses[name]
+
+
+def initialize_workspace(workspace: Path, seed: int) -> None:
+ materialize(workspace, seed)
+ subprocess.run(["git", "init", "-q"], cwd=workspace, check=True)
+ subprocess.run(["git", "add", "-A"], cwd=workspace, check=True)
+ subprocess.run(
+ ["git", "-c", "user.name=Eval Fixture", "-c", "user.email=eval@invalid",
+ "commit", "-qm", "synthetic baseline"],
+ cwd=workspace,
+ check=True,
+ )
+
+
+def harness_command(harness: dict[str, object], model: str) -> list[str]:
+ values = {"prompt": TASK_PROMPT, "model": model, "repo": str(REPO)}
+ return [str(part).format(**values) for part in harness["cmd"]]
+
+
+def run_process(
+ command: list[str], workspace: Path, env: dict[str, str], timeout: int
+) -> dict[str, object]:
+ started = time.monotonic()
+ first_output = None
+ stdout_parts: list[str] = []
+ stderr_parts: list[str] = []
+ process = subprocess.Popen(
+ command,
+ cwd=workspace,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ bufsize=1,
+ )
+ assert process.stdout is not None and process.stderr is not None
+ selector = selectors.DefaultSelector()
+ selector.register(process.stdout, selectors.EVENT_READ, stdout_parts)
+ selector.register(process.stderr, selectors.EVENT_READ, stderr_parts)
+ streams = 2
+ while streams and time.monotonic() - started < timeout:
+ for key, _ in selector.select(timeout=0.5):
+ line = key.fileobj.readline()
+ if not line:
+ selector.unregister(key.fileobj)
+ streams -= 1
+ continue
+ if first_output is None:
+ first_output = time.monotonic() - started
+ key.data.append(line)
+ timed_out = process.poll() is None
+ if timed_out:
+ process.kill()
+ process.wait(timeout=10)
+ return {
+ "exit": process.returncode,
+ "timed_out": timed_out,
+ "wall_s": round(time.monotonic() - started, 3),
+ "first_output_s": round(first_output, 3) if first_output is not None else None,
+ "stdout": "".join(stdout_parts),
+ "stderr": "".join(stderr_parts),
+ }
+
+
+def usage_from(stderr: str) -> dict[str, int]:
+ match = USAGE_RE.search(stderr)
+ if not match:
+ return {}
+ calls, input_tokens, cached_tokens, output_tokens = map(int, match.groups())
+ return {
+ "model_calls": calls,
+ "input_tokens": input_tokens,
+ "cached_tokens": cached_tokens,
+ "output_tokens": output_tokens,
+ }
+
+
+def efficiency_score(wall_s: float, model_calls: int | None) -> float:
+ calls = 0.5 if model_calls is None else 1 / (1 + max(0, model_calls - 12) / 12)
+ latency = 1 / (1 + max(0.0, wall_s - 300) / 600)
+ return round((calls + latency) / 2, 6)
+
+
+def model_judge(
+ command: str | None,
+ workspace: Path,
+ seed: int,
+ deterministic_report: dict[str, object],
+) -> tuple[float, dict[str, object]]:
+ if not command:
+ return 0.5, {"used": False, "score": 0.5, "reason": "neutral default"}
+ payload = {
+ "rubric": (
+ "Judge only maintainability, clarity, and scope discipline. Correctness has "
+ "already been verified. Return JSON: {\"score\": 0..1, \"reason\": \"...\"}."
+ ),
+ "task": TASK_PROMPT,
+ "deterministic_report": deterministic_report,
+ "solution_diff": solution_diff(workspace, seed),
+ }
+ try:
+ run = subprocess.run(
+ shlex.split(command),
+ input=json.dumps(payload),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ timeout=180,
+ )
+ value = json.loads(run.stdout)
+ score = float(value["score"])
+ if run.returncode != 0 or not 0 <= score <= 1:
+ raise ValueError("invalid judge result")
+ return score, {"used": True, "score": score, "reason": str(value.get("reason", ""))[:500]}
+ except (OSError, subprocess.TimeoutExpired, ValueError, KeyError, json.JSONDecodeError) as exc:
+ return 0.0, {"used": True, "score": 0.0, "error": str(exc), "fail_closed": True}
+
+
+def final_reward(
+ deterministic: dict[str, object],
+ wall_s: float,
+ model_calls: int | None,
+ judge_score: float,
+) -> tuple[float, float]:
+ if not deterministic["deterministic_pass"]:
+ return float(deterministic["score"]), 0.0
+ efficiency = efficiency_score(wall_s, model_calls)
+ return round(0.9 + 0.05 * efficiency + 0.05 * judge_score, 6), efficiency
+
+
+def one_run(args: argparse.Namespace, rep: int) -> dict[str, object]:
+ base = Path(tempfile.mkdtemp(prefix=f"graff-{ENVIRONMENT_ID}-"))
+ workspace = base / "workspace"
+ initialize_workspace(workspace, args.seed + rep - 1)
+ harness = load_harness(args.harness)
+ command = harness_command(harness, args.model)
+ env = dict(os.environ, **{str(k): str(v) for k, v in harness.get("env", {}).items()})
+ process = run_process(command, workspace, env, args.timeout)
+ deterministic = grade(workspace, args.seed + rep - 1)
+ usage = usage_from(str(process["stderr"]))
+ judge_score, judge = model_judge(
+ args.judge_command if deterministic["deterministic_pass"] else None,
+ workspace,
+ args.seed + rep - 1,
+ deterministic,
+ )
+ reward, efficiency = final_reward(
+ deterministic,
+ float(process["wall_s"]),
+ usage.get("model_calls"),
+ judge_score,
+ )
+ record = {
+ "environment": ENVIRONMENT_ID,
+ "seed": args.seed + rep - 1,
+ "rep": rep,
+ "harness": args.harness,
+ "model": args.model,
+ "reward": reward,
+ "efficiency": efficiency,
+ "grader": deterministic,
+ "judge": judge,
+ "process": {key: value for key, value in process.items() if key not in {"stdout", "stderr"}},
+ "usage": usage,
+ "answer_head": str(process["stdout"])[:300],
+ }
+ if args.keep:
+ kept = ROOT / ".runs" / f"{int(time.time())}-{rep}"
+ kept.parent.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(workspace), kept)
+ record["workspace"] = str(kept)
+ shutil.rmtree(base, ignore_errors=True)
+ else:
+ shutil.rmtree(base, ignore_errors=True)
+ return record
+
+
+def self_test(seed: int) -> None:
+ with tempfile.TemporaryDirectory(prefix="graff-long-horizon-selftest-") as raw:
+ workspace = Path(raw)
+ materialize(workspace, seed)
+ baseline = grade(workspace, seed)
+ if baseline["deterministic_pass"]:
+ raise SystemExit("self-test failed: unfinished baseline passed")
+ apply_reference(workspace)
+ solved = grade(workspace, seed)
+ if not solved["deterministic_pass"]:
+ print(json.dumps(solved, indent=2))
+ raise SystemExit("self-test failed: reference solution did not pass")
+ (workspace / "TASK.md").write_text("tampered\n", encoding="utf-8")
+ tampered = grade(workspace, seed)
+ if tampered["score"] != 0.0:
+ raise SystemExit("self-test failed: fixture tampering was not fatal")
+ print(f"self-test ok: baseline rejected, reference accepted, tampering rejected (seed {seed})")
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--harness", default="graff-dev")
+ parser.add_argument("--model", default="gpt-5.6-luna")
+ parser.add_argument("--seed", type=int, default=469)
+ parser.add_argument("--reps", type=int, default=1)
+ parser.add_argument("--timeout", type=int, default=1800)
+ parser.add_argument("--judge-command", help="external JSON-in/JSON-out maintainability judge")
+ parser.add_argument("--keep", action="store_true")
+ parser.add_argument("--self-test", action="store_true")
+ args = parser.parse_args()
+ if args.self_test:
+ self_test(args.seed)
+ return
+
+ RESULTS.mkdir(parents=True, exist_ok=True)
+ output = RESULTS / f"run-{time.strftime('%Y%m%d-%H%M%S')}.jsonl"
+ records = []
+ with output.open("w", encoding="utf-8") as stream:
+ for rep in range(1, args.reps + 1):
+ record = one_run(args, rep)
+ records.append(record)
+ stream.write(json.dumps(record, sort_keys=True) + "\n")
+ stream.flush()
+ print(
+ f"rep {rep}: reward={record['reward']:.3f} "
+ f"checks={record['grader']['passed']}/{record['grader']['total']} "
+ f"wall={record['process']['wall_s']}s"
+ )
+ passed = sum(record["grader"]["deterministic_pass"] for record in records)
+ mean = sum(record["reward"] for record in records) / len(records)
+ print(f"summary: {passed}/{len(records)} deterministic pass; mean reward={mean:.3f}")
+ print(f"results: {output}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/evals/long_horizon/test_eval.py b/evals/long_horizon/test_eval.py
new file mode 100644
index 00000000..87dbef6b
--- /dev/null
+++ b/evals/long_horizon/test_eval.py
@@ -0,0 +1,42 @@
+import tempfile
+import unittest
+from pathlib import Path
+
+from environment import materialize
+from grader import grade
+from reference import apply_reference
+from run import final_reward
+
+
+class EnvironmentTests(unittest.TestCase):
+ def test_baseline_fails_and_reference_passes_across_seeds(self):
+ for seed in (1, 469, 9001):
+ with self.subTest(seed=seed), tempfile.TemporaryDirectory() as raw:
+ workspace = Path(raw)
+ materialize(workspace, seed)
+ self.assertFalse(grade(workspace, seed)["deterministic_pass"])
+ apply_reference(workspace)
+ report = grade(workspace, seed)
+ self.assertTrue(report["deterministic_pass"], report)
+
+ def test_protected_fixture_tampering_forces_zero(self):
+ with tempfile.TemporaryDirectory() as raw:
+ workspace = Path(raw)
+ materialize(workspace, 469)
+ apply_reference(workspace)
+ (workspace / "tests/test_api.py").write_text("# easier\n", encoding="utf-8")
+ report = grade(workspace, 469)
+ self.assertFalse(report["deterministic_pass"])
+ self.assertEqual(0.0, report["score"])
+
+ def test_incorrect_solution_cannot_enter_passing_reward_band(self):
+ failing = {"deterministic_pass": False, "score": 0.8}
+ passing = {"deterministic_pass": True, "score": 0.9}
+ fail_reward, _ = final_reward(failing, 1, 1, 1.0)
+ pass_reward, _ = final_reward(passing, 1, 1, 0.0)
+ self.assertLessEqual(fail_reward, 0.8)
+ self.assertGreaterEqual(pass_reward, 0.9)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/src/prompt_goal_tests.zig b/src/prompt_goal_tests.zig
new file mode 100644
index 00000000..0ab2f326
--- /dev/null
+++ b/src/prompt_goal_tests.zig
@@ -0,0 +1,30 @@
+const std = @import("std");
+const prompts = @import("prompts.zig");
+const agent_mod = @import("agent.zig");
+const playbook = @import("playbook.zig");
+
+test "pinStandingGoal: active objective rides the prefix; paused and cleared disarm" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const saved = playbook.g_root_inject;
+ playbook.g_root_inject = false; // composeRoot would need a live io
+ defer playbook.g_root_inject = saved;
+ var agent: agent_mod.Agent = undefined;
+ agent.goal = null;
+ defer {
+ agent.goal = null;
+ prompts.pinStandingGoal(&agent, a);
+ }
+ try prompts.setSystemPrompts(&agent, "BASE", a);
+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal:") == null);
+ agent.goal = .{ .objective = "keep the build green", .status = .active };
+ prompts.pinStandingGoal(&agent, a);
+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal: keep the build green]") != null);
+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "BASE") != null);
+ agent.goal = .{ .objective = "keep the build green", .status = .paused };
+ prompts.pinStandingGoal(&agent, a);
+ try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal:") == null);
+ agent.goal = null;
+ prompts.pinStandingGoal(&agent, a);
+}
diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zig
index a0814d06..6faa242d 100644
--- a/src/prompt_snapshot_tests.zig
+++ b/src/prompt_snapshot_tests.zig
@@ -588,30 +588,3 @@ test "unattended one-shots are told the REAL approval map up front; attended ses
try std.testing.expect(std.mem.indexOf(u8, unattended, "--yolo") != null);
try std.testing.expect(std.mem.indexOf(u8, unattended, ".harness/settings.json") != null);
}
-
-test "pinStandingGoal: active objective rides the prefix; paused and cleared disarm" {
- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena_state.deinit();
- const a = arena_state.allocator();
- const playbook = @import("playbook.zig");
- const saved = playbook.g_root_inject;
- playbook.g_root_inject = false; // composeRoot would need a live io
- defer playbook.g_root_inject = saved;
- var agent: agent_mod.Agent = undefined;
- agent.goal = null;
- defer {
- agent.goal = null;
- prompts.pinStandingGoal(&agent, a);
- }
- try prompts.setSystemPrompts(&agent, "BASE", a);
- try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal:") == null);
- agent.goal = .{ .objective = "keep the build green", .status = .active };
- prompts.pinStandingGoal(&agent, a);
- try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal: keep the build green]") != null);
- try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "BASE") != null);
- agent.goal = .{ .objective = "keep the build green", .status = .paused };
- prompts.pinStandingGoal(&agent, a);
- try std.testing.expect(std.mem.indexOf(u8, agent.sys_normal, "[standing goal:") == null);
- agent.goal = null;
- prompts.pinStandingGoal(&agent, a);
-}
diff --git a/src/prompts.zig b/src/prompts.zig
index b934571a..9680dc2c 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -471,8 +471,9 @@ pub const compact_instruction =
\\work. Be thorough but compact. Reply with only the summary.
;
-test { // #421/#410: the capability matrix + the full-capability golden. An unreferenced module's tests never run.
+test { // #421/#410: prompt snapshots and goal-prefix behavior must stay reachable.
_ = @import("prompt_snapshot_tests.zig");
+ _ = @import("prompt_goal_tests.zig");
}
// The harness has always run a returned tool batch concurrently, for subagents