package_evidence_canon.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. #!/usr/bin/env python3
  2. """Canonical evidence selection for review-compact / review-debug packages.
  3. Owns:
  4. - compact default receipt allowlist
  5. - canonical placement under evidence/
  6. - logical alias records (one physical copy)
  7. - result-sensitive PASS/FAIL log retention policy
  8. Process lane receipts and matrix reruns stay out of review-compact unless
  9. ``include_process_evidence`` is set (review-debug enables that by default).
  10. """
  11. from __future__ import annotations
  12. import fnmatch
  13. import hashlib
  14. import json
  15. import os
  16. from dataclasses import dataclass
  17. from pathlib import Path
  18. from typing import Any, Callable, Iterable
  19. ROOT = Path(__file__).resolve().parents[1]
  20. DEFAULT_ALLOWLIST_PATH = ROOT / "config" / "review_compact_evidence_allowlist.json"
  21. EVIDENCE_CANON_SCHEMA = "cpld-evidence-canon-v1"
  22. EVIDENCE_ALIAS_REASON = "canonical_evidence_single_physical_copy"
  23. PROCESS_EXCLUDE_RULE = "process_evidence_not_in_compact_allowlist"
  24. NON_ALLOWLIST_RECEIPT_RULE = "receipt_not_on_compact_allowlist"
  25. LOG_SUMMARY_SUFFIX = ".pass-summary.json"
  26. PackageItemFactory = Callable[..., Any]
  27. @dataclass(frozen=True)
  28. class CanonicalEntry:
  29. key: str
  30. canonical_path: str
  31. match_basenames: tuple[str, ...]
  32. match_workspace_paths: tuple[str, ...]
  33. match_path_contains: tuple[str, ...]
  34. @dataclass(frozen=True)
  35. class EvidenceAllowlist:
  36. canonical_entries: tuple[CanonicalEntry, ...]
  37. process_path_prefixes: tuple[str, ...]
  38. process_basename_globs: tuple[str, ...]
  39. summary_statuses: frozenset[str]
  40. full_statuses: frozenset[str]
  41. pass_summary_fields: tuple[str, ...]
  42. raw: dict[str, Any]
  43. @property
  44. def by_key(self) -> dict[str, CanonicalEntry]:
  45. return {entry.key: entry for entry in self.canonical_entries}
  46. @property
  47. def canonical_paths(self) -> frozenset[str]:
  48. return frozenset(entry.canonical_path.casefold() for entry in self.canonical_entries)
  49. def load_allowlist(path: Path | None = None) -> EvidenceAllowlist:
  50. allowlist_path = path or DEFAULT_ALLOWLIST_PATH
  51. payload = json.loads(allowlist_path.read_text(encoding="utf-8"))
  52. if payload.get("schema") != "cpld-review-compact-evidence-allowlist-v1":
  53. raise ValueError(f"unsupported evidence allowlist schema: {payload.get('schema')}")
  54. entries: list[CanonicalEntry] = []
  55. for row in payload.get("canonical_entries", []):
  56. entries.append(
  57. CanonicalEntry(
  58. key=str(row["key"]),
  59. canonical_path=str(row["canonical_path"]),
  60. match_basenames=tuple(
  61. str(item).casefold() for item in row.get("match_basenames", [])
  62. ),
  63. match_workspace_paths=tuple(
  64. str(item).casefold() for item in row.get("match_workspace_paths", [])
  65. ),
  66. match_path_contains=tuple(
  67. str(item).casefold() for item in row.get("match_path_contains", [])
  68. ),
  69. )
  70. )
  71. process = payload.get("process_evidence", {})
  72. log_policy = payload.get("log_policy", {})
  73. return EvidenceAllowlist(
  74. canonical_entries=tuple(entries),
  75. process_path_prefixes=tuple(
  76. str(item).casefold() for item in process.get("path_prefixes", [])
  77. ),
  78. process_basename_globs=tuple(
  79. str(item).casefold() for item in process.get("basename_globs", [])
  80. ),
  81. summary_statuses=frozenset(
  82. str(item).casefold() for item in log_policy.get("summary_statuses", [])
  83. ),
  84. full_statuses=frozenset(
  85. str(item).casefold() for item in log_policy.get("full_statuses", [])
  86. ),
  87. pass_summary_fields=tuple(
  88. str(item) for item in log_policy.get("pass_summary_fields", [])
  89. ),
  90. raw=payload,
  91. )
  92. def _basename(relative: str) -> str:
  93. return relative.casefold().rsplit("/", 1)[-1]
  94. def _strip_layout_prefix(relative: str) -> str:
  95. lower = relative.casefold()
  96. for prefix in ("evidence/", "source/", "meta/", "workspace-current/"):
  97. if lower.startswith(prefix):
  98. return relative[len(prefix) :]
  99. return relative
  100. def match_canonical_entry(
  101. relative: str,
  102. allowlist: EvidenceAllowlist,
  103. *,
  104. workspace_original: str | None = None,
  105. ) -> CanonicalEntry | None:
  106. original = (workspace_original or _strip_layout_prefix(relative)).casefold()
  107. name = _basename(original)
  108. package_lower = relative.casefold()
  109. # Historical / process trees must not become current via basename coincidence.
  110. if is_process_evidence(relative, allowlist) or is_process_evidence(original, allowlist):
  111. return None
  112. for entry in allowlist.canonical_entries:
  113. if original in entry.match_workspace_paths:
  114. return entry
  115. if package_lower == entry.canonical_path.casefold():
  116. return entry
  117. if entry.match_path_contains and any(
  118. token in package_lower or token in original for token in entry.match_path_contains
  119. ):
  120. # Avoid matching unrelated summary.json files.
  121. if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower:
  122. continue
  123. return entry
  124. if name in entry.match_basenames:
  125. if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower:
  126. continue
  127. return entry
  128. return None
  129. def workspace_canonical_path(
  130. original_relative: str,
  131. allowlist: EvidenceAllowlist | None = None,
  132. ) -> str | None:
  133. """Map a workspace-relative path onto its compact canonical evidence path."""
  134. allowlist = allowlist or load_allowlist()
  135. entry = match_canonical_entry(original_relative, allowlist, workspace_original=original_relative)
  136. if entry is None:
  137. return None
  138. return entry.canonical_path
  139. def is_process_evidence(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool:
  140. allowlist = allowlist or load_allowlist()
  141. lower = relative.casefold()
  142. original = _strip_layout_prefix(relative).casefold()
  143. name = _basename(original)
  144. for prefix in allowlist.process_path_prefixes:
  145. if lower.startswith(prefix) or original.startswith(prefix):
  146. return True
  147. if f"/{prefix.rstrip('/')}/" in f"/{lower}/" or f"/{prefix.rstrip('/')}/" in f"/{original}/":
  148. return True
  149. for pattern in allowlist.process_basename_globs:
  150. if fnmatch.fnmatch(name, pattern):
  151. return True
  152. # Deep-review rounds are process; summary is canonical.
  153. if ("deep-review" in original or "deep-review" in lower) and name.startswith("round-"):
  154. return True
  155. return False
  156. def is_compact_allowlisted(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool:
  157. allowlist = allowlist or load_allowlist()
  158. return match_canonical_entry(relative, allowlist) is not None
  159. def normalize_result_status(status: str | None) -> str:
  160. if status is None:
  161. return "unknown"
  162. return str(status).strip().casefold()
  163. def log_retention_for_status(
  164. status: str | None,
  165. allowlist: EvidenceAllowlist | None = None,
  166. ) -> str:
  167. """PASS/not_run → summary; FAIL/BLOCKED/TIMEOUT/CRASH → full."""
  168. allowlist = allowlist or load_allowlist()
  169. normalized = normalize_result_status(status)
  170. if normalized in allowlist.full_statuses:
  171. return "full"
  172. if normalized in allowlist.summary_statuses:
  173. return "summary"
  174. # Heuristic for compound statuses like pass_with_warnings.
  175. if any(token in normalized for token in ("fail", "blocked", "timeout", "crash", "error")):
  176. return "full"
  177. if normalized.startswith("pass") or normalized in {"ok", "success", "not_run"}:
  178. return "summary"
  179. return "full"
  180. def build_pass_log_summary(
  181. *,
  182. source_path: str,
  183. status: str,
  184. metadata: dict[str, Any] | None = None,
  185. allowlist: EvidenceAllowlist | None = None,
  186. ) -> dict[str, Any]:
  187. allowlist = allowlist or load_allowlist()
  188. metadata = dict(metadata or {})
  189. summary: dict[str, Any] = {
  190. "schema": "cpld-pass-log-summary-v1",
  191. "source_log": source_path,
  192. "status": normalize_result_status(status),
  193. "retention": "summary",
  194. "note": (
  195. "PASS/not_run lanes keep a summary only in review-compact; "
  196. "full stdout/stderr is omitted by result-sensitive log policy."
  197. ),
  198. }
  199. for field in allowlist.pass_summary_fields:
  200. if field in metadata:
  201. summary[field] = metadata[field]
  202. return summary
  203. def extract_status_from_receipt(path: Path) -> str | None:
  204. try:
  205. payload = json.loads(path.read_text(encoding="utf-8"))
  206. except (OSError, UnicodeError, json.JSONDecodeError):
  207. return None
  208. if not isinstance(payload, dict):
  209. return None
  210. for key in ("status", "result", "overall_status", "matrix_status"):
  211. value = payload.get(key)
  212. if isinstance(value, str) and value.strip():
  213. return value
  214. lanes = payload.get("lanes")
  215. if isinstance(lanes, dict):
  216. statuses = [
  217. normalize_result_status(str(item.get("status")))
  218. for item in lanes.values()
  219. if isinstance(item, dict) and item.get("status") is not None
  220. ]
  221. for bad in ("fail", "failed", "blocked", "timeout", "crash", "error"):
  222. if bad in statuses:
  223. return bad
  224. if statuses and all(item in {"pass", "passed", "ok", "success", "not_run"} for item in statuses):
  225. return "pass"
  226. return None
  227. def _sha256_file(path: Path) -> str:
  228. digest = hashlib.sha256()
  229. with path.open("rb") as handle:
  230. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  231. digest.update(chunk)
  232. return digest.hexdigest()
  233. def _sha256_bytes(payload: bytes) -> str:
  234. return hashlib.sha256(payload).hexdigest()
  235. def prefer_canonical_path(paths: Iterable[str], allowlist: EvidenceAllowlist | None = None) -> str:
  236. """Choose the allowlisted canonical path when present among duplicates."""
  237. allowlist = allowlist or load_allowlist()
  238. path_list = list(paths)
  239. if not path_list:
  240. raise ValueError("prefer_canonical_path requires at least one path")
  241. def rank(path: str) -> tuple[int, int, str]:
  242. entry = match_canonical_entry(path, allowlist)
  243. if entry is not None and path.casefold() == entry.canonical_path.casefold():
  244. return (0, 0, path.casefold())
  245. if entry is not None:
  246. return (1, 0, path.casefold())
  247. lower = path.casefold()
  248. under_evidence = 0 if lower.startswith("evidence/") else 1
  249. return (2, under_evidence, lower)
  250. return sorted(path_list, key=rank)[0]
  251. @dataclass
  252. class StagedEvidenceFile:
  253. absolute: Path
  254. relative: str
  255. key: str | None
  256. original_path: str
  257. retention: str | None = None
  258. @dataclass
  259. class EvidenceCanonResult:
  260. staged: list[StagedEvidenceFile]
  261. aliases: list[dict[str, Any]]
  262. excluded: list[dict[str, str]]
  263. log_policy_actions: list[dict[str, Any]]
  264. catalog: list[dict[str, Any]]
  265. def _candidate_status_for_log(log_path: Path) -> str | None:
  266. stem = log_path.name
  267. parent = log_path.parent
  268. # Prefer sibling *-receipt.json / *.json with matching stem prefix.
  269. patterns = [
  270. f"{log_path.stem}-receipt.json",
  271. f"{log_path.stem}.json",
  272. "formal-receipt.json",
  273. "td-primary-receipt.json",
  274. "matrix-receipt.json",
  275. "verification-matrix-final.json",
  276. ]
  277. for name in patterns:
  278. candidate = parent / name
  279. if candidate.is_file():
  280. status = extract_status_from_receipt(candidate)
  281. if status is not None:
  282. return status
  283. for candidate in sorted(parent.glob("*-receipt.json")):
  284. status = extract_status_from_receipt(candidate)
  285. if status is not None:
  286. return status
  287. return None
  288. def stage_evidence_root(
  289. evidence_root: Path,
  290. *,
  291. staging_root: Path,
  292. include_process_evidence: bool = False,
  293. allowlist: EvidenceAllowlist | None = None,
  294. make_item: PackageItemFactory | None = None,
  295. ) -> EvidenceCanonResult:
  296. """Stage an external delivery/run evidence tree into canonical evidence/ paths."""
  297. del make_item # packager wraps StagedEvidenceFile itself
  298. allowlist = allowlist or load_allowlist()
  299. evidence_root = evidence_root.resolve(strict=True)
  300. staging_root.mkdir(parents=True, exist_ok=True)
  301. # key -> list of (abs, original_rel, sha, size)
  302. matched: dict[str, list[tuple[Path, str, str, int]]] = {}
  303. process_files: list[tuple[Path, str]] = []
  304. log_actions: list[dict[str, Any]] = []
  305. excluded: list[dict[str, str]] = []
  306. for dirpath, dirnames, filenames in os.walk(evidence_root):
  307. dirnames.sort(key=lambda name: name.casefold())
  308. filenames.sort(key=lambda name: name.casefold())
  309. base = Path(dirpath)
  310. for filename in filenames:
  311. absolute = base / filename
  312. if not absolute.is_file() or absolute.is_symlink():
  313. continue
  314. original = absolute.relative_to(evidence_root).as_posix()
  315. if is_process_evidence(original, allowlist):
  316. if include_process_evidence:
  317. process_files.append((absolute, original))
  318. else:
  319. excluded.append({"path": f"evidence/process/{original}", "rule": PROCESS_EXCLUDE_RULE})
  320. continue
  321. entry = match_canonical_entry(original, allowlist, workspace_original=original)
  322. if entry is None:
  323. # Non-allowlisted evidence stays process-only for compact.
  324. if include_process_evidence:
  325. process_files.append((absolute, original))
  326. else:
  327. excluded.append(
  328. {
  329. "path": f"evidence/process/{original}",
  330. "rule": NON_ALLOWLIST_RECEIPT_RULE,
  331. }
  332. )
  333. continue
  334. sha = _sha256_file(absolute)
  335. size = absolute.stat().st_size
  336. matched.setdefault(entry.key, []).append((absolute, original, sha, size))
  337. staged: list[StagedEvidenceFile] = []
  338. aliases: list[dict[str, Any]] = []
  339. catalog: list[dict[str, Any]] = []
  340. for key, copies in sorted(matched.items()):
  341. entry = allowlist.by_key[key]
  342. # Prefer identical content groups; if hashes differ, keep the largest (likely final).
  343. by_hash: dict[str, list[tuple[Path, str, str, int]]] = {}
  344. for copy in copies:
  345. by_hash.setdefault(copy[2], []).append(copy)
  346. chosen_hash = max(by_hash.keys(), key=lambda digest: (by_hash[digest][0][3], digest))
  347. chosen_group = by_hash[chosen_hash]
  348. primary_abs, primary_orig, primary_sha, primary_size = chosen_group[0]
  349. dest = staging_root / Path(*entry.canonical_path.split("/"))
  350. dest.parent.mkdir(parents=True, exist_ok=True)
  351. if primary_abs.resolve() != dest.resolve():
  352. dest.write_bytes(primary_abs.read_bytes())
  353. staged.append(
  354. StagedEvidenceFile(
  355. absolute=dest,
  356. relative=entry.canonical_path,
  357. key=key,
  358. original_path=primary_orig,
  359. )
  360. )
  361. # Alias = other discovery paths that would have duplicated bytes.
  362. other_logical = sorted(
  363. {
  364. f"evidence/from/{orig}"
  365. for _abs, orig, digest, _size in copies
  366. if digest == chosen_hash
  367. }
  368. )
  369. other_logical = [
  370. path
  371. for path in other_logical
  372. if path.casefold() != f"evidence/from/{primary_orig}".casefold()
  373. ]
  374. if other_logical:
  375. aliases.append(
  376. {
  377. "key": key,
  378. "sha256": primary_sha,
  379. "size": primary_size,
  380. "physical_path": entry.canonical_path,
  381. "logical_paths": other_logical,
  382. "reason": EVIDENCE_ALIAS_REASON,
  383. }
  384. )
  385. for _abs, orig, digest, _size in copies:
  386. if digest == chosen_hash:
  387. continue
  388. excluded.append(
  389. {
  390. "path": f"evidence/from/{orig}",
  391. "rule": "conflicting_evidence_hash_not_selected",
  392. }
  393. )
  394. catalog.append(
  395. {
  396. "key": key,
  397. "canonical_path": entry.canonical_path,
  398. "sha256": primary_sha,
  399. "size": primary_size,
  400. "source_original": primary_orig,
  401. "role": "compact_default",
  402. "duplicate_sources": [orig for _a, orig, digest, _s in copies if digest == chosen_hash],
  403. }
  404. )
  405. if include_process_evidence:
  406. for absolute, original in process_files:
  407. rel = f"evidence/process/{original}"
  408. dest = staging_root / Path(*rel.split("/"))
  409. dest.parent.mkdir(parents=True, exist_ok=True)
  410. if absolute.suffix.casefold() in {".log", ".logw"}:
  411. status = _candidate_status_for_log(absolute) or "unknown"
  412. retention = log_retention_for_status(status, allowlist)
  413. log_actions.append(
  414. {
  415. "path": original,
  416. "status": normalize_result_status(status),
  417. "retention": retention,
  418. }
  419. )
  420. if retention == "summary":
  421. summary = build_pass_log_summary(
  422. source_path=original,
  423. status=status,
  424. metadata={
  425. "artifact_hashes": {"source_log_sha256": _sha256_file(absolute)},
  426. "result_summary": f"{normalize_result_status(status)} (full log omitted)",
  427. "warning_summary": [],
  428. },
  429. allowlist=allowlist,
  430. )
  431. dest = dest.with_name(dest.name + LOG_SUMMARY_SUFFIX)
  432. dest.parent.mkdir(parents=True, exist_ok=True)
  433. dest.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
  434. staged.append(
  435. StagedEvidenceFile(
  436. absolute=dest,
  437. relative=dest.relative_to(staging_root).as_posix(),
  438. key=None,
  439. original_path=original,
  440. retention="summary",
  441. )
  442. )
  443. continue
  444. dest.write_bytes(absolute.read_bytes())
  445. staged.append(
  446. StagedEvidenceFile(
  447. absolute=dest,
  448. relative=rel,
  449. key=None,
  450. original_path=original,
  451. retention="full" if absolute.suffix.casefold() in {".log", ".logw"} else None,
  452. )
  453. )
  454. aliases.sort(key=lambda row: str(row["physical_path"]).casefold())
  455. excluded.sort(key=lambda row: row["path"].casefold())
  456. catalog.sort(key=lambda row: str(row["key"]))
  457. return EvidenceCanonResult(
  458. staged=staged,
  459. aliases=aliases,
  460. excluded=excluded,
  461. log_policy_actions=log_actions,
  462. catalog=catalog,
  463. )
  464. def filter_package_items_for_compact(
  465. items: Iterable[Any],
  466. *,
  467. profile: str,
  468. include_process_evidence: bool,
  469. allowlist: EvidenceAllowlist | None = None,
  470. relative_attr: str = "candidate",
  471. ) -> tuple[list[Any], list[dict[str, str]], list[dict[str, Any]]]:
  472. """Drop process / non-allowlisted evidence from review-compact collections.
  473. Items whose package path is under evidence/ (or workspace receipts that look
  474. like evidence) are filtered. Source/meta board-viewer derived assets are kept.
  475. """
  476. allowlist = allowlist or load_allowlist()
  477. include_process = include_process_evidence or profile == "review-debug"
  478. if profile not in {"review-compact", "review-debug"}:
  479. return list(items), [], []
  480. kept: list[Any] = []
  481. excluded: list[dict[str, str]] = []
  482. remaps: list[dict[str, Any]] = []
  483. for item in items:
  484. candidate = getattr(item, relative_attr)
  485. relative = candidate.relative if hasattr(candidate, "relative") else str(candidate)
  486. lower = relative.casefold()
  487. original = getattr(item, "original_path", _strip_layout_prefix(relative))
  488. # Board-viewer derived assets and meta are not receipt allowlist subjects.
  489. if lower.startswith("evidence/board-viewer/") or lower.startswith("meta/"):
  490. kept.append(item)
  491. continue
  492. if not (
  493. lower.startswith("evidence/")
  494. or lower.startswith("source/receipts/")
  495. or str(original).casefold().startswith("receipts/")
  496. ):
  497. kept.append(item)
  498. continue
  499. if is_process_evidence(relative, allowlist) or is_process_evidence(str(original), allowlist):
  500. if include_process:
  501. kept.append(item)
  502. else:
  503. excluded.append({"path": relative, "rule": PROCESS_EXCLUDE_RULE})
  504. continue
  505. if is_compact_allowlisted(relative, allowlist) or is_compact_allowlisted(str(original), allowlist):
  506. kept.append(item)
  507. continue
  508. # Historical receipts/ under evidence that are not on the allowlist.
  509. if include_process:
  510. kept.append(item)
  511. else:
  512. excluded.append({"path": relative, "rule": NON_ALLOWLIST_RECEIPT_RULE})
  513. return kept, excluded, remaps
  514. def build_evidence_canon_index_fields(
  515. *,
  516. catalog: list[dict[str, Any]],
  517. aliases: list[dict[str, Any]],
  518. log_policy_actions: list[dict[str, Any]],
  519. include_process_evidence: bool,
  520. profile: str,
  521. ) -> dict[str, Any]:
  522. return {
  523. "schema": EVIDENCE_CANON_SCHEMA,
  524. "profile": profile,
  525. "include_process_evidence": include_process_evidence or profile == "review-debug",
  526. "compact_default_keys": sorted(
  527. {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
  528. ),
  529. "catalog": catalog,
  530. "aliases": aliases,
  531. "log_policy": {
  532. "schema": "cpld-result-sensitive-log-policy-v1",
  533. "pass_retention": "summary",
  534. "fail_retention": "full",
  535. "actions": log_policy_actions,
  536. },
  537. }
  538. def compact_default_key_list(allowlist: EvidenceAllowlist | None = None) -> list[str]:
  539. allowlist = allowlist or load_allowlist()
  540. return [entry.key for entry in allowlist.canonical_entries]