Przeglądaj źródła

build: bind harness to generated source closure

Codex Resource Selftest 4 miesięcy temu
rodzic
commit
4657603cc2
2 zmienionych plików z 147 dodań i 58 usunięć
  1. 105 35
      tools/codex_harness.py
  2. 42 23
      tools/prod2u_p4_normal_v3_build.py

+ 105 - 35
tools/codex_harness.py

@@ -5,6 +5,7 @@ from __future__ import annotations
 
 import hashlib
 import json
+import os
 import re
 import shutil
 import subprocess
@@ -18,7 +19,6 @@ 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}$")
 SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
-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"}
@@ -26,28 +26,7 @@ AGENT_SELECTION_SOURCES = frozenset(
 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 = (
-    "src/generated/prod2u_door_temp_params.vh",
-    "src/common/uart_rx_byte.v",
-    "src/common/uart_tx_byte.v",
-    "src/common/crc16_serial.v",
-    "src/common/frame_rx.v",
-    "src/common/frame_tx.v",
-    "src/common/payload_ram.v",
-    "src/modules/output_target_ram.v",
-    "src/modules/pwm_scheduler.v",
-    "src/modules/shared_500us_tick.v",
-    "src/modules/host_watchdog.v",
-    "src/modules/door_motor_engine.v",
-    "src/modules/i2c_word_reader.v",
-    "src/modules/temperature_reader.v",
-    "src/modules/temperature_ram.v",
-    "src/project/command_controller.v",
-    "src/project/project_adapter.v",
-    "src/rtl/prod2u_por.v",
-    "src/rtl/prod2u_p4_i2c_stop_start_read.v",
-    "src/top/prod2u_p4_normal_v3_top.v",
-)
+SOURCE_MANIFEST_PATH = Path("src/generated/td-source-manifest.json")
 PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md")
 REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md")
 VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json")
@@ -130,7 +109,10 @@ def _canonical_sha256(value: Mapping[str, Any]) -> str:
 
 
 def _repo_root(root: Path | None = None) -> Path:
-    return Path(root or Path(__file__).resolve().parents[1]).resolve()
+    candidate = Path(root or Path(__file__).resolve().parents[1]).expanduser().resolve()
+    if not candidate.is_dir():
+        raise ValueError(f"repository root is not a directory: {candidate}")
+    return candidate
 
 
 def _run_git(
@@ -147,6 +129,7 @@ def _run_git(
         raise ValueError("git args must be a non-empty sequence of non-empty strings")
     return subprocess.run(
         ["git", "-C", str(_repo_root(root)), *values],
+        cwd=_repo_root(root),
         capture_output=True,
         check=check,
         shell=False,
@@ -158,22 +141,80 @@ def _run_git(
 def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
     repo = _repo_root(root)
     project_path = repo / PROJECT_PATH
-    missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()]
+    generated_path = repo / SOURCE_MANIFEST_PATH
+    try:
+        generated = json.loads(generated_path.read_text(encoding="utf-8-sig"))
+    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+        raise ValueError(f"generated source manifest is not readable: {generated_path}") from exc
+    if not isinstance(generated, Mapping) or not isinstance(generated.get("sources"), list):
+        raise ValueError("generated source manifest has no sources list")
+    source_paths = []
+    for value in generated["sources"]:
+        if not isinstance(value, str) or not value:
+            raise ValueError("generated source manifest contains an invalid path")
+        candidate = Path(value)
+        if candidate.is_absolute() or ".." in candidate.parts:
+            raise ValueError(f"generated source manifest contains unsafe path: {value}")
+        source_paths.append(candidate.as_posix())
+    if len(source_paths) != len(set(source_paths)):
+        raise ValueError("generated source manifest contains duplicate paths")
+    missing = [path for path in source_paths if not (repo / path).is_file()]
     if missing:
         raise FileNotFoundError(f"missing active source: {missing[0]}")
-    source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS}
+    source_hashes = {path: sha256_file(repo / path) for path in source_paths}
     payload = {
         "schema": "prod2u-simple-source-manifest-v1",
         "project_id": PROJECT_ID,
         "project": PROJECT_PATH.as_posix(),
         "project_sha256": sha256_file(project_path),
-        "sources": list(SOURCE_PATHS),
+        "generated_source_manifest": SOURCE_MANIFEST_PATH.as_posix(),
+        "generated_source_manifest_sha256": sha256_file(generated_path),
+        "sources": source_paths,
         "source_sha256": source_hashes,
     }
     payload["manifest_sha256"] = _canonical_sha256(payload)
     return payload
 
 
+def _git_identity(root: Path) -> dict[str, str]:
+    repo = _repo_root(root)
+    top = _run_git(repo, ["rev-parse", "--show-toplevel"]).stdout.decode("utf-8", "strict").strip()
+    branch = _run_git(repo, ["branch", "--show-current"]).stdout.decode("utf-8", "strict").strip()
+    head = _run_git(repo, ["rev-parse", "HEAD"]).stdout.decode("ascii", "strict").strip().lower()
+    actual_root = Path(top).expanduser().resolve()
+    if actual_root != repo:
+        raise ValueError(f"worktree root mismatch: expected {repo}, git reports {actual_root}")
+    if not FULL_COMMIT_RE.fullmatch(head):
+        raise ValueError("worktree HEAD is not a full commit")
+    return {"root": str(actual_root), "branch": branch, "head": head}
+
+
+def validate_worktree_identity(
+    root: Path,
+    *,
+    expected_branch: str | None = None,
+    expected_head: str | None = None,
+    assigned_base_commit: str | None = None,
+    protected_root: Path | None = None,
+) -> dict[str, str]:
+    identity = _git_identity(root)
+    protected_value = protected_root or os.environ.get("PROD2U_PROTECTED_REPO_ROOT")
+    if protected_value and Path(protected_value).expanduser().resolve() == Path(identity["root"]):
+        raise ValueError("protected_worktree_violation: writes are forbidden in protected repository")
+    if expected_branch is not None and identity["branch"] != expected_branch:
+        raise ValueError("worktree branch does not match expected branch")
+    if expected_head is not None:
+        _validate_full_commit(expected_head, "expected_head")
+        if identity["head"] != expected_head:
+            raise ValueError("worktree HEAD does not match expected HEAD")
+    if assigned_base_commit is not None:
+        _validate_full_commit(assigned_base_commit, "assigned_base_commit")
+        ancestry = _run_git(Path(identity["root"]), ["merge-base", "--is-ancestor", assigned_base_commit, identity["head"]], check=False)
+        if ancestry.returncode != 0:
+            raise ValueError("assigned base is not an ancestor of worktree HEAD")
+    return identity
+
+
 def current_commit8(root: Path | None = None) -> str:
     repo = _repo_root(root)
     result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"])
@@ -306,10 +347,18 @@ def validate_agent_task_report(
         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"]:
+    feature_branch = report.get("feature_branch")
+    if not isinstance(feature_branch, str) or not feature_branch.strip():
         raise ValueError("feature_branch must be non-empty")
-    if not isinstance(report.get("worktree"), str) or not report["worktree"]:
+    worktree = report.get("worktree")
+    if not isinstance(worktree, str) or not worktree.strip():
         raise ValueError("worktree must be non-empty")
+    report_worktree = Path(worktree).expanduser().resolve()
+    identity = validate_worktree_identity(
+        report_worktree,
+        expected_branch=feature_branch,
+        assigned_base_commit=assigned_base,
+    )
     status = report.get("status")
     if status not in AGENT_TASK_STATUSES:
         raise ValueError("unsupported agent task status")
@@ -321,6 +370,8 @@ def validate_agent_task_report(
         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"]
+        if task_id in dependency_map:
+            raise ValueError(f"duplicate dependency task_id: {task_id}")
         result_commit = _validate_full_commit(
             dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True
         )
@@ -348,22 +399,35 @@ def validate_agent_task_report(
         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):
+    if result_commit is None and not (
+        (isinstance(read_only_report, str) and read_only_report.strip())
+        or isinstance(read_only_report, Mapping)
+    ):
         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 result_commit is not None:
+        resolved = _run_git(report_worktree, ["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")
+        if identity["head"] != result_commit:
+            raise ValueError("report result_commit does not match report worktree HEAD")
         ancestry = _run_git(
-            root,
+            report_worktree,
             ["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)
+        changed_paths_for_result(report_worktree, 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}}"])
+        if result_commit is not None:
+            ancestry = _run_git(
+                root,
+                ["merge-base", "--is-ancestor", result_commit, integration_commit],
+                check=False,
+            )
+            if ancestry.returncode != 0:
+                raise ValueError("integration commit does not contain result commit")
     return dict(report)
 
 
@@ -417,7 +481,13 @@ def init_run(run_id: str, root: Path | None = None) -> Path:
             "run_id": run_id,
             "project_id": PROJECT_ID,
             "status": "DESIGN_FROZEN",
-            "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md",
+            "authority": [
+                PROJECT_PATH.as_posix(),
+                REQUIREMENTS_PATH.as_posix(),
+                PROTOCOL_PATH.as_posix(),
+                SOURCE_MANIFEST_PATH.as_posix(),
+            ],
+            "source_binding": build_source_manifest(repo),
             "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
         },
     )

+ 42 - 23
tools/prod2u_p4_normal_v3_build.py

@@ -21,28 +21,46 @@ SYNTHESIS_INPUT_SCHEMA = "prod2u-simple-synthesis-inputs-v2"
 TARGET_DEVICE = "EF2L45BG256B"
 PROJECT_CONFIG_PATH = "projects/prod2u-door-temp/project.json"
 TD_SOURCE_MANIFEST_PATH = "src/generated/td-source-manifest.json"
-PRODUCTION_RTL_SOURCES = (
-    "src/generated/prod2u_door_temp_params.vh",
-    "src/common/uart_rx_byte.v",
-    "src/common/uart_tx_byte.v",
-    "src/common/crc16_serial.v",
-    "src/common/frame_rx.v",
-    "src/common/frame_tx.v",
-    "src/common/payload_ram.v",
-    "src/modules/output_target_ram.v",
-    "src/modules/pwm_scheduler.v",
-    "src/modules/shared_500us_tick.v",
-    "src/modules/host_watchdog.v",
-    "src/modules/door_motor_engine.v",
-    "src/modules/i2c_word_reader.v",
-    "src/modules/temperature_reader.v",
-    "src/modules/temperature_ram.v",
-    "src/project/command_controller.v",
-    "src/project/project_adapter.v",
-    "src/rtl/prod2u_por.v",
-    "src/rtl/prod2u_p4_i2c_stop_start_read.v",
-    "src/top/prod2u_p4_normal_v3_top.v",
-)
+REPOSITORY_ROOT = Path(__file__).resolve().parents[1]
+
+
+def _source_manifest_path(root: Path | None = None) -> Path:
+    return Path(root or REPOSITORY_ROOT).resolve() / TD_SOURCE_MANIFEST_PATH
+
+
+def load_source_manifest(root: Path | None = None) -> dict[str, Any]:
+    """Load the generated source closure; consumers must not maintain a copy."""
+
+    path = _source_manifest_path(root)
+    try:
+        value = json.loads(path.read_text(encoding="utf-8-sig"))
+    except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+        raise ValueError(f"source manifest is not readable: {path}") from exc
+    if not isinstance(value, dict):
+        raise ValueError("source manifest root must be an object")
+    sources = value.get("sources")
+    if not isinstance(sources, list) or not sources:
+        raise ValueError("source manifest sources must be a non-empty list")
+    normalized: list[str] = []
+    for source in sources:
+        if not isinstance(source, str) or not source:
+            raise ValueError("source manifest contains an invalid source path")
+        candidate = Path(source)
+        if candidate.is_absolute() or ".." in candidate.parts:
+            raise ValueError(f"source manifest contains unsafe path: {source}")
+        normalized.append(candidate.as_posix())
+    if len(normalized) != len(set(normalized)):
+        raise ValueError("source manifest contains duplicate source paths")
+    value["sources"] = normalized
+    return value
+
+
+def active_source_paths(root: Path | None = None) -> tuple[str, ...]:
+    return tuple(load_source_manifest(root)["sources"])
+
+
+# Compatibility export for existing callers. The generated manifest is authoritative.
+PRODUCTION_RTL_SOURCES = active_source_paths()
 
 
 def _write_json(path: Path, payload: Mapping[str, Any]) -> None:
@@ -95,7 +113,7 @@ def build_synthesis_input_manifest(
     """Hash the exact source, constraint, and TD inputs used by production."""
 
     source_root = Path(root).resolve()
-    rtl = list(PRODUCTION_RTL_SOURCES)
+    rtl = list(active_source_paths(source_root))
     fixed = [
         "constraints/prod2u_p4_normal_v3.adc",
         "constraints/prod2u_p4_normal_v3.sdc",
@@ -126,6 +144,7 @@ def build_synthesis_input_manifest(
         "project_config_sha256": inputs[PROJECT_CONFIG_PATH],
         "td_source_manifest_path": TD_SOURCE_MANIFEST_PATH,
         "td_source_manifest_sha256": inputs[TD_SOURCE_MANIFEST_PATH],
+        "source_manifest_authority": "generated",
         "sha256": _canonical_sha256(manifest_binding),
     }