Recreate-AAA / bench_builder /builder_progress.py
CharlieDreemur's picture
RecreateAAA 0.1.0 from Recreate-AAA/Recreate-AAA@7da1a3d
966b234 verified
Raw History Blame Contribute Delete
53.1 kB
"""Versioned Builder self-checks and immutable evidence, shared by MCP, CLI and UI."""
from __future__ import annotations
from collections import Counter, OrderedDict
from contextlib import contextmanager
from copy import deepcopy
from datetime import datetime, timezone
from functools import lru_cache
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile
import threading
import time
from typing import Any, Iterator
from bench_builder.builder_evidence import _atomic_write_json
from bench_builder.contract_audit import audit_fields, is_informational
from bench_builder.independent_review import REPLAY_EVIDENCE_PREFIX, is_fidelity_requirement
from bench_builder.requirement_scoring import (
dependency_map, evidence_times, gate_self_checks, parse_time_verdicts, time_key, weighted_percentage,
)
from bench_builder.taxonomy import project_requirement_taxonomy, summarize_requirement_taxonomy
from bench_builder.util.digest import sha256_file
from bench_builder.util.process import run_isolated, tail
class BuilderProgressError(ValueError):
pass
RUNTIME_IDS = ("startup", "core_controls", "main_flow", "terminal_transition", "public_input_trace")
# Wall-clock budget for one preview: browser start, 15 s page load and 15 s screenshot (plus wait_ms).
PREVIEW_LIMIT_SECONDS = 60
_PROJECT_ROOT = Path(__file__).resolve().parents[1]
STATUSES = {"passed", "partial", "failed", "pending", "unavailable"}
# Per-time statuses of a check that cites several reference times, by normalized verdict.
TIME_STATUSES = {"pass": "passed", "partial": "partial", "fail": "failed"}
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp"}
def _now() -> str:
return datetime.now(timezone.utc).isoformat()
def _json(value: Any) -> bytes:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
def _hash(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
@lru_cache(maxsize=256)
def _resolved_root(root: str) -> str:
return os.path.normcase(os.path.realpath(root))
def _inside(root: Path, path: str | Path) -> Path:
raw = root / path
resolved = raw.resolve()
base, target = _resolved_root(str(root)), os.path.normcase(str(resolved))
if (target != base and not target.startswith(base.rstrip(os.sep) + os.sep)) or raw.is_symlink():
raise BuilderProgressError("Evidence path must stay inside this run")
return resolved
# Sized above the file count of a candidate with node_modules: an LRU smaller than one walk
# misses on every file, and progress is polled every second.
@lru_cache(maxsize=16384)
def _file_hash(path: str, size: int, modified: int, changed: int) -> str:
return sha256_file(Path(path))
def game_version(candidate: Path) -> tuple[str | None, Path | None]:
output = next((p for p in (candidate / "dist", candidate / "build", candidate)
if (p / "index.html").is_file()), None)
if output is None:
return None, None
output = _inside(candidate, output)
# Direct WebGames serve dependencies (including Three.js) from node_modules.
# Proof files belong in verification/ so screenshots cannot manufacture builds.
ignored = {"verification", "reference_screenshots", ".git", ".runtime", ".agents", ".bin"}
# Opt in new runs only; retained histories keep their original version algorithm.
policy = candidate.parent / "progress-policy.json"
if policy.is_file() and json.loads(policy.read_text()).get("version") == 2:
ignored.add("candidate_screenshots")
# Directory entries carry their link state, so containment is enforced while
# walking instead of resolving every file (a filesystem round trip each on Windows).
records = []
prefix = len(str(output).rstrip(os.sep)) + 1
folders = [output]
while folders:
with os.scandir(folders.pop()) as entries:
for entry in entries:
linked = entry.is_symlink() or getattr(entry, "is_junction", lambda: False)()
if entry.is_dir(follow_symlinks=False) or (linked and entry.is_dir()):
if entry.name in ignored:
continue
if entry.is_symlink():
raise BuilderProgressError("Runtime output contains a linked directory")
if linked:
# Junctions were walked before; keep accepting ones that stay inside.
_inside(output, Path(entry.path).relative_to(output))
folders.append(Path(entry.path))
continue
name = entry.name
if name in {"builder_checks.json", "game_design.json"} or name.endswith(".md"):
continue
if linked:
raise BuilderProgressError("Evidence path must stay inside this run")
# Windows directory listings carry size and mtime, so no extra round trip per file.
stat = entry.stat()
digest = _file_hash(entry.path, stat.st_size, stat.st_mtime_ns, 0)
records.append((entry.path[prefix:].replace(os.sep, "/"), digest))
return "v-" + _hash(_json(sorted(records))), output
@contextmanager
def _process_lock(path: Path) -> Iterator[None]:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a+b") as stream:
if path.stat().st_size == 0:
stream.write(b"\0")
stream.flush()
deadline = time.monotonic() + 15
while True:
try:
stream.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except OSError:
if time.monotonic() > deadline:
raise BuilderProgressError("Progress is busy; retry the same request_id") from None
time.sleep(.05)
try:
yield
finally:
stream.seek(0)
if os.name == "nt":
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
else:
fcntl.flock(stream, fcntl.LOCK_UN)
_History = tuple[list[dict[str, Any]], int]
_HISTORY_CACHE: OrderedDict[str, tuple[tuple[int, ...], _History]] = OrderedDict()
_HISTORY_LOCK = threading.Lock()
def _history_signature(stat: os.stat_result) -> tuple[int, ...]:
return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns)
def _read_history(path: str) -> _History:
# Cache one current projection per file, never sixteen growing copies of
# the same history. Returned histories remain independent after an append.
with Path(path).open("rb") as stream:
signature = _history_signature(os.fstat(stream.fileno()))
with _HISTORY_LOCK:
cached = _HISTORY_CACHE.get(path)
if cached is not None and cached[0] == signature:
_HISTORY_CACHE.move_to_end(path)
return cached[1]
_HISTORY_CACHE.pop(path, None)
del cached
rows, valid_end = [], 0
for line in stream:
# Match bytes.splitlines: a lone CR or unfinished final record is
# uncommitted. A crash during append cannot create a snapshot.
carriage_return = line.find(b"\r")
if not line.endswith(b"\n") or 0 <= carriage_return < len(line) - 2:
break
try:
row = json.loads(line)
if not isinstance(row, dict) or row.get("snapshot_id") != f"s{len(rows)+1:06d}":
raise ValueError()
except ValueError:
raise BuilderProgressError("Progress history contains an invalid committed record") from None
rows.append(row)
valid_end += len(line)
result = rows, valid_end
if _history_signature(os.fstat(stream.fileno())) == signature:
with _HISTORY_LOCK:
_HISTORY_CACHE[path] = signature, result
_HISTORY_CACHE.move_to_end(path)
while len(_HISTORY_CACHE) > 16:
_HISTORY_CACHE.popitem(last=False)
return result
def _requirement_scores(checks: list[dict[str, Any]], catalog: dict[str, Any],
dependencies: dict[str, tuple[str, ...]], target: int,
excluded: frozenset[str] | set[str] = frozenset(), *, strict: bool = False) -> dict[str, Any]:
counted = [row for row in checks if row["requirement_id"] not in excluded]
counts = Counter(row["status"] for row in counted)
total = len(counted)
required = (total * target + 99) // 100
if not strict:
# Plain scoring (strict completion off): every reported pass counts, unweighted.
passed_count = counts["passed"]
return {
"total": total, "passed": passed_count, "partial": counts["partial"], "failed": counts["failed"],
"pending": counts["pending"] + counts["unavailable"] + counts["needs_recheck"],
"needsRecheck": counts["needs_recheck"],
"freshPassed": sum(r["status"] == "passed" and r["assessment"] == "rechecked" for r in counted),
"carriedPassed": sum(r["status"] == "passed" and r["assessment"] == "carried_forward" for r in counted),
"percentage": (passed_count * 1000 // total) / 10 if total else 0,
"targetPercent": target, "requiredPassed": required,
"targetSatisfied": bool(total) and passed_count >= required,
}
# A self-reported pass counts only when the prerequisite instances it relies on happened.
reported = {row["requirement_id"] for row in counted if row["status"] == "passed"}
# An excluded prerequisite (not visible in the reference) cannot be confirmed either way, so it
# never holds back the rows after it.
gated = [{**row, "status": "passed", "times": None} if row["requirement_id"] in excluded else row
for row in checks]
passed, blocked = gate_self_checks(gated, catalog, dependencies)
passed -= set(excluded)
blocked = {key: value for key, value in blocked.items() if key not in excluded}
weighted = weighted_percentage(
(catalog.get(row["requirement_id"], {"id": row["requirement_id"]}) for row in counted), passed)
checks = counted
return {
"total": total, "passed": len(passed), "reportedPassed": len(reported),
"blockedByDependencies": len(blocked),
"blockedRequirementIds": sorted(blocked),
"blockedBy": {key: [blocker.to_json() for blocker in blocked[key]] for key in sorted(blocked)},
"partial": counts["partial"], "failed": counts["failed"],
"pending": counts["pending"] + counts["unavailable"] + counts["needs_recheck"],
"needsRecheck": counts["needs_recheck"],
"freshPassed": sum(r["requirement_id"] in passed and r["assessment"] == "rechecked" for r in checks),
"carriedPassed": sum(r["requirement_id"] in passed and r["assessment"] == "carried_forward" for r in checks),
"percentage": (len(passed) * 1000 // total) / 10 if total else 0,
"weightedPercentage": weighted,
# One gate: the weighted share (the plain percentage is reported beside it).
"targetPercent": target, "targetSatisfied": bool(total) and weighted >= target,
}
def _measured_by_probes(checks: list[dict[str, Any]], contract: dict[str, Any], candidate: Path,
version: str | None, errors: list[str]) -> None:
"""A requirement with scored rule probes takes its status from them, not from a report: passed when they
all passed on ``version``, otherwise at most partial (bench_builder.self_check)."""
from bench_builder.self_check import PROBES, probe_gate, scored_probes
probed = scored_probes(contract)
blocked = probe_gate(contract, candidate, version)
held = []
for row in checks:
key = row["requirement_id"]
if key not in probed:
continue
if key not in blocked:
if row["status"] != "passed":
row.update(status="passed", reason="its rule probes passed on this build", assessment="rechecked",
verified_version=version)
if not row.get("evidence"):
row["evidence"] = [{"source_path": PROBES, "build_version": version}]
elif row["status"] == "passed":
row["status"] = "partial"
held.append(key)
if held:
errors.append(f"{', '.join(held[:20])}{' …' if len(held) > 20 else ''}: counted once their rule probes pass on "
"this build (" + "; ".join(f"{key}: {blocked[key]}" for key in held[:3]) + ")")
def summarize(snapshot: dict[str, Any], target: int, *, strict: bool = False) -> dict[str, Any]:
"""Progress toward ``target``. ``strict`` (strict completion) gates passes on their prerequisites,
weights them and leaves contract-audit not-visible rows out; otherwise every pass counts once."""
runtime = snapshot["runtime_checks"]
dependencies, dependency_warnings = dependency_map(
snapshot.get("requirement_dependencies") if strict else None,
(row["requirement_id"] for row in snapshot["checks"]))
catalog = {row["id"]: row for row in snapshot.get("requirements") or []}
checked = {row["requirement_id"] for row in snapshot["checks"]}
# Rows the contract audit found not visible in the reference stay listed but outside the target.
informational = {key for key, row in catalog.items() if strict and is_informational(row)} & checked
scores = _requirement_scores(snapshot["checks"], catalog, dependencies, target, informational, strict=strict)
return {
"state": "available", **scores,
"runtimeChecks": [{"id": r["requirement_id"], "status": "pending" if r["status"] == "needs_recheck" else r["status"]} for r in runtime],
"runtimeSatisfied": all(any(r["requirement_id"] == key and r["status"] == "passed" for r in runtime) for key in RUNTIME_IDS[:4]),
"updatedAt": snapshot["created_at"],
"warnings": [*snapshot.get("attachment_errors", []), *dependency_warnings], "buildVersion": snapshot["build_version"],
**({"informational": len(informational)} if informational else {}),
}
def strict_scoring(run_dir: Path) -> bool:
"""Whether the build uses strict completion (``independent_review`` on in its harness options)."""
try:
data = json.loads((Path(run_dir) / "result.json").read_text(encoding="utf-8-sig"))
options = data.get("build", {}).get("harness_options") or {}
except (OSError, ValueError, TypeError, AttributeError):
return False
return isinstance(options, dict) and str(options.get("independent_review", "")).casefold() == "on"
class BuilderProgressService:
def __init__(self, run_dir: Path, target_percent: int | None = None):
self.run = Path(run_dir).resolve()
self.candidate = _inside(self.run, "candidate")
self.store = _inside(self.run, "agent/progress")
self.history_path = _inside(self.run, "agent/progress/snapshots.jsonl")
self.target_override = target_percent
def target(self) -> int:
if self.target_override is not None:
return max(1, min(100, int(self.target_override)))
try:
data = json.loads((self.run / "result.json").read_text(encoding="utf-8-sig"))
return max(1, min(100, int(data.get("build", {}).get("completion_threshold_percent", 100))))
except (OSError, ValueError, TypeError):
return 100
def strict(self) -> bool:
return strict_scoring(self.run)
def contract(self) -> tuple[dict[str, Any], str]:
contract, digest, _ = self._contract_with_lineage()
return contract, digest
def _contract_with_lineage(self) -> tuple[dict[str, Any], str, list[str]]:
paths = ("public-inputs/video_agent/analysis/game_design.json", "progress-contract.json", "candidate/game_design.json")
path = next((_inside(self.run, p) for p in paths if _inside(self.run, p).is_file()), None)
if path is None:
raise BuilderProgressError("Create a stable game_design.json requirement list before reporting checks")
try:
raw = path.read_bytes()
contract = json.loads(raw.decode("utf-8-sig"))
rows = contract.get("observable_requirements", contract.get("requirements"))
ids = [row.get("id") for row in rows]
if not ids or any(not isinstance(key, str) or not key.strip() for key in ids) or len(ids) != len(set(ids)):
raise ValueError()
except (ValueError, TypeError, AttributeError):
raise BuilderProgressError("Canonical requirements must have unique nonempty IDs") from None
contract["observable_requirements"] = rows
digest = _hash(raw)
lineage = [digest]
additions_path = _inside(self.run, "requirement_additions.json")
if additions_path.is_file():
try:
additions = json.loads(additions_path.read_text(encoding="utf-8-sig"))
if additions.get("schema_version") != 1 or additions.get("base_contract_sha256") != digest:
raise ValueError()
revisions = additions["revisions"]
if not isinstance(revisions, list) or not revisions:
raise ValueError()
revision_ids, known_ids = set(), set(ids)
for revision in revisions:
key = revision["id"]
if not isinstance(key, str) or not key.strip() or key in revision_ids:
raise ValueError()
if any(not isinstance(revision.get(k), str) or not revision[k].strip()
for k in ("authorization", "reason")):
raise ValueError()
extra = revision["requirements"]
amendments = revision.get("amendments", [])
if not isinstance(extra, list) or not isinstance(amendments, list) or (not extra and not amendments):
raise ValueError()
for row in extra:
key_id = row["id"]
if (not isinstance(key_id, str) or not key_id.strip() or key_id in known_ids
or not isinstance(row.get("acceptance"), str) or not row["acceptance"].strip()):
raise ValueError()
required = row.get("required_evidence", [])
if (not isinstance(required, list)
or any(kind not in ("capture", "artifact") for kind in required)):
raise ValueError()
known_ids.add(key_id)
rows.extend(extra)
if amendments:
from bench_builder.requirement_revisions import apply_amendments
changed = apply_amendments(rows, amendments)
contract.setdefault("metric_revisions", []).append({
"id": key, "changed_ids": changed, "reason": revision["reason"],
})
revision_ids.add(key)
digest = _hash(_json([digest, revision]))
lineage.append(digest)
except (ValueError, TypeError, AttributeError, KeyError):
raise BuilderProgressError("User requirement additions must preserve the base and append unique IDs or hash-bound amendments") from None
return contract, digest, lineage
@staticmethod
def _reconcile_requirements(snapshot: dict[str, Any], contract: dict[str, Any], digest: str, lineage: list[str]) -> bool:
if snapshot["contract_sha256"] == digest:
return False
if snapshot["contract_sha256"] not in lineage:
raise BuilderProgressError("Canonical contract changed; preserve prior requirements and append only user-authorized revisions")
previous = {row["id"]: row for row in snapshot.get("requirements", [])}
amended = {key for revision in contract.get("metric_revisions", []) for key in revision["changed_ids"]}
invalid = {row["id"] for row in BuilderProgressService.requirement_catalog(contract)
if row["id"] in amended and previous.get(row["id"]) != row}
# A changed prerequisite also requires dependent claims to be checked again.
while True:
expanded = invalid | {row["requirement_id"] for row in contract.get("requirement_dependencies", [])
if invalid.intersection(row.get("depends_on", []))}
if expanded == invalid:
break
invalid = expanded
for check in snapshot["checks"]:
if check["requirement_id"] in invalid and check["status"] in {"passed", "partial", "failed"}:
check["previous_status"] = check["status"]
check["status"] = "needs_recheck"
known = {row["requirement_id"] for row in snapshot["checks"]}
for row in contract["observable_requirements"]:
if row["id"] not in known:
snapshot["checks"].append({"requirement_id": row["id"], "status": "pending", "reason": "",
"evidence": [], "verified_version": None, "assessment": "rechecked", "updated_at": None})
return True
def history(self) -> list[dict[str, Any]]:
if not self.history_path.is_file():
return []
return _read_history(str(self.history_path))[0]
@staticmethod
def requirement_catalog(contract: dict[str, Any]) -> list[dict[str, Any]]:
return [{"id": r["id"], "category": r.get("category") or "uncategorized",
"attribute": r.get("attribute") or r["id"], "acceptance": r.get("acceptance") or "",
"evidence_refs": r.get("evidence_refs") or [],
"target_instance_ids": r.get("target_instance_ids") or [],
**({"weight": r["weight"]} if "weight" in r else {}),
**audit_fields(r),
**project_requirement_taxonomy(r, contract.get("taxonomy_version"))}
for r in contract["observable_requirements"]]
@staticmethod
def taxonomy_diagnostics(requirements: list[dict[str, Any]], checks: list[dict[str, Any]]) -> dict[str, Any]:
return summarize_requirement_taxonomy(
requirements, {r["requirement_id"]: r["status"] for r in checks},
status_names=("passed", "partial", "failed", "pending", "unavailable", "needs_recheck"),
default_status="pending", denominator="builder_canonical_requirement_ids",
)
def _seed(self, contract: dict[str, Any]) -> dict[str, Any]:
def row(key: str) -> dict[str, Any]:
return {"requirement_id": key, "status": "pending", "reason": "", "evidence": [],
"verified_version": None, "assessment": "rechecked", "updated_at": None}
result = {"checks": [row(r["id"]) for r in contract["observable_requirements"]],
"instance_checks": [row(r["instance_id"]) for r in contract.get("reference_instances", [])],
"runtime_checks": [row(key) for key in RUNTIME_IDS], "captures": [], "artifacts": []}
legacy_path = _inside(self.candidate, "builder_checks.json")
if legacy_path.is_file():
try:
legacy = json.loads(legacy_path.read_text(encoding="utf-8-sig"))
result["legacy_ledger"] = legacy
result["legacy_reported_at"] = datetime.fromtimestamp(legacy_path.stat().st_mtime, timezone.utc).isoformat()
by_id = {r.get("requirement_id", r.get("id")): r for r in legacy.get("requirement_checks", []) if isinstance(r, dict)}
for item in result["checks"]:
old = by_id.get(item["requirement_id"], {})
if old.get("status") in {"passed", "pass", "partial", "failed"}:
item.update(status="needs_recheck", reason="Imported legacy check; evidence version is unconfirmed", assessment="legacy")
except (ValueError, AttributeError):
result["legacy_import_error"] = "Legacy report could not be parsed; original file remains unchanged until a valid update"
return result
@staticmethod
def _invalidate(snapshot: dict[str, Any]) -> None:
for group in ("checks", "instance_checks", "runtime_checks"):
for row in snapshot[group]:
if row["status"] in {"passed", "partial", "failed"}:
row["previous_status"] = row["status"]
row["status"] = "needs_recheck"
def _save_media(self, data: bytes, suffix: str) -> str:
media_id = _hash(data) + suffix
path = _inside(self.store, "media/" + media_id)
path.parent.mkdir(parents=True, exist_ok=True)
if not path.exists():
handle, temporary = tempfile.mkstemp(dir=path.parent, suffix=".tmp")
try:
with os.fdopen(handle, "wb") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
Path(temporary).unlink(missing_ok=True)
return media_id
def _register_capture(self, item: dict[str, Any], version: str | None, origin: str = "agent_reported") -> dict[str, Any]:
from PIL import Image
path = _inside(self.candidate, str(item.get("path", "")))
payload = path.read_bytes()
import io
with Image.open(io.BytesIO(payload)) as img:
width, height = img.size
declared = item.get("build_version") if origin == "agent_reported" else version
captured_at = item.get("captured_at") or datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()
media_id = self._save_media(payload, path.suffix.lower())
capture_id = "cap-" + _hash(_json([media_id, declared, captured_at, origin]))[:24]
return {"capture_id": capture_id, "media_id": media_id, "label": str(item.get("label") or path.stem),
"build_version": declared, "origin": origin, "captured_at": captured_at,
"width": width, "height": height, "path": str(self.store / "media" / media_id)}
def _capture_preview(self, output: Path, version: str, options: dict[str, Any]) -> dict[str, Any]:
width, height = int(options.get("width", 960)), int(options.get("height", 540))
wait_ms = int(options.get("wait_ms", 1200))
if not 160 <= width <= 3840 or not 90 <= height <= 2160 or not 0 <= wait_ms <= 10000:
raise BuilderProgressError("Preview dimensions or wait_ms are outside supported limits")
directory = _inside(self.candidate, "verification")
directory.mkdir(parents=True, exist_ok=True)
handle, filename = tempfile.mkstemp(suffix=".png", dir=directory)
os.close(handle)
path = Path(filename)
try:
# The browser runs in its own process group: a page that stalls its renderer must not
# hold this MCP call (and the agent's turn) until the harness inactivity timeout.
job = {"output": str(output), "path": str(path), "width": width, "height": height, "wait_ms": wait_ms}
limit = PREVIEW_LIMIT_SECONDS + wait_ms / 1000
try:
run_isolated([sys.executable, "-m", "bench_builder.builder_progress", "--render-preview",
json.dumps(job)], limit, cwd=_PROJECT_ROOT)
except subprocess.TimeoutExpired:
raise BuilderProgressError(
f"Preview capture did not finish within {limit:g} s and its browser was stopped. The page "
"probably blocks its main thread while loading (an endless loop or a very long first frame). "
"Fix the stall, attach your own screenshot in captures, or pass preview mode 'none'.") from None
except subprocess.CalledProcessError as exc:
raise BuilderProgressError(
f"Preview capture failed: {tail(exc.stderr) or f'exit {exc.returncode}'}; "
"attach your own screenshot in captures or retry.") from None
return self._register_capture({"path": str(path), "label": str(options.get("label", "Game preview")), "captured_at": _now()}, version, "tool")
finally:
path.unlink(missing_ok=True)
def _evidence(self, evidence: list[dict[str, Any]], snapshot: dict[str, Any], aliases: dict[str, str], version: str | None) -> list[dict[str, Any]]:
result = []
captures = {c["capture_id"]: c for c in snapshot["captures"]}
artifacts = {a["artifact_id"]: a for a in snapshot["artifacts"]}
for raw in evidence or []:
try:
result.extend(self._evidence_item(raw, snapshot, aliases, version, captures, artifacts))
except (OSError, ValueError, TypeError, AttributeError, KeyError) as exc:
snapshot.setdefault("attachment_errors", []).append(f"Attachment omitted: {exc}")
return result
def _evidence_item(self, raw, snapshot, aliases, version, captures, artifacts):
item = deepcopy(raw)
if item.get("capture_id"):
key = aliases.get(item["capture_id"], item["capture_id"])
if key not in captures:
raise BuilderProgressError(f"Unknown capture_id: {key}")
capture = captures[key]
item = {"capture_id": key, "build_version": capture["build_version"], "path": capture["path"]}
if "bbox" in raw:
box = raw["bbox"]
item["bbox"] = box
elif item.get("artifact_id"):
if item["artifact_id"] not in artifacts:
raise BuilderProgressError("Unknown artifact_id")
item = deepcopy(artifacts[item["artifact_id"]])
elif item.get("path"):
path = _inside(self.candidate, item["path"])
declared = item.get("build_version")
media_id = self._save_media(path.read_bytes(), path.suffix.lower())
artifact_id = "art-" + _hash(_json([media_id, declared]))
item = {"artifact_id": artifact_id, "media_id": media_id, "build_version": declared, "path": str(self.store / "media" / media_id),
"source_path": path.relative_to(self.candidate).as_posix()}
artifacts[artifact_id] = item
if not any(a["artifact_id"] == artifact_id for a in snapshot["artifacts"]):
snapshot["artifacts"].append(item)
else:
raise BuilderProgressError("Evidence must reference a registered capture or a verification artifact")
return [item]
def update_progress(self, request_id: str, base_snapshot_id: str = "", summary: str = "",
checks=None, runtime_checks=None, instance_checks=None, captures=None, preview=None):
# Serialize batches and merge each into the latest snapshot, without agent retries.
with _process_lock(_inside(self.store, ".update-lock")):
return self._update_progress(request_id, base_snapshot_id, summary, checks,
runtime_checks, instance_checks, captures, preview)
def _update_progress(self, request_id: str, base_snapshot_id: str = "", summary: str = "",
checks: list[dict[str, Any]] | None = None, runtime_checks: list[dict[str, Any]] | None = None,
instance_checks: list[dict[str, Any]] | None = None, captures: list[dict[str, Any]] | None = None,
preview: dict[str, Any] | None = None) -> dict[str, Any]:
"""Publish a batch of self-checks and immutable screenshots. Read get_progress first.
captures: [{id: optional alias, path, label, build_version, captured_at?}].
checks: [{requirement_id,status,reason,evidence:[{capture_id,bbox?}|{path,build_version}],
assessment?: 'rechecked'|'carried_forward',
times?: {"<evidence time>": 'passed'|'partial'|'failed'}}].
preview: {mode:'auto'|'capture'|'none', width?:960,height?:540,wait_ms?:1200}.
A capture-only call returns pictures to inspect before reporting passes.
"""
if not isinstance(request_id, str) or not 1 <= len(request_id) <= 160:
raise BuilderProgressError("request_id must be a stable nonempty string up to 160 characters")
request_hash = _hash(_json([base_snapshot_id, summary, checks, runtime_checks, instance_checks, captures, preview]))
for previous in self.history():
if previous["request_id"] == request_id:
if previous["request_hash"] != request_hash:
raise BuilderProgressError("request_id was already used for different content")
with _process_lock(_inside(self.store, ".lock")):
self._project(self.history()[-1])
return self._response(previous)
contract, contract_hash, lineage = self._contract_with_lineage()
version, output = game_version(self.candidate)
history = self.history()
latest = history[-1] if history else None
base_snapshot_id = latest["snapshot_id"] if latest else ""
snapshot = deepcopy(latest) if latest else self._seed(contract)
if latest:
self._reconcile_requirements(snapshot, contract, contract_hash, lineage)
snapshot.pop("legacy_ledger", None)
snapshot["attachment_errors"] = []
aliases = {}
report_capture_ids = []
for item in captures or []:
try:
capture = self._register_capture(item, version)
except (OSError, ValueError, TypeError, AttributeError, KeyError) as exc:
snapshot["attachment_errors"].append(f"Screenshot omitted: {exc}")
continue
if capture["capture_id"] not in report_capture_ids:
report_capture_ids.append(capture["capture_id"])
if item.get("id"):
aliases[item["id"]] = capture["capture_id"]
if not any(c["capture_id"] == capture["capture_id"] for c in snapshot["captures"]):
snapshot["captures"].append(capture)
options = preview or {"mode": "auto"}
mode = options.get("mode", "auto")
if mode not in {"auto", "capture", "none"}:
mode = "none"
snapshot["attachment_errors"].append("Preview omitted: unknown mode")
current_captures = [c for c in snapshot["captures"] if version and c["build_version"] == version]
capture_error = None
if mode == "capture" or (mode == "auto" and not current_captures):
if version and output:
try:
capture = self._capture_preview(output, version, options)
snapshot["captures"].append(capture)
current_captures.append(capture)
if capture["capture_id"] not in report_capture_ids:
report_capture_ids.append(capture["capture_id"])
except BuilderProgressError as exc:
capture_error = str(exc)
except Exception as exc:
capture_error = f"Preview capture failed ({type(exc).__name__}); provide a harness screenshot or retry."
else:
capture_error = "No runnable index.html yet; publish a preview after building the game."
timestamp = _now()
fidelity_ids = {r["id"] for r in contract["observable_requirements"] if is_fidelity_requirement(r)}
cited_times = {r["id"]: evidence_times(r) for r in contract["observable_requirements"]}
for group, updates in (("checks", checks), ("runtime_checks", runtime_checks), ("instance_checks", instance_checks)):
by_id = {r["requirement_id"]: r for r in snapshot[group]}
seen = set()
for update in updates or []:
if not isinstance(update, dict):
snapshot["attachment_errors"].append(f"{group} entry skipped: expected an object")
continue
key = update.get("requirement_id")
if not isinstance(key, str) or key not in by_id:
snapshot["attachment_errors"].append(f"{group} entry skipped: unknown ID {key}")
continue
status = update.get("status")
if not isinstance(status, str) or status not in STATUSES:
snapshot["attachment_errors"].append(f"{key} skipped: unsupported status {status}")
continue
if key in seen:
snapshot["attachment_errors"].append(f"Duplicate {key}: using the last valid entry")
seen.add(key)
reason = update.get("reason", "")
if not isinstance(reason, str):
snapshot["attachment_errors"].append(f"{key}: reason converted to text")
reason = str(reason) if reason is not None else ""
reason = reason.strip()
assessment = update.get("assessment", "rechecked")
row = by_id[key]
evidence = self._evidence(update.get("evidence", row["evidence"]), snapshot, aliases, version)
if group == "checks" and key in fidelity_ids and status == "passed" and not any(
str(item.get("source_path", "")).startswith(REPLAY_EVIDENCE_PREFIX) for item in evidence):
# Frame fidelity must be shown on the evaluator's replay, not on hand-picked screenshots.
status = "partial"
snapshot["attachment_errors"].append(
f"{key}: a replay-fidelity window passes only with replay_compare evidence "
f"({REPLAY_EVIDENCE_PREFIX}...); recorded as partial")
row.update(status=status, reason=reason, evidence=evidence, verified_version=version,
assessment=assessment, updated_at=timestamp)
row.pop("previous_status", None)
row.pop("times", None)
if group == "checks" and update.get("times") is not None:
# Per-time statuses say which instance of a multi-time requirement happened.
raw, cited = update["times"], cited_times.get(key, [])
graded = parse_time_verdicts(raw, cited) if status in TIME_STATUSES.values() else {}
if graded:
row["times"] = {time_key(t): TIME_STATUSES[value] for t, value in sorted(graded.items())}
if not isinstance(raw, dict) or len(graded) < len(raw):
snapshot["attachment_errors"].append(
f"{key}: times keeps passed/partial/failed entries for its evidence times "
f"({', '.join(map(time_key, cited)) or 'none'}) on a graded check; others ignored")
_measured_by_probes(snapshot["checks"], contract, self.candidate, version, snapshot["attachment_errors"])
snapshot.update(snapshot_id=f"s{len(history)+1:06d}", parent_snapshot_id=base_snapshot_id,
build_version=version, created_at=timestamp, summary=str(summary), request_id=request_id,
request_hash=request_hash, contract_sha256=contract_hash,
report_capture_ids=report_capture_ids,
preview=current_captures[-1] if current_captures else None, capture_error=capture_error)
snapshot["requirements"] = self.requirement_catalog(contract)
snapshot["requirement_dependencies"] = contract.get("requirement_dependencies") or []
snapshot["taxonomy_diagnostics"] = self.taxonomy_diagnostics(snapshot["requirements"], snapshot["checks"])
snapshot["references"] = self.references(archive=True)
snapshot["progress"] = summarize(snapshot, self.target(), strict=self.strict())
old = {r["requirement_id"]: r["status"] for r in latest["checks"]} if latest else {}
snapshot["change"] = {"passed": sum(r["status"] == "passed" and old.get(r["requirement_id"]) != "passed" for r in snapshot["checks"]),
"regressed": sum(r["status"] != "passed" and old.get(r["requirement_id"]) == "passed" for r in snapshot["checks"])}
with _process_lock(_inside(self.store, ".lock")):
current = self.history()
for previous in current:
if previous["request_id"] == request_id:
if previous["request_hash"] != request_hash:
raise BuilderProgressError("request_id was already used for different content")
self._project(current[-1])
return self._response(previous)
if (current[-1]["snapshot_id"] if current else "") != base_snapshot_id:
raise BuilderProgressError("Concurrent progress update; get_progress then retry")
valid_end = 0
if self.history_path.exists():
_, valid_end = _read_history(str(self.history_path))
with self.history_path.open("r+b" if self.history_path.exists() else "w+b") as stream:
stream.truncate(valid_end)
stream.seek(valid_end)
stream.write(_json(snapshot) + b"\n")
stream.flush()
os.fsync(stream.fileno())
self._project(snapshot)
return self._response(snapshot)
def _project(self, snapshot: dict[str, Any]) -> None:
ledger = {"assessment": "Builder self-assessment; no independent Judge", "snapshot_id": snapshot["snapshot_id"],
"build_version": snapshot["build_version"], "canonical_sha256": snapshot["contract_sha256"],
"completion": snapshot["progress"], "requirement_checks": snapshot["checks"],
"instance_checks": snapshot["instance_checks"],
"runtime_checks": {r["requirement_id"]: r for r in snapshot["runtime_checks"]}}
_atomic_write_json(_inside(self.candidate, "builder_checks.json"), ledger)
def _response(self, snapshot: dict[str, Any]) -> dict[str, Any]:
return {**self.summary(snapshot), "pending_ids": [r["requirement_id"] for r in snapshot["checks"] if r["status"] != "passed"],
"captures": [c for c in snapshot["captures"] if c["build_version"] == snapshot["build_version"]][-12:],
"instance_progress": dict(Counter(r["status"] for r in snapshot["instance_checks"]))}
@staticmethod
def summary(snapshot: dict[str, Any]) -> dict[str, Any]:
return {**{key: snapshot.get(key) for key in ("snapshot_id", "build_version", "created_at", "summary", "progress", "preview", "capture_error", "change", "report_capture_ids")},
**({"taxonomy_diagnostics": snapshot["taxonomy_diagnostics"]} if "taxonomy_diagnostics" in snapshot else {})}
def get_progress(self, status: str | None = None, requirement_ids: list[str] | None = None) -> dict[str, Any]:
"""Read the last report and current output version; filter checks after a context reset."""
history = self.history()
contract, digest, lineage = self._contract_with_lineage()
version = game_version(self.candidate)[0]
catalog = self.requirement_catalog(contract)
def selection(checks):
filtered = [r for r in checks if (not status or r["status"] == status)
and (not requirement_ids or r["requirement_id"] in requirement_ids)]
ids = {r["requirement_id"] for r in filtered}
return {"checks": filtered, "requirements": [r for r in catalog if r["id"] in ids],
"taxonomy_diagnostics": self.taxonomy_diagnostics(catalog, checks)}
# Score with the current catalog and dependencies, so older snapshots get them too.
scoring = {"requirements": catalog, "requirement_dependencies": contract.get("requirement_dependencies") or []}
if not history:
seed = self._seed(contract)
seed.update(created_at=None, build_version=version, **scoring)
_measured_by_probes(seed["checks"], contract, self.candidate, version, seed.setdefault("attachment_errors", []))
return {"snapshot_id": "", "current_version": version, "progress": summarize(seed, self.target(), strict=self.strict()),
**selection(seed["checks"]), "captures": []}
latest = deepcopy(history[-1])
requirements_changed = self._reconcile_requirements(latest, contract, digest, lineage)
changed = version != latest["build_version"]
# Probed requirements take their status from the probes on the build as it stands.
latest.setdefault("attachment_errors", [])
_measured_by_probes(latest["checks"], contract, self.candidate, version, latest["attachment_errors"])
latest.update(scoring)
latest["progress"] = summarize(latest, self.target(), strict=self.strict())
latest["progress"]["unreportedVersion"] = changed
latest["progress"]["unreportedRequirements"] = requirements_changed
return {**self._response(latest), "current_version": version,
**selection(latest["checks"]),
"runtime_checks": latest["runtime_checks"]}
def references(self, archive: bool = False) -> list[dict[str, Any]]:
history = self.history()
saved = history[-1].get("references", []) if history else []
if saved and all(not r["media_id"].startswith("ref-") for r in saved):
return deepcopy(saved)
contract, _ = self.contract()
result = []
evidence = list(contract.get("evidence", []))
if (self.run / "development-inputs.json").is_file():
images = self.run / "public-inputs"
evidence.extend({"id": "development-" + _hash(p.relative_to(images).as_posix().encode()),
"frame_path": p.relative_to(images).as_posix(),
"description": p.name}
for p in sorted(images.rglob("*")) if p.is_file() and p.suffix.lower() in IMAGE_SUFFIXES | {".webm", ".mp4"})
for item in evidence:
relative = item.get("frame_path")
if not relative:
continue
for prefix in ("public-inputs/video_agent", "candidate/reference_screenshots/video_agent", "public-inputs"):
if not (self.run / prefix / relative).is_file(): # cheap; resolving a missing path is not
continue
path = _inside(self.run, Path(prefix) / relative)
if path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES | {".webm", ".mp4"}:
legacy_id = "ref-" + _hash(path.relative_to(self.run).as_posix().encode())
reference = {"id": item["id"], "label": item.get("description", item["id"]),
"media_id": legacy_id, "timestamp_seconds": item.get("timestamp_seconds")}
if path.suffix.lower() in {".webm", ".mp4"}:
reference["kind"] = "video"
if archive and reference.get("kind") != "video":
reference.update(media_id=self._save_media(path.read_bytes(), path.suffix.lower()), legacy_media_id=legacy_id)
else:
reference["path"] = str(path)
size = item.get("image_size")
if isinstance(size, list) and len(size) == 2:
reference.update(width=size[0], height=size[1])
result.append(reference)
break
return result
def list_snapshots(self) -> dict[str, Any]:
history = self.history()
latest = history[-1] if history else {}
result = {"snapshots": [self.summary(s) for s in reversed(history)],
"current_version": None, "latest_snapshot_id": latest.get("snapshot_id"),
"requirements": deepcopy(latest.get("requirements", [])),
"references": deepcopy(latest.get("references", []))}
errors = []
try:
contract, digest, lineage = self._contract_with_lineage()
if latest:
self._reconcile_requirements(deepcopy(latest), contract, digest, lineage)
result["requirements"] = self.requirement_catalog(contract)
if contract.get("generated_fallback"):
result["notice"] = "One broad recreation requirement: progress is 0% or 100%. Runtime checks are reported separately."
result["references"] = [{k: v for k, v in r.items() if k != "path"} for r in self.references()]
except (OSError, ValueError) as exc:
errors.append(f"Current requirements unavailable: {exc}")
try:
result["current_version"] = game_version(self.candidate)[0]
except (OSError, ValueError) as exc:
errors.append(f"Current game version unavailable: {exc}")
if errors:
result["error"] = "; ".join(errors)
return result
def snapshot(self, snapshot_id: str) -> dict[str, Any]:
for snapshot in self.history():
if snapshot["snapshot_id"] == snapshot_id:
return deepcopy(snapshot)
raise BuilderProgressError("Progress snapshot was not found")
def _verified_media(self, media_id: str) -> Path:
if re.fullmatch(r"[0-9a-f]{64}(?:\.[a-zA-Z0-9_-]+)?", media_id):
path = _inside(self.store, "media/" + media_id)
if path.is_file():
return path
raise BuilderProgressError("Progress attachment file is unavailable")
def media(self, media_id: str) -> Path:
if media_id.startswith("ref-"):
for snapshot in reversed(self.history()):
for reference in snapshot.get("references", []):
if reference.get("legacy_media_id") == media_id:
return self._verified_media(reference["media_id"])
for reference in self.references():
if reference["media_id"] == media_id:
return _inside(self.run, reference["path"])
elif re.fullmatch(r"[0-9a-f]{64}(?:\.[a-zA-Z0-9_-]+)?", media_id):
registered = any(any(c["media_id"] == media_id for c in s["captures"])
or any(a.get("media_id", a["artifact_id"]) == media_id for a in s["artifacts"])
or any(r["media_id"] == media_id for r in s.get("references", [])) for s in self.history())
if registered:
return self._verified_media(media_id)
raise BuilderProgressError("Progress media was not found")
def _render_preview(job: dict[str, Any]) -> None:
"""Body of the preview child process: load the build once and screenshot it."""
from playwright.sync_api import sync_playwright
from bench_builder.webgame_playwright import _serve, _install_network_guard
with _serve(Path(job["output"])) as url, sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
try:
context = browser.new_context(viewport={"width": job["width"], "height": job["height"]},
service_workers="block")
_install_network_guard(context, origin=url, diagnostics=[])
page = context.new_page()
page.goto(url, wait_until="load", timeout=15000)
page.wait_for_timeout(job["wait_ms"])
page.screenshot(path=job["path"], timeout=15000)
finally:
browser.close()
def main(argv: list[str] | None = None) -> int:
argv = sys.argv[1:] if argv is None else argv
if len(argv) != 2 or argv[0] != "--render-preview":
print("usage: python -m bench_builder.builder_progress --render-preview <job-json>", file=sys.stderr)
return 2
try:
_render_preview(json.loads(argv[1]))
except Exception as exc: # the parent shows the last stderr line to the agent
print(f"{type(exc).__name__}: {str(exc)[:500]}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())