Files
ThothII/harness/nsp/teardown.py
T
marcopan 4b584934c8 feat(harness): teardown_to_phase -- artifact teardown on rollback (D15)
Cancella ogni artefatto la cui fase produttrice > target, usando artifacts_out di
workflow.yaml. Risolve il bug latente di ChironeWp3: ctes/*.sql orfani (non piu'
nel piano dopo un re-derive) restavano su disco e bloccavano finalize.
Da chiamare insieme all'append di phase_reopened per mantenere stato coerente.
6 tests (target 4/1/7, empty, missing, orfani CTE). 26 total passing.
2026-06-26 22:37:18 +02:00

55 lines
2.1 KiB
Python

"""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 ChironeWp3: 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 nsp.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