#!/usr/bin/env python3 """Canonical evidence selection for review-compact / review-debug packages. Owns: - compact default receipt allowlist - canonical placement under evidence/ - logical alias records (one physical copy) - result-sensitive PASS/FAIL log retention policy Process lane receipts and matrix reruns stay out of review-compact unless ``include_process_evidence`` is set (review-debug enables that by default). """ from __future__ import annotations import fnmatch import hashlib import json import os from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, Iterable ROOT = Path(__file__).resolve().parents[1] DEFAULT_ALLOWLIST_PATH = ROOT / "config" / "review_compact_evidence_allowlist.json" EVIDENCE_CANON_SCHEMA = "cpld-evidence-canon-v1" EVIDENCE_ALIAS_REASON = "canonical_evidence_single_physical_copy" PROCESS_EXCLUDE_RULE = "process_evidence_not_in_compact_allowlist" NON_ALLOWLIST_RECEIPT_RULE = "receipt_not_on_compact_allowlist" LOG_SUMMARY_SUFFIX = ".pass-summary.json" PackageItemFactory = Callable[..., Any] @dataclass(frozen=True) class CanonicalEntry: key: str canonical_path: str match_basenames: tuple[str, ...] match_workspace_paths: tuple[str, ...] match_path_contains: tuple[str, ...] @dataclass(frozen=True) class EvidenceAllowlist: canonical_entries: tuple[CanonicalEntry, ...] process_path_prefixes: tuple[str, ...] process_basename_globs: tuple[str, ...] summary_statuses: frozenset[str] full_statuses: frozenset[str] pass_summary_fields: tuple[str, ...] raw: dict[str, Any] @property def by_key(self) -> dict[str, CanonicalEntry]: return {entry.key: entry for entry in self.canonical_entries} @property def canonical_paths(self) -> frozenset[str]: return frozenset(entry.canonical_path.casefold() for entry in self.canonical_entries) def load_allowlist(path: Path | None = None) -> EvidenceAllowlist: allowlist_path = path or DEFAULT_ALLOWLIST_PATH payload = json.loads(allowlist_path.read_text(encoding="utf-8")) if payload.get("schema") != "cpld-review-compact-evidence-allowlist-v1": raise ValueError(f"unsupported evidence allowlist schema: {payload.get('schema')}") entries: list[CanonicalEntry] = [] for row in payload.get("canonical_entries", []): entries.append( CanonicalEntry( key=str(row["key"]), canonical_path=str(row["canonical_path"]), match_basenames=tuple( str(item).casefold() for item in row.get("match_basenames", []) ), match_workspace_paths=tuple( str(item).casefold() for item in row.get("match_workspace_paths", []) ), match_path_contains=tuple( str(item).casefold() for item in row.get("match_path_contains", []) ), ) ) process = payload.get("process_evidence", {}) log_policy = payload.get("log_policy", {}) return EvidenceAllowlist( canonical_entries=tuple(entries), process_path_prefixes=tuple( str(item).casefold() for item in process.get("path_prefixes", []) ), process_basename_globs=tuple( str(item).casefold() for item in process.get("basename_globs", []) ), summary_statuses=frozenset( str(item).casefold() for item in log_policy.get("summary_statuses", []) ), full_statuses=frozenset( str(item).casefold() for item in log_policy.get("full_statuses", []) ), pass_summary_fields=tuple( str(item) for item in log_policy.get("pass_summary_fields", []) ), raw=payload, ) def _basename(relative: str) -> str: return relative.casefold().rsplit("/", 1)[-1] def _strip_layout_prefix(relative: str) -> str: lower = relative.casefold() for prefix in ("evidence/", "source/", "meta/", "workspace-current/"): if lower.startswith(prefix): return relative[len(prefix) :] return relative def match_canonical_entry( relative: str, allowlist: EvidenceAllowlist, *, workspace_original: str | None = None, ) -> CanonicalEntry | None: original = (workspace_original or _strip_layout_prefix(relative)).casefold() name = _basename(original) package_lower = relative.casefold() # Historical / process trees must not become current via basename coincidence. if is_process_evidence(relative, allowlist) or is_process_evidence(original, allowlist): return None for entry in allowlist.canonical_entries: if original in entry.match_workspace_paths: return entry if package_lower == entry.canonical_path.casefold(): return entry if entry.match_path_contains and any( token in package_lower or token in original for token in entry.match_path_contains ): # Avoid matching unrelated summary.json files. if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower: continue return entry if name in entry.match_basenames: if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower: continue return entry return None def workspace_canonical_path( original_relative: str, allowlist: EvidenceAllowlist | None = None, ) -> str | None: """Map a workspace-relative path onto its compact canonical evidence path.""" allowlist = allowlist or load_allowlist() entry = match_canonical_entry(original_relative, allowlist, workspace_original=original_relative) if entry is None: return None return entry.canonical_path def is_process_evidence(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool: allowlist = allowlist or load_allowlist() lower = relative.casefold() original = _strip_layout_prefix(relative).casefold() name = _basename(original) for prefix in allowlist.process_path_prefixes: if lower.startswith(prefix) or original.startswith(prefix): return True if f"/{prefix.rstrip('/')}/" in f"/{lower}/" or f"/{prefix.rstrip('/')}/" in f"/{original}/": return True for pattern in allowlist.process_basename_globs: if fnmatch.fnmatch(name, pattern): return True # Deep-review rounds are process; summary is canonical. if ("deep-review" in original or "deep-review" in lower) and name.startswith("round-"): return True return False def is_compact_allowlisted(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool: allowlist = allowlist or load_allowlist() return match_canonical_entry(relative, allowlist) is not None def normalize_result_status(status: str | None) -> str: if status is None: return "unknown" return str(status).strip().casefold() def log_retention_for_status( status: str | None, allowlist: EvidenceAllowlist | None = None, ) -> str: """PASS/not_run → summary; FAIL/BLOCKED/TIMEOUT/CRASH → full.""" allowlist = allowlist or load_allowlist() normalized = normalize_result_status(status) if normalized in allowlist.full_statuses: return "full" if normalized in allowlist.summary_statuses: return "summary" # Heuristic for compound statuses like pass_with_warnings. if any(token in normalized for token in ("fail", "blocked", "timeout", "crash", "error")): return "full" if normalized.startswith("pass") or normalized in {"ok", "success", "not_run"}: return "summary" return "full" def build_pass_log_summary( *, source_path: str, status: str, metadata: dict[str, Any] | None = None, allowlist: EvidenceAllowlist | None = None, ) -> dict[str, Any]: allowlist = allowlist or load_allowlist() metadata = dict(metadata or {}) summary: dict[str, Any] = { "schema": "cpld-pass-log-summary-v1", "source_log": source_path, "status": normalize_result_status(status), "retention": "summary", "note": ( "PASS/not_run lanes keep a summary only in review-compact; " "full stdout/stderr is omitted by result-sensitive log policy." ), } for field in allowlist.pass_summary_fields: if field in metadata: summary[field] = metadata[field] return summary def extract_status_from_receipt(path: Path) -> str | None: try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeError, json.JSONDecodeError): return None if not isinstance(payload, dict): return None for key in ("status", "result", "overall_status", "matrix_status"): value = payload.get(key) if isinstance(value, str) and value.strip(): return value lanes = payload.get("lanes") if isinstance(lanes, dict): statuses = [ normalize_result_status(str(item.get("status"))) for item in lanes.values() if isinstance(item, dict) and item.get("status") is not None ] for bad in ("fail", "failed", "blocked", "timeout", "crash", "error"): if bad in statuses: return bad if statuses and all(item in {"pass", "passed", "ok", "success", "not_run"} for item in statuses): return "pass" return None def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _sha256_bytes(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest() def prefer_canonical_path(paths: Iterable[str], allowlist: EvidenceAllowlist | None = None) -> str: """Choose the allowlisted canonical path when present among duplicates.""" allowlist = allowlist or load_allowlist() path_list = list(paths) if not path_list: raise ValueError("prefer_canonical_path requires at least one path") def rank(path: str) -> tuple[int, int, str]: entry = match_canonical_entry(path, allowlist) if entry is not None and path.casefold() == entry.canonical_path.casefold(): return (0, 0, path.casefold()) if entry is not None: return (1, 0, path.casefold()) lower = path.casefold() under_evidence = 0 if lower.startswith("evidence/") else 1 return (2, under_evidence, lower) return sorted(path_list, key=rank)[0] @dataclass class StagedEvidenceFile: absolute: Path relative: str key: str | None original_path: str retention: str | None = None @dataclass class EvidenceCanonResult: staged: list[StagedEvidenceFile] aliases: list[dict[str, Any]] excluded: list[dict[str, str]] log_policy_actions: list[dict[str, Any]] catalog: list[dict[str, Any]] def _candidate_status_for_log(log_path: Path) -> str | None: stem = log_path.name parent = log_path.parent # Prefer sibling *-receipt.json / *.json with matching stem prefix. patterns = [ f"{log_path.stem}-receipt.json", f"{log_path.stem}.json", "formal-receipt.json", "td-primary-receipt.json", "matrix-receipt.json", "verification-matrix-final.json", ] for name in patterns: candidate = parent / name if candidate.is_file(): status = extract_status_from_receipt(candidate) if status is not None: return status for candidate in sorted(parent.glob("*-receipt.json")): status = extract_status_from_receipt(candidate) if status is not None: return status return None def stage_evidence_root( evidence_root: Path, *, staging_root: Path, include_process_evidence: bool = False, allowlist: EvidenceAllowlist | None = None, make_item: PackageItemFactory | None = None, ) -> EvidenceCanonResult: """Stage an external delivery/run evidence tree into canonical evidence/ paths.""" del make_item # packager wraps StagedEvidenceFile itself allowlist = allowlist or load_allowlist() evidence_root = evidence_root.resolve(strict=True) staging_root.mkdir(parents=True, exist_ok=True) # key -> list of (abs, original_rel, sha, size) matched: dict[str, list[tuple[Path, str, str, int]]] = {} process_files: list[tuple[Path, str]] = [] log_actions: list[dict[str, Any]] = [] excluded: list[dict[str, str]] = [] for dirpath, dirnames, filenames in os.walk(evidence_root): dirnames.sort(key=lambda name: name.casefold()) filenames.sort(key=lambda name: name.casefold()) base = Path(dirpath) for filename in filenames: absolute = base / filename if not absolute.is_file() or absolute.is_symlink(): continue original = absolute.relative_to(evidence_root).as_posix() if is_process_evidence(original, allowlist): if include_process_evidence: process_files.append((absolute, original)) else: excluded.append({"path": f"evidence/process/{original}", "rule": PROCESS_EXCLUDE_RULE}) continue entry = match_canonical_entry(original, allowlist, workspace_original=original) if entry is None: # Non-allowlisted evidence stays process-only for compact. if include_process_evidence: process_files.append((absolute, original)) else: excluded.append( { "path": f"evidence/process/{original}", "rule": NON_ALLOWLIST_RECEIPT_RULE, } ) continue sha = _sha256_file(absolute) size = absolute.stat().st_size matched.setdefault(entry.key, []).append((absolute, original, sha, size)) staged: list[StagedEvidenceFile] = [] aliases: list[dict[str, Any]] = [] catalog: list[dict[str, Any]] = [] for key, copies in sorted(matched.items()): entry = allowlist.by_key[key] # Prefer identical content groups; if hashes differ, keep the largest (likely final). by_hash: dict[str, list[tuple[Path, str, str, int]]] = {} for copy in copies: by_hash.setdefault(copy[2], []).append(copy) chosen_hash = max(by_hash.keys(), key=lambda digest: (by_hash[digest][0][3], digest)) chosen_group = by_hash[chosen_hash] primary_abs, primary_orig, primary_sha, primary_size = chosen_group[0] dest = staging_root / Path(*entry.canonical_path.split("/")) dest.parent.mkdir(parents=True, exist_ok=True) if primary_abs.resolve() != dest.resolve(): dest.write_bytes(primary_abs.read_bytes()) staged.append( StagedEvidenceFile( absolute=dest, relative=entry.canonical_path, key=key, original_path=primary_orig, ) ) # Alias = other discovery paths that would have duplicated bytes. other_logical = sorted( { f"evidence/from/{orig}" for _abs, orig, digest, _size in copies if digest == chosen_hash } ) other_logical = [ path for path in other_logical if path.casefold() != f"evidence/from/{primary_orig}".casefold() ] if other_logical: aliases.append( { "key": key, "sha256": primary_sha, "size": primary_size, "physical_path": entry.canonical_path, "logical_paths": other_logical, "reason": EVIDENCE_ALIAS_REASON, } ) for _abs, orig, digest, _size in copies: if digest == chosen_hash: continue excluded.append( { "path": f"evidence/from/{orig}", "rule": "conflicting_evidence_hash_not_selected", } ) catalog.append( { "key": key, "canonical_path": entry.canonical_path, "sha256": primary_sha, "size": primary_size, "source_original": primary_orig, "role": "compact_default", "duplicate_sources": [orig for _a, orig, digest, _s in copies if digest == chosen_hash], } ) if include_process_evidence: for absolute, original in process_files: rel = f"evidence/process/{original}" dest = staging_root / Path(*rel.split("/")) dest.parent.mkdir(parents=True, exist_ok=True) if absolute.suffix.casefold() in {".log", ".logw"}: status = _candidate_status_for_log(absolute) or "unknown" retention = log_retention_for_status(status, allowlist) log_actions.append( { "path": original, "status": normalize_result_status(status), "retention": retention, } ) if retention == "summary": summary = build_pass_log_summary( source_path=original, status=status, metadata={ "artifact_hashes": {"source_log_sha256": _sha256_file(absolute)}, "result_summary": f"{normalize_result_status(status)} (full log omitted)", "warning_summary": [], }, allowlist=allowlist, ) dest = dest.with_name(dest.name + LOG_SUMMARY_SUFFIX) dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") staged.append( StagedEvidenceFile( absolute=dest, relative=dest.relative_to(staging_root).as_posix(), key=None, original_path=original, retention="summary", ) ) continue dest.write_bytes(absolute.read_bytes()) staged.append( StagedEvidenceFile( absolute=dest, relative=rel, key=None, original_path=original, retention="full" if absolute.suffix.casefold() in {".log", ".logw"} else None, ) ) aliases.sort(key=lambda row: str(row["physical_path"]).casefold()) excluded.sort(key=lambda row: row["path"].casefold()) catalog.sort(key=lambda row: str(row["key"])) return EvidenceCanonResult( staged=staged, aliases=aliases, excluded=excluded, log_policy_actions=log_actions, catalog=catalog, ) def filter_package_items_for_compact( items: Iterable[Any], *, profile: str, include_process_evidence: bool, allowlist: EvidenceAllowlist | None = None, relative_attr: str = "candidate", ) -> tuple[list[Any], list[dict[str, str]], list[dict[str, Any]]]: """Drop process / non-allowlisted evidence from review-compact collections. Items whose package path is under evidence/ (or workspace receipts that look like evidence) are filtered. Source/meta board-viewer derived assets are kept. """ allowlist = allowlist or load_allowlist() include_process = include_process_evidence or profile == "review-debug" if profile not in {"review-compact", "review-debug"}: return list(items), [], [] kept: list[Any] = [] excluded: list[dict[str, str]] = [] remaps: list[dict[str, Any]] = [] for item in items: candidate = getattr(item, relative_attr) relative = candidate.relative if hasattr(candidate, "relative") else str(candidate) lower = relative.casefold() original = getattr(item, "original_path", _strip_layout_prefix(relative)) # Board-viewer derived assets and meta are not receipt allowlist subjects. if lower.startswith("evidence/board-viewer/") or lower.startswith("meta/"): kept.append(item) continue if not ( lower.startswith("evidence/") or lower.startswith("source/receipts/") or str(original).casefold().startswith("receipts/") ): kept.append(item) continue if is_process_evidence(relative, allowlist) or is_process_evidence(str(original), allowlist): if include_process: kept.append(item) else: excluded.append({"path": relative, "rule": PROCESS_EXCLUDE_RULE}) continue if is_compact_allowlisted(relative, allowlist) or is_compact_allowlisted(str(original), allowlist): kept.append(item) continue # Historical receipts/ under evidence that are not on the allowlist. if include_process: kept.append(item) else: excluded.append({"path": relative, "rule": NON_ALLOWLIST_RECEIPT_RULE}) return kept, excluded, remaps def build_evidence_canon_index_fields( *, catalog: list[dict[str, Any]], aliases: list[dict[str, Any]], log_policy_actions: list[dict[str, Any]], include_process_evidence: bool, profile: str, ) -> dict[str, Any]: return { "schema": EVIDENCE_CANON_SCHEMA, "profile": profile, "include_process_evidence": include_process_evidence or profile == "review-debug", "compact_default_keys": sorted( {str(row["key"]) for row in catalog if row.get("role") == "compact_default"} ), "catalog": catalog, "aliases": aliases, "log_policy": { "schema": "cpld-result-sensitive-log-policy-v1", "pass_retention": "summary", "fail_retention": "full", "actions": log_policy_actions, }, } def compact_default_key_list(allowlist: EvidenceAllowlist | None = None) -> list[str]: allowlist = allowlist or load_allowlist() return [entry.key for entry in allowlist.canonical_entries]