Browse Source

harness: record native agent ownership and stale results

Codex Resource Selftest 4 months ago
parent
commit
6f59ea8e7d
2 changed files with 442 additions and 10 deletions
  1. 194 0
      tests/unit/test_codex_harness.py
  2. 248 10
      tools/codex_harness.py

+ 194 - 0
tests/unit/test_codex_harness.py

@@ -1,8 +1,10 @@
 import hashlib
 import json
+import subprocess
 import tempfile
 import unittest
 from pathlib import Path
+from unittest.mock import patch
 
 from tools import codex_harness
 from tools import prod2u_p4_harness
@@ -167,6 +169,198 @@ class CodexHarnessTests(unittest.TestCase):
             sorted(manifest["layers"]["icarus"]),
         )
 
+    def test_agent_task_report_accepts_unconstrained_observations_and_full_commits(self):
+        base = "aae04014eb520a815438de051950c014bd9ea9c6"
+        report = {
+            "schema": codex_harness.AGENT_TASK_REPORT_SCHEMA,
+            "run_id": "d" * 32,
+            "task_id": "capability_probe",
+            "dependencies": [],
+            "assigned_base_commit": base,
+            "result_commit": base,
+            "integration_commit": None,
+            "feature_branch": "codex/phase-0-native-ma-" + "d" * 32,
+            "worktree": str(Path.cwd()),
+            "owned_paths": [],
+            "native_thread": {
+                "model_policy": "unconstrained",
+                "reasoning_effort_policy": "unconstrained",
+                "observed_model": "observed",
+                "observed_reasoning_effort": "observed",
+                "model_selection_source": "unknown",
+                "effort_selection_source": "not_exposed",
+                "observation_source": "thread_metadata",
+                "observed_permission_mode": None,
+            },
+            "status": "completed",
+            "read_only_report": None,
+        }
+        validated = codex_harness.validate_agent_task_report(
+            report,
+            expected_run_id="d" * 32,
+            expected_base_commit=base,
+            root=Path.cwd(),
+        )
+        self.assertEqual(validated["assigned_base_commit"], base)
+
+    def test_agent_task_report_accepts_read_only_report_with_unexposed_observations(self):
+        base = "aae04014eb520a815438de051950c014bd9ea9c6"
+        report = {
+            "schema": codex_harness.AGENT_TASK_REPORT_SCHEMA,
+            "run_id": "e" * 32,
+            "task_id": "repo_process_audit",
+            "dependencies": [],
+            "assigned_base_commit": base,
+            "result_commit": None,
+            "integration_commit": None,
+            "feature_branch": "codex/phase-0-native-ma-" + "e" * 32,
+            "worktree": str(Path.cwd()),
+            "owned_paths": [],
+            "native_thread": {
+                "model_policy": "unconstrained",
+                "reasoning_effort_policy": "unconstrained",
+                "observed_model": None,
+                "observed_reasoning_effort": None,
+                "model_selection_source": "not_exposed",
+                "effort_selection_source": None,
+                "observation_source": "not_exposed",
+                "observed_permission_mode": "not_exposed",
+            },
+            "status": "completed",
+            "read_only_report": "read-only evidence",
+        }
+        validated = codex_harness.validate_agent_task_report(
+            report,
+            expected_run_id="e" * 32,
+            expected_base_commit=base,
+        )
+        self.assertEqual(validated["read_only_report"], "read-only evidence")
+
+    def test_agent_task_report_rejects_stale_assigned_base(self):
+        base = "aae04014eb520a815438de051950c014bd9ea9c6"
+        report = {
+            "schema": codex_harness.AGENT_TASK_REPORT_SCHEMA,
+            "run_id": "f" * 32,
+            "task_id": "stale",
+            "dependencies": [],
+            "assigned_base_commit": "0" * 40,
+            "result_commit": None,
+            "integration_commit": None,
+            "feature_branch": "branch",
+            "worktree": "worktree",
+            "owned_paths": [],
+            "native_thread": {
+                "model_policy": "unconstrained",
+                "reasoning_effort_policy": "unconstrained",
+            },
+            "status": "completed",
+            "read_only_report": "stale",
+        }
+        with self.assertRaisesRegex(ValueError, "stale"):
+            codex_harness.validate_agent_task_report(
+                report,
+                expected_run_id="f" * 32,
+                expected_base_commit=base,
+            )
+
+    def test_agent_task_report_rejects_dependency_mismatch_but_preserves_integration_conflict(self):
+        base = "aae04014eb520a815438de051950c014bd9ea9c6"
+        report = {
+            "schema": codex_harness.AGENT_TASK_REPORT_SCHEMA,
+            "run_id": "1" * 32,
+            "task_id": "dependent",
+            "dependencies": [
+                {
+                    "task_id": "producer",
+                    "result_commit": "2" * 40,
+                    "integration_commit": None,
+                }
+            ],
+            "assigned_base_commit": base,
+            "result_commit": None,
+            "integration_commit": None,
+            "feature_branch": "branch",
+            "worktree": "worktree",
+            "owned_paths": [],
+            "native_thread": {
+                "model_policy": "unconstrained",
+                "reasoning_effort_policy": "unconstrained",
+            },
+            "status": "integration_conflict",
+            "read_only_report": "conflicting paths",
+        }
+        with self.assertRaisesRegex(ValueError, "dependency"):
+            codex_harness.validate_agent_task_report(
+                report,
+                expected_run_id="1" * 32,
+                expected_base_commit=base,
+                expected_dependencies={
+                    "producer": {"result_commit": "3" * 40, "integration_commit": None}
+                },
+            )
+        report["dependencies"][0]["result_commit"] = "3" * 40
+        validated = codex_harness.validate_agent_task_report(
+            report,
+            expected_run_id="1" * 32,
+            expected_base_commit=base,
+            expected_dependencies={
+                "producer": {"result_commit": "3" * 40, "integration_commit": None}
+            },
+        )
+        self.assertEqual(validated["status"], "integration_conflict")
+
+    def test_name_status_z_parses_rename_and_copy_paths(self):
+        events = codex_harness.parse_name_status_z(
+            b"R100\0old.txt\0new.txt\0C100\0source.txt\0copy.txt\0M\0owned.txt\0"
+        )
+        self.assertEqual(
+            events,
+            [
+                ("R100", ("old.txt", "new.txt")),
+                ("C100", ("source.txt", "copy.txt")),
+                ("M", ("owned.txt",)),
+            ],
+        )
+
+    def test_owned_paths_require_exact_files_or_explicit_directory_prefixes(self):
+        events = [("R100", ("tests/unit/old.py", "tests/unit/new.py"))]
+        self.assertEqual(
+            codex_harness.validate_changed_paths(events, ["tests/unit/"]),
+            ["tests/unit/old.py", "tests/unit/new.py"],
+        )
+        with self.assertRaisesRegex(ValueError, "owned"):
+            codex_harness.validate_changed_paths(events, ["tests/unit/old.py"])
+        with self.assertRaisesRegex(ValueError, "path"):
+            codex_harness.validate_changed_paths([("M", ("../outside.py",))], ["tests/"])
+        with self.assertRaisesRegex(ValueError, "glob"):
+            codex_harness.validate_changed_paths(events, ["tests/*.py"])
+
+    def test_agent_receipt_aggregation_preserves_hashes_and_bindings(self):
+        aggregate = codex_harness.aggregate_agent_receipt_bindings(
+            {
+                "unit": {
+                    "verification_run_id": "a" * 32,
+                    "commit": "b" * 40,
+                    "artifact_sha256": "c" * 64,
+                }
+            },
+            expected_run_id="a" * 32,
+            expected_commit="b" * 40,
+        )
+        self.assertEqual(aggregate["receipts"]["unit"]["artifact_sha256"], "c" * 64)
+
+    def test_current_commit8_uses_the_git_wrapper(self):
+        completed = subprocess.CompletedProcess(
+            args=["git"], returncode=0, stdout=b"0123abcd\n", stderr=b""
+        )
+        with patch.object(codex_harness.subprocess, "run", return_value=completed) as run:
+            self.assertEqual(codex_harness.current_commit8(Path.cwd()), "0123abcd")
+        args, kwargs = run.call_args
+        self.assertEqual(args[0][0], "git")
+        self.assertFalse(kwargs["shell"])
+        self.assertFalse(kwargs["text"])
+        self.assertIn("timeout", kwargs)
+
 
 if __name__ == "__main__":
     unittest.main()

+ 248 - 10
tools/codex_harness.py

@@ -10,12 +10,18 @@ import shutil
 import subprocess
 import uuid
 from datetime import datetime, timezone
-from pathlib import Path
-from typing import Any, Mapping
+from pathlib import Path, PurePosixPath
+from typing import Any, Iterable, Mapping, Sequence
 
 
 RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
 COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
+FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
+AGENT_TASK_REPORT_SCHEMA = "prod2u-native-agent-task-report-v1"
+AGENT_SELECTION_SOURCES = frozenset(
+    {"explicit", "inherited", "automatic", "default", "not_exposed", "unknown"}
+)
+AGENT_TASK_STATUSES = frozenset({"completed", "blocked", "failed", "integration_conflict"})
 PROJECT_ID = "prod2u-door-temp"
 PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
 SOURCE_PATHS = (
@@ -123,6 +129,28 @@ def _repo_root(root: Path | None = None) -> Path:
     return Path(root or Path(__file__).resolve().parents[1]).resolve()
 
 
+def _run_git(
+    root: Path,
+    args: Sequence[str],
+    *,
+    timeout_seconds: float = 10.0,
+    check: bool = True,
+) -> subprocess.CompletedProcess[bytes]:
+    if timeout_seconds <= 0:
+        raise ValueError("timeout_seconds must be positive")
+    values = [str(value) for value in args]
+    if not values or any(not value for value in values):
+        raise ValueError("git args must be a non-empty sequence of non-empty strings")
+    return subprocess.run(
+        ["git", "-C", str(_repo_root(root)), *values],
+        capture_output=True,
+        check=check,
+        shell=False,
+        text=False,
+        timeout=timeout_seconds,
+    )
+
+
 def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
     repo = _repo_root(root)
     project_path = repo / PROJECT_PATH
@@ -144,19 +172,229 @@ def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
 
 def current_commit8(root: Path | None = None) -> str:
     repo = _repo_root(root)
-    result = subprocess.run(
-        ["git", "rev-parse", "--short=8", "HEAD"],
-        cwd=repo,
-        check=True,
-        capture_output=True,
-        text=True,
-    )
-    commit = result.stdout.strip().lower()
+    result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"])
+    commit = result.stdout.decode("ascii").strip().lower()
     if not COMMIT_RE.fullmatch(commit):
         raise ValueError(f"unexpected commit: {commit}")
     return commit
 
 
+def _validate_full_commit(value: Any, field: str, *, allow_none: bool = False) -> str | None:
+    if value is None and allow_none:
+        return None
+    if not isinstance(value, str) or not FULL_COMMIT_RE.fullmatch(value):
+        raise ValueError(f"{field} must be a 40-character lowercase hexadecimal commit")
+    return value
+
+
+def _validate_observation_fields(native_thread: Mapping[str, Any]) -> None:
+    if native_thread.get("model_policy") != "unconstrained":
+        raise ValueError("native_thread.model_policy must be unconstrained")
+    if native_thread.get("reasoning_effort_policy") != "unconstrained":
+        raise ValueError("native_thread.reasoning_effort_policy must be unconstrained")
+    for field in ("model_selection_source", "effort_selection_source"):
+        value = native_thread.get(field)
+        if value is not None and value not in AGENT_SELECTION_SOURCES:
+            raise ValueError(f"{field} has an unsupported selection source")
+    observation_source = native_thread.get("observation_source")
+    if observation_source is not None and not isinstance(observation_source, str):
+        raise ValueError("observation_source must be a string or null")
+    for field in ("observed_model", "observed_reasoning_effort", "observed_permission_mode"):
+        value = native_thread.get(field)
+        if value is not None and not isinstance(value, str):
+            raise ValueError(f"{field} must be a string or null")
+
+
+def _normalise_repo_path(value: Any, *, owned: bool = False) -> str:
+    if not isinstance(value, str) or not value:
+        raise ValueError("path must be a non-empty string")
+    raw = value.replace("\\", "/")
+    if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
+        raise ValueError(f"path must be relative: {value}")
+    if any(part == ".." for part in PurePosixPath(raw).parts):
+        raise ValueError(f"path contains parent traversal: {value}")
+    normalised = PurePosixPath(raw).as_posix()
+    if normalised in {"", "."}:
+        raise ValueError(f"path is not a file or directory: {value}")
+    if owned and any(token in normalised for token in "*?["):
+        raise ValueError("owned paths must not contain glob syntax")
+    return normalised
+
+
+def _normalise_owned_path(value: Any) -> str:
+    directory = isinstance(value, str) and value.replace("\\", "/").endswith("/")
+    normalised = _normalise_repo_path(value, owned=True)
+    return normalised.rstrip("/") + "/" if directory else normalised
+
+
+def parse_name_status_z(payload: bytes) -> list[tuple[str, tuple[str, ...]]]:
+    tokens = payload.split(b"\0")
+    if tokens and tokens[-1] == b"":
+        tokens.pop()
+    events: list[tuple[str, tuple[str, ...]]] = []
+    index = 0
+    while index < len(tokens):
+        try:
+            status = tokens[index].decode("utf-8", "surrogateescape")
+        except UnicodeDecodeError as exc:
+            raise ValueError("git status contains undecodable status") from exc
+        index += 1
+        if not status:
+            raise ValueError("git status contains an empty status")
+        path_count = 2 if status[0] in {"R", "C"} else 1
+        if index + path_count > len(tokens):
+            raise ValueError("git status has an incomplete path record")
+        paths = tuple(token.decode("utf-8", "surrogateescape") for token in tokens[index : index + path_count])
+        events.append((status, paths))
+        index += path_count
+    return events
+
+
+def validate_changed_paths(
+    events: Iterable[tuple[str, Iterable[str]]],
+    owned_paths: Iterable[str],
+) -> list[str]:
+    owned = [_normalise_owned_path(path) for path in owned_paths]
+    changed: list[str] = []
+    for _status, raw_paths in events:
+        for raw_path in raw_paths:
+            path = _normalise_repo_path(raw_path)
+            changed.append(path)
+            if not any(
+                path == candidate
+                or (candidate.endswith("/") and path.startswith(candidate))
+                for candidate in owned
+            ):
+                raise ValueError(f"changed path is outside owned paths: {path}")
+    return changed
+
+
+def changed_paths_for_result(
+    root: Path,
+    assigned_base_commit: str,
+    result_commit: str,
+    owned_paths: Iterable[str],
+) -> list[str]:
+    _validate_full_commit(assigned_base_commit, "assigned_base_commit")
+    _validate_full_commit(result_commit, "result_commit")
+    result = _run_git(
+        root,
+        ["diff", "--name-status", "-z", "--find-renames", assigned_base_commit, result_commit],
+    )
+    return validate_changed_paths(parse_name_status_z(result.stdout), owned_paths)
+
+
+def validate_agent_task_report(
+    report: Mapping[str, Any],
+    *,
+    expected_run_id: str,
+    expected_base_commit: str,
+    root: Path | None = None,
+    expected_dependencies: Mapping[str, Mapping[str, str | None]] | None = None,
+) -> dict[str, Any]:
+    if report.get("schema") != AGENT_TASK_REPORT_SCHEMA:
+        raise ValueError("unexpected agent task report schema")
+    if not RUN_ID_RE.fullmatch(expected_run_id) or report.get("run_id") != expected_run_id:
+        raise ValueError("run_id mismatch")
+    _validate_full_commit(expected_base_commit, "expected_base_commit")
+    assigned_base = _validate_full_commit(report.get("assigned_base_commit"), "assigned_base_commit")
+    if assigned_base != expected_base_commit:
+        raise ValueError("stale assigned base mismatch")
+    if not isinstance(report.get("task_id"), str) or not report["task_id"]:
+        raise ValueError("task_id must be non-empty")
+    if not isinstance(report.get("feature_branch"), str) or not report["feature_branch"]:
+        raise ValueError("feature_branch must be non-empty")
+    if not isinstance(report.get("worktree"), str) or not report["worktree"]:
+        raise ValueError("worktree must be non-empty")
+    status = report.get("status")
+    if status not in AGENT_TASK_STATUSES:
+        raise ValueError("unsupported agent task status")
+    dependencies = report.get("dependencies", [])
+    if not isinstance(dependencies, list):
+        raise ValueError("dependencies must be a list")
+    dependency_map: dict[str, dict[str, str | None]] = {}
+    for dependency in dependencies:
+        if not isinstance(dependency, Mapping) or not isinstance(dependency.get("task_id"), str):
+            raise ValueError("dependency entries must contain task_id")
+        task_id = dependency["task_id"]
+        result_commit = _validate_full_commit(
+            dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True
+        )
+        integration_commit = _validate_full_commit(
+            dependency.get("integration_commit"),
+            f"dependency {task_id} integration_commit",
+            allow_none=True,
+        )
+        dependency_map[task_id] = {
+            "result_commit": result_commit,
+            "integration_commit": integration_commit,
+        }
+    if expected_dependencies is not None and dependency_map != dict(expected_dependencies):
+        raise ValueError("stale dependency mismatch")
+    native_thread = report.get("native_thread")
+    if not isinstance(native_thread, Mapping):
+        raise ValueError("native_thread must be an object")
+    _validate_observation_fields(native_thread)
+    owned_paths = report.get("owned_paths", [])
+    if not isinstance(owned_paths, list):
+        raise ValueError("owned_paths must be a list")
+    [_normalise_owned_path(path) for path in owned_paths]
+    result_commit = _validate_full_commit(report.get("result_commit"), "result_commit", allow_none=True)
+    integration_commit = _validate_full_commit(
+        report.get("integration_commit"), "integration_commit", allow_none=True
+    )
+    read_only_report = report.get("read_only_report")
+    if result_commit is None and (not isinstance(read_only_report, str) or not read_only_report):
+        raise ValueError("task report requires result_commit or read_only_report")
+    if root is not None and result_commit is not None:
+        resolved = _run_git(root, ["rev-parse", "--verify", f"{result_commit}^{{commit}}"]).stdout
+        if resolved.decode("ascii", "strict").strip().lower() != result_commit:
+            raise ValueError("result commit does not resolve to the supplied full SHA")
+        ancestry = _run_git(
+            root,
+            ["merge-base", "--is-ancestor", assigned_base, result_commit],
+            check=False,
+        )
+        if ancestry.returncode != 0:
+            raise ValueError("stale result commit is not based on assigned base")
+        changed_paths_for_result(root, assigned_base, result_commit, owned_paths)
+    if root is not None and integration_commit is not None:
+        _run_git(root, ["rev-parse", "--verify", f"{integration_commit}^{{commit}}"])
+    return dict(report)
+
+
+def aggregate_agent_receipt_bindings(
+    receipts: Mapping[str, Mapping[str, Any]],
+    *,
+    expected_run_id: str,
+    expected_commit: str,
+) -> dict[str, Any]:
+    if not RUN_ID_RE.fullmatch(expected_run_id):
+        raise ValueError("expected_run_id must be 32 lowercase hexadecimal characters")
+    aggregate: dict[str, Any] = {
+        "schema": "prod2u-native-agent-receipt-aggregate-v1",
+        "run_id": expected_run_id,
+        "commit": expected_commit,
+        "receipts": {},
+    }
+    for name, receipt in receipts.items():
+        if not isinstance(receipt, Mapping):
+            raise ValueError(f"receipt must be an object: {name}")
+        observed_run_id = receipt.get("verification_run_id", receipt.get("run_id"))
+        if observed_run_id != expected_run_id:
+            raise ValueError(f"receipt run_id mismatch: {name}")
+        if receipt.get("commit") != expected_commit:
+            raise ValueError(f"receipt commit mismatch: {name}")
+        hashes: dict[str, str] = {}
+        for field, value in receipt.items():
+            if field.endswith("_sha256"):
+                if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
+                    raise ValueError(f"receipt hash is invalid: {name}.{field}")
+                hashes[field] = value
+        aggregate["receipts"][name] = hashes
+    return aggregate
+
+
 def _write_json(path: Path, value: Mapping[str, Any]) -> None:
     Path(path).parent.mkdir(parents=True, exist_ok=True)
     Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")