Search / scripts /check_refactor_coverage.py
vomebook
Retire obsolete ebook Reader compatibility and test scaffolding
262c3c2
Raw History Blame Contribute Delete
5.78 kB
"""Reviewed Refactor23 extraction: preserve the parent by requiring full coverage.
The transport parent has no application debt. Consequently no missing line or
arc can be transferred to an extracted module. The explicit symbol map records
where its behavior moved. Frozen sources prove the historical symbol spans;
the actual destination code (including new wiring) is held to 100% coverage.
"""
import ast
import hashlib
import json
from pathlib import Path
from scripts.backend_paths import (
READER_RESOURCE_RETIREMENT_FILE, RETIRED_READER_RESOURCE_MODULES,
has_migration, migrate_paths, migration, reviewed_source,
)
MAP_FILE = 'scripts/coverage-anchors/refactor23-map.json'
MAP_SHA = '28c0bfc6825799cc1e851c0eefb06949341cc332a63557888781fff49d83a5e1'
SNAPSHOT_DIR = 'scripts/coverage-anchors/refactor23'
PARENT_SHA = '769155429400702a51524f3d2cf2d6dee19b26f67ea08a1f9db22aec70fa61ef'
def refactor_layout(root: Path) -> bool:
# The backend path marker routes migrated trees into the pinned Refactor23
# proof regardless of app import formatting. Historical fixtures copy the
# Refactor23 map too, so that map alone cannot identify the live layout.
app = root / 'backend/app.py'
return has_migration(root) or (app.is_file() and 'from backend.search.domain.ordering import' in app.read_text())
def _symbols(source: bytes) -> dict:
result = {}
def visit(body, prefix=''):
for node in body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
name = prefix + node.name
result[name] = [min([node.lineno] + [d.lineno for d in node.decorator_list]), node.end_lineno]
if isinstance(node, ast.ClassDef):
visit(node.body, name + '.')
visit(ast.parse(source).body)
return result
def _reviewed_manifest(root: Path) -> dict:
raw = (root / MAP_FILE).read_bytes()
if hashlib.sha256(raw).hexdigest() != MAP_SHA:
raise ValueError('refactor coverage requires exact reviewed source mapping')
return json.loads(raw)
def _reviewed_destinations(root: Path, manifest: dict, *, frozen: bool) -> dict[str, bytes]:
before = {}
for name, digest in manifest['sources'].items():
data = ((root / SNAPSHOT_DIR / (name + '.snapshot')).read_bytes() if frozen else reviewed_source(root, name))
if hashlib.sha256(data).hexdigest() != digest:
raise ValueError(f'refactor coverage requires exact reviewed source: {name}')
before[name] = data
return before
def frozen_refactor_sources(root: Path) -> dict[str, bytes]:
"""Verified bytes for historical fixtures, not an approval of live code."""
return _reviewed_destinations(root, _reviewed_manifest(root), frozen=True)
def migrate_refactor_baseline(root: Path, previous: dict) -> dict:
"""Prove the extraction, then migrate the remaining historical coordinates."""
manifest = _reviewed_manifest(root)
parent = (root / 'scripts/coverage-anchors/refactor-parent-app.py.snapshot').read_bytes()
if hashlib.sha256(parent).hexdigest() != PARENT_SHA or manifest['parent_sha256'] != PARENT_SHA:
raise ValueError('refactor coverage requires exact reviewed source parent')
paths_migrated = has_migration(root)
before = _reviewed_destinations(root, manifest, frozen=paths_migrated)
symbols = {name: _symbols(data) for name, data in before.items()}
old_symbols = {name: span for name, span in _symbols(parent).items() if '.' not in name}
if set(old_symbols) != set(manifest['symbols']):
raise ValueError('refactor mapping must account for every parent symbol')
for name, entry in manifest['symbols'].items():
if entry['old'] != old_symbols[name] or not entry['targets']:
raise ValueError(f'unmapped refactor parent symbol: {name}')
for target, symbol, start, end in entry['targets']:
if symbols[target].get(symbol) != [start, end]:
raise ValueError(f'invalid refactor destination: {target}:{symbol}')
entry = previous['backend/app.py']
if entry['missing_lines'] or entry['missing_arcs']:
raise ValueError('refactor cannot transfer application debt without a coordinate proof')
if not {1062, 1063} <= set(entry['lines']) or not {
(1062, 1063), (1062, 1067)} <= {tuple(arc) for arc in entry['arcs']}:
raise ValueError('star-browse coverage baseline must retain both dispatch branches')
if set(manifest['sources']) & (set(previous) - {'backend/app.py'}):
raise ValueError('refactor extraction must not introduce legacy debt')
remaining = {name: dict(value) for name, value in previous.items() if name != 'backend/app.py'}
if paths_migrated:
remaining = migrate_paths(root, remaining, refactor_before=before)
moves = migration(root)['moves']
# migrate_paths verified the exact retirement and confirmed the files
# are absent. Only these three frozen, debt-free destinations may be
# absent; every surviving destination still needs live coverage.
retired = (RETIRED_READER_RESOURCE_MODULES if (root / READER_RESOURCE_RETIREMENT_FILE).is_file()
else frozenset())
for name in before:
target = moves.get(name, name)
if target in remaining:
raise ValueError(f'refactor destination must not carry backend coverage debt: {target}')
if target not in retired and not (root / target).is_file():
raise ValueError(f'missing live refactor destination: {target}')
# No report participates in this proof. The ordinary gate requires every
# statement and arc in the actual app and extracted destinations.
return remaining