"""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 = "", 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 \n{cli} update --request -\n```\n" "Replace 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())