Files
ThothII/harness/tht/cli/decision_cmd.py
T
marcopanandClaude Fable 5 1ab0015460 fix(harness): state-integrity pass — reopen order, atomic decision batch, bash anti-bypass
Audit findings 5.1-5.3.

5.1 `phase reopen` now appends `phase_reopened` BEFORE the artifact
teardown: a crash between the two used to leave later-phase artifacts
deleted with the ledger still at the old phase (resume entered a phase
missing its artifacts). The inverse half-state — reopened with stale later
artifacts — is benign. Order locked by tests/test_phase_reopen_order.py.

5.2 New `tht decision add-batch --doc -`: N substantive decisions in ONE
atomic ledger write (meta types and cte_approved stay on `decision add`;
strictest min-phase enforced). reviewer_schema_linking now builds the
complete curation set and persists it with a single add-batch call — a
mid-loop failure can no longer leave the audit ledger half-written, and a
retry cannot duplicate the first K decisions.

5.3 The anti-bypass hook now also blocks BASH mutations of protected
state (`echo >> review_decisions.jsonl`, `sed -i` on the manifest,
`cat > tht-gate.js`, python open('w'), mv/rm/tee/…): FORBIDDEN only
covered tht subcommands and the write/edit hook only covered pi's own
tools. Read-only access (cat/grep/tail/ls) stays allowed.

Also: knownDecisionTypes is defensive — a workflow meta declaring NO
emits at all (older tht, minimal stubs) skips pre-validation instead of
rejecting every substantive type; with emits present, unknown types are
still rejected before the widget (new L1 test).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 01:51:38 +02:00

225 lines
9.0 KiB
Python

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-batch")
def add_batch_cmd(
session: str = typer.Option(..., "--session", help="Id della sessione."),
doc: str = typer.Option(..., "--doc", help="Array JSON di decisioni; usa '-' per stdin."),
config: Path = CONFIG_OPT,
) -> None:
"""Registra N decisioni sostanziali con un'unica scrittura atomica del ledger.
Per i gate che persistono una curation completa (es. schema linking:
table_* + column_*): un fallimento a metà non lascia mai il ledger
mezzo-scritto — o tutte o nessuna. I tipi meta (phase_*,
decision_retracted) e cte_approved restano su `decision add`."""
from tht.decisions import DecisionInput
cfg = _load_config_or_exit(config)
load_session_or_exit(cfg, session)
excluded = {
"phase_approved", "phase_auto_approved", "phase_reopened",
"phase_skipped", "decision_retracted", "cte_approved",
}
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]
for decision in decisions:
if decision.type in excluded:
raise ValueError(
f"tipo '{decision.type}' non ammesso in batch (usa 'decision add')"
)
except (OSError, json.JSONDecodeError, ValidationError, ValueError) as error:
typer.secho(
f"ERRORE: batch di decisioni 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
workflow = load_workflow()
require_phase_or_exit(
cfg, session, max(workflow.decision_min_phase(d.type) for d in decisions)
)
records = session_repository(cfg).append_decisions(session, decisions)
typer.secho(
f"OK: registrate {len(records)} decisioni in un'unica scrittura atomica.",
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 <seq> (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)