package_evidence_canon.py 23 KB

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