"""Artifact teardown on rollback (spec D15, ยง4.8). teardown_to_phase cancella ogni artefatto la cui fase produttrice > target, usando la mappa artifacts_out di workflow.yaml. Risolve il bug latente di the reference implementation: dopo un re-derive con piano CTE diverso, i vecchi ctes/*.sql orfani restavano su disco e bloccavano finalize (che itera glob('*.sql') esigendo che ognuno sia testato). Da chiamare insieme all'append di phase_reopened per mantenere lo stato coerente (l'artefatto su disco e il ledger effective devono allinearsi -- vedi phase.py). """ from __future__ import annotations import shutil from dataclasses import dataclass, field from pathlib import Path from tht.workflow import load_workflow @dataclass class TeardownReport: target_phase: int deleted_files: list[str] = field(default_factory=list) def teardown_to_phase(session_dir: str | Path, target_phase: int) -> TeardownReport: """Cancella gli artefatti delle fasi > target_phase. Ritorna il report dei cancellati. - File artefatto (es. 'schema_linking.json'): unlink se esiste. - Directory artefatto (es. 'ctes/'): rimuove ricorsivamente (con tutti i .sql orfani). - Artefatti di fase <= target: preservati (sono lavoro valido). - Artefatti mancanti: noop (sessione nuova). """ session_dir = Path(session_dir) wf = load_workflow() report = TeardownReport(target_phase=target_phase) for phase in wf.phases: if phase.num <= target_phase: continue for artifact in phase.artifacts_out: target = session_dir / artifact.rstrip("/") is_dir = artifact.endswith("/") if is_dir: if target.exists() and target.is_dir(): # registra ogni file prima di rimuovere (utile per audit/debug orfani) for f in sorted(target.glob("*")): if f.is_file(): report.deleted_files.append(f.name) shutil.rmtree(target) else: if target.exists(): target.unlink() report.deleted_files.append(artifact) return report