Recreate-AAA / bench_builder /builder_progress_tools.py
CharlieDreemur's picture
Sync with Recreate-AAA/Recreate-AAA@937b1cb
3d79c01 verified
Raw History Blame Contribute Delete
17 kB
"""Run-bound Builder progress MCP/CLI adapters and prompt materialization."""
from __future__ import annotations
import argparse
from functools import wraps
import hashlib
import inspect
import json
import os
from pathlib import Path
import shlex
import sys
from typing import Any, Literal
# Harnesses launch this absolute file from the candidate, outside the repository.
if not __package__:
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
_BINDING_MARKER = "<!-- builder-progress-mcp: "
_SKILL_SOURCE = Path(__file__).resolve().parents[1] / "skills/builder-progress/SKILL.md"
_CAPTURE_SUGGESTION = (
"Optional: attach several current-version screenshots to each progress report when useful, "
"showing the beginning, middle and ending/outcome of the gameplay or verification segment "
"you actually exercised. Use captures with descriptive labels and capture times. "
"Zero, one or many screenshots are accepted; missing stages never block a report. "
"Do not replay the entire game merely for this suggestion or invent an unvisited ending."
)
# These harnesses execute tools against the live local candidate. DSH is local,
# but builds in a separate copy until the turn ends.
# Recreate-AAA: the builds `recreate build` prepares, whose tools run as local servers (`recreate tool`).
LOCAL_BUILDER_PROGRESS_HARNESSES = frozenset({"own-agent"})
class BuilderProgressTools:
"""Keep the public transport schema independent of service implementation details."""
def __init__(self, service: Any):
self.service = service
def get_progress(
self, status: str | None = None, requirement_ids: list[str] | None = None,
detail: Literal["summary", "full"] = "summary",
) -> dict[str, Any]:
"""Read compact progress, versions and check IDs/statuses on resume.
Pass requirement_ids to read the complete selected checks and requirements.
detail='full' returns the full catalog and evidence metadata without an ID filter.
Summary mode changes only this response, never the stored checks or scoring.
"""
if detail not in {"summary", "full"}:
raise ValueError("detail must be summary or full")
result = self.service.get_progress(status=status, requirement_ids=requirement_ids)
if detail == "full" or requirement_ids:
return {**result, "capture_suggestion": _CAPTURE_SUGGESTION}
omitted = {"requirements", "taxonomy_diagnostics", "captures", "pending_ids"}
summary = {key: value for key, value in result.items() if key not in omitted}
# One line per requirement was ~20 KB on every resume. Ids are grouped by status instead, and the
# pending ones (every id in game_design.json that is not listed) are only counted.
summary.pop("checks", None)
summary["checks_by_status"] = _by_status(result.get("checks", []), asked=status)
if "taxonomy_diagnostics" in result:
summary["taxonomy_diagnostics"] = {
"invalid_requirement_ids": result["taxonomy_diagnostics"].get("invalid_requirement_ids", [])}
return {**summary, "detail": "summary",
"details_available": "Requirement ids not listed under checks_by_status are pending. Use "
"requirement_ids for complete selected requirements/checks; use "
"detail='full' for the full catalog, evidence and taxonomy diagnostics."}
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 one batch of evidence and checks; the service computes versions/counts.
Reuse request_id only for an identical retry. base_snapshot_id is optional;
batches merge into the latest snapshot. Evidence and version labels are optional
metadata, not acceptance gates. No source or carry-forward audit is required.
checks/runtime_checks/instance_checks use requirement_id, status, reason,
evidence and optional assessment (rechecked or carried_forward). A check that
cites several reference times may add times: {"<time>": passed|partial|failed}.
captures use id (alias), path, label, build_version and optional captured_at.
Optional suggestion: attach several screenshots showing the beginning,
middle and ending/outcome of the segment actually tested, using descriptive
labels. Zero, one or many are accepted; missing stages do not block reports.
This does not require replaying the whole game for every update.
Evidence uses capture_id (alias or returned ID), or path and build_version
for a verification artifact. preview.mode is auto, capture or none.
"""
result = self.service.update_progress(
request_id=request_id, base_snapshot_id=base_snapshot_id, summary=summary,
checks=checks, runtime_checks=runtime_checks, instance_checks=instance_checks,
captures=captures, preview=preview,
)
# The stored snapshot is unchanged; the answer leaves out the lists that only repeat the catalog
# (every pending id, the taxonomy tables): 42 such answers were a sixth of one build's context.
short = {key: value for key, value in result.items() if key not in {"pending_ids", "taxonomy_diagnostics"}}
if "pending_ids" in result:
short["pending_count"] = len(result["pending_ids"])
invalid = (result.get("taxonomy_diagnostics") or {}).get("invalid_requirement_ids")
if invalid:
short["invalid_requirement_ids"] = invalid
return short
def _by_status(checks: list[dict[str, Any]], asked: str | None = None) -> dict[str, Any]:
"""Ids per status; pending ones are only counted unless the caller asked for that status."""
grouped: dict[str, list[str]] = {}
for check in checks:
grouped.setdefault(str(check.get("status") or "pending"), []).append(str(check.get("requirement_id")))
return {status: (len(ids) if status == "pending" != asked else ids) for status, ids in sorted(grouped.items())}
def create_builder_progress_mcp_server(service: Any) -> Any:
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from bench_builder.mcp_annotations import LOCAL_WRITE, READ_ONLY
def expose(method):
@wraps(method)
def call(**kwargs):
try:
return method(**kwargs)
except (OSError, ValueError) as exc:
# Expected validation/conflict errors must reach the agent intact.
raise ToolError(str(exc)) from exc
return call
adapter = BuilderProgressTools(service)
server = MCPServer("builder_progress")
server.tool(name="get_progress", annotations=READ_ONLY)(expose(adapter.get_progress))
server.tool(name="update_progress", annotations=LOCAL_WRITE)(expose(adapter.update_progress))
return server
def builder_progress_mcp_servers(run_dir: Path) -> tuple[dict[str, Any], ...]:
"""Bind only the run root; a changed completion target must not change MCP identity."""
return ({
"name": "builder_progress",
"command": sys.executable,
"args": [str(Path(__file__).resolve()), "--run-dir", str(run_dir.resolve()), "--stdio"],
"env": [],
},)
def _saved_progress_servers(run_dir: Path, plugin_id: str) -> tuple[dict[str, Any], ...]:
"""Reuse existing prompt/config evidence, including before the first tool call."""
from gamedev_bench_harness.acp import normalize_mcp_servers
prompt_path = run_dir / "prompt.md"
prompt = prompt_path.read_text(encoding="utf-8") if prompt_path.is_file() else ""
if _BINDING_MARKER in prompt:
raw = prompt.rsplit(_BINDING_MARKER, 1)[1].split(" -->", 1)[0]
saved = json.loads(raw)
if not isinstance(saved, list) or any(
not isinstance(server, dict) or server.get("name") != "builder_progress"
for server in saved
) or len(saved) > 1:
raise ValueError("saved Builder progress MCP binding is invalid")
return normalize_mcp_servers(tuple(saved))
# acpx already persists the actual tools before starting its provider session.
config_path = run_dir / "agent/video-tools-mcp.json"
if plugin_id in LOCAL_BUILDER_PROGRESS_HARNESSES and config_path.is_file():
saved = json.loads(config_path.read_text(encoding="utf-8"))["mcpServers"]
return tuple(server for server in normalize_mcp_servers(tuple(saved))
if server["name"] == "builder_progress")
return ()
def _shell_command(argv: list[str]) -> str:
if os.name == "nt":
return "& " + " ".join("'" + arg.replace("'", "''") + "'" for arg in argv)
return shlex.join(argv)
def prepare_builder_progress_prompt(
prompt: str, *, run_dir: Path, candidate: Path, public: Path,
plugin_id: str, resume: bool,
) -> tuple[str, tuple[dict[str, Any], ...]]:
"""Call before replacing prompt.md so resumes retain their original tool binding."""
if plugin_id not in LOCAL_BUILDER_PROGRESS_HARNESSES:
return prompt, ()
servers = (_saved_progress_servers(run_dir, plugin_id) if resume
else builder_progress_mcp_servers(run_dir))
skill_path = candidate / ".agents/skills/builder-progress/SKILL.md"
skill = _SKILL_SOURCE.read_text(encoding="utf-8")
skill_path.parent.mkdir(parents=True, exist_ok=True)
skill_path.write_text(skill, encoding="utf-8")
cli = _shell_command([
sys.executable, str(Path(__file__).resolve()), "--run-dir", str(run_dir.resolve()),
])
instructions = skill.split("---", 2)[-1].strip()
if (run_dir / "progress-contract.json").is_file():
instructions += "\nThis run uses progress-contract.json as its fixed requirement contract. Do not replace it.\n"
prompt += (
"\n\n" + instructions + "\n\n"
f"Skill snapshot: `{skill_path.resolve()}`\n"
f"Run root: `{run_dir.resolve()}`\n"
f"Candidate: `{candidate.resolve()}`\n"
f"Public handoff: `{public.resolve()}`\n"
f"Canonical contract: `{(run_dir / 'public-inputs/video_agent/analysis/game_design.json').resolve()}`\n"
f"Contract fallback: `{(candidate / 'game_design.json').resolve()}`\n"
f"Tool-owned latest view: `{(candidate / 'builder_checks.json').resolve()}`\n\n"
+ ("Use MCP server `builder_progress`: `get_progress` and `update_progress`.\n"
if servers else "Use the following CLI through the existing native shell tool.\n")
+ f"CLI ({'PowerShell' if os.name == 'nt' else 'POSIX shell'}):\n"
f"```\n{cli} get\n{cli} get --status pending\n"
f"{cli} update --request <json-path>\n{cli} update --request -\n```\n"
"Replace <json-path> with a quoted path to your batch JSON; '-' reads JSON from stdin. "
"The CLI calls the same service as MCP.\n"
+ _BINDING_MARKER + json.dumps(servers, ensure_ascii=True) + " -->\n"
)
additions = run_dir / "requirement_additions.json"
if additions.is_file() and _has_user_revisions(additions):
contract, _ = _create_service(run_dir).contract()
total = len(contract["observable_requirements"])
scope_sources = (additions, candidate / "USER_REQUIREMENTS_UPDATE.md")
identities = "\n".join(
f"- `{source.resolve()}`: "
+ (f"sha256={hashlib.sha256(source.read_bytes()).hexdigest()}"
if source.is_file() else "missing at prompt preparation")
for source in scope_sources
)
prompt += (
"\n\n## User-expanded requirement scope\n\n"
f"The user has added binding requirements. The effective checklist now has {total} IDs, "
"including the original handoff and all authorized additions. An earlier completed goal "
"or 100% report covered an older scope and does not satisfy this request. "
"On first encounter, read the scope sources in full and inspect the cited supplementary "
"reference. Record their SHA-256 identities and a concise scope summary in your durable "
"checkpoint only after actually reading them. On resume, verify current file identities: "
"when they match that read record, reuse the summary and fetch the complete requirements "
"and reference evidence needed for the next batch; do not concatenate unchanged catalogs "
"again. If a source changed or no read record exists, read it in full before implementation. "
"The fingerprints below describe preparation-time bytes, not proof that you read them. "
"A missing supplementary source remains an explicit evidence gap, never a waived requirement. "
"Use get_progress for the combined denominator and current pending IDs. Preserve the "
"original contract and every addition; never remove, weaken or mark additions unavailable "
"merely because they were not visible in the successful source video. "
"If the previous native goal is already complete, create a new goal for this expanded "
"scope in the same session and candidate. Implement and verify all required additions, "
"publish evidence through update_progress, and meet the current completion target. "
"Completion still requires fresh acceptance evidence for the entire effective scope.\n\n"
"Scope source identities at prompt preparation:\n" + identities + "\n"
)
return prompt, servers
def _has_user_revisions(additions: Path) -> bool:
# Harness-policy revisions (replay-fidelity windows) explain themselves in their own prompt section.
from bench_builder.independent_review import HARNESS_REVISION_ID
try:
revisions = json.loads(additions.read_text(encoding="utf-8-sig")).get("revisions") or []
except (OSError, ValueError, AttributeError):
return True
return any(isinstance(r, dict) and r.get("id") != HARNESS_REVISION_ID for r in revisions)
def _create_service(run_dir: Path) -> Any:
from bench_builder.builder_progress import BuilderProgressService
return BuilderProgressService(run_dir.resolve())
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--run-dir", type=Path, required=True, help="Bound run root, not candidate/")
parser.add_argument("--stdio", action="store_true", help="Serve MCP over stdio (alias for serve)")
commands = parser.add_subparsers(dest="command")
get = commands.add_parser("get", help="Read the latest snapshot and progress")
get.add_argument("--status")
get.add_argument("--requirement-id", action="append", dest="requirement_ids")
get.add_argument("--detail", choices=("summary", "full"), default="summary")
update = commands.add_parser("update", help="Publish a batch JSON object")
update.add_argument("--request", required=True, help="JSON file path, or '-' for stdin")
commands.add_parser("serve", help="Serve MCP over stdio")
args = parser.parse_args(argv)
if (args.stdio and args.command) or (not args.stdio and not args.command):
parser.error("choose get, update, serve, or --stdio")
try:
request = None
if args.command == "update":
request = json.loads(sys.stdin.read() if args.request == "-" else
Path(args.request).read_text(encoding="utf-8-sig"))
if not isinstance(request, dict):
raise ValueError("update request must be a JSON object")
# Reject missing/unknown top-level fields before invoking the service.
inspect.signature(BuilderProgressTools.update_progress).bind(None, **request)
service = _create_service(args.run_dir)
if args.stdio or args.command == "serve":
create_builder_progress_mcp_server(service).run(transport="stdio")
return 0
adapter = BuilderProgressTools(service)
result = (adapter.get_progress(status=args.status, requirement_ids=args.requirement_ids, detail=args.detail)
if args.command == "get" else adapter.update_progress(**request))
print(json.dumps(result, ensure_ascii=True))
return 0
except (OSError, ValueError, TypeError) as exc:
print(json.dumps({"error": str(exc)}, ensure_ascii=True), file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())