"""Verify a coverage.py JSON report covers the complete backend inventory. Modules in the audited legacy baseline must not regress in covered statements or branches. Every other production backend module must be fully covered. """ from __future__ import annotations import json import ast import difflib import hashlib from pathlib import Path import sys # Support both the direct CLI and package imports used by gate tests. if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from scripts.check_transport_coverage import transport_baseline, transport_layout ROOT = Path(__file__).resolve().parents[1] BASELINE_FILE = "quality/baselines/backend-coverage-debt.json" READER_ARCHIVE_OLD_APP_SHA = "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca" READER_ARCHIVE_NEW_APP_SHA = "6acee59dcd272f367340da70c2ec6c2a90e71b6076aa2318e10eb12b5e39235f" READER_ARCHIVE_OLD_DEBT_SHA = "eac5463c1f64f29a551baf216433e950e939493fee855d001814786daad8a13a" TYPING_NEW_APP_SHA = "02350a36d2f22c20ba82bfedae564b7b6186ec3d884952e9ccd33f3ed6122b98" TYPING_OLD_DEBT_SHA = "0caa77489676631f9e8f23da7340c741e73b90ad0744ab9b20070b9a866d05d1" TYPING_REVIEW_SHA = "4196e9f8f9aba299025107cd59bf9b0ef27528d8b5059cd8fa80b97c28116d82" RANGE_OLD_APP_SHA = "febd804ffe83685d17f043e9a9a5d60bea4ac3b4399ffbef5527c10e3465f121" RANGE_NEW_APP_SHA = "6bd515f891cb732fa701cc8b3042e6e927d8423869c836ae1f2719bcbecfb7f7" RANGE_MODULE_SHA = "8d6eb60fb15bab4f303e3ff689ca083ad9fa49ef92c928b75bfdc9aea88ce825" TERM_NEW_APP_SHA = "0c64e9323c7b7512f666d6ce69f151c33d8bef3d31c9b5c14fb14834eb6c94ed" TERM_MODULE_SHA = "4d66ea84242625e56e6b387506050527fed6e557b813af34bc7986aaba76970d" WARM_NEW_APP_SHA = "f9fe394346923e0d36f06908d7092a842330b5474b464c8a02dd46c12a6e8e8b" WARM_MODULE_SHA = "b720d87c5fb86d2cac1fb1fc2c7933477e106af7689fff56e6217c446604ab6a" SINGLE_NEW_APP_SHA = "c67201f73947c546f1ae2fdb5de59d97b0d730ae3b90d5c92ddea0ef1ed07a23" SINGLE_MODULE_SHA = "8cdde250384a5b9900f664d376a5472693e98f77522937d138acead6068be411" SEARCH_RELEASE_APP_SHA = "a97ac73340331b5c0e6e8d17149b541d758d25e7cb25841544f3fe9219548fb5" SEARCH_RELEASE_TERM_SHA = "dc2251331033e4787f7a4edabdf8de6351b85b1c160fbf1b0392734ada9babbf" SEARCH_RELEASE_DEBT_SHA = "d7bed3e96d3cbdc8dc20d9c8f5a92dbc96d4d0f6c2e45fb6237bad9c2c70bed5" SEARCH_RELEASE_DIFF_SHA = "2155663554e77d4f3ffe4164a154b9c9d4c1ad216f5b7b37d3ba1a6b8e765b85" SEARCH_SIGMA_APP_SHA = "cd78aa10d6202c71ce7c99bc7da06c0842bbe2adece90f60ff01347a1eafda02" # A reviewed constant-only change keeps every sigma-layout coordinate intact. SEARCH_SIGMA_VERSION_APP_SHA = "20f24996fd3366a6e3bb903fd959f26385fe02c16037793c59b51a953cd1c63f" SEARCH_SIGMA_OLD_DEBT_SHA = "0326c931227ea305f66e2ca42108a288660d2b88e530bed6637a1f57d92618a3" SEO_PATH_OLD_SHA = "4ce6a235f862a1281199ea5de4b9b8dccaa048254842fe278ddd3545dceb97e7" SEO_PATH_NEW_SHA = "b263f903ae185449ee0e0c375a4d7529420ab673f9d9ceb2772d65d8b7a84615" SEO_PATH_OLD_DEBT_SHA = "ddf16ced4e535becfb2d481ae655931b3d174e8b8aa028c07bc7b6a92cce99af" SEO_PATH_OLD_ENTRY_SHA = "50d39238ff2b2d33e94b4d57b2cb6b7dabeeb8833381202d19e39e53bd2e500a" PROXY_SAFETY_PARENT_DEBT_SHA = "c6faa63b2edc0c91d8139532d3640a266b3e345eb59d3b689cc72259bd1df944" PROXY_SAFETY_OLD_APP_SHA = SEARCH_SIGMA_VERSION_APP_SHA PROXY_SAFETY_NEW_APP_SHA = "5cecc3a293b0d98c684cf67b087300fceb445efe64f2c6bff705b09f03f3f466" PROXY_SAFETY_OLD_STREAMS_SHA = "b13d42a2a4a80bd364dd2143bb9132e3fca831e38a9022b5ed339a17ba097c82" PROXY_SAFETY_NEW_STREAMS_SHA = "1ea7166805ef52c2afb8ccd2da09c4c37a4aa22cd901fc5768552395659c9f55" PROXY_SAFETY_NEW_RANGE_SHA = "966395157c044f254d0c0734231b6af55f1c63bb32e250ff037b644438a68367" PROXY_SAFETY_APP_DIFF_SHA = "68416eb9c40727cbd188657b3a8409dc5c7c4569edbf58f500b0ff216d0da130" PROXY_SAFETY_STREAMS_DIFF_SHA = "76ef2e037fee17c6f8aca062213455e9fd158f078fa9b92d670edc6049712a61" BROWSE_NEW_APP_SHA = "64c479aea84f7b4b8b3f7fdacdc188d34e2c174aa2ee21748a20ba0d4b31211a" BROWSE_MODULE_SHA = "78a1f1d3217e3d6b83573a1d311222cd9d1f66d735d10dc8c96bcee5bda92fa1" BROWSE_PARENT_ENTRY_SHA = "ad7eca33e0ab4fa1ef3b23747417ecc0545feda00ebe0592aeb21c086cd88c41" LIFESPAN_APP_SHA = "652c1576d8e3cb4802254205d4dd978b325966966af52972dea260e63e6d1ba0" LIFESPAN_PARENT_DEBT_SHA = "f7cbc7bf0ccb5f60cfeb6b72cccb46291dce5f8b5d7fcd7f52fa1ab2889a5faa" def migrate_retired_txt_app_baseline(root: Path, previous: dict[str, dict[str, object]], old_source: Path) -> dict[str, dict[str, object]]: """Translate one independently pinned baseline across the reviewed TXT deletion. Only deleted lines and arcs wholly inside them are retired. Later source edits are checked against the ordinary line and branch coverage ratchet. """ old = old_source.read_bytes() if hashlib.sha256(old).hexdigest() != "144a94519c57fff1da752d26cb514f99fb7ffda7f068da06a726d842f3a61442": raise ValueError("unexpected source for retired TXT baseline") # The historical target remains a reviewed migration anchor even after # future app changes. Subsequent migrations must also use pinned anchors. anchor = (root / "scripts/coverage-anchors/retired-txt-app.py.snapshot").read_bytes() new = anchor if hashlib.sha256(new).hexdigest() != "b81421ba994354d34991af6ee181e6aba5b935c1eb300f242ab349a4e68036f2": raise ValueError("retired TXT baseline migration requires the reviewed target anchor") if "backend/app.py" not in previous: raise ValueError("previous baseline lacks backend/app.py") line_map: dict[int, int] = {} removed: set[int] = set() for op, start, end, new_start, _new_end in difflib.SequenceMatcher( None, old.decode().splitlines(), new.decode().splitlines(), autojunk=False).get_opcodes(): if op == "equal": line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) elif op == "delete": removed.update(range(start + 1, end + 1)) # Both replacements remove only imports for the retired proxy. line_map.update({29: 28, 70: 69}) random_target = (root / "scripts/coverage-anchors/retired-random-txt-app.py.snapshot").read_bytes() if hashlib.sha256(random_target).hexdigest() != "83276576ce2a1cfd439d8b901446a567b46eb49e99077ccf04a97dabfa5c22cd": raise ValueError("retired random TXT migration requires the reviewed target anchor") random_map: dict[int, int] = {} random_removed: set[int] = set() for op, start, end, new_start, new_end in difflib.SequenceMatcher( None, anchor.decode().splitlines(), random_target.decode().splitlines(), autojunk=False).get_opcodes(): if op == "equal": random_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) elif op == "delete": random_removed.update(range(start + 1, end + 1)) elif op == "replace" and end - start == new_end - new_start == 1: # The global declaration and packed-index tuple lose TXT entries. random_map[start + 1] = new_start + 1 else: raise ValueError("unexpected retired random TXT anchor change") stage_one_map = line_map line_map = {original: random_map[intermediate] for original, intermediate in stage_one_map.items() if intermediate in random_map} removed.update(original for original, intermediate in stage_one_map.items() if intermediate in random_removed) def line(number: int) -> int: sign = -1 if number < 0 else 1 return sign * line_map[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") mapped: list[int] = [] for number in values: if number in line_map: mapped.append(line(number)) elif number not in removed: raise ValueError(f"unmapped previous baseline line: {number}") return sorted(mapped) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") mapped: list[list[int]] = [] for start, end in values: if abs(start) in line_map and abs(end) in line_map: mapped.append([line(start), line(end)]) elif [start, end] == [1445, 1449]: # The old false branch fell into the removed TXT shutdown block; # it now falls through to the preserved bucket shutdown. mapped.append([random_map[1417], random_map[1421]]) elif abs(start) not in removed: raise ValueError(f"unmapped previous baseline branch: {start}, {end}") return sorted(mapped) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"]) covered_arcs = arcs(entry["arcs"]) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_folder_tree_app_baseline(root: Path, previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Map a single reviewed extraction; moved coverage is guarded by 100% on the new module.""" expected = ( (old_source, "83276576ce2a1cfd439d8b901446a567b46eb49e99077ccf04a97dabfa5c22cd"), (new_source, "4a05aa049a763b52238aeb8a86621c9532555e55f0d9391de9f16afa49df0639"), (extracted_source, "95d04cfe5ad79e1cbe6218edeba4567c001f7961f199cfd04363123a1e391fd3"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("folder-tree coverage migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/folder_tree.py" in previous: raise ValueError("folder-tree coverage migration requires the original module inventory") old = old_source.read_text().splitlines() new = new_source.read_text().splitlines() line_map: dict[int, int] = {} moved: set[int] = set() changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if op == "replace": moved.update(range(start + 1, end + 1)) if changes != [("insert", 34, 34, 34, 35), ("replace", 1234, 1281, 1235, 1236)]: raise ValueError("unexpected folder-tree source diff") def line(number: int) -> int: sign = -1 if number < 0 else 1 return sign * line_map[abs(number)] def lines(values: object, *, missing: bool) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") mapped: list[int] = [] for number in values: if number in line_map: mapped.append(line(number)) elif number not in moved or missing: raise ValueError(f"unmapped or uncovered extracted line: {number}") return sorted(mapped) def arcs(values: object, *, missing: bool) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") mapped: list[list[int]] = [] for start, end in values: if abs(start) in moved: if missing: raise ValueError(f"uncovered extracted branch: {start}, {end}") continue if [start, end] == [1233, 1235]: mapped.append([1234, 1236]) elif abs(start) in line_map and abs(end) in line_map: mapped.append([line(start), line(end)]) else: raise ValueError(f"unmapped previous branch: {start}, {end}") return sorted(mapped) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"], missing=False) covered_arcs = arcs(entry["arcs"], missing=False) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True), } return result def migrate_search_projection_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Map the reviewed projection extraction; the new module remains outside the debt.""" expected = ( (old_source, "4a05aa049a763b52238aeb8a86621c9532555e55f0d9391de9f16afa49df0639"), (new_source, "b73c5db076ae1dce7c8988fc30049d2c0120ffdf9b6d6b2fd02a4b97e726b3cb"), (extracted_source, "a5be97d44e9371c6cc91d7c5753f7f83c6fc64a288a779141ea35f4278324179"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-projection coverage migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/search_projection.py" in previous: raise ValueError("search-projection coverage migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() line_map: dict[int, int] = {} moved: set[int] = set() changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": line_map.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if op == "replace": moved.update(range(start + 1, end + 1)) if changes != [("insert", 35, 35, 35, 36), ("replace", 622, 636, 623, 624), ("replace", 639, 644, 627, 628)]: raise ValueError("unexpected search-projection source diff") def translate(number: int) -> int: return (-1 if number < 0 else 1) * line_map[abs(number)] def lines(values: object, *, missing: bool) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") result: list[int] = [] for number in values: if number in line_map: result.append(translate(number)) elif number not in moved or missing: raise ValueError(f"unmapped or uncovered projection line: {number}") return sorted(result) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) not in line_map or abs(end) not in line_map: raise ValueError(f"unmapped projection branch: {start}, {end}") result.append([translate(start), translate(end)]) return sorted(result) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"], missing=False) covered_arcs = arcs(entry["arcs"]) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_search_candidates_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate the pinned extraction, requiring complete coverage in the new module.""" expected = ( (old_source, "b73c5db076ae1dce7c8988fc30049d2c0120ffdf9b6d6b2fd02a4b97e726b3cb"), (new_source, "bd3de63841020bfc3c16f5015894ae39ff08c38e6a6d3bc03129e1b86ed91a84"), (extracted_source, "81dbe74b8142aed5447478e2a05c36150a5a2abf67f4aa0b55bc3d43b297cec4"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-candidates coverage migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/search_candidates.py" in previous: raise ValueError("search-candidates coverage migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} moved: set[int] = set() changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if op == "replace": moved.update(range(start + 1, end + 1)) if changes != [("insert", 35, 35, 35, 36), ("insert", 263, 263, 264, 284), ("replace", 264, 300, 285, 287)]: raise ValueError("unexpected search-candidates source diff") def translate(number: int) -> int: return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object, *, missing: bool) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") result: list[int] = [] for number in values: if number in mapping: result.append(translate(number)) elif number not in moved or missing: raise ValueError(f"unmapped or uncovered candidate line: {number}") return sorted(result) def arcs(values: object, *, missing: bool) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if missing: raise ValueError(f"uncovered candidate branch: {start}, {end}") if abs(end) not in moved: raise ValueError(f"unexpected candidate branch endpoint: {start}, {end}") continue if abs(start) not in mapping or abs(end) not in mapping: raise ValueError(f"unmapped candidate branch: {start}, {end}") result.append([translate(start), translate(end)]) return sorted(result) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"], missing=False) covered_arcs = arcs(entry["arcs"], missing=False) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True), } return result def migrate_search_bootstrap_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate only the independently reviewed initial-payload extraction.""" expected = ( (old_source, "bd3de63841020bfc3c16f5015894ae39ff08c38e6a6d3bc03129e1b86ed91a84"), (new_source, "f9582d39a22dbe75c29422c58d978b586e5d38e483e51d75eefa906d25e3d713"), (extracted_source, "41fd419e58c036b00f35bc2e8c8fee12e757f748ef69b56560c2b059addfa24d"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-bootstrap coverage migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/search_bootstrap.py" in previous: raise ValueError("search-bootstrap coverage migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} moved: set[int] = set() changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if op == "replace": moved.update(range(start + 1, end + 1)) if changes != [("insert", 35, 35, 35, 36), ("replace", 751, 756, 752, 765), ("replace", 758, 777, 767, 769)]: raise ValueError("unexpected search-bootstrap source diff") def translate(number: int) -> int: return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object, *, missing: bool) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") result: list[int] = [] for number in values: if number in mapping: result.append(translate(number)) elif number not in moved or missing: raise ValueError(f"unmapped or uncovered bootstrap line: {number}") return sorted(result) def arcs(values: object, *, missing: bool) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if missing: raise ValueError(f"uncovered bootstrap branch: {start}, {end}") if abs(end) not in moved: raise ValueError(f"unexpected bootstrap branch endpoint: {start}, {end}") continue if abs(start) not in mapping or abs(end) not in mapping: raise ValueError(f"unmapped bootstrap branch: {start}, {end}") result.append([translate(start), translate(end)]) return sorted(result) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"], missing=False) covered_arcs = arcs(entry["arcs"], missing=False) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True), } return result def migrate_reader_archive_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate only the reviewed reader-archive extraction. Lines and arcs of the moved validator leave backend/app.py; the new module must independently reach 100% statements and branches, so no coverage is lost. """ expected = ( (old_source, "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca"), (new_source, "6acee59dcd272f367340da70c2ec6c2a90e71b6076aa2318e10eb12b5e39235f"), (extracted_source, "9439528bdad3127c8c794489a7edbf940d7cac9a7341e7bc6e2ca09c2751bb24"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("reader-archive coverage migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/reader_archive.py" in previous: raise ValueError("reader-archive coverage migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} moved: set[int] = set() changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if op in ("delete", "replace"): moved.update(range(start + 1, end + 1)) if changes != [("replace", 1656, 1666, 1656, 1660), ("replace", 1669, 1777, 1663, 1665)]: raise ValueError("unexpected reader-archive source diff") function_exit = -1669 def translate(number: int) -> int: return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid previous baseline lines") result: list[int] = [] for number in values: if number in mapping: result.append(translate(number)) elif number not in moved: raise ValueError(f"unmapped reader-archive line: {number}") return sorted(result) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid previous baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if abs(end) not in moved and end != function_exit: raise ValueError(f"unexpected reader-archive branch endpoint: {start}, {end}") continue if abs(start) not in mapping or abs(end) not in mapping: raise ValueError(f"unmapped reader-archive branch: {start}, {end}") result.append([translate(start), translate(end)]) return sorted(result) result = {name: dict(item) for name, item in previous.items()} entry = previous["backend/app.py"] covered_lines = lines(entry["lines"]) covered_arcs = arcs(entry["arcs"]) result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_folder_contents_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Carry every retained app coordinate across the pinned folder-content extraction. The new module must independently satisfy the ordinary 100% coverage gate, including previously uncovered branches moved from the legacy app. """ expected = ( (old_source, TYPING_NEW_APP_SHA), (new_source, "febd804ffe83685d17f043e9a9a5d60bea4ac3b4399ffbef5527c10e3465f121"), (extracted_source, "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("folder-contents migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/folder_contents.py" in previous: raise ValueError("folder-contents migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 36, 36, 36, 37), ("replace", 1272, 1314, 1273, 1280)]: raise ValueError("unexpected folder-contents source diff") moved = set(range(1273, 1315)) entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid folder-contents baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid folder-contents baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate folder-contents coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped folder-contents coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid folder-contents baseline lines") result: list[int] = [] for value in values: if value in moved: continue result.append(translate(value)) return sorted(result) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid folder-contents baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if abs(end) not in moved: raise ValueError(f"unexpected folder-contents branch endpoint: {start}, {end}") continue result.append([translate(start), translate(end)]) return sorted(result) covered_lines = lines(entry["lines"]) covered_arcs = arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_seo_path_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, parent_debt: Path) -> dict[str, dict[str, object]]: """Map the reviewed equivalent path predicate without retiring old coverage.""" expected = ((old_source, SEO_PATH_OLD_SHA), (new_source, SEO_PATH_NEW_SHA), (parent_debt, SEO_PATH_OLD_DEBT_SHA)) if any(not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("SEO path migration requires exact reviewed sources and baseline") old = old_source.read_text().splitlines() new = new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("replace", 137, 138, 137, 142)]: raise ValueError("unexpected SEO path source diff") mapping[138] = 140 entry = previous.get("backend/seo.py") reviewed = json.loads(parent_debt.read_text()).get("backend/seo.py") if (not isinstance(entry, dict) or not isinstance(reviewed, dict) or hashlib.sha256(json.dumps(reviewed, sort_keys=True, separators=(",", ":")).encode()).hexdigest() != SEO_PATH_OLD_ENTRY_SHA): raise ValueError("SEO path migration requires exact previous baseline") for covered, missing in (("lines", "missing_lines"), ("arcs", "missing_arcs")): convert = tuple if covered == "arcs" else int if (not {convert(value) for value in entry[covered]} <= {convert(value) for value in reviewed[covered]} or not {convert(value) for value in reviewed[missing]} <= {convert(value) for value in entry[missing]} or not {convert(value) for value in entry[missing]} <= {convert(value) for value in reviewed[covered] + reviewed[missing]}): raise ValueError("SEO path migration requires a reviewed baseline subset") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped SEO path coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid SEO path baseline lines") return sorted(translate(value) for value in values) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid SEO path baseline arcs") return sorted([[translate(start), translate(end)] for start, end in values]) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) if entry["covered_lines"] != len(covered_lines) or entry["covered_branches"] != len(covered_arcs): raise ValueError("invalid SEO path baseline counts") result = {name: dict(item) for name, item in previous.items()} result["backend/seo.py"] = {"covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"])} return result def reviewed_browse_source(root: Path, source_sha: str) -> bool: """Permit only the exact browse extraction on the previously audited proxy layout.""" if source_sha != BROWSE_NEW_APP_SHA: return False anchor = root / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot" module = root / "backend/search_browse.py" return (anchor.is_file() and module.is_file() and reviewed_proxy_safety_source(root, PROXY_SAFETY_NEW_APP_SHA) and hashlib.sha256(anchor.read_bytes()).hexdigest() == PROXY_SAFETY_NEW_APP_SHA and hashlib.sha256(module.read_bytes()).hexdigest() == BROWSE_MODULE_SHA) def migrate_search_browse_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path) -> dict[str, dict[str, object]]: """Move audited browse paths only when the new module is independently 100% covered.""" expected = ((old_source, PROXY_SAFETY_NEW_APP_SHA), (new_source, BROWSE_NEW_APP_SHA), (extracted_source, BROWSE_MODULE_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-browse migration requires exact reviewed sources") entry = previous.get("backend/app.py") if not isinstance(entry, dict) or "backend/search_browse.py" in previous: raise ValueError("search-browse migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() operations = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes() changes = [item for item in operations if item[0] != "equal"] if changes != [("insert", 42, 42, 42, 43), ("insert", 1027, 1027, 1028, 1044), ("replace", 1097, 1131, 1114, 1126)]: raise ValueError("unexpected search-browse source diff") mapping = {index + 1: new_start + 1 + index - start for op, start, end, new_start, _ in operations if op == "equal" for index in range(start, end)} moved = set(range(1098, 1132)) fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid search-browse baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid search-browse baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate search-browse coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped search-browse coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object, *, missing: bool) -> list[int]: if not isinstance(values, list): raise ValueError("invalid search-browse baseline lines") result: list[int] = [] for value in values: if value in moved: if missing: raise ValueError(f"uncovered search-browse extraction line: {value}") continue result.append(translate(value)) return sorted(result) def arcs(values: object, *, missing: bool) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid search-browse baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if missing or abs(end) not in moved: raise ValueError(f"uncovered or crossing search-browse branch: {start}, {end}") continue if (start, end) == (1097, 1098): result.append([translate(start), 1115]) else: result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"], missing=False), arcs(entry["arcs"], missing=False) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True), } return result def reviewed_lifespan_source(root: Path, source_sha: str) -> bool: parent = root / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot" return (source_sha == LIFESPAN_APP_SHA and parent.is_file() and hashlib.sha256(parent.read_bytes()).hexdigest() == BROWSE_NEW_APP_SHA and reviewed_browse_source(root, BROWSE_NEW_APP_SHA)) def migrate_lifespan_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Translate all parent coordinates; new code remains outside the debt.""" if (hashlib.sha256(old_source.read_bytes()).hexdigest() != BROWSE_NEW_APP_SHA or hashlib.sha256(new_source.read_bytes()).hexdigest() != LIFESPAN_APP_SHA): raise ValueError("lifespan migration requires exact reviewed sources") operations = difflib.SequenceMatcher(None, old_source.read_text().splitlines(), new_source.read_text().splitlines(), autojunk=False).get_opcodes() if [op for op in operations if op[0] != "equal"] != [ ("replace", 1335, 1336, 1335, 1356), ("insert", 1352, 1352, 1372, 1374)]: raise ValueError("unexpected lifespan source diff") mapping = {i + 1: new_start + 1 + i - start for op, start, end, new_start, _ in operations if op == "equal" for i in range(start, end)} # The old await is now the shielded await. Its incoming false branch # still targets creation of the close task instead. mapping[1336] = 1341 entry = previous.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("lifespan migration requires app baseline") for covered, missing, count in (("lines", "missing_lines", "covered_lines"), ("arcs", "missing_arcs", "covered_branches")): convert = tuple if covered == "arcs" else lambda x: x a, b = entry[covered], entry[missing] if (entry[count] != len(a) or len(a) != len({convert(x) for x in a}) or len(b) != len({convert(x) for x in b}) or {convert(x) for x in a} & {convert(x) for x in b}): raise ValueError("invalid lifespan baseline coordinates") def translate(n: int) -> int: if type(n) is not int or abs(n) not in mapping: raise ValueError(f"unmapped lifespan coordinate: {n}") return (-1 if n < 0 else 1) * mapping[abs(n)] def arcs(values: list) -> list: return sorted([[1332, 1337] if [a, b] == [1332, 1336] else [translate(a), translate(b)] for a, b in values]) result = {name: dict(value) for name, value in previous.items()} lines = sorted(translate(n) for n in entry["lines"]) branches = arcs(entry["arcs"]) result["backend/app.py"] = {"lines": lines, "arcs": branches, "missing_lines": sorted(translate(n) for n in entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), "covered_lines": len(lines), "covered_branches": len(branches)} return result def lifespan_baseline_layout(debt: dict[str, dict[str, object]], parent: dict[str, dict[str, object]], parent_source: Path, current_source: Path) -> str: """Recognize only coordinate inventories belonging unambiguously to a pinned layout.""" current = migrate_lifespan_baseline(parent, parent_source, current_source) entry = debt.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("lifespan baseline lacks app entry") def coordinates(item: dict[str, object]) -> tuple[set, set]: return (set(item["lines"]) | set(item["missing_lines"]), {tuple(arc) for arc in item["arcs"] + item["missing_arcs"]}) lines, arcs = coordinates(entry) old_lines, old_arcs = coordinates(parent["backend/app.py"]) new_lines, new_arcs = coordinates(current["backend/app.py"]) # New-layout baselines may promote newly covered code, but may not # introduce unknown missing coordinates. Their covered coordinates may # include the reviewed new block. matches_old = lines <= old_lines and arcs <= old_arcs allowed_new_lines = new_lines | set(range(1337, 1357)) | {1373, 1374} matches_new = (lines <= allowed_new_lines and arcs <= (new_arcs | { (1339, 1340), (1344, 1345), (1344, 1346), (1346, 1347), (1346, 1339), (1349, 1350), (1349, 1351), (1373, 1374), (1373, -1295)})) if matches_old == matches_new: raise ValueError("ambiguous or unrecognized lifespan baseline layout") return "lifespan-parent" if matches_old else "current" def historical_reader_range_module(path: Path) -> Path: """Use the immutable pre-fix module for the historical extraction proof.""" if path.name != "reader_range_cache.py" or not path.is_file(): return path if hashlib.sha256(path.read_bytes()).hexdigest() != PROXY_SAFETY_NEW_RANGE_SHA: return path root = path.parent.parent app = root / "backend/app.py" source_sha = hashlib.sha256(app.read_bytes()).hexdigest() if app.is_file() else "" anchor = root / "scripts/coverage-anchors/proxy-safety-old-range.py.snapshot" if ((reviewed_proxy_safety_source(root, source_sha) or reviewed_browse_source(root, source_sha) or reviewed_lifespan_source(root, source_sha)) and anchor.is_file() and hashlib.sha256(anchor.read_bytes()).hexdigest() == RANGE_MODULE_SHA): return anchor return path def migrate_reader_range_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate the reviewed subrange move; the new module must be 100% covered.""" expected = ((old_source, RANGE_OLD_APP_SHA), (new_source, RANGE_NEW_APP_SHA), (historical_reader_range_module(extracted_source), RANGE_MODULE_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("reader-range migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/reader_range_cache.py" in previous: raise ValueError("reader-range migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 55, 55, 55, 56), ("replace", 2866, 2894, 2867, 2872)]: raise ValueError("unexpected reader-range source diff") moved = set(range(2867, 2895)) entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid reader-range baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid reader-range baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate reader-range coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped reader-range coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid reader-range baseline lines") return sorted(translate(value) for value in values if value not in moved) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid reader-range baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if abs(end) not in moved: raise ValueError(f"unexpected reader-range branch endpoint: {start}, {end}") continue result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_search_term_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate the reviewed search-term move; the new module must be 100% covered.""" expected = ((old_source, RANGE_NEW_APP_SHA), (new_source, TERM_NEW_APP_SHA), (extracted_source, TERM_MODULE_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-term migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/search_term_candidates.py" in previous: raise ValueError("search-term migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 39, 39, 39, 40), ("replace", 724, 780, 725, 732)]: raise ValueError("unexpected search-term source diff") moved = set(range(725, 781)) entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid search-term baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid search-term baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate search-term coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped search-term coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid search-term baseline lines") return sorted(translate(value) for value in values if value not in moved) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid search-term baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if abs(end) not in moved: raise ValueError(f"unexpected search-term branch endpoint: {start}, {end}") continue result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_single_term_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate the reviewed single-term move; the new module must be 100% covered.""" expected = ((old_source, WARM_NEW_APP_SHA), (new_source, SINGLE_NEW_APP_SHA), (extracted_source, SINGLE_MODULE_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("single-term migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/single_term_marker.py" in previous: raise ValueError("single-term migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("replace", 41, 42, 41, 43), ("replace", 1128, 1184, 1129, 1137)]: raise ValueError("unexpected single-term source diff") moved = set(range(1129, 1185)) | {42} entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid single-term baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid single-term baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate single-term coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped single-term coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid single-term baseline lines") return sorted(translate(value) for value in values if value not in moved) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid single-term baseline arcs") result: list[list[int]] = [] for start, end in values: if [start, end] == [1077, 1129]: result.append([translate(start), 1130]) continue if abs(start) in moved: if abs(end) not in moved: raise ValueError(f"unexpected single-term branch endpoint: {start}, {end}") continue result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_download_warm_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, extracted_source: Path ) -> dict[str, dict[str, object]]: """Translate the reviewed download-warm move; the new module must be 100% covered.""" expected = ((old_source, TERM_NEW_APP_SHA), (new_source, WARM_NEW_APP_SHA), (extracted_source, WARM_MODULE_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("download-warm migration requires exact reviewed sources") if "backend/app.py" not in previous or "backend/download_warm.py" in previous: raise ValueError("download-warm migration requires the original module inventory") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 35, 35, 35, 37), ("replace", 1238, 1253, 1240, 1241), ("replace", 1256, 1268, 1244, 1248)]: raise ValueError("unexpected download-warm source diff") moved = set(range(1239, 1254)) | set(range(1257, 1269)) entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid download-warm baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid download-warm baseline counts") if (len(entry["lines"]) != len(set(entry["lines"])) or len(entry["missing_lines"]) != len(set(entry["missing_lines"])) or len(entry["arcs"]) != len({tuple(arc) for arc in entry["arcs"]}) or len(entry["missing_arcs"]) != len({tuple(arc) for arc in entry["missing_arcs"]}) or set(entry["lines"]) & set(entry["missing_lines"]) or {tuple(arc) for arc in entry["arcs"]} & {tuple(arc) for arc in entry["missing_arcs"]}): raise ValueError("overlapping or duplicate download-warm coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped download-warm coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid download-warm baseline lines") return sorted(translate(value) for value in values if value not in moved) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid download-warm baseline arcs") result: list[list[int]] = [] for start, end in values: if abs(start) in moved: if abs(end) not in moved: raise ValueError(f"unexpected download-warm branch endpoint: {start}, {end}") continue result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def search_release_mapping(old_source: Path, new_source: Path) -> dict[int, int]: """Map unchanged coordinates across the pinned search semantics change.""" expected = ((old_source, SINGLE_NEW_APP_SHA), (new_source, SEARCH_RELEASE_APP_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("search-release migration requires exact reviewed sources") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() opcodes = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes() changes = [list(opcode) for opcode in opcodes if opcode[0] != "equal"] if hashlib.sha256(json.dumps(changes, separators=(",", ":")).encode()).hexdigest() != SEARCH_RELEASE_DIFF_SHA: raise ValueError("unexpected search-release source diff") return {index + 1: start_new + 1 + index - start for op, start, end, start_new, _ in opcodes if op == "equal" for index in range(start, end)} def migrate_search_release_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path, old_term: Path, new_term: Path) -> dict[str, dict[str, object]]: """Retire only changed coordinates and demand full replacement coverage. Unchanged lines and branches retain their prior status. Edited search code and the modified term-candidate module are absent from prior debt, so the regular ratchet requires every replacement statement and branch. """ mapping = search_release_mapping(old_source, new_source) if (hashlib.sha256(old_term.read_bytes()).hexdigest() != SINGLE_MODULE_SHA or hashlib.sha256(new_term.read_bytes()).hexdigest() != SEARCH_RELEASE_TERM_SHA): raise ValueError("search-release migration requires exact reviewed term sources") if "backend/app.py" not in previous or "backend/search_term_candidates.py" in previous: raise ValueError("search-release migration requires original inventory") entry = previous["backend/app.py"] fields = ("lines", "missing_lines", "arcs", "missing_arcs") if not all(isinstance(entry.get(field), list) for field in fields): raise ValueError("invalid search-release baseline coordinates") if (entry.get("covered_lines") != len(entry["lines"]) or entry.get("covered_branches") != len(entry["arcs"])): raise ValueError("invalid search-release baseline counts") old_count = len(old_source.read_text().splitlines()) lines = entry["lines"] + entry["missing_lines"] arcs = entry["arcs"] + entry["missing_arcs"] if (any(type(value) is not int or not 1 <= value <= old_count for value in lines) or len(lines) != len(set(lines)) or any(not isinstance(arc, list) or len(arc) != 2 or any(type(value) is not int or not 1 <= abs(value) <= old_count for value in arc) for arc in arcs) or len(arcs) != len({tuple(arc) for arc in arcs})): raise ValueError("invalid or overlapping search-release coordinates") redirected = {(705, 707): (731, 735), (708, 710): (738, 740), (1036, 1038): (1083, 1085), (1157, 1158): (1246, 1247)} def translate(number: int) -> int: return (-1 if number < 0 else 1) * mapping[abs(number)] def moved_lines(values: list[int]) -> list[int]: return sorted(translate(value) for value in values if value in mapping) def moved_arcs(values: list[list[int]]) -> list[list[int]]: result = [] for start, end in values: replacement = redirected.get((start, end)) if replacement is not None: result.append(list(replacement)) elif abs(start) in mapping and abs(end) in mapping: result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = moved_lines(entry["lines"]), moved_arcs(entry["arcs"]) # The former star-only dispatch was changed, not removed. Retain both # branches explicitly under the new wildcard-aware condition. if 992 in entry["lines"]: covered_lines.append(1033) if [992, 993] in entry["arcs"]: covered_arcs.append([1033, 1034]) if [992, 997] in entry["arcs"]: covered_arcs.append([1033, 1038]) covered_lines.sort() covered_arcs.sort() missing_lines, missing_arcs = moved_lines(entry["missing_lines"]), moved_arcs(entry["missing_arcs"]) if (set(covered_lines) & set(missing_lines) or len(covered_lines + missing_lines) != len(set(covered_lines + missing_lines)) or {tuple(arc) for arc in covered_arcs} & {tuple(arc) for arc in missing_arcs} or len(covered_arcs + missing_arcs) != len({tuple(arc) for arc in covered_arcs + missing_arcs})): raise ValueError("overlapping translated search-release coordinates") result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": missing_lines, "missing_arcs": missing_arcs, } return result def migrate_search_sigma_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Translate the pinned contextual-sigma fallback; no old coverage is retired.""" if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in ( (old_source, SEARCH_RELEASE_APP_SHA), (new_source, SEARCH_SIGMA_APP_SHA))): raise ValueError("search-sigma migration requires exact reviewed sources") mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher( None, old_source.read_text().splitlines(), new_source.read_text().splitlines(), autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 735, 735, 735, 740)]: raise ValueError("unexpected search-sigma source diff") entry = previous.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("missing search-sigma application baseline") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped search-sigma coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid search-sigma baseline lines") return sorted(translate(value) for value in values) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid search-sigma baseline arcs") result = [] for start, end in values: # The old index-fallback branch now enters the sigma condition. if (start, end) == (735, 737): result.append([translate(start), 740]) else: result.append([translate(start), translate(end)]) return sorted(result) covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) if (entry.get("covered_lines") != len(covered_lines) or entry.get("covered_branches") != len(covered_arcs)): raise ValueError("invalid search-sigma baseline counts") result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = {"covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"])} return result def proxy_safety_mapping(old_source: Path, new_source: Path, *, streams: bool = False) -> dict[int, int]: """Translate every covered coordinate across the pinned transport fix.""" expected = ((old_source, PROXY_SAFETY_OLD_STREAMS_SHA if streams else PROXY_SAFETY_OLD_APP_SHA), (new_source, PROXY_SAFETY_NEW_STREAMS_SHA if streams else PROXY_SAFETY_NEW_APP_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("proxy-safety migration requires exact reviewed sources") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() operations = difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes() changes = [list(item) for item in operations if item[0] != "equal"] digest = hashlib.sha256(json.dumps(changes, separators=(",", ":")).encode()).hexdigest() if digest != (PROXY_SAFETY_STREAMS_DIFF_SHA if streams else PROXY_SAFETY_APP_DIFF_SHA): raise ValueError("unexpected proxy-safety source diff") mapping = {index + 1: new_start + 1 + index - start for op, start, end, new_start, _ in operations if op == "equal" for index in range(start, end)} # These lines only moved under a new ownership/cache-policy guard. The # earlier behavior and its covered branches remain mandatory. preserved = ({153: 160, 154: 161} if streams else { 2356: 2360, 2357: 2361, 2358: 2362, 2359: 2364, 2361: 2366, 2362: 2367, 2363: 2368, 2364: 2369, 2365: 2370, 2399: 2438, 2400: 2439, 2401: 2440, 2402: 2441, 2403: 2442, 2404: 2443, 2405: 2444, 2406: 2445, 2407: 2446, 2410: 2449, 2411: 2450, 2412: 2451, 2413: 2452, 2414: 2453, 2415: 2454, }) if set(preserved) & set(mapping): raise ValueError("proxy-safety explicit map overlaps unchanged source") for old_line, new_line in preserved.items(): if old[old_line - 1].strip() != new[new_line - 1].strip() and not ( streams and old_line in (153, 154)) and not (old_line == 2358 and not streams): raise ValueError("proxy-safety mapped behavior changed unexpectedly") mapping.update(preserved) return mapping def migrate_proxy_safety_baseline(previous: dict[str, dict[str, object]], old_app: Path, new_app: Path, old_streams: Path, new_streams: Path) -> dict[str, dict[str, object]]: """Preserve prior lines/arcs and force all added transport code to be covered.""" result = {name: dict(item) for name, item in previous.items()} for name, old_path, new_path, streams in (("backend/app.py", old_app, new_app, False), ("backend/proxy_streams.py", old_streams, new_streams, True)): mapping = proxy_safety_mapping(old_path, new_path, streams=streams) entry = previous.get(name) if not isinstance(entry, dict): raise ValueError("missing proxy-safety parent baseline") def translate(value: int) -> int: if type(value) is not int or abs(value) not in mapping: raise ValueError(f"unmapped proxy-safety coordinate: {value}") return (-1 if value < 0 else 1) * mapping[abs(value)] lines = sorted(translate(value) for value in entry["lines"]) missing_lines = sorted(translate(value) for value in entry["missing_lines"]) # The new cache-validation and overflow/early-response guards sit # between otherwise unchanged branches. Preserve those original paths # at their semantically equivalent new entry/exit points. redirected = ({(152, 153): (156, 157), (157, 168): (164, 170)} if streams else {(2398, 2399): (2427, 2431), (2487, 2493): (2527, 2529)}) def arc(start: int, end: int) -> list[int]: replacement = redirected.get((start, end)) return list(replacement) if replacement is not None else [translate(start), translate(end)] arcs = sorted([arc(start, end) for start, end in entry["arcs"]]) missing_arcs = sorted([arc(start, end) for start, end in entry["missing_arcs"]]) if (entry["covered_lines"] != len(lines) or entry["covered_branches"] != len(arcs) or len(set(lines + missing_lines)) != len(lines) + len(missing_lines) or len({tuple(arc) for arc in arcs + missing_arcs}) != len(arcs) + len(missing_arcs)): raise ValueError("invalid or overlapping proxy-safety coordinates") result[name] = {"covered_lines": len(lines), "covered_branches": len(arcs), "lines": lines, "missing_lines": missing_lines, "arcs": arcs, "missing_arcs": missing_arcs} return result def reviewed_proxy_safety_source(root: Path, source_sha: str) -> bool: if source_sha != PROXY_SAFETY_NEW_APP_SHA: return False anchors = root / "scripts/coverage-anchors" expected = ((anchors / "proxy-safety-old-app.py.snapshot", PROXY_SAFETY_OLD_APP_SHA), (anchors / "proxy-safety-new-app.py.snapshot", PROXY_SAFETY_NEW_APP_SHA), (anchors / "proxy-safety-old-streams.py.snapshot", PROXY_SAFETY_OLD_STREAMS_SHA), (anchors / "proxy-safety-new-streams.py.snapshot", PROXY_SAFETY_NEW_STREAMS_SHA), (anchors / "proxy-safety-old-range.py.snapshot", RANGE_MODULE_SHA), (anchors / "proxy-safety-new-range.py.snapshot", PROXY_SAFETY_NEW_RANGE_SHA), (anchors / "proxy-safety-old-backend-coverage-debt.json", PROXY_SAFETY_PARENT_DEBT_SHA), (root / "backend/proxy_streams.py", PROXY_SAFETY_NEW_STREAMS_SHA), (root / "backend/reader_range_cache.py", PROXY_SAFETY_NEW_RANGE_SHA)) return all(path.is_file() and hashlib.sha256(path.read_bytes()).hexdigest() == digest for path, digest in expected) def migrate_native_postings_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Translate the reviewed posting-decoder wrapper without relaxing coverage.""" expected = ( (old_source, "dba3681ac430bc10a20235a3b06b676f4c481aae71404591a92afefbe559d4ba"), (new_source, "95d1c3fd9e41c0bb1cc875f349c611033fea50eb848b5b4ae2fb39bdc2cdeba5"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("native-postings coverage migration requires exact reviewed sources") entry = previous.get("backend/search_indexes.py") entry_bytes = json.dumps(entry, sort_keys=True, separators=(",", ":")).encode() if hashlib.sha256(entry_bytes).hexdigest() != "026965bf8ea2948ce608589c9e920b0b73e6d29d75bcd7ae97549cdcb03e0ae5": raise ValueError("native-postings coverage migration requires exact previous index baseline") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("replace", 13, 14, 13, 14), ("replace", 15, 16, 15, 19), ("insert", 41, 41, 44, 58)]: raise ValueError("unexpected native-postings source diff") # Import and optional-extension fallback retain the same coverage meaning. mapping.update({14: 14, 16: 16}) def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped native-postings coverage coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid native-postings baseline lines") return sorted(translate(number) for number in values) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid native-postings baseline arcs") return sorted([[translate(start), translate(end)] for start, end in values]) if not isinstance(entry, dict): raise ValueError("missing native-postings baseline") covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/search_indexes.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_star_browse_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Translate only the reviewed all-star dispatch insertion, preserving every coordinate.""" expected = ( (old_source, "db91dcb900f0e4b22a31c62e75b14aec01a62cf7640b8e34fa57a11f53a12920"), (new_source, "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d"), ) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("star-browse migration requires exact reviewed sources") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("insert", 967, 967, 967, 974)]: raise ValueError("unexpected star-browse source diff") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped star-browse coverage coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid star-browse baseline lines") result = [translate(number) for number in values] if len(result) != len(set(result)): raise ValueError("duplicate star-browse baseline lines") return sorted(result) def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid star-browse baseline arcs") result = [[translate(start), translate(end)] for start, end in values] if len(result) != len({tuple(arc) for arc in result}): raise ValueError("duplicate star-browse baseline arcs") return sorted(result) entry = previous.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("missing star-browse application baseline") covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) if entry["covered_lines"] != len(covered_lines) or entry["covered_branches"] != len(covered_arcs): raise ValueError("invalid star-browse baseline counts") result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def migrate_pdf_limit_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Move reviewed coverage coordinates across the exact PDF-limit edit. Only the now-deleted bounded-range selection and its two obsolete branches are retired. Newly introduced PDF paths must be covered separately. """ expected = ((old_source, "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d"), (new_source, "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca")) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("PDF limit migration requires exact reviewed sources") old, new = old_source.read_text().splitlines(), new_source.read_text().splitlines() mapping: dict[int, int] = {} changes: list[tuple[str, int, int, int, int]] = [] for op, start, end, new_start, new_end in difflib.SequenceMatcher(None, old, new, autojunk=False).get_opcodes(): if op == "equal": mapping.update({index + 1: new_start + 1 + index - start for index in range(start, end)}) else: changes.append((op, start, end, new_start, new_end)) if changes != [("replace", 1624, 1627, 1624, 1627), ("replace", 2034, 2035, 2034, 2036), ("insert", 2383, 2383, 2384, 2386), ("insert", 2450, 2450, 2453, 2454), ("delete", 2458, 2459, 2462, 2462), ("delete", 2460, 2463, 2463, 2463), ("replace", 2508, 2509, 2508, 2511)]: raise ValueError("unexpected PDF limit source diff") mapping[1627] = 1627 # Replaced import-time constant remains covered. # These exact statements and branches implemented the removed special # bounded-range ceiling; both new PDF paths are checked as new coverage. retired_lines = {2459, 2461, 2463} retired_arcs = {(2461, 2463), (2461, 2466)} entry = previous.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("missing PDF limit application baseline") line_values = entry.get("lines"), entry.get("missing_lines") arc_values = entry.get("arcs"), entry.get("missing_arcs") if not all(isinstance(values, list) for values in (*line_values, *arc_values)): raise ValueError("invalid PDF limit baseline coordinates") if (set(line_values[0]) & set(line_values[1]) or {tuple(arc) for arc in arc_values[0]} & {tuple(arc) for arc in arc_values[1]}): raise ValueError("PDF limit baseline coordinates overlap") if (any(len(values) != len(set(values)) for values in line_values) or any(len(values) != len({tuple(arc) for arc in values}) for values in arc_values)): raise ValueError("duplicate PDF limit baseline coordinates") def translate(number: int) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped PDF limit coverage coordinate: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def lines(values: object, *, missing: bool = False) -> list[int]: if not isinstance(values, list): raise ValueError("invalid PDF limit baseline lines") if missing and retired_lines.intersection(values): raise ValueError("retired PDF limit lines cannot be baseline debt") result = [translate(number) for number in values if number not in retired_lines] if len(result) != len(set(result)): raise ValueError("duplicate PDF limit baseline lines") return sorted(result) def arcs(values: object, *, missing: bool = False) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid PDF limit baseline arcs") if missing and retired_arcs.intersection(map(tuple, values)): raise ValueError("retired PDF limit arcs cannot be baseline debt") result = [[translate(start), translate(end)] for start, end in values if (start, end) not in retired_arcs] if len(result) != len({tuple(arc) for arc in result}): raise ValueError("duplicate PDF limit baseline arcs") return sorted(result) if entry.get("covered_lines") != len(entry.get("lines", [])) or entry.get("covered_branches") != len(entry.get("arcs", [])): raise ValueError("invalid PDF limit baseline counts") covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"], missing=True), "missing_arcs": arcs(entry["missing_arcs"], missing=True), } return result GENERIC_CALLABLES = frozenset({"set", "dict", "list", "tuple", "frozenset", "OrderedDict", "defaultdict", "deque"}) class _TypingNormalizer(ast.NodeTransformer): """Erase annotations, casts and subscripted constructors; executable code stays intact.""" def visit_arg(self, node: ast.arg) -> ast.arg: node.annotation = None return node def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef: self.generic_visit(node) node.returns = None return node def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> ast.AsyncFunctionDef: self.generic_visit(node) node.returns = None return node def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AST | None: self.generic_visit(node) if node.value is None: return None return ast.copy_location(ast.Assign(targets=[node.target], value=node.value), node) def visit_alias(self, node: ast.alias) -> ast.alias: if node.asname == node.name: node.asname = None return node def visit_Call(self, node: ast.Call) -> ast.AST: self.generic_visit(node) if isinstance(node.func, ast.Name) and node.func.id == "cast" and len(node.args) == 2 and not node.keywords: return node.args[1] if (isinstance(node.func, ast.Subscript) and isinstance(node.func.value, ast.Name) and node.func.value.id in GENERIC_CALLABLES): node.func = node.func.value return node def _typing_statements(source: str) -> list[tuple[int, str, str]]: """Executable statements as (line, kind, structural signature) in source order.""" tree = _TypingNormalizer().visit(ast.parse(source)) result: list[tuple[int, str, str]] = [] def signature(node: ast.stmt) -> str: fields = {name: getattr(node, name, None) for name in node._fields} for name, value in fields.items(): if isinstance(value, list) and value and isinstance(value[0], (ast.stmt, ast.excepthandler)): fields[name] = [] if "decorator_list" in fields: fields["decorator_list"] = [] return ast.dump(type(node)(**fields), annotate_fields=False) def visit(body: list[ast.stmt]) -> None: for node in body: if isinstance(node, ast.Match): raise ValueError("unsupported match statement in typing migration") for decorator in getattr(node, "decorator_list", []): result.append((decorator.lineno, "decorator", ast.dump(decorator, annotate_fields=False))) result.append((node.lineno, type(node).__name__, signature(node))) for field in ("body", "orelse", "finalbody"): visit(getattr(node, field, None) or []) for handler in getattr(node, "handlers", None) or []: plain = ast.ExceptHandler(type=handler.type, name=handler.name, body=[]) result.append((handler.lineno, "ExceptHandler", ast.dump(plain, annotate_fields=False))) visit(handler.body) visit(tree.body) return result def typing_alignment(old_source: str, new_source: str ) -> tuple[dict[int, int], dict[int, int], list[int], list[list[object]]]: """Align two sources statement by statement; only type-only insertions may change the shape.""" old, new = _typing_statements(old_source), _typing_statements(new_source) lines: dict[int, int] = {} entries: dict[int, int] = {} added: list[int] = [] review: list[list[object]] = [] for op, a0, a1, b0, b1 in difflib.SequenceMatcher(None, [s[2] for s in old], [s[2] for s in new], autojunk=False).get_opcodes(): if op == "equal": for offset in range(a1 - a0): lines[old[a0 + offset][0]] = entries[old[a0 + offset][0]] = new[b0 + offset][0] continue olds, news = old[a0:a1], new[b0:b1] review.append([op, [[s[0], s[1]] for s in olds], [[s[0], s[1]] for s in news]]) entry = b0 for kop, k0, k1, m0, m1 in difflib.SequenceMatcher(None, [s[1] for s in olds], [s[1] for s in news], autojunk=False).get_opcodes(): if kop == "equal": for offset in range(k1 - k0): lines[olds[k0 + offset][0]] = news[m0 + offset][0] entries[olds[k0 + offset][0]] = new[entry][0] entry = b0 + m0 + offset + 1 elif kop == "insert": added.extend(s[0] for s in news[m0:m1]) else: raise ValueError("typing edit changed statement kinds") return lines, entries, added, review def migrate_backend_typing_app_baseline(previous: dict[str, dict[str, object]], old_source: Path, new_source: Path) -> dict[str, dict[str, object]]: """Translate coordinates across the reviewed annotation-only edit of backend/app.py.""" expected = ((old_source, READER_ARCHIVE_NEW_APP_SHA), (new_source, TYPING_NEW_APP_SHA)) if any(hashlib.sha256(path.read_bytes()).hexdigest() != digest for path, digest in expected): raise ValueError("backend typing coverage migration requires exact reviewed sources") mapping, entries, added, review = typing_alignment(old_source.read_text(), new_source.read_text()) digest = hashlib.sha256(json.dumps({"added": added, "review": review}, separators=(",", ":")).encode()).hexdigest() if digest != TYPING_REVIEW_SHA: raise ValueError("unexpected backend typing source diff") entry = previous.get("backend/app.py") if not isinstance(entry, dict): raise ValueError("missing backend typing application baseline") def line(number: object) -> int: if type(number) is not int or abs(number) not in mapping: raise ValueError(f"unmapped backend typing line: {number}") return (-1 if number < 0 else 1) * mapping[abs(number)] def target(number: object) -> int: if type(number) is int and number > 0 and number in entries: return entries[number] return line(number) def lines(values: object) -> list[int]: if not isinstance(values, list): raise ValueError("invalid backend typing baseline lines") result = sorted(line(number) for number in values) if len(result) != len(set(result)): raise ValueError("duplicate backend typing baseline lines") return result def arcs(values: object) -> list[list[int]]: if not isinstance(values, list): raise ValueError("invalid backend typing baseline arcs") result = sorted([line(start), target(end)] for start, end in values) if len(result) != len({tuple(arc) for arc in result}): raise ValueError("duplicate backend typing baseline arcs") return result covered_lines, covered_arcs = lines(entry["lines"]), arcs(entry["arcs"]) if entry.get("covered_lines") != len(covered_lines) or entry.get("covered_branches") != len(covered_arcs): raise ValueError("invalid backend typing baseline counts") result = {name: dict(item) for name, item in previous.items()} result["backend/app.py"] = { "covered_lines": len(covered_lines), "covered_branches": len(covered_arcs), "lines": covered_lines, "arcs": covered_arcs, "missing_lines": lines(entry["missing_lines"]), "missing_arcs": arcs(entry["missing_arcs"]), } return result def type_only_lines(path: Path) -> set[int]: """Only typing overload/protocol declarations are non-executable here.""" source = path.read_text() tree = ast.parse(source) lines: set[int] = set() # coverage.py associates blank separators with the preceding overload or # Protocol method. Blank physical lines have no executable behavior. lines.update(index for index, line in enumerate(source.splitlines(), 1) if not line.strip()) for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and any( isinstance(dec, ast.Name) and dec.id == "overload" for dec in node.decorator_list): lines.update(range(node.lineno, (node.end_lineno or node.lineno) + 1)) lines.update(dec.lineno for dec in node.decorator_list) elif isinstance(node, ast.ClassDef) and any( isinstance(base, ast.Name) and base.id == "Protocol" for base in node.bases): lines.update(range(node.lineno, (node.end_lineno or node.lineno) + 1)) return lines def migrate_ci_baseline_to_lifespan_parent(root: Path, previous: dict) -> dict: """Replay the audited chain from the independently pinned CI baseline.""" anchors = root / "scripts/coverage-anchors" anchor = anchors / "search-projection-old-backend-coverage-debt.json" if (hashlib.sha256(anchor.read_bytes()).hexdigest() != "70e9311f50ba1407227de9ba42fd591d93826f92898d07873ce5f58cbebf2a29" or previous != json.loads(anchor.read_text())): raise ValueError("transport migration requires the independently pinned parent or CI debt") # Each existing translator checks its exact reviewed sources and preserves # covered/missing coordinates. Use only immutable snapshots, not live # canonical modules or current coverage reports. def source(name: str) -> Path: return anchors / (name + ".py.snapshot") steps = ( (migrate_search_projection_app_baseline, source("search-projection-old-app"), source("search-projection-new-app"), source("search-projection-new-module")), (migrate_search_candidates_app_baseline, source("search-projection-new-app"), source("search-candidates-new-app"), source("search-candidates-new-module")), (migrate_search_bootstrap_app_baseline, source("search-candidates-new-app"), source("search-bootstrap-new-app"), source("search-bootstrap-new-module")), (migrate_native_postings_baseline, source("native-postings-old-index"), source("native-postings-new-index")), (migrate_star_browse_app_baseline, source("star-browse-old-app"), source("pdf-limit-old-app")), (migrate_pdf_limit_app_baseline, source("pdf-limit-old-app"), source("reader-archive-old-app")), (migrate_reader_archive_app_baseline, source("reader-archive-old-app"), source("reader-archive-new-app"), source("reader-archive-new-module")), (migrate_backend_typing_app_baseline, source("reader-archive-new-app"), source("backend-typing-new-app")), (migrate_folder_contents_app_baseline, source("backend-typing-new-app"), source("range-cache-old-app"), source("folder-contents-new-module")), (migrate_reader_range_app_baseline, source("range-cache-old-app"), source("term-candidates-old-app"), source("proxy-safety-old-range")), (migrate_search_term_app_baseline, source("term-candidates-old-app"), source("download-warm-old-app"), source("single-term-old-module")), (migrate_download_warm_app_baseline, source("download-warm-old-app"), source("single-term-old-app"), source("download-warm-new-module")), (migrate_single_term_app_baseline, source("single-term-old-app"), source("search-release-old-app"), source("search-release-old-term")), (migrate_search_release_baseline, source("search-release-old-app"), source("search-release-new-app"), source("search-release-old-term"), source("search-release-new-term")), (migrate_search_sigma_baseline, source("search-release-new-app"), source("search-sigma-new-app")), (migrate_seo_path_baseline, source("seo-path-old-seo"), source("seo-path-new-seo"), anchors / "seo-path-old-debt.json"), (migrate_proxy_safety_baseline, source("proxy-safety-old-app"), source("proxy-safety-new-app"), source("proxy-safety-old-streams"), source("proxy-safety-new-streams")), (migrate_search_browse_baseline, source("proxy-safety-new-app"), source("lifespan-parent-app"), source("search-browse-new-module")), ) for migrate, *sources in steps: previous = migrate(previous, *sources) return previous def coverage_debt_errors(baseline: dict, previous_baseline: dict) -> list[str]: """Require every prior exercised coordinate and forbid growing missing debt.""" errors = [] for path in sorted(set(baseline) - set(previous_baseline)): errors.append(f"backend coverage debt cannot grow: {path}") for path in sorted(set(baseline) & set(previous_baseline)): old, new = previous_baseline[path], baseline[path] if (new["covered_lines"] < old["covered_lines"] or new["covered_branches"] < old["covered_branches"] or not set(old["lines"]) <= set(new["lines"]) or not { tuple(arc) for arc in old["arcs"]} <= {tuple(arc) for arc in new["arcs"]} or not set(new["missing_lines"]) <= set(old["missing_lines"]) or not {tuple(arc) for arc in new["missing_arcs"]} <= { tuple(arc) for arc in old["missing_arcs"]}): errors.append(f"backend coverage debt cannot remove prior exercised lines or arcs: {path}") return errors def coverage_errors(root: Path, report: dict[str, object], baseline: dict[str, dict[str, object]], previous_baseline: dict[str, dict[str, object]] | None = None, *, baseline_layout: str = "current", previous_layout: str = "current") -> list[str]: if baseline_layout not in ("current", "lifespan-parent") or previous_layout not in ("current", "lifespan-parent"): raise ValueError("unknown coverage baseline layout") if baseline_layout == "lifespan-parent" or (previous_baseline is not None and previous_layout == "lifespan-parent"): app_source = root / "backend/app.py" if not app_source.is_file() or not reviewed_lifespan_source(root, hashlib.sha256(app_source.read_bytes()).hexdigest()): raise ValueError("lifespan parent layout requires reviewed target") anchor = root / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot" if baseline_layout == "lifespan-parent": baseline = migrate_lifespan_baseline(baseline, anchor, app_source) if previous_baseline is not None and previous_layout == "lifespan-parent": previous_baseline = migrate_lifespan_baseline(previous_baseline, anchor, app_source) meta = report.get("meta") if not isinstance(meta, dict) or meta.get("branch_coverage") is not True: return ["coverage JSON must include branch coverage"] files = report.get("files") if not isinstance(files, dict): return ["coverage JSON has no files"] sources = {path.relative_to(root).as_posix() for path in (root / "backend").rglob("*.py") if "__pycache__" not in path.relative_to(root).parts} sources.add("app.py") errors: list[str] = [] transport = (root / 'backend/app.py').is_file() and transport_layout(root) if transport: # Independent files often resolve to the same historical inventory. # Validate its migration once per check, not once per equal copy. The # comparison stays in place; distinct inventories are always verified. same_baseline = (previous_baseline is not None and json.dumps(previous_baseline, sort_keys=True) == json.dumps(baseline, sort_keys=True)) baseline = transport_baseline(root, baseline) if same_baseline: previous_baseline = baseline elif previous_baseline is not None: previous_baseline = transport_baseline(root, previous_baseline) if previous_baseline is not None: errors.extend(coverage_debt_errors(baseline, previous_baseline)) for path in sorted(set(baseline) - sources): errors.append(f"stale backend coverage debt entry: {path}") for path in sorted(sources): source_text = (root / path).read_text() if any(marker in source_text.lower() for marker in ( "pragma: no cover", "pragma: no branch", "pragma: no mutate")): errors.append(f"coverage pragmas are forbidden in backend source: {path}") if path == "backend/app.py" and transport and path in baseline: # Source-pinned migration preserves the existing browse dispatch. # Refactor23 instead requires 100% for the entire app and all # extracted modules after validating the parent's dispatch ratchet. entry = baseline[path] if not {1062, 1063} <= set(entry['lines']) or not { (1062, 1063), (1062, 1067)} <= {tuple(arc) for arc in entry['arcs']}: errors.append("star-browse coverage baseline must retain both dispatch branches") if path == "backend/app.py" and not transport and (root / "scripts/coverage-anchors/star-browse-old-app.py.snapshot").exists(): source_sha = hashlib.sha256(source_text.encode()).hexdigest() pdf_anchor = root / "scripts/coverage-anchors/pdf-limit-old-app.py.snapshot" reviewed_pdf_source = pdf_anchor.exists() and hashlib.sha256(pdf_anchor.read_bytes()).hexdigest() == "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d" archive_anchor = root / "scripts/coverage-anchors/reader-archive-old-app.py.snapshot" reviewed_archive_source = (reviewed_pdf_source and archive_anchor.exists() and hashlib.sha256(archive_anchor.read_bytes()).hexdigest() == READER_ARCHIVE_OLD_APP_SHA) typing_anchor = root / "scripts/coverage-anchors/backend-typing-new-app.py.snapshot" reviewed_typing_source = (reviewed_archive_source and typing_anchor.exists() and hashlib.sha256(typing_anchor.read_bytes()).hexdigest() == TYPING_NEW_APP_SHA) folder_source = root / "backend/folder_contents.py" reviewed_folder_source = (reviewed_typing_source and folder_source.exists() and hashlib.sha256(folder_source.read_bytes()).hexdigest() == "931758f2f2b76b4cbe51a00b3a5f408c48d9b4e42104476ee21cdd49a083b56d") sigma_source = root / "scripts/coverage-anchors/search-sigma-new-app.py.snapshot" sigma_debt = root / "scripts/coverage-anchors/search-sigma-old-debt.json" reviewed_browse = (reviewed_browse_source(root, source_sha) or reviewed_lifespan_source(root, source_sha)) reviewed_proxy = reviewed_proxy_safety_source(root, source_sha) or reviewed_browse reviewed_sigma = ((source_sha in (SEARCH_SIGMA_APP_SHA, SEARCH_SIGMA_VERSION_APP_SHA) or reviewed_proxy) and sigma_source.exists() and sigma_debt.exists() and hashlib.sha256(sigma_source.read_bytes()).hexdigest() == SEARCH_SIGMA_APP_SHA and hashlib.sha256(sigma_debt.read_bytes()).hexdigest() == SEARCH_SIGMA_OLD_DEBT_SHA) release_source_sha = SEARCH_RELEASE_APP_SHA if reviewed_sigma else source_sha if source_sha != "7ae334c03f2d0b047332abf145b794f01e2921188313f5a8ee323399b006073d" and not ( reviewed_pdf_source and source_sha == "282870ab2574f5201c90dcffd2f04ad452f89fa70a1791f868272d327430c0ca") and not ( reviewed_archive_source and source_sha == READER_ARCHIVE_NEW_APP_SHA) and not ( reviewed_typing_source and source_sha == TYPING_NEW_APP_SHA) and not ( reviewed_folder_source and source_sha == RANGE_OLD_APP_SHA) and not ( reviewed_folder_source and source_sha == RANGE_NEW_APP_SHA and (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and (root / "backend/reader_range_cache.py").exists() and hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA) and not ( reviewed_folder_source and source_sha == TERM_NEW_APP_SHA and (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and (root / "backend/reader_range_cache.py").exists() and hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and (root / "backend/search_term_candidates.py").exists() and hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == TERM_MODULE_SHA) and not ( reviewed_folder_source and source_sha == WARM_NEW_APP_SHA and (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and (root / "backend/reader_range_cache.py").exists() and hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and (root / "backend/search_term_candidates.py").exists() and hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and (root / "backend/download_warm.py").exists() and hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA) and not ( reviewed_folder_source and source_sha == SINGLE_NEW_APP_SHA and (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and (root / "backend/reader_range_cache.py").exists() and hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA and (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and (root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and (root / "backend/download_warm.py").exists() and hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA and (root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").read_bytes()).hexdigest() == WARM_NEW_APP_SHA and (root / "backend/search_term_candidates.py").exists() and hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == SINGLE_MODULE_SHA) and not ( reviewed_folder_source and release_source_sha == SEARCH_RELEASE_APP_SHA and (root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/range-cache-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_OLD_APP_SHA and (root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot").read_bytes()).hexdigest() == RANGE_NEW_APP_SHA and (root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-module.py.snapshot").read_bytes()).hexdigest() == TERM_MODULE_SHA and (root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/download-warm-old-app.py.snapshot").read_bytes()).hexdigest() == TERM_NEW_APP_SHA and (root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/single-term-old-app.py.snapshot").read_bytes()).hexdigest() == WARM_NEW_APP_SHA and (root / "scripts/coverage-anchors/search-release-old-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-app.py.snapshot").read_bytes()).hexdigest() == SINGLE_NEW_APP_SHA and (root / "scripts/coverage-anchors/search-release-new-app.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/search-release-new-app.py.snapshot").read_bytes()).hexdigest() == SEARCH_RELEASE_APP_SHA and (root / "scripts/coverage-anchors/search-release-old-term.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-term.py.snapshot").read_bytes()).hexdigest() == SINGLE_MODULE_SHA and (root / "scripts/coverage-anchors/search-release-new-term.py.snapshot").exists() and hashlib.sha256((root / "scripts/coverage-anchors/search-release-new-term.py.snapshot").read_bytes()).hexdigest() == SEARCH_RELEASE_TERM_SHA and (root / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json").exists() and hashlib.sha256((root / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json").read_bytes()).hexdigest() == SEARCH_RELEASE_DEBT_SHA and (root / "backend/search_term_candidates.py").exists() and hashlib.sha256((root / "backend/search_term_candidates.py").read_bytes()).hexdigest() == SEARCH_RELEASE_TERM_SHA and (root / "backend/reader_range_cache.py").exists() and (hashlib.sha256((root / "backend/reader_range_cache.py").read_bytes()).hexdigest() == RANGE_MODULE_SHA or reviewed_proxy) and (root / "backend/download_warm.py").exists() and hashlib.sha256((root / "backend/download_warm.py").read_bytes()).hexdigest() == WARM_MODULE_SHA): errors.append("star-browse coverage ratchet requires exact reviewed app source") else: entry = baseline.get(path, {}) if reviewed_browse: first, second, third = 1057, 1058, 1062 elif reviewed_proxy: first, second, third = 1040, 1041, 1045 elif reviewed_sigma: first, second, third = 1038, 1039, 1043 elif source_sha == SEARCH_RELEASE_APP_SHA: first, second, third = 1033, 1034, 1038 elif source_sha == SINGLE_NEW_APP_SHA: first, second, third = 992, 993, 997 elif source_sha == WARM_NEW_APP_SHA: first, second, third = 991, 992, 996 elif source_sha == TERM_NEW_APP_SHA: first, second, third = 989, 990, 994 elif source_sha == RANGE_NEW_APP_SHA: first, second, third = 1037, 1038, 1042 elif source_sha == RANGE_OLD_APP_SHA: first, second, third = 1036, 1037, 1041 else: first, second, third = (1035, 1036, 1040) if source_sha == TYPING_NEW_APP_SHA else (971, 972, 976) if not {first, second} <= set(entry.get("lines", [])) or not { (first, second), (first, third)} <= {tuple(arc) for arc in entry.get("arcs", [])}: errors.append("star-browse coverage baseline must retain both dispatch branches") item = files.get(path) if not isinstance(item, dict) or not isinstance(item.get("summary"), dict): errors.append(f"missing backend coverage report: {path}") continue summary = item["summary"] excluded = item.get("excluded_lines") if (not isinstance(excluded, list) or not all(isinstance(value, int) for value in excluded) or not set(excluded) <= type_only_lines(root / path)): errors.append(f"non-type-only coverage exclusions are forbidden: {path}") statements = summary.get("num_statements") branches = summary.get("num_branches") covered = summary.get("covered_lines") covered_branches = summary.get("covered_branches") executed_lines, missing_lines = item.get("executed_lines"), item.get("missing_lines") executed_arcs, missing_arcs = item.get("executed_branches"), item.get("missing_branches") if not all(isinstance(value, list) for value in (executed_lines, missing_lines, executed_arcs, missing_arcs)): errors.append(f"coverage JSON lacks detailed lines or branch arcs: {path}") continue if not all(isinstance(value, int) and value >= 0 for value in (statements, branches, covered, covered_branches)): errors.append(f"invalid backend coverage summary: {path}") continue if covered > statements or covered_branches > branches: errors.append(f"impossible backend coverage summary: {path}") continue if path in baseline: minimum = baseline[path] if set(minimum["lines"]) & set(minimum["missing_lines"]): errors.append(f"backend coverage baseline lines overlap: {path}") if {tuple(arc) for arc in minimum["arcs"]} & {tuple(arc) for arc in minimum["missing_arcs"]}: errors.append(f"backend coverage baseline branches overlap: {path}") if covered < minimum["covered_lines"] or covered_branches < minimum["covered_branches"]: errors.append(f"backend coverage regressed: {path}") if not set(map(int, minimum["lines"])) <= set(executed_lines): errors.append(f"previously covered lines not exercised: {path}") if not {tuple(arc) for arc in minimum["arcs"]} <= {tuple(arc) for arc in executed_arcs}: errors.append(f"previously covered branches not exercised: {path}") old_lines = set(minimum["lines"]) | set(minimum["missing_lines"]) old_arcs = {tuple(arc) for arc in minimum["arcs"] + minimum["missing_arcs"]} if not set(missing_lines) <= old_lines: errors.append(f"new or changed backend lines lack tests: {path}") if not {tuple(arc) for arc in missing_arcs} <= old_arcs: errors.append(f"new or changed backend branches lack tests: {path}") elif covered != statements or covered_branches != branches: errors.append(f"new backend module requires 100% statements and branches: {path}") return errors def main() -> int: if len(sys.argv) not in (2, 3, 4, 5): print("usage: python scripts/check_backend_coverage.py COVERAGE_JSON [BASELINE_DEBT_JSON [OLD_APP_SOURCE [FOLDER_TREE_OLD_APP_SOURCE]]]", file=sys.stderr) return 2 report = json.loads(Path(sys.argv[1]).read_text()) baseline = json.loads((ROOT / BASELINE_FILE).read_text()) previous = json.loads(Path(sys.argv[2]).read_text()) if len(sys.argv) >= 3 else None if transport_layout(ROOT): try: if len(sys.argv) > 3: raise ValueError('transport layout accepts the pinned parent baseline only') errors = coverage_errors(ROOT, report, baseline, previous) except (KeyError, OSError, ValueError) as error: print(f'transport coverage migration failed: {error}', file=sys.stderr) return 1 if errors: print('\n'.join(errors), file=sys.stderr) return 1 print('Backend coverage inventory: pinned parent retained; changed code and new modules fully covered') return 0 if len(sys.argv) >= 4 and previous is not None: previous = migrate_retired_txt_app_baseline(ROOT, previous, Path(sys.argv[3])) if len(sys.argv) == 5 and previous is not None: previous = migrate_folder_tree_app_baseline(ROOT, previous, Path(sys.argv[4]), ROOT / "backend/app.py", ROOT / "backend/folder_tree.py") # A pinned old baseline can cross the audited folder-tree extraction only # when the exact source/anchor hashes match and no extracted line/arc was # previously uncovered. Normal same-revision baselines stay untouched. if len(sys.argv) == 3 and previous is not None: projection_migrated = False candidates_migrated = False anchor = ROOT / "scripts/coverage-anchors/folder-tree-old-backend-coverage-debt.json" if anchor.exists() and hashlib.sha256(anchor.read_bytes()).hexdigest() == "1417d624b79c06c77f4abe326f7bb9e60af34446af9873623a7d3d1efdbfddf9": anchored = json.loads(anchor.read_text()) if previous == anchored: previous = migrate_folder_tree_app_baseline( ROOT, previous, ROOT / "scripts/coverage-anchors/folder-tree-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/folder-tree-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/folder-tree-new-module.py.snapshot") projection = ROOT / "scripts/coverage-anchors/search-projection-old-backend-coverage-debt.json" if (projection.exists() and hashlib.sha256(projection.read_bytes()).hexdigest() == "70e9311f50ba1407227de9ba42fd591d93826f92898d07873ce5f58cbebf2a29"): if previous == json.loads(projection.read_text()): previous = migrate_search_projection_app_baseline( previous, ROOT / "scripts/coverage-anchors/search-projection-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-projection-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-projection-new-module.py.snapshot") projection_migrated = True candidate = ROOT / "scripts/coverage-anchors/search-candidates-old-backend-coverage-debt.json" if (candidate.exists() and hashlib.sha256(candidate.read_bytes()).hexdigest() == "fd77ed345dee0c50314cc2ed7941e25f358bdbd4118ce7af308a5d1aa7046a8c"): if projection_migrated or previous == json.loads(candidate.read_text()): previous = migrate_search_candidates_app_baseline( previous, ROOT / "scripts/coverage-anchors/search-projection-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-candidates-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-candidates-new-module.py.snapshot") candidates_migrated = True bootstrap = ROOT / "scripts/coverage-anchors/search-bootstrap-old-backend-coverage-debt.json" if (bootstrap.exists() and hashlib.sha256(bootstrap.read_bytes()).hexdigest() == "0313ee14bed3d7638251ff3252ae1f7a16409ed1f8ab97ee6dafa13497ab4eba"): if candidates_migrated or previous == json.loads(bootstrap.read_text()): previous = migrate_search_bootstrap_app_baseline( previous, ROOT / "scripts/coverage-anchors/search-candidates-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-bootstrap-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/search-bootstrap-new-module.py.snapshot") native_anchor = ROOT / "scripts/coverage-anchors/native-postings-old-index.py.snapshot" if previous is not None and native_anchor.exists() and previous.get("backend/search_indexes.py") != baseline.get("backend/search_indexes.py"): previous = migrate_native_postings_baseline(previous, native_anchor, ROOT / "backend/search_indexes.py") star_anchor = ROOT / "scripts/coverage-anchors/star-browse-old-app.py.snapshot" pdf_anchor = ROOT / "scripts/coverage-anchors/pdf-limit-old-app.py.snapshot" pdf_baseline_anchor = ROOT / "scripts/coverage-anchors/pdf-limit-old-backend-coverage-debt.json" archive_old = ROOT / "scripts/coverage-anchors/reader-archive-old-app.py.snapshot" archive_new = ROOT / "scripts/coverage-anchors/reader-archive-new-app.py.snapshot" archive_module = ROOT / "scripts/coverage-anchors/reader-archive-new-module.py.snapshot" archive_debt = ROOT / "scripts/coverage-anchors/reader-archive-old-backend-coverage-debt.json" # The pre-extraction baseline already includes the star and PDF edits, so it # crosses only the reviewed reader-archive move; older baselines chain to it. direct_archive_baseline = (archive_debt.exists() and previous is not None and hashlib.sha256(archive_debt.read_bytes()).hexdigest() == READER_ARCHIVE_OLD_DEBT_SHA and previous == json.loads(archive_debt.read_text())) direct_pdf_baseline = (pdf_baseline_anchor.exists() and hashlib.sha256(pdf_baseline_anchor.read_bytes()).hexdigest() == "1276a5ac7800edeb0c4b5af19df9215a75ad26cb4c4285e648023076c1bcbac2" and previous is not None and previous.get("backend/app.py") == json.loads(pdf_baseline_anchor.read_text()).get("backend/app.py")) typing_new = ROOT / "scripts/coverage-anchors/backend-typing-new-app.py.snapshot" typing_debt = ROOT / "scripts/coverage-anchors/backend-typing-old-backend-coverage-debt.json" # A baseline already in post-extraction coordinates crosses only the typing edit. direct_typing_baseline = (typing_debt.exists() and previous is not None and hashlib.sha256(typing_debt.read_bytes()).hexdigest() == TYPING_OLD_DEBT_SHA and previous == json.loads(typing_debt.read_text())) # Only the exact typed-layout baseline can bypass older layout migrations. # Recognize its source-independent app entry so independently pinned and # same-parent comparisons work without accepting arbitrary coordinates. folder_parent_digest = "744882b25d160a5f6009033a43cd57d6568e8fb381e14b108ac9f8e5bd4a8b55" direct_folder_parent = (previous is not None and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == folder_parent_digest) range_parent_digest = "aace013b131faa8de56b81f039bae24842a8f0d769977ea8b08b8daccffbf1f0" direct_range_parent = (previous is not None and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == range_parent_digest) term_parent_digest = "c0e92d7bb0d9939662e84fc7c0b63c60a6ac2124491773a42c19303046ee58a5" direct_term_parent = (previous is not None and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == term_parent_digest) warm_parent_digest = "fb53051c2f393bace1273912cc5a0fd609858756746b798bd84dd1fe2b7d9591" direct_warm_parent = (previous is not None and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == warm_parent_digest) single_parent_digest = "af6016448274db1e2307c4c6a138718d8cb7ab9591e2f7779dd6d0ea4f17f668" direct_single_parent = (previous is not None and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == single_parent_digest) # Same-source debt improvements stay in current coordinates. Running the # historical translators again would treat an exact parent as an old layout. release_old = ROOT / "scripts/coverage-anchors/search-release-old-app.py.snapshot" release_new = ROOT / "scripts/coverage-anchors/search-release-new-app.py.snapshot" release_debt = ROOT / "scripts/coverage-anchors/search-release-old-backend-coverage-debt.json" release_old_term = ROOT / "scripts/coverage-anchors/search-release-old-term.py.snapshot" release_new_term = ROOT / "scripts/coverage-anchors/search-release-new-term.py.snapshot" sigma_new = ROOT / "scripts/coverage-anchors/search-sigma-new-app.py.snapshot" sigma_debt = ROOT / "scripts/coverage-anchors/search-sigma-old-debt.json" current_sha = hashlib.sha256((ROOT / "backend/app.py").read_bytes()).hexdigest() lifespan_layout = reviewed_lifespan_source(ROOT, current_sha) # Parent-coordinate baseline is independently pinned. Current-coordinate # inputs are identified by explicit membership against that fixed layout, # never by comparing the two untrusted baseline arguments to one another. parent_debt_path = ROOT / "scripts/coverage-anchors/lifespan-parent-backend-coverage-debt.json" if lifespan_layout and (not parent_debt_path.is_file() or hashlib.sha256(parent_debt_path.read_bytes()).hexdigest() != LIFESPAN_PARENT_DEBT_SHA): print("lifespan parent debt anchor missing or tampered", file=sys.stderr) return 1 parent_debt = json.loads(parent_debt_path.read_text()) if lifespan_layout else None baseline_layout = previous_layout = "current" if lifespan_layout: try: baseline_layout = lifespan_baseline_layout(baseline, parent_debt, ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot", ROOT / "backend/app.py") if previous is not None: try: previous_layout = lifespan_baseline_layout(previous, parent_debt, ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot", ROOT / "backend/app.py") except ValueError: # Historical layouts must still pass the existing pinned # translators; they are not assumed to be current. previous_layout = "lifespan-parent" if previous_layout == "current": # Historical translators below operate on parent coordinates. # Same-layout inputs are compared separately at the end. current_previous, previous = previous, None else: current_previous = None else: current_previous = None except (KeyError, TypeError, ValueError) as error: print(f"lifespan baseline layout error: {error}", file=sys.stderr) return 1 else: current_previous = None browse_layout = reviewed_browse_source(ROOT, current_sha) or lifespan_layout browse_target = (ROOT / "scripts/coverage-anchors/lifespan-parent-app.py.snapshot" if lifespan_layout else ROOT / "backend/app.py") proxy_layout = reviewed_proxy_safety_source(ROOT, current_sha) or browse_layout sigma_layout = (sigma_new.exists() and sigma_debt.exists() and hashlib.sha256(sigma_new.read_bytes()).hexdigest() == SEARCH_SIGMA_APP_SHA and hashlib.sha256(sigma_debt.read_bytes()).hexdigest() == SEARCH_SIGMA_OLD_DEBT_SHA and (current_sha in (SEARCH_SIGMA_APP_SHA, SEARCH_SIGMA_VERSION_APP_SHA) or proxy_layout)) release_layout = (release_old.exists() and release_new.exists() and (sigma_layout or hashlib.sha256((ROOT / "backend/app.py").read_bytes()).hexdigest() == SEARCH_RELEASE_APP_SHA)) direct_release_parent = (previous is not None and release_layout and release_debt.exists() and hashlib.sha256(release_debt.read_bytes()).hexdigest() == SEARCH_RELEASE_DEBT_SHA and previous.get("backend/app.py") == json.loads(release_debt.read_text()).get("backend/app.py")) direct_sigma_parent = (previous is not None and sigma_layout and previous.get("backend/app.py") == json.loads(sigma_debt.read_text()).get("backend/app.py")) proxy_parent = ROOT / "scripts/coverage-anchors/proxy-safety-old-backend-coverage-debt.json" browse_direct_parent = (previous is not None and browse_layout and hashlib.sha256(json.dumps(previous.get("backend/app.py"), sort_keys=True, separators=(",", ":")).encode()).hexdigest() == BROWSE_PARENT_ENTRY_SHA) # A parent already at the reviewed sigma layout must not pass through the # older translators a second time, including older unaffected SEO debt. proxy_baseline = json.loads(proxy_parent.read_text()) if proxy_layout and proxy_parent.is_file() else {} direct_proxy_parent = (previous is not None and proxy_layout and all( previous.get(name) == proxy_baseline.get(name) for name in ("backend/app.py", "backend/proxy_streams.py"))) current_release_parent = direct_sigma_parent or direct_proxy_parent or browse_direct_parent if previous is not None: parent_entry = previous.get("backend/app.py") parent_digest = hashlib.sha256(json.dumps(parent_entry, sort_keys=True, separators=(",", ":")).encode()).hexdigest() # These exact fixtures exercise improvements in the new layout. Their # parent coordinates are already current, not inputs to a translator. current_release_parent = direct_sigma_parent or direct_proxy_parent or browse_direct_parent or (release_layout and parent_digest in ( "e02a53f3222a025a886ec3415574f15bbd26fcc1283c2277920912082b171628", "16eec37e636ed6f7f3be140ad1bba5f43337b5181a3446156618c72071f9f40b", "3e74a5905c3f96bf9aef82f4eea281a5322981cbd70b0a0cf6e635bb5d1f6338", )) if parent_digest in ("e7183c108470275129c4b12f2ad9f8e7a3d572ad14d46a96109f65ad10331d99", "0d241c8acac39f666a18b0f3da843320a98fe37ce59da7fab8a4c23bb9bb17e6", "9f32a4a3f31ea8556c6f2295874203c17bf9c39c658ba3bd454302eb42d24477", "3ef2aa68154c57eec732e9315b65e02bca8ac9a23570ee02b48c538bf5359858") or direct_release_parent or current_release_parent: direct_single_parent = True current_layout_parent = True else: current_layout_parent = False else: current_layout_parent = False if (previous is not None and star_anchor.exists() and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_pdf_baseline and not direct_archive_baseline and not direct_typing_baseline and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent): try: # Historical migrations target their original immutable source, # never the later PDF edit. target = pdf_anchor if pdf_anchor.exists() else ROOT / "backend/app.py" previous = migrate_star_browse_app_baseline(previous, star_anchor, target) except ValueError as error: print(f"star-browse coverage migration failed: {error}", file=sys.stderr) return 1 if (previous is not None and pdf_anchor.exists() and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_archive_baseline and not direct_typing_baseline and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent): try: target = archive_old if archive_old.exists() else ROOT / "backend/app.py" previous = migrate_pdf_limit_app_baseline(previous, pdf_anchor, target) except ValueError as error: print(f"PDF limit coverage migration failed: {error}", file=sys.stderr) return 1 archive_migrated = False if (previous is not None and archive_old.exists() and "backend/reader_archive.py" not in previous and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_typing_baseline and not direct_folder_parent and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent): try: previous = migrate_reader_archive_app_baseline(previous, archive_old, archive_new, archive_module) archive_migrated = True except ValueError as error: print(f"reader-archive coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and typing_new.exists() and (archive_migrated or direct_typing_baseline): try: previous = migrate_backend_typing_app_baseline(previous, archive_new, typing_new) except ValueError as error: print(f"backend typing coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_range_parent and not direct_term_parent and not direct_warm_parent and not direct_single_parent: try: previous = migrate_folder_contents_app_baseline( previous, typing_new, ROOT / "scripts/coverage-anchors/range-cache-old-app.py.snapshot", ROOT / "backend/folder_contents.py") except (OSError, ValueError) as error: print(f"folder-contents coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_term_parent and not direct_warm_parent and not direct_single_parent: try: previous = migrate_reader_range_app_baseline( previous, ROOT / "scripts/coverage-anchors/range-cache-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot", ROOT / "backend/reader_range_cache.py") except (OSError, ValueError) as error: print(f"reader-range coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_warm_parent and not direct_single_parent: try: previous = migrate_search_term_app_baseline( previous, ROOT / "scripts/coverage-anchors/term-candidates-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/download-warm-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/single-term-old-module.py.snapshot") except (OSError, ValueError) as error: print(f"search-term coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not direct_single_parent: try: previous = migrate_download_warm_app_baseline( previous, ROOT / "scripts/coverage-anchors/download-warm-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/single-term-old-app.py.snapshot", ROOT / "backend/download_warm.py") except (OSError, ValueError) as error: print(f"download-warm coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and previous.get("backend/app.py") != baseline.get("backend/app.py") and not current_layout_parent: try: previous = migrate_single_term_app_baseline( previous, ROOT / "scripts/coverage-anchors/single-term-old-app.py.snapshot", release_old if release_layout else ROOT / "backend/app.py", release_old_term if release_layout else ROOT / "backend/search_term_candidates.py") except (OSError, ValueError) as error: print(f"single-term coverage migration failed: {error}", file=sys.stderr) return 1 if (previous is not None and release_layout and not current_release_parent and previous.get("backend/app.py") != baseline.get("backend/app.py")): try: if hashlib.sha256(release_debt.read_bytes()).hexdigest() != SEARCH_RELEASE_DEBT_SHA: raise ValueError("unexpected search-release parent baseline") previous = migrate_search_release_baseline(previous, release_old, release_new, release_old_term, release_new_term) except (OSError, ValueError) as error: print(f"search-release coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and sigma_layout and not direct_proxy_parent and not browse_direct_parent and previous.get("backend/app.py") != baseline.get("backend/app.py"): try: previous = migrate_search_sigma_baseline(previous, release_new, sigma_new) except (OSError, ValueError) as error: print(f"search-sigma coverage migration failed: {error}", file=sys.stderr) return 1 seo_anchor = ROOT / "scripts/coverage-anchors/seo-path-old-seo.py.snapshot" if previous is not None and seo_anchor.exists() and previous.get("backend/seo.py") != baseline.get("backend/seo.py"): try: previous = migrate_seo_path_baseline(previous, seo_anchor, ROOT / "backend/seo.py", ROOT / "scripts/coverage-anchors/seo-path-old-debt.json") except (OSError, ValueError, KeyError) as error: print(f"SEO path coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and proxy_layout and not browse_direct_parent and previous.get("backend/app.py") != baseline.get("backend/app.py"): try: previous = migrate_proxy_safety_baseline(previous, ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot" if browse_layout else ROOT / "backend/app.py", ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot", ROOT / "backend/proxy_streams.py") except (OSError, ValueError, KeyError) as error: print(f"proxy-safety coverage migration failed: {error}", file=sys.stderr) return 1 if previous is not None and browse_layout: try: old_app = ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot" if previous.get("backend/app.py") != baseline.get("backend/app.py"): previous = migrate_search_browse_baseline(previous, old_app, browse_target, ROOT / "backend/search_browse.py") else: # A same-layout baseline is supported, but cannot become its own # proof of coverage. Reconstruct the independently hash-pinned # pre-extraction parent and keep its full ratchet in force too. anchored = migrate_proxy_safety_baseline(proxy_baseline, ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot", old_app, ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot", ROOT / "backend/proxy_streams.py") anchored = migrate_search_browse_baseline(anchored, old_app, browse_target, ROOT / "backend/search_browse.py") anchor_errors = coverage_errors(ROOT, report, baseline, anchored, baseline_layout=baseline_layout, previous_layout="lifespan-parent" if lifespan_layout else "current") if anchor_errors: print("\n".join(anchor_errors), file=sys.stderr) return 1 except (OSError, ValueError, KeyError) as error: print(f"search-browse coverage migration failed: {error}", file=sys.stderr) return 1 if lifespan_layout: try: # Always enforce the independently pinned historical chain, even # when no parent is supplied or both supplied debts are weakened. anchored = migrate_proxy_safety_baseline(proxy_baseline, ROOT / "scripts/coverage-anchors/proxy-safety-old-app.py.snapshot", ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot", ROOT / "scripts/coverage-anchors/proxy-safety-old-streams.py.snapshot", ROOT / "backend/proxy_streams.py") anchored = migrate_search_browse_baseline(anchored, ROOT / "scripts/coverage-anchors/proxy-safety-new-app.py.snapshot", browse_target, ROOT / "backend/search_browse.py") anchor_errors = coverage_errors(ROOT, report, baseline, anchored, baseline_layout=baseline_layout, previous_layout="lifespan-parent") anchor_errors += coverage_errors(ROOT, report, baseline, parent_debt, baseline_layout=baseline_layout, previous_layout="lifespan-parent") if anchor_errors: print("\n".join(anchor_errors), file=sys.stderr) return 1 except (OSError, ValueError, KeyError) as error: print(f"lifespan historical coverage proof failed: {error}", file=sys.stderr) return 1 if lifespan_layout and current_previous is not None: errors = coverage_errors(ROOT, report, baseline, current_previous, baseline_layout=baseline_layout, previous_layout="current") else: errors = coverage_errors(ROOT, report, baseline, previous, baseline_layout=baseline_layout, previous_layout="lifespan-parent" if lifespan_layout else "current") if errors: print("\n".join(errors), file=sys.stderr) return 1 print("Backend coverage inventory: no regressions; new modules have 100% statements and branches") return 0 if __name__ == "__main__": raise SystemExit(main())