Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/patches/181f2e44fb823cb7 # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/interplane-mv#21 (code only) closed derived `181f2e44fb823cb7` #21 Imported from GitHub aien-dev/interplane-mv#21 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `b06ef24d15572d0543bcdc535cf2dbb6d11fed6c` · Head `b9a0931a5e1520c442c19aa9b35fcc61887d8535` greptile-apps[bot] reviewed (COMMENTED) on 2026-10-04 23:54 UTC `aien-dev` has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan . ### Fetch it A git bundle of the pull request's head, 19597 bytes. ``` curl -fsSL https://interplane.io/drakestapleton/interplane-mv/patches/181f2e44fb823cb7.bundle -o 181f2e44fb823cb7.bundle git fetch 181f2e44fb823cb7.bundle refs/pull/21/head ``` Raw bundle · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/interplane-mv 21 b9a0931a5e1520c442c19aa9b35fcc61887d8535 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"interplane-mv","number":21,"url":"https://github.com/aien-dev/interplane-mv/pull/21","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:00Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/CHANGELOG.md b/CHANGELOG.md index 472ec82..ed6ed8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - 0.2 report: `docs/REPORT-0.2.md`. Pre-registered gate verdict FAIL (O1 0.865, O2 0/5; T 0.877 and S pass). - Qwen3.5-9B qualified on llama.cpp b11398 and SGLang 0.5.20 (both probes 14/14); Rust probe aligned with the Python probe. - Benchmark corpus (44 tasks), protocol, paired runner and analyzer; run `qual-20261004T2207Z`. +- Bench simulated backends `sim-1` (`bench/stubs/backends.json`, `run_bench.py --backends sim-1`): every tool a task lists executes deterministically after Odysseus authorizes it; `validate.py` checks coverage, determinism and that stores do not leak expansion answers. Default stays the 0.2 reference behaviour; `inputs_digest` updated. - AIEN adapter on the real `EffectAuthority` path (sovereign-core #203, #204, pinned 6554aac), single-use approval tests. - `selection.measure`: `rendered_bytes` and an optional unit-disciplined `tokens` block (`bytes`, `tokens_model_reported`, `tokens_endpoint_tokenizer`, `tokens_estimated`); `TokenCounter` with `BytesOnly` and `EstimatedTokens` (estimator v1) in both languages. diff --git a/bench/CORPUS-DIGEST.txt b/bench/CORPUS-DIGEST.txt index 83aaf32..7f553ef 100644 --- a/bench/CORPUS-DIGEST.txt +++ b/bench/CORPUS-DIGEST.txt @@ -2,6 +2,6 @@ # tasks_digest: tasks/*.json; inputs_digest: domains.json, prompts/, schema/, fixtures/, stubs/, tasks/; # each = sha256 over `sha256sum` lines in LC_ALL=C path order, paths relative to bench/. tasks_digest sha256:818ad12d42ba24c0e505f61e400ac9684dbfba68e56ee5c7e2ca5b7fb3e59e34 -inputs_digest sha256:50cc0670e828da2aca1f39e7c84f1e9511eae251f42137c3b5795377a4b3482d +inputs_digest sha256:b4906b94362ee05f8ed7c5c7a2f15b3b6f0ae628d3f1a7d03659f350e80983dd protocol_sha256 sha256:7f9888cef23895177d2d3905b612693b023c5ae53fcafb004f9413ec0c1ec81e tasks 44 dev 7 qual 37 diff --git a/bench/README.md b/bench/README.md index fb394dd..fb541bc 100644 --- a/bench/README.md +++ b/bench/README.md @@ -17,6 +17,9 @@ runner is a separate lane; this directory is everything it needs. The protocol i | `prompts/system.md` | The one system prompt for every task and both conditions (digest pinned in each task). | | `fixtures//` | Small workspaces, copied byte-for-byte into a fresh temp dir per run. | | `stubs/.json` | Fixed results for read-only Odysseus tools the reference adapter does not execute. | +| `stubs/backends.json` | Simulated backends `sim-1`: for every tool a task lists, which backend answers it after Odysseus authorizes the call, and its documented semantics. | +| `stubs/stores/.json` | Private-data stores (notes, memory, calendar, contacts, editor documents, models, tokens) read by the `sim-1` backends. A fixture without a file has empty stores. | +| `tools/sim_backends.py` | The `sim-1` simulators (stdlib only), shared by the runner and the validator. | | `tools/validate.py` | Structural validator (stdlib only). CI job `bench-structural` runs it. | | `tools/stats.py` | The pre-registered paired statistics (Newcombe 1998 method 10, exact McNemar), with a self-test against the paper's table. | | `CORPUS-DIGEST.txt` | Frozen digests of the corpus; CI recomputes and compares. | @@ -80,7 +83,25 @@ reference and is never used for judging. - **Only `read_file`, `ls`, `glob` and `grep` execute.** The reference adapter executes only these four. Every other authorized tool returns `execution_error` "not executed by the reference adapter". Rare and multidomain tasks therefore use `stub_results` for the read-only private - tools they need. The catalog has no stat, hash, count or git tool, so none is used. + tools they need. The catalog has no stat, hash, count or git tool, so none is used. This is + the 0.2 behaviour (`run_bench.py --backends reference`, the default). The 0.2 run analysis + (`runs/qual-20261004T2207Z-analysis/error-classification.md`) found 80 of 87 execution errors + came from this gap. +- **Simulated backends `sim-1` (`--backends sim-1`, added after the 0.2 run).** Every tool any task + lists now has a backend in `stubs/backends.json`. Per authorized call the order is: the task's + `fault_injection`, the task's `stub_results`, the registry, the reference adapter. Kinds: + `executable` (the four above), `odysseus_handler` (`get_workspace`: Odysseus's own handler; the + workspace sits at a fixed temp path so its text is stable), `computed` (deterministic + simulators over the fixture's store or the run's workspace copy; writes stay in the run), and + `declared_failure` (`bash`, `python`: always the same documented error, because shell output + cannot be simulated deterministically). `validate.py` fails when a task lists a tool with no + backend, when an answer or recovery task lists a `declared_failure` tool, when a simulator is + not deterministic on some fixture, or when a store holds the answer of an expansion task on its + fixture (that would make expansion unnecessary). Tools no task lists keep the reference + behaviour. Intended failures (`fault_injection`, the missing path in `exec_failure-003`) are + unchanged. Before `sim-1`, 39 of 44 tasks (33 of 37 qual) listed a tool without a working + backend; with it, 1 (`approval-003`, whose `bash`/`python` alternatives are meant to stop at + approval). - **Denials come from Odysseus's own gates:** - The caller must be an admin to read files at all. `NON_ADMIN_BLOCKED_TOOLS` includes `read_file`, `ls`, `grep` and `glob`, so a non-admin cannot read the workspace and then be @@ -135,4 +156,8 @@ exist. and the analyzer. `tools/analyze.py ` (stdlib only, no inference) writes `summary.json`, `summary.md` and `tasks.csv`, byte-identically for the same input. - Offline tests: `tools/test_analyze.py` (stdlib, runs in CI against a checked-in synthetic run) - and `tools/test_runner_offline.py` (a scripted fake endpoint; needs the Odysseus venv). + and `tools/test_runner_offline.py` (a scripted fake endpoint; needs the Odysseus venv; also runs + every `sim-1` backend kind twice and checks the results are identical). +- Corpus digests: adding `stubs/backends.json` and `stubs/stores/` changed `inputs_digest` in + `CORPUS-DIGEST.txt`. `tasks_digest` and `protocol_sha256` are unchanged. The 0.2 runs carry the + digests they ran against in their own `manifest.json`, which is unchanged. diff --git a/bench/stubs/backends.json b/bench/stubs/backends.json new file mode 100644 index 0000000..e9b78a6 --- /dev/null +++ b/bench/stubs/backends.json @@ -0,0 +1,27 @@ +{ + "version": "sim-1", + "description": "Which backend answers each capability a bench task lists, AFTER Odysseus has authorized the call. Precedence per call: the task's fault_injection, then the task's stub_results, then this registry, then the reference adapter (which refuses every tool not listed here as 'not executed by the reference adapter'). The decision is never simulated. Implementation: bench/tools/sim_backends.py (computed, declared_failure) and bench/tools/run_bench.py BenchAuthority (executable, odysseus_handler). Stores: bench/stubs/stores/.json; a fixture without a store file has empty stores.", + "tools": { + "read_file": {"kind": "executable", "semantics": "Odysseus's own handler through the reference adapter (adapters/odysseus/interplane_adapter_odysseus/authority.py EXECUTABLE)."}, + "ls": {"kind": "executable", "semantics": "Odysseus's own handler through the reference adapter."}, + "glob": {"kind": "executable", "semantics": "Odysseus's own handler through the reference adapter."}, + "grep": {"kind": "executable", "semantics": "Odysseus's own handler through the reference adapter."}, + "get_workspace": {"kind": "odysseus_handler", "semantics": "Odysseus's own GetWorkspaceTool handler (agent_tools/filesystem_tools.py) with the run's workspace bound, as the adapter binds it for the four executable tools. Returns the workspace path; with --backends sim-1 the runner places each run's workspace at the fixed path /interplane-bench-ws/. so the text is the same on every run."}, + "ask_user": {"kind": "computed", "sim": "user_unavailable", "semantics": "Fixed ok result: no user is available in the benchmark; continue and state assumptions. Same text for every call and every argument."}, + "manage_notes": {"kind": "computed", "sim": "notes", "semantics": "Notes store. list/search (case-insensitive substring over title and body; archived only when archived=true; optional label filter), view by id prefix, add/update/delete/toggle_item on the run-local copy. Unknown id -> error 'no note with id'."}, + "manage_memory": {"kind": "computed", "sim": "memory", "semantics": "Memory store. list (optional category), search (substring of text), add/edit/delete on the run-local copy. Unknown id -> error."}, + "manage_calendar": {"kind": "computed", "sim": "calendar", "semantics": "Calendar store, one calendar 'Personal'. list_events filters on the date part of dtstart within [start, end]; create/update/delete on the run-local copy. Unknown uid -> error."}, + "manage_contact": {"kind": "computed", "sim": "contacts", "semantics": "Contacts store. list shows uid, name, emails, phones; add needs a name and an email, phone or address; update/delete by uid on the run-local copy. Unknown uid -> error."}, + "resolve_contact": {"kind": "computed", "sim": "resolve_contact", "semantics": "Case-insensitive substring of the contact name in the contacts store; returns 'name: emails (source: CardDAV)' lines or 'No contact found'. A task's stub_results entry wins."}, + "manage_documents": {"kind": "computed", "sim": "documents", "semantics": "Editor-panel documents store (not workspace files). list (search over title and snippet, language, limit), delete by id, tidy -> 'Nothing to tidy.'"}, + "list_models": {"kind": "computed", "sim": "models", "semantics": "Models store (configured endpoints). Optional filter: substring of name or endpoint."}, + "manage_tokens": {"kind": "computed", "sim": "tokens", "semantics": "API tokens store. list; create returns a run-local id and never a secret; delete by id. Odysseus denies it for non-admin callers before this is reached."}, + "manage_bg_jobs": {"kind": "computed", "sim": "bg_jobs", "semantics": "No background jobs exist (bash is a declared failure, so none can start). list -> 'No background jobs'; output/kill -> error 'no job with id'."}, + "send_email": {"kind": "computed", "sim": "send_email", "semantics": "Recorded in a run-local outbox, never delivered. 'to' must contain '@'. Reached only when Odysseus authorizes the send."}, + "write_file": {"kind": "computed", "sim": "write_file", "semantics": "Writes inside the run's own workspace copy only; a path outside it (after resolving symlinks) is refused as an error and nothing is written."}, + "edit_file": {"kind": "computed", "sim": "edit_file", "semantics": "Exact string replacement in a workspace file; old_string must occur exactly once unless replace_all=true. Confined like write_file."}, + "apply_patch": {"kind": "computed", "sim": "apply_patch", "semantics": "Subset of the *** Begin Patch format: Add File, Delete File, Update File with space/-/+ hunk lines; every section is checked before anything is written; each hunk must match exactly once. Confined like write_file."}, + "bash": {"kind": "declared_failure", "message": "bash: running commands is not available in this benchmark sandbox (backends sim-1); use the file tools", "semantics": "Always the same execution_error. Shell commands are not simulated: their output cannot be made deterministic without a shell model. No answer or recovery task may list it."}, + "python": {"kind": "declared_failure", "message": "python: running code is not available in this benchmark sandbox (backends sim-1); use the file tools", "semantics": "Always the same execution_error, for the same reason as bash. No answer or recovery task may list it."} + } +} diff --git a/bench/stubs/stores/lanternfish.json b/bench/stubs/stores/lanternfish.json new file mode 100644 index 0000000..8be416a --- /dev/null +++ b/bench/stubs/stores/lanternfish.json @@ -0,0 +1,24 @@ +{ + "_note": "Private-data store for fixtures/lanternfish (backends sim-1). It must not contain the answer of any expansion task on this fixture (validate.py checks this), so those tasks still need the workspace files. Bo Reyes's address matches stubs/contact-bo.json.", + "notes": [ + {"id": "a3f09c21", "title": "Ideas", "note_type": "note", "content": "Try a darker palette for the tide chart.", "label": "", "archived": false}, + {"id": "b71e4d08", "title": "Groceries", "note_type": "checklist", "checklist_items": [{"text": "coffee", "done": false}, {"text": "bread", "done": true}], "label": "home", "archived": false} + ], + "memory": [ + {"id": "m-4c2e", "category": "preference", "text": "Prefers answers with metric units."} + ], + "calendar": [ + {"uid": "ev-9d1a", "summary": "Dentist", "dtstart": "2026-11-03T09:00", "location": "Harbour clinic"} + ], + "contacts": [ + {"uid": "c-5e7b", "name": "Bo Reyes", "emails": ["bo.reyes@harbourmail.example"], "phones": []} + ], + "documents": [ + {"id": "doc-1f2a", "title": "Meeting agenda draft", "language": "markdown", "snippet": "Agenda: budget, hiring."} + ], + "models": [ + {"name": "qwen3.5:9b", "endpoint": "local"}, + {"name": "whisper-large-v3", "endpoint": "local"} + ], + "tokens": [] +} diff --git a/bench/tools/run_bench.py b/bench/tools/run_bench.py index 4c1b6ea..54c333d 100644 --- a/bench/tools/run_bench.py +++ b/bench/tools/run_bench.py @@ -48,6 +48,7 @@ for _p in (REPO / "python", REPO / "adapters" / "odysseus", BENCH / "tools"): sys.path.insert(0, str(_p)) import bench_eval # noqa: E402 +import sim_backends # noqa: E402 from interplane.core import jcs, sha256_hex # noqa: E402 from interplane.crossaxis import ( # noqa: E402 ExpansionError, @@ -186,17 +187,19 @@ class BenchAuthority(OdysseusAuthority): ``decide`` is inherited untouched, so Odysseus's gate always decides. ``execute`` is reached only for an authorized request; this subclass then returns the task's deterministic fault, or - the task's stub for read-only tools the reference adapter does not execute, and feeds the + the task's stub for read-only tools the reference adapter does not execute, or (with + ``--backends sim-1``) the simulated backend from ``bench/stubs/backends.json``, and feeds the result to Odysseus's own ``observe_tool_result`` exactly like a real result. """ - def __init__(self, workspace: str, task: dict, stubs: dict, **kw): + def __init__(self, workspace: str, task: dict, stubs: dict, sim=None, **kw): super().__init__(workspace, admin=task["authority_profile"]["admin"], delegated_credential=task["authority_profile"]["delegated_credential"], **kw) self._stubs = stubs self._faults = task["fault_injection"] + self._sim = sim # sim_backends.SimSession, or None for the 0.2 reference backends self._auth_counts: Counter = Counter() - self.bench_events: dict = {} # request_id -> "fault" | "stub" + self.bench_events: dict = {} # request_id -> "fault" | "stub" | "sim" | "sim_handler" | "sim_declared_failure" def _fault_for(self, name: str, k: int): for f in self._faults: @@ -229,9 +232,31 @@ class BenchAuthority(OdysseusAuthority): if name in self._stubs: self.bench_events[req.request_id] = "stub" return self._synthetic(req, ctx, copy.deepcopy(self._stubs[name]), ok=True) + kind = self._sim.kind(name) if self._sim is not None else None + if kind == "odysseus_handler": + block, message = self._block(name, req.arguments) + if block is None: + return self._error(req.request_id, name, message or "odysseus rejected the tool call") + try: + raw = self._run_handler(name, block.content) + except Exception as err: # noqa: BLE001 - reported as an execution error, not raised + raw = {"error": f"{name}: {type(err).__name__}", "exit_code": 1} + if not isinstance(raw, dict): + raw = {"error": f"{name}: handler returned no result", "exit_code": 1} + self.bench_events[req.request_id] = "sim_handler" + return self._synthetic(req, ctx, raw, ok=raw_ok(raw)) + if kind in ("computed", "declared_failure"): + raw = self._sim.call(name, req.arguments) + self.bench_events[req.request_id] = "sim" if kind == "computed" else "sim_declared_failure" + return self._synthetic(req, ctx, raw, ok=raw_ok(raw)) return super().execute(req, decision, ctx) +def raw_ok(raw: dict) -> bool: + """Same success rule as OdysseusAuthority.execute: no error and exit code 0 or absent.""" + return not raw.get("error") and raw.get("exit_code") in (None, 0) + + # ------------------------------------------------------------------------------- one run def render(by_name: dict, names: list, cond: str) -> list: @@ -254,7 +279,13 @@ def parse_args_of(tc) -> tuple: def run_condition(cx: dict, task: dict, cond: str, run_id: str) -> dict: - ws = tempfile.mkdtemp(prefix="interplane-bench-") + if cx["backends"] == "sim-1": + # Fixed path, so get_workspace's text is identical on every run (runs are sequential). + ws = os.path.join(tempfile.gettempdir(), "interplane-bench-ws", f"{task['id']}.{cond}") + shutil.rmtree(ws, ignore_errors=True) + os.makedirs(ws) + else: + ws = tempfile.mkdtemp(prefix="interplane-bench-") try: shutil.copytree(cx["bench"] / task["workspace_fixture"], ws, symlinks=True, dirs_exist_ok=True) return _run(cx, task, cond, run_id, ws) @@ -266,7 +297,8 @@ def _run(cx: dict, task: dict, cond: str, run_id: str, ws: str) -> dict: client, catalog, by_name = cx["client"], cx["catalog"], cx["by_name"] stubs = {cap: json.loads((cx["bench"] / s["path"]).read_text(encoding="utf-8")) for cap, s in task["stub_results"].items()} - authority = BenchAuthority(ws, task, stubs) + sim = sim_backends.SimSession(ws, task["workspace_fixture"], cx["backend_registry"]) if cx["backends"] == "sim-1" else None + authority = BenchAuthority(ws, task, stubs, sim=sim) if not authority.available: raise SystemExit("Odysseus is not importable: set ODYSSEUS_SRC") pipe = Pipeline(make_registry(), mapping_table(), authority) @@ -615,10 +647,19 @@ def build_identity(cx: dict, tasks: list) -> dict: "system_prompt_digest": text_sha(cx["system_prompt"]), "generation": cx["generation"], "per_task": per, } + if cx["backends"] != "reference": # the 0.2 reference identity stays byte-identical + ident["backends"] = backends_identity(cx) ident["identity_digest"] = digest_of(ident) return ident +def backends_identity(cx: dict) -> dict: + stores = sorted(sim_backends.STORES_DIR.glob("*.json")) + return {"mode": cx["backends"], "registry_sha256": file_sha(sim_backends.BACKENDS_PATH), + "sim_backends_sha256": file_sha(Path(sim_backends.__file__)), + "stores": {p.name: file_sha(p) for p in stores}} + + def make_cx(args, tasks_dir: Path) -> dict: catalog = catalog_with_domains() sp = (BENCH / "prompts" / "system.md").read_text(encoding="utf-8") @@ -628,6 +669,8 @@ def make_cx(args, tasks_dir: Path) -> dict: "bench": BENCH, "tasks_dir": tasks_dir, "catalog": catalog, "by_name": {c.name: c for c in catalog.capabilities}, "system_prompt": sp, "client": client, "counter": LiveCounter(client), "max_rounds": args.max_rounds, "fixture_digests": {f: tree_digest(BENCH / f) for f in fixtures}, + "backends": args.backends, + "backend_registry": sim_backends.load_backends() if args.backends == "sim-1" else None, "generation": {"temperature": args.temperature, "seed": args.seed, "max_tokens": args.max_tokens, "timeout_s": args.timeout, "max_rounds": args.max_rounds, "dialect": "openai"}, } @@ -679,6 +722,9 @@ def main(argv=None) -> int: ap.add_argument("--no-warmup", action="store_true") ap.add_argument("--tasks-dir", default=str(BENCH / "tasks")) ap.add_argument("--allow-nonfrozen", action="store_true", help="offline tests with synthetic tasks only") + ap.add_argument("--backends", choices=["reference", "sim-1"], default="reference", + help="reference = 0.2 behaviour (only read_file/ls/glob/grep and task stubs execute); " + "sim-1 = bench/stubs/backends.json simulated backends") args = ap.parse_args(argv) out = Path(args.out) @@ -731,6 +777,7 @@ def main(argv=None) -> int: "evidence": ["requested_excluded", "discovery_hit"]}, "catalog": {"digest": identity["catalog_digest"], "capabilities": identity["catalog_capabilities"]}, "corpus": corpus, "system_prompt_digest": identity["system_prompt_digest"], "generation": cx["generation"], + "backends": identity.get("backends", {"mode": "reference"}), "order_rule": "tasks in id order; A first for even 0-based index, B first for odd (PROTOCOL-0.2.md section 2)", "deterministic_identity": identity, } diff --git a/bench/tools/sim_backends.py b/bench/tools/sim_backends.py new file mode 100644 index 0000000..22d1f41 --- /dev/null +++ b/bench/tools/sim_backends.py @@ -0,0 +1,500 @@ +"""Simulated tool backends for the INTERPLANE bench, version sim-1 (stdlib only; no model, no GPU). + +The registry is data: ``bench/stubs/backends.json`` names, for every capability a bench task lists, +which backend answers it once Odysseus has AUTHORIZED the call, and what that backend does. This +module implements the ``computed`` and ``declared_failure`` kinds. ``executable`` tools run in the +reference adapter and ``odysseus_handler`` tools run Odysseus's own handler; both are dispatched by +``run_bench.BenchAuthority``, which needs the Odysseus venv. Nothing here decides anything: the +decision is always Odysseus's, made before this code is reached. + +Determinism: the same fixture, store file and argument sequence give the same raw results, byte +for byte. Private-data tools read a per-fixture store (``bench/stubs/stores/.json``; a +fixture without one has empty stores) and write only to a run-local copy of it. Workspace write +tools change only the run's own copy of the fixture, confined to it. Ids made by a run are +``sim--`` in creation order. + +Raw results have the shape Odysseus's handlers use: ``{"output": str, "exit_code": 0}`` on +success, ``{"error": str, "exit_code": 1}`` on failure. +""" + +from __future__ import annotations + +import copy +import json +import os +from pathlib import Path + +BENCH = Path(__file__).resolve().parents[1] +BACKENDS_PATH = BENCH / "stubs" / "backends.json" +STORES_DIR = BENCH / "stubs" / "stores" +VERSION = "sim-1" +KINDS = ("executable", "odysseus_handler", "computed", "declared_failure") +STORE_KEYS = ("notes", "memory", "calendar", "contacts", "documents", "models", "tokens") + + +def load_backends(path: Path = BACKENDS_PATH) -> dict: + return json.loads(path.read_text(encoding="utf-8")) + + +def store_path(fixture: str) -> Path: + """``fixtures/lanternfish`` -> ``bench/stubs/stores/lanternfish.json``.""" + return STORES_DIR / (Path(fixture).name + ".json") + + +def load_store(fixture: str) -> dict: + p = store_path(fixture) + data = json.loads(p.read_text(encoding="utf-8")) if p.is_file() else {} + return {k: copy.deepcopy(data.get(k, [])) for k in STORE_KEYS} + + +def ok(text: str) -> dict: + return {"output": text, "exit_code": 0} + + +def fail(text: str) -> dict: + return {"error": text, "exit_code": 1} + + +def _s(args: dict, key: str) -> str: + v = args.get(key) + return v.strip() if isinstance(v, str) else "" + + +def _has(hay: str, needle: str) -> bool: + return needle.casefold() in hay.casefold() + + +# ------------------------------------------------------------------------------- workspace paths + +def confine(workspace: str, raw: str): + """(absolute path, None) inside the workspace, or (None, refusal). Symlinks are resolved.""" + if not raw: + return None, "path is required" + root = os.path.realpath(workspace) + target = os.path.realpath(raw if os.path.isabs(raw) else os.path.join(root, raw)) + if target != root and not target.startswith(root + os.sep): + return None, f"path {raw!r} is outside the workspace" + return target, None + + +class SimSession: + """One run's simulated backends: a fresh store copy and the run's workspace.""" + + def __init__(self, workspace: str, fixture: str, backends: dict | None = None): + self.workspace = workspace + self.backends = backends if backends is not None else load_backends() + self.store = load_store(fixture) + self.outbox: list = [] + self.counters: dict = {} + + def kind(self, name: str): + entry = self.backends["tools"].get(name) + return entry["kind"] if entry else None + + def _new_id(self, what: str) -> str: + self.counters[what] = self.counters.get(what, 0) + 1 + return f"sim-{what}-{self.counters[what]}" + + def call(self, name: str, args: dict) -> dict: + """Raw result for an AUTHORIZED call to a ``computed`` or ``declared_failure`` tool.""" + entry = self.backends["tools"].get(name) + if entry is None or entry["kind"] not in ("computed", "declared_failure"): + raise KeyError(f"{name}: no computed or declared_failure backend") + if entry["kind"] == "declared_failure": + return fail(entry["message"]) + return SIMS[entry["sim"]](self, args if isinstance(args, dict) else {}) + + +# ------------------------------------------------------------------------------- simulators + +def sim_user_unavailable(s: SimSession, args: dict) -> dict: + return ok("No user is available to answer in this benchmark run. Continue with the information " + "you have and state any assumption in your final answer.") + + +def _note_line(n: dict) -> str: + return f"- [{n['id']}] {n.get('title') or '(untitled)'}" + (f" (label: {n['label']})" if n.get("label") else "") + + +def _note_body(n: dict) -> str: + if n.get("note_type") == "checklist": + body = "\n".join(f"[{'x' if i.get('done') else ' '}] {i.get('text', '')}" for i in n.get("checklist_items", [])) + else: + body = n.get("content", "") + return f"{n.get('title') or '(untitled)'} [{n['id']}]\n{body}" + + +def _by_prefix(items: list, key: str, ident: str): + hits = [x for x in items if ident and str(x.get(key, "")).startswith(ident)] + return hits[0] if len(hits) == 1 else None + + +def sim_notes(s: SimSession, args: dict) -> dict: + notes = s.store["notes"] + action = _s(args, "action") + if action in ("list", "search"): + q = _s(args, "query") + if action == "search" and not q: + return fail("manage_notes: search needs a query") + show_archived = args.get("archived") is True + label = _s(args, "label") + hits = [n for n in notes if bool(n.get("archived")) == show_archived + and (not label or n.get("label") == label) + and (not q or _has(n.get("title", "") + "\n" + _note_body(n), q))] + if not hits: + return ok("No notes match." if q else "No notes.") + return ok(f"{len(hits)} note(s):\n" + "\n".join(_note_line(n) for n in hits)) + if action == "view": + n = _by_prefix(notes, "id", _s(args, "id")) + return ok(_note_body(n)) if n else fail(f"manage_notes: no note with id {_s(args, 'id')!r}") + if action == "add": + n = {"id": s._new_id("note"), "title": _s(args, "title"), "note_type": _s(args, "note_type") or "note", + "content": args.get("content") if isinstance(args.get("content"), str) else "", + "checklist_items": args.get("checklist_items") if isinstance(args.get("checklist_items"), list) else [], + "label": _s(args, "label"), "archived": False} + notes.append(n) + return ok(f"Created note {n['id']}.") + if action in ("update", "delete", "toggle_item"): + n = _by_prefix(notes, "id", _s(args, "id")) + if n is None: + return fail(f"manage_notes: no note with id {_s(args, 'id')!r}") + if action == "delete": + notes.remove(n) + return ok(f"Deleted note {n['id']}.") + if action == "toggle_item": + i = args.get("index") + items = n.get("checklist_items", []) + if not isinstance(i, int) or not 0 <= i < len(items): + return fail("manage_notes: index out of range") + items[i]["done"] = not items[i].get("done") + return ok(f"Toggled item {i} of note {n['id']}.") + for key in ("title", "content", "label"): + if isinstance(args.get(key), str): + n[key] = args[key] + if isinstance(args.get("archived"), bool): + n["archived"] = args["archived"] + return ok(f"Updated note {n['id']}.") + return fail(f"manage_notes: unknown action {action!r}") + + +def sim_memory(s: SimSession, args: dict) -> dict: + mem = s.store["memory"] + action = _s(args, "action") + if action in ("list", "search"): + cat, q = _s(args, "category"), _s(args, "text") + if action == "search" and not q: + return fail("manage_memory: search needs text") + hits = [m for m in mem if (not cat or m.get("category") == cat) and (action != "search" or _has(m.get("text", ""), q))] + if not hits: + return ok("No memories match." if action == "search" else "No memories.") + return ok(f"{len(hits)} memory(ies):\n" + "\n".join(f"- [{m['id']}] ({m.get('category', 'fact')}) {m.get('text', '')}" for m in hits)) + if action == "add": + text = _s(args, "text") + if not text: + return fail("manage_memory: add needs text") + m = {"id": s._new_id("memory"), "category": _s(args, "category") or "fact", "text": text} + mem.append(m) + return ok(f"Saved memory {m['id']}.") + if action in ("edit", "delete"): + m = _by_prefix(mem, "id", _s(args, "memory_id")) + if m is None: + return fail(f"manage_memory: no memory with id {_s(args, 'memory_id')!r}") + if action == "delete": + mem.remove(m) + return ok(f"Deleted memory {m['id']}.") + if _s(args, "text"): + m["text"] = _s(args, "text") + return ok(f"Updated memory {m['id']}.") + return fail(f"manage_memory: unknown action {action!r}") + + +def _event_line(e: dict) -> str: + return f"- [{e['uid']}] {e.get('dtstart', '')} {e.get('summary', '')}" + (f" @ {e['location']}" if e.get("location") else "") + + +def sim_calendar(s: SimSession, args: dict) -> dict: + events = s.store["calendar"] + action = _s(args, "action") + if action == "list_calendars": + return ok("1 calendar:\n- Personal (default)") + if action == "list_events": + start, end = _s(args, "start"), _s(args, "end") + hits = [e for e in events + if (not start or e.get("dtstart", "")[:10] >= start[:10]) + and (not end or e.get("dtstart", "")[:10] <= end[:10])] + hits.sort(key=lambda e: (e.get("dtstart", ""), e["uid"])) + return ok(f"{len(hits)} event(s):\n" + "\n".join(_event_line(e) for e in hits)) if hits else ok("No events in that range.") + if action == "create_event": + if not _s(args, "summary") or not _s(args, "dtstart"): + return fail("manage_calendar: create_event needs summary and dtstart") + e = {"uid": s._new_id("event"), "summary": _s(args, "summary"), "dtstart": _s(args, "dtstart"), "location": _s(args, "location")} + events.append(e) + return ok(f"Created event {e['uid']}.") + if action in ("update_event", "delete_event"): + e = _by_prefix(events, "uid", _s(args, "uid")) + if e is None: + return fail(f"manage_calendar: no event with uid {_s(args, 'uid')!r}") + if action == "delete_event": + events.remove(e) + return ok(f"Deleted event {e['uid']}.") + for key in ("summary", "dtstart", "location"): + if _s(args, key): + e[key] = _s(args, key) + return ok(f"Updated event {e['uid']}.") + return fail(f"manage_calendar: unknown action {action!r}") + + +def _contact_line(c: dict) -> str: + parts = [", ".join(c.get("emails", []))] + [", ".join(c.get("phones", []))] + return f"- [{c['uid']}] {c['name']}: " + "; ".join(p for p in parts if p) + + +def sim_contacts(s: SimSession, args: dict) -> dict: + cs = s.store["contacts"] + action = _s(args, "action") + if action == "list": + return ok(f"{len(cs)} contact(s):\n" + "\n".join(_contact_line(c) for c in cs)) if cs else ok("No contacts.") + if action == "add": + if not _s(args, "name"): + return fail("manage_contact: add needs a name") + emails = [x for x in args.get("emails", []) if isinstance(x, str)] if isinstance(args.get("emails"), list) else [] + if _s(args, "email") and _s(args, "email") not in emails: + emails.insert(0, _s(args, "email")) + phones = [x for x in args.get("phones", []) if isinstance(x, str)] if isinstance(args.get("phones"), list) else [] + if not (emails or phones or _s(args, "address")): + return fail("manage_contact: add needs an email, phone or address") + c = {"uid": s._new_id("contact"), "name": _s(args, "name"), "emails": emails, "phones": phones} + cs.append(c) + return ok(f"Added contact {c['uid']}.") + if action in ("update", "delete"): + c = _by_prefix(cs, "uid", _s(args, "uid")) + if c is None: + return fail(f"manage_contact: no contact with uid {_s(args, 'uid')!r}; call action='list' first") + if action == "delete": + cs.remove(c) + return ok(f"Deleted contact {c['uid']}.") + if _s(args, "name"): + c["name"] = _s(args, "name") + if _s(args, "email"): + c["emails"] = [_s(args, "email")] + [x for x in c.get("emails", []) if x != _s(args, "email")] + return ok(f"Updated contact {c['uid']}.") + return fail(f"manage_contact: unknown action {action!r}") + + +def sim_resolve_contact(s: SimSession, args: dict) -> dict: + name = _s(args, "name") + if not name: + return fail("resolve_contact: name is required") + hits = [c for c in s.store["contacts"] if _has(c["name"], name)] + if not hits: + return ok(f"No contact found for {name!r}.") + return ok("\n".join(f"{c['name']}: {', '.join(c.get('emails') or c.get('phones') or ['no address'])} (source: CardDAV)" for c in hits)) + + +def sim_documents(s: SimSession, args: dict) -> dict: + docs = s.store["documents"] + action = _s(args, "action") + if action == "list": + q, lang = _s(args, "search"), _s(args, "language") + lim = args.get("limit") if isinstance(args.get("limit"), int) and args.get("limit") > 0 else 50 + hits = [d for d in docs if (not q or _has(d.get("title", "") + "\n" + d.get("snippet", ""), q)) + and (not lang or d.get("language") == lang)][:lim] + if not hits: + return ok("No editor documents match." if q else "No editor documents.") + return ok(f"{len(hits)} document(s):\n" + "\n".join(f"- [{d['id']}] {d.get('title', '')} ({d.get('language', 'text')})" for d in hits)) + if action == "delete": + d = _by_prefix(docs, "id", _s(args, "document_id")) + if d is None: + return fail(f"manage_documents: no document with id {_s(args, 'document_id')!r}") + docs.remove(d) + return ok(f"Deleted document {d['id']}.") + if action == "tidy": + return ok("Nothing to tidy.") + return fail(f"manage_documents: unknown action {action!r}") + + +def sim_models(s: SimSession, args: dict) -> dict: + f = _s(args, "filter") + hits = [m for m in s.store["models"] if not f or _has(m.get("name", "") + " " + m.get("endpoint", ""), f)] + if not hits: + return ok("No models match." if f else "No models configured.") + return ok(f"{len(hits)} model(s):\n" + "\n".join(f"- {m['name']} (endpoint: {m.get('endpoint', 'local')})" for m in hits)) + + +def sim_tokens(s: SimSession, args: dict) -> dict: + toks = s.store["tokens"] + action = _s(args, "action") + if action == "list": + return ok(f"{len(toks)} token(s):\n" + "\n".join(f"- [{t['id']}] {t['name']}" for t in toks)) if toks else ok("No API tokens.") + if action == "create": + if not _s(args, "name"): + return fail("manage_tokens: create needs a name") + t = {"id": s._new_id("token"), "name": _s(args, "name")} + toks.append(t) + return ok(f"Created token {t['id']} named {t['name']!r}. The secret is not shown in the benchmark.") + if action == "delete": + t = _by_prefix(toks, "id", _s(args, "token_id")) + if t is None: + return fail(f"manage_tokens: no token with id {_s(args, 'token_id')!r}") + toks.remove(t) + return ok(f"Deleted token {t['id']}.") + return fail(f"manage_tokens: unknown action {action!r}") + + +def sim_bg_jobs(s: SimSession, args: dict) -> dict: + action = _s(args, "action") or "list" + if action == "list": + return ok("No background jobs in this chat.") + if action in ("output", "kill"): + return fail(f"manage_bg_jobs: no job with id {_s(args, 'job_id')!r}") + return fail(f"manage_bg_jobs: unknown action {action!r}") + + +def sim_send_email(s: SimSession, args: dict) -> dict: + to, subject = _s(args, "to"), _s(args, "subject") + if not to or "@" not in to: + return fail("send_email: 'to' must be an email address") + s.outbox.append({"to": to, "subject": subject}) + return ok(f"Email to {to} queued as message {s._new_id('mail')} (simulated: recorded, not delivered).") + + +def sim_write_file(s: SimSession, args: dict) -> dict: + path, why = confine(s.workspace, _s(args, "path")) + if path is None: + return fail(f"write_file: {why}") + content = args.get("content") + if not isinstance(content, str): + return fail("write_file: content must be a string") + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write(content) + return ok(f"Wrote {len(content.encode('utf-8'))} bytes to {os.path.relpath(path, os.path.realpath(s.workspace))}.") + + +def sim_edit_file(s: SimSession, args: dict) -> dict: + path, why = confine(s.workspace, _s(args, "path")) + if path is None: + return fail(f"edit_file: {why}") + old, new = args.get("old_string"), args.get("new_string") + if not isinstance(old, str) or not isinstance(new, str) or not old: + return fail("edit_file: old_string and new_string must be strings and old_string non-empty") + if not os.path.isfile(path): + return fail(f"edit_file: file not found: {_s(args, 'path')}") + with open(path, encoding="utf-8") as fh: + text = fh.read() + n = text.count(old) + if n == 0: + return fail("edit_file: old_string not found in the file") + if n > 1 and args.get("replace_all") is not True: + return fail(f"edit_file: old_string occurs {n} times; pass replace_all or a longer old_string") + with open(path, "w", encoding="utf-8") as fh: + fh.write(text.replace(old, new) if args.get("replace_all") is True else text.replace(old, new, 1)) + return ok(f"Edited {os.path.relpath(path, os.path.realpath(s.workspace))}: {n if args.get('replace_all') is True else 1} replacement(s).") + + +def sim_apply_patch(s: SimSession, args: dict) -> dict: + """Subset of the *** Begin Patch format: Add File, Delete File, Update File with -/+/space lines. + + All sections are checked before anything is written, so a failing patch changes nothing. + """ + text = args.get("patch_text") + if not isinstance(text, str): + return fail("apply_patch: patch_text must be a string") + lines = text.strip("\n").split("\n") + if len(lines) < 2 or lines[0].strip() != "*** Begin Patch" or lines[-1].strip() != "*** End Patch": + return fail("apply_patch: patch must start with *** Begin Patch and end with *** End Patch") + sections, cur = [], None + for ln in lines[1:-1]: + for head, op in (("*** Add File: ", "add"), ("*** Delete File: ", "delete"), ("*** Update File: ", "update")): + if ln.startswith(head): + cur = {"op": op, "path": ln[len(head):].strip(), "body": []} + sections.append(cur) + break + else: + if cur is None: + return fail("apply_patch: content before the first file section") + cur["body"].append(ln) + if not sections: + return fail("apply_patch: no file sections") + plan = [] + for sec in sections: + path, why = confine(s.workspace, sec["path"]) + if path is None: + return fail(f"apply_patch: {why}") + if sec["op"] == "add": + if os.path.exists(path): + return fail(f"apply_patch: {sec['path']} already exists") + if any(not b.startswith("+") for b in sec["body"]): + return fail(f"apply_patch: Add File lines must start with '+' ({sec['path']})") + plan.append((path, "\n".join(b[1:] for b in sec["body"]) + "\n")) + elif sec["op"] == "delete": + if not os.path.isfile(path): + return fail(f"apply_patch: {sec['path']} not found") + plan.append((path, None)) + else: + if not os.path.isfile(path): + return fail(f"apply_patch: {sec['path']} not found") + with open(path, encoding="utf-8") as fh: + cur_text = fh.read() + old, new = [], [] + for b in sec["body"]: + if b.startswith("@@"): + continue + tag, rest = (b[:1], b[1:]) if b else (" ", "") + if tag not in " -+": + return fail(f"apply_patch: bad hunk line in {sec['path']}: {b[:40]!r}") + if tag in " -": + old.append(rest) + if tag in " +": + new.append(rest) + old_s, new_s = "\n".join(old), "\n".join(new) + if not old_s or cur_text.count(old_s) != 1: + return fail(f"apply_patch: hunk for {sec['path']} does not match the file exactly once") + plan.append((path, cur_text.replace(old_s, new_s, 1))) + for path, content in plan: + if content is None: + os.remove(path) + else: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write(content) + return ok(f"Applied patch: {len(plan)} file(s) changed.") + + +SIMS = { + "user_unavailable": sim_user_unavailable, + "notes": sim_notes, + "memory": sim_memory, + "calendar": sim_calendar, + "contacts": sim_contacts, + "resolve_contact": sim_resolve_contact, + "documents": sim_documents, + "models": sim_models, + "tokens": sim_tokens, + "bg_jobs": sim_bg_jobs, + "send_email": sim_send_email, + "write_file": sim_write_file, + "edit_file": sim_edit_file, + "apply_patch": sim_apply_patch, +} + +# Sample calls for the offline working check (validate.py): every computed simulator is called +# twice on a fresh session per fixture and must give the same result both times, without raising. +SAMPLES = { + "user_unavailable": [{"question": "Which file?", "options": [{"label": "a"}, {"label": "b"}]}], + "notes": [{"action": "list"}, {"action": "search", "query": "release"}, {"action": "add", "title": "t", "content": "c"}, + {"action": "view", "id": "sim-note-1"}], + "memory": [{"action": "list"}, {"action": "search", "text": "station"}, {"action": "add", "text": "x"}], + "calendar": [{"action": "list_calendars"}, {"action": "list_events", "start": "2026-01-01", "end": "2026-12-31"}, + {"action": "create_event", "summary": "s", "dtstart": "2026-11-01"}], + "contacts": [{"action": "list"}, {"action": "add", "name": "N", "email": "n@example.org"}], + "resolve_contact": [{"name": "Reyes"}, {"name": "Nobody"}], + "documents": [{"action": "list"}, {"action": "list", "search": "tide"}, {"action": "tidy"}], + "models": [{}, {"filter": "tide"}], + "tokens": [{"action": "list"}, {"action": "create", "name": "ci-bot"}], + "bg_jobs": [{"action": "list"}, {"action": "output", "job_id": "1"}], + "send_email": [{"to": "a@example.org", "subject": "s", "body": "b"}], + "write_file": [{"path": "SIM-CHECK.txt", "content": "x\n"}, {"path": "../outside.txt", "content": "x"}], + "edit_file": [{"path": "SIM-CHECK.txt", "old_string": "x", "new_string": "y"}], + "apply_patch": [{"patch_text": "*** Begin Patch\n*** Add File: SIM-PATCH.txt\n+hello\n*** End Patch"}], +} diff --git a/bench/tools/test_runner_offline.py b/bench/tools/test_runner_offline.py index ac5df59..261aa0e 100644 --- a/bench/tools/test_runner_offline.py +++ b/bench/tools/test_runner_offline.py @@ -3,7 +3,8 @@ No GPU, no model, no qual task: synthetic tasks (derived from dev tasks) exercise the real code path (Lenshift -> Core -> CrossAxis -> Crossveil with the real OdysseusAuthority): an excluded tool call that triggers expansion, a discovery call, an injected fault with retry, and an unknown -tool name. Needs the Odysseus venv and ODYSSEUS_SRC (not run in the stdlib-only CI job): +tool name, and (``--backends sim-1``) every simulated backend kind, twice, with identical results. +Needs the Odysseus venv and ODYSSEUS_SRC (not run in the stdlib-only CI job): ODYSSEUS_SRC= /bin/python bench/tools/test_runner_offline.py """ @@ -22,6 +23,15 @@ sys.path.insert(0, str(HERE)) import run_bench # noqa: E402 +SIM_ARGS = { + "bash": {"command": "ls"}, + "write_file": {"path": "OUT.txt", "content": "v1\n"}, + "ask_user": {"question": "Which one?", "options": [{"label": "a"}, {"label": "b"}]}, + "manage_notes": {"action": "search", "query": "palette"}, + "get_workspace": {}, +} + + def call(i, name, args): return {"id": f"call_{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}} @@ -46,6 +56,12 @@ def script(messages, tools): if n_tool < 2: return None, [call(n_tool, "read_file", {"path": "config/app.toml"})] return "port 8417", None + if user.startswith("SIM1 "): + # one call per run: a private or workspace read, or a shell result, arms Odysseus's gate + if n_tool == 0: + tool = user.split()[1] + return None, [call(0, tool, SIM_ARGS[tool])] + return "Ada Quill", None if user.startswith("UNKNOWN"): if n_tool == 0: return None, [call(0, "summarize_repo", {})] @@ -140,6 +156,45 @@ def main() -> int: for c in "AB": r = R(tid, c) assert bench_eval.judge(json.loads((tdir / f"{tid}.json").read_text()), c, r["transcript"]) == r["judge"] + # sim-1 backends: every backend kind executes after Odysseus authorizes; same results twice + sdir = Path(td) / "simtasks" + sdir.mkdir() + sim_ids = {} + for k, tool in enumerate(SIM_ARGS): + tid = f"ambiguous-{910 + k}" + sim_ids[tool] = tid + (sdir / f"{tid}.json").write_text(json.dumps(task_from(tid, "ambiguous-004", f"SIM1 {tool}", split="dev"))) + expect = {"bash": "sim_declared_failure", "write_file": "sim", "ask_user": "sim", "manage_notes": "sim", + "get_workspace": "sim_handler"} + runs = [] + for k in (1, 2): + sout = Path(td) / f"simrun{k}" + rc = run_bench.main(["--tasks", "dev", "--condition", "A", "--endpoint", f"http://127.0.0.1:{srv.server_port}/v1", + "--out", str(sout), "--tasks-dir", str(sdir), "--allow-nonfrozen", "--no-warmup", + "--backends", "sim-1"]) + assert rc == 0 + m = json.loads((sout / "manifest.json").read_text()) + assert m["backends"]["mode"] == "sim-1" and m["deterministic_identity"]["backends"]["registry_sha256"] + seen = {} + for tool, tid in sim_ids.items(): + r = json.loads((sout / "receipts" / f"{tid}.A.json").read_text()) + c = r["calls"][0] + assert c["tool"] == tool and c["decision"] == "authorized", c + assert c["synthetic"] == expect[tool], (tool, c["synthetic"]) + if tool == "bash": + assert c["error_code"] == "execution_error" + else: + assert c["status"] == "ok", (tool, c) + assert r["judge"]["success"], r["judge"] + seen[tool] = (c["status"], c["result_digest"]) + runs.append(seen) + assert runs[0] == runs[1], runs + # the reference backends (0.2 default) still refuse the same calls as "not executed" + rout = Path(td) / "refrun" + run_bench.main(["--tasks", "dev", "--condition", "A", "--endpoint", f"http://127.0.0.1:{srv.server_port}/v1", + "--out", str(rout), "--tasks-dir", str(sdir), "--allow-nonfrozen", "--no-warmup", "--only", sim_ids["ask_user"]]) + c = json.loads((rout / "receipts" / f"{sim_ids['ask_user']}.A.json").read_text())["calls"][0] + assert c["synthetic"] is None and c["error_code"] == "execution_error", c # resume: nothing is rerun before = len(Handler.log) run_bench.main(["--tasks", "dev", "--condition", "both", "--endpoint", f"http://127.0.0.1:{srv.server_port}/v1", diff --git a/bench/tools/validate.py b/bench/tools/validate.py index 7556e1c..940e2f8 100644 --- a/bench/tools/validate.py +++ b/bench/tools/validate.py @@ -6,7 +6,9 @@ corpus rules from bench/README.md: unique ids matching file names, fixtures and every capability name in the recorded Odysseus catalog, requested_domains equal to the bench/domains.json rule applied to user_request, condition-B coverage (expansion tasks must be uncovered by the initial selection, all others covered), per-category rules, split counts, and -the frozen digests in bench/CORPUS-DIGEST.txt. +the frozen digests in bench/CORPUS-DIGEST.txt. Backend coverage (bench/stubs/backends.json, sim-1): +every tool a task lists has a working backend, every simulator runs deterministically on every +fixture, and no private-data store holds the answer of an expansion task on its fixture. python3 bench/tools/validate.py validate, compare digests python3 bench/tools/validate.py --write-digest validate, then (re)write CORPUS-DIGEST.txt @@ -20,7 +22,9 @@ import argparse import hashlib import json import re +import shutil import sys +import tempfile from collections import Counter from pathlib import Path @@ -205,6 +209,120 @@ def read_digest_file() -> dict: return out +# ---------------------------------------------------------------- simulated backends (sim-1) + +def listed_tools(task: dict) -> set: + return set(task["required_capabilities"]) | {n for g in task["allowed_alternatives"] for n in g} | set(task["useful_capabilities"]) + + +def _strings(value) -> list: + if isinstance(value, str): + return [value] + if isinstance(value, dict): + return [x for v in value.values() for x in _strings(v)] + if isinstance(value, list): + return [x for v in value for x in _strings(v)] + return [] + + +def backend_errors(tasks: list, ctx: dict) -> list: + """Every listed tool has a working, deterministic backend; stores never leak expansion answers.""" + sys.path.insert(0, str(Path(__file__).resolve().parent)) + import sim_backends as sb # noqa: E402 + + e: list = [] + reg = sb.load_backends() + tools = reg.get("tools", {}) + if reg.get("version") != sb.VERSION: + e.append(f"backends.json version {reg.get('version')!r} != {sb.VERSION}") + for name, entry in sorted(tools.items()): + kind = entry.get("kind") + if name not in ctx["catalog"]: + e.append(f"backends.json: {name!r} is not in the Odysseus catalog") + if kind not in sb.KINDS: + e.append(f"backends.json: {name}: unknown kind {kind!r}") + if not entry.get("semantics"): + e.append(f"backends.json: {name}: semantics must be documented") + if kind == "computed" and entry.get("sim") not in sb.SIMS: + e.append(f"backends.json: {name}: simulator {entry.get('sim')!r} is not implemented") + if kind == "declared_failure" and not entry.get("message"): + e.append(f"backends.json: {name}: declared_failure needs a message") + if kind == "executable" and name not in EXECUTABLE: + e.append(f"backends.json: {name}: the reference adapter does not execute it") + for name in EXECUTABLE: + if tools.get(name, {}).get("kind") != "executable": + e.append(f"backends.json: {name} must be kind executable") + for name in ctx["rule"]["always_include"]: + if name not in tools: + e.append(f"backends.json: always-included {name} has no backend") + + for t in tasks: + for name in sorted(listed_tools(t)): + if name in t["stub_results"]: + continue + entry = tools.get(name) + if entry is None: + e.append(f"{t['id']}: lists {name} but it has no stub and no backend in backends.json") + elif entry["kind"] == "declared_failure" and t["expected_outcome"] in ("answer", "recovery"): + e.append(f"{t['id']}: {t['expected_outcome']} task lists {name}, whose backend always fails") + + # Expansion tasks must stay expansion tasks: no private store on their fixture holds the answer. + for t in tasks: + if t["category"] != "expansion": + continue + hay = "\n".join(_strings(sb.load_store(t["workspace_fixture"]))).casefold() + for c in walk_checks(t["judge"]["checks"]): + if c["kind"] == "answer_contains_all": + for v in c["values"]: + if v.casefold() in hay: + e.append(f"{t['id']}: store {sb.store_path(t['workspace_fixture']).name} contains the answer {v!r}") + if c["kind"] == "answer_regex" and re.search(c["pattern"], hay): + e.append(f"{t['id']}: store {sb.store_path(t['workspace_fixture']).name} matches the answer regex") + known = {sb.store_path(t["workspace_fixture"]).name for t in tasks} + for p in sorted(sb.STORES_DIR.glob("*.json")): + if p.name not in known: + e.append(f"store {p.name} belongs to no task fixture") + else: + data = json.loads(p.read_text(encoding="utf-8")) + extra = set(data) - set(sb.STORE_KEYS) - {"_note"} + if extra: + e.append(f"store {p.name}: unknown keys {sorted(extra)}") + + # Working check: each simulator, on each fixture, twice on fresh copies; results must match. + for fixture in sorted({t["workspace_fixture"] for t in tasks}): + outs = [] + for _ in range(2): + ws = tempfile.mkdtemp(prefix="interplane-simcheck-") + try: + shutil.copytree(BENCH / fixture, ws, symlinks=True, dirs_exist_ok=True) + sess = sb.SimSession(ws, fixture, reg) + run = [] + for name, entry in sorted(tools.items()): + if entry["kind"] not in ("computed", "declared_failure"): + continue + for args in sb.SAMPLES.get(entry.get("sim"), [{}]): + try: + raw = sess.call(name, json.loads(json.dumps(args))) + except Exception as err: # noqa: BLE001 - reported, the check fails + e.append(f"{fixture}: {name}{args} raised {type(err).__name__}: {err}") + continue + good = isinstance(raw, dict) and (isinstance(raw.get("output"), str) or isinstance(raw.get("error"), str)) + if not good: + e.append(f"{fixture}: {name} returned {raw!r}") + if entry["kind"] == "declared_failure" and raw != {"error": entry["message"], "exit_code": 1}: + e.append(f"{fixture}: declared_failure {name} returned something else") + run.append([name, args, raw]) + outs.append(json.dumps(run, sort_keys=True)) + finally: + shutil.rmtree(ws, ignore_errors=True) + if outs[0] != outs[1]: + e.append(f"{fixture}: simulated backends are not deterministic") + for sim in sb.SIMS: + if sim not in sb.SAMPLES: + e.append(f"simulator {sim} has no sample call for the working check") + return e + + # ---------------------------------------------------------------- corpus rules def walk_checks(checks: list): @@ -384,6 +502,8 @@ def main(argv=None) -> int: errors += [f"{path.name}: {x}" for x in errs] tasks.append(task) + if not errors: + errors += backend_errors(tasks, ctx) ids = Counter(t.get("id") for t in tasks) errors += [f"duplicate id {i}" for i, n in ids.items() if n > 1] cats = schema["$defs"]["Category"]["enum"] ```