import json import sys from pathlib import Path from typing import get_args import typer from pydantic import ValidationError from tht.cli.config_cmd import CONFIG_OPT from tht.cli.schema_cmd import _load_config_or_exit from tht.cli.session_cmd import load_session_or_exit, load_snapshot_or_exit, session_repository decision_app = typer.Typer(help="Decisioni del reviewer (per sessione, append-only)") @decision_app.command("add-join-set") def add_join_set_cmd( session: str = typer.Option(..., "--session", help="Id della sessione."), doc: str = typer.Option(..., "--doc", help="Array JSON di join; usa '-' per stdin."), config: Path = CONFIG_OPT, ) -> None: """Registra un insieme completo di join con un'unica sostituzione atomica del ledger.""" from tht.decisions import DecisionInput cfg = _load_config_or_exit(config) load_session_or_exit(cfg, session) try: raw = sys.stdin.read() if doc == "-" else Path(doc).read_text() payload = json.loads(raw) if not isinstance(payload, list) or not payload: raise ValueError("il documento deve essere un array JSON non vuoto") decisions = [DecisionInput.model_validate(item) for item in payload] if any(decision.type != "join_modified" for decision in decisions): raise ValueError("tutte le decisioni devono avere type=join_modified") except (OSError, json.JSONDecodeError, ValidationError, ValueError) as error: typer.secho(f"ERRORE: set di join non valido: {error}", fg=typer.colors.RED, err=True) raise typer.Exit(code=1) from error from tht.cli.phase_cmd import require_phase_or_exit from tht.workflow import load_workflow require_phase_or_exit(cfg, session, load_workflow().decision_min_phase("join_modified")) records = session_repository(cfg).append_decisions(session, decisions) typer.secho( f"OK: registrato set atomico di {len(records)} join.", fg=typer.colors.GREEN, ) @decision_app.command("add") def add_cmd( session: str = typer.Option(..., "--session", help="Id della sessione."), type: str = typer.Option(..., "--type", help="Tipo di decisione."), subject: str = typer.Option(..., "--subject", help="Oggetto (tabella, colonna, concetto)."), detail: str = typer.Option("", "--detail"), rationale: str = typer.Option("", "--rationale"), retracts: int = typer.Option( None, "--retracts", help="Solo per type=decision_retracted: seq della decisione da ritirare (D15).", ), config: Path = CONFIG_OPT, ) -> None: """Registra una decisione del reviewer nella sessione.""" from tht.decisions import DecisionType cfg = _load_config_or_exit(config) load_session_or_exit(cfg, session) valid = get_args(DecisionType) if type not in valid: typer.secho( f"ERRORE: tipo '{type}' non valido. Tipi: {', '.join(valid)}", fg=typer.colors.RED, err=True, ) raise typer.Exit(code=1) if type == "decision_retracted" and retracts is None: typer.secho( "ERRORE: decision_retracted richiede --retracts (la decisione da ritirare).", fg=typer.colors.RED, err=True, ) raise typer.Exit(code=1) from tht.cli.phase_cmd import require_phase_or_exit from tht.workflow import load_workflow require_phase_or_exit(cfg, session, load_workflow().decision_min_phase(type)) snapshot = load_snapshot_or_exit(cfg, session) if type == "cte_approved": # Un CTE si approva solo se appartiene al piano persistito. Senza piano # (o con subject fuori piano) l'approvazione e' priva di significato: # rifiutala (exit 5) invece di sporcare il ledger. Regressione quo-8, # dove fu registrato un cte_approved:cte_plan senza alcun cte_plan.json. from tht.phase import cte_plan plan = cte_plan(snapshot) if not plan: typer.secho( "ERRORE: nessun piano CTE (cte_plan.json) in sessione. Persisti prima " "il piano con reviewer_confirm kind:'cte_plan', poi approva i CTE.", fg=typer.colors.RED, err=True, ) raise typer.Exit(code=5) if subject not in plan: typer.secho( f"ERRORE: '{subject}' non e' un CTE del piano ({', '.join(plan)}). " "Usa un nome di CTE del piano.", fg=typer.colors.RED, err=True, ) raise typer.Exit(code=5) record = session_repository(cfg).append_decisions(session, [{ "type": type, "subject": subject, "detail": detail, "rationale": rationale, "retracts": retracts, }])[0] typer.secho(f"OK: decisione [{record.seq}] {record.type}: {record.subject}", fg=typer.colors.GREEN) @decision_app.command("retract") def retract_cmd( session: str = typer.Option(..., "--session", help="Id della sessione."), config: Path = CONFIG_OPT, ) -> None: """Ritira l'ultima decisione sostanziale della fase corrente (D15 granularita' step). Granularita' (a) del rollback §4.8: 'rispondi di nuovo a questa domanda'. Scrive un marker decision_retracted (append-only, l'audit resta) che effective_decisions onora; il widget corrente puo' essere riproposto. Non cambia la fase.""" from tht.phase import effective_decisions cfg = _load_config_or_exit(config) load_session_or_exit(cfg, session) snapshot = load_snapshot_or_exit(cfg, session) # Ultima decisione NON-meta della vista effective = quella associata al widget corrente. meta = { "phase_approved", "phase_auto_approved", "phase_reopened", "phase_skipped", "decision_retracted", } substantive = [d for d in effective_decisions(snapshot) if d.type not in meta] if not substantive: typer.secho( "Nessuna decisione sostanziale da ritirare nella fase corrente.", fg=typer.colors.YELLOW, err=True, ) raise typer.Exit(code=6) target = substantive[-1] record = session_repository(cfg).append_decisions(session, [{ "type": "decision_retracted", "subject": target.subject, "rationale": f"ritira [{target.seq}] {target.type}", "retracts": target.seq, }])[0] typer.secho( f"OK: ritirata decisione [{target.seq}] {target.type}: {target.subject} " f"(marker #{record.seq}).", fg=typer.colors.GREEN, ) @decision_app.command("list") def list_cmd( session: str = typer.Option(..., "--session"), config: Path = CONFIG_OPT, ) -> None: """Elenca le decisioni della sessione.""" cfg = _load_config_or_exit(config) decisions = load_snapshot_or_exit(cfg, session).decisions if not decisions: typer.echo("Nessuna decisione registrata.") return for d in decisions: line = f"[{d.seq}] {d.ts:%Y-%m-%d %H:%M} {d.type}: {d.subject}" if d.detail: line += f" — {d.detail}" if d.rationale: line += f" ({d.rationale})" typer.echo(line)