"""Millennium Lab round 3, P vs NP hunt 3 of 4: the FULL fragment with defeaters.

Reads NeuruhAI/lead-recipe-os read-only (vendored clone at
../vendor/lead-recipe-os; a fresh fetch 2026-11-20 confirmed HEAD
7363dcb1efab4dad3e44c7408ba921b193304ff7, unchanged from round 2, and the
fresh tree is byte-identical to the vendor tree on the five files this
hunt reads) and runs the real registry loader, the real evaluator, the
real composer and the real validator. No ledger writes, no deploys.

Fragment FULL-COMP: LogicNode trees over the composer grammar ops
(ALL, ANY, NOT, ABSENT, WITHIN_DAYS, SEQUENCE, RECURRENCE, NEAR,
ADJACENT), flat ALL at top as the composer builds, where any leaf clause
may carry defeater=True and/or decisive=True. The composer itself never
emits a defeater clause (round 2 probe: 0 of 200; re-probed here), so
defeater trees are hand-built by composing a plain request and swapping
signal_logic, then validated for real with validate(). A bare leaf with
defeater=True and no enclosing NOT evaluates identically to a plain leaf;
the defeater rule lives only in the NOT case of evaluate_logic, so the
defeater extension of the node pool is the NOT(defeater leaf) forms.

Decision problem: given a timeline, does a validate()-passing tree in
FULL-COMP exist that evaluates SATISFIED on the timeline?

Attack direction (a) constructive: extend the round 2 greedy search with
the defeater node forms, verify the per-signal dichotomy (for every
signal and every timeline, exactly one of leaf(s) and NOT(defeater
leaf(s)) is SATISFIED), and build real witnesses through compose plus
validate. Attack direction (b) hardness: three fresh 3-SAT encodings
that use the defeater rule (C: formula in tree with defeater negation,
assignment in timeline; D: formula in timeline as clause slots,
assignment in tree; E: formula in the validity layer), run on SAT and
UNSAT instances with the real evaluator and validator.

Run: cd ~/workspace/millennium-lab && \
  ~/workspace/sovereign-runtime/.venv/bin/python compute/p_vs_np_r3.py
Writes data/p_vs_np_r3.json next to this file's parent data dir.
"""
import json
import random
import sys
import time
from collections import Counter
from datetime import date
from pathlib import Path

HERE = Path(__file__).resolve().parent
LAB = HERE.parent
VENDOR = LAB / "vendor" / "lead-recipe-os"
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(VENDOR))

import p_vs_np_r2 as r2  # noqa: E402
from lead_recipe_os.composer.compose import ComposeRequest, compose  # noqa: E402
from lead_recipe_os.composer.validate import validate  # noqa: E402
from lead_recipe_os.registry.contracts import ALL, NOT, leaf  # noqa: E402
from lead_recipe_os.registry.store import load_default  # noqa: E402
from lead_recipe_os.signals.graph import evaluate_logic  # noqa: E402
from lead_recipe_os.signals.model import SignalInstance  # noqa: E402

AS_OF = r2.AS_OF
SUBJECT = r2.SUBJECT
LOOSE = r2.LOOSE
RELATIONS = r2.RELATIONS
BLOCKED_STATES = ("SOURCE_REQUIRED", "WALLED", "PROPOSED", "MISSING")

DEFEATER_KINDS = ("NOT_DEF", "NOT_DEF_DEC", "NOT_DEF_ABS", "DEC_PL")


# ---------------------------------------------------------------------------
# defeater node pool
# ---------------------------------------------------------------------------

def defeater_node_kinds(sid):
    """The node forms the defeater rule can change. A bare defeater leaf
    evaluates identically to a plain leaf (evaluate_clause ignores the
    flag); only NOT reads it, and decisive matters only for how a
    CONTRADICTED child combines under ALL."""
    return [
        ("NOT_DEF", NOT(leaf(sid, state="PRESENT", defeater=True, **LOOSE))),
        ("NOT_DEF_DEC", NOT(leaf(sid, state="PRESENT", decisive=True,
                                 defeater=True, **LOOSE))),
        ("NOT_DEF_ABS", NOT(leaf(sid, state="ABSENT", defeater=True, **LOOSE))),
        ("DEC_PL", leaf(sid, state="PRESENT", decisive=True, **LOOSE)),
    ]


def candidate_nodes_full(timeline, signals, relations=None, seq_cap=20):
    out = r2.candidate_nodes(timeline, signals, relations, seq_cap=seq_cap)
    for sid in signals:
        out.extend(defeater_node_kinds(sid))
    return out


def greedy_search_full(timeline, signals, relations=None):
    t0 = time.time()
    cands = candidate_nodes_full(timeline, signals, relations)
    sat = []
    by_kind = {}
    for kind, node in cands:
        if r2.eval_node(node, timeline, relations) == "SATISFIED":
            sat.append((kind, node))
            by_kind[kind] = by_kind.get(kind, 0) + 1
    return {"found": bool(sat), "n_candidates": len(cands),
            "n_satisfied": len(sat), "by_kind": by_kind,
            "seconds": round(time.time() - t0, 4), "satisfied": sat}


# ---------------------------------------------------------------------------
# defeater witnesses: compose a plain request, swap in a defeater tree,
# validate for real. Validity takes no timeline, so validate results are
# cached per request shape across timelines.
# ---------------------------------------------------------------------------

class WitnessCache:
    def __init__(self, registry):
        self.registry = registry
        self.cache = {}

    def _validate_swapped(self, key, recipe):
        if key in self.cache:
            return self.cache[key]
        try:
            report = validate(recipe, self.registry)
            rec = {"validate_passed": bool(report.passed),
                   "failed_checks": [k for k, v in report.checks.items()
                                     if not v.get("ok")]}
        except Exception as e:  # noqa: BLE001
            rec = {"validate_passed": False, "failed_checks": ["validate_error"],
                   "error": str(e)[:200]}
        self.cache[key] = rec
        return rec

    def single(self, sid, timeline, relations=None, decisive=False):
        kind = "NOT_DEF_DEC" if decisive else "NOT_DEF"
        req = ComposeRequest(name="defeater witness", vertical="real_estate",
                             target="land_parcel", negative=[sid])
        try:
            recipe = compose(req, self.registry)
        except Exception as e:  # noqa: BLE001
            return {"kind": kind, "stage": "compose", "ok": False,
                    "error": str(e)[:200]}
        kw = dict(decisive=True) if decisive else {}
        tree = ALL(NOT(leaf(sid, state="PRESENT", defeater=True, **LOOSE, **kw)),
                   label="defeater witness")
        cand = recipe.model_copy(update={"signal_logic": tree})
        rec = self._validate_swapped(("single", sid, decisive), cand)
        outcome = evaluate_logic(cand.signal_logic, timeline, AS_OF,
                                 relations=relations).outcome
        return {"kind": kind, "stage": "validate+evaluate",
                "ok": bool(rec["validate_passed"]) and outcome == "SATISFIED",
                "validate_passed": rec["validate_passed"],
                "failed_checks": rec["failed_checks"],
                "eval_outcome": outcome, "recipe_id": cand.recipe_id}

    def pair(self, sid_def, sid_plain, timeline, registry_signals, relations=None):
        req = ComposeRequest(name="defeater pair witness", vertical="real_estate",
                             target="land_parcel", required=[sid_plain],
                             negative=[sid_def])
        try:
            recipe = compose(req, self.registry)
        except Exception as e:  # noqa: BLE001
            return {"kind": "PAIR:NOT_DEF+PL", "stage": "compose",
                    "ok": False, "error": str(e)[:200]}
        tree = ALL(leaf(sid_plain, state="PRESENT", **LOOSE),
                   NOT(leaf(sid_def, state="PRESENT", defeater=True, **LOOSE)),
                   label="defeater pair witness")
        cand = recipe.model_copy(update={"signal_logic": tree})
        rec = self._validate_swapped(("pair", sid_def, sid_plain), cand)
        outcome = evaluate_logic(cand.signal_logic, timeline, AS_OF,
                                 relations=relations).outcome
        return {"kind": "PAIR:NOT_DEF+PL", "stage": "validate+evaluate",
                "ok": bool(rec["validate_passed"]) and outcome == "SATISFIED",
                "validate_passed": rec["validate_passed"],
                "failed_checks": rec["failed_checks"],
                "eval_outcome": outcome, "recipe_id": cand.recipe_id}


def decide_full(timeline, signals, registry, relations=None, cache=None,
                source_feasible=None):
    """Validity-aware decision for FULL-COMP on one timeline: plain
    witnesses first (round 2 path), then defeater singles, then pairs."""
    g = greedy_search_full(timeline, signals, relations)
    sat = g["satisfied"]
    plain_sat = [(k, n) for k, n in sat if k not in DEFEATER_KINDS]
    w = None
    if plain_sat:
        w = r2.build_witness(plain_sat, timeline, registry, relations)
    attempts = list(w["attempts"]) if w else []
    if not (w and w["built"]):
        defs = [(k, n) for k, n in sat if k in ("NOT_DEF", "NOT_DEF_DEC")]
        def key_of(kn):
            k, n = kn
            sid = n.args[0].clause.signal
            feas = 0 if source_feasible.get(sid, True) else 1
            return (feas, 0 if k == "NOT_DEF" else 1, sid)
        for kind, node in sorted(defs, key=key_of)[:8]:
            sid = node.args[0].clause.signal
            att = cache.single(sid, timeline, relations,
                               decisive=(kind == "NOT_DEF_DEC"))
            attempts.append(att)
            if att["ok"]:
                w = {"built": True, "kind": kind, "recipe_id": att["recipe_id"],
                     "attempts": attempts}
                break
    if not (w and w["built"]):
        plains = [(k, n) for k, n in plain_sat
                  if k in ("PL_default", "PL_loose")]
        defs = [(k, n) for k, n in sat if k == "NOT_DEF"]
        tried = 0
        for _, dnode in defs[:4]:
            for _, pnode in plains[:4]:
                if tried >= 6:
                    break
                sid_def = dnode.args[0].clause.signal
                sid_plain = pnode.clause.signal
                if sid_def == sid_plain:
                    continue
                att = cache.pair(sid_def, sid_plain, timeline, signals, relations)
                attempts.append(att)
                tried += 1
                if att["ok"]:
                    w = {"built": True, "kind": "PAIR:NOT_DEF+PL",
                         "recipe_id": att["recipe_id"], "attempts": attempts}
                    break
            if w and w["built"]:
                break
    if w is None:
        w = {"built": False, "attempts": attempts}
    n_def_sat = sum(1 for k, _ in sat if k in DEFEATER_KINDS)
    n_def_feas = sum(1 for k, n in sat
                     if k in ("NOT_DEF", "NOT_DEF_DEC")
                     and source_feasible.get(n.args[0].clause.signal, True))
    return {"found_nodes": g["found"], "n_candidates": g["n_candidates"],
            "n_satisfied": g["n_satisfied"], "by_kind": g["by_kind"],
            "seconds": g["seconds"],
            "n_satisfied_defeater_nodes": n_def_sat,
            "n_satisfied_defeater_source_feasible": n_def_feas,
            "decision_valid_recipe_exists": bool(w["built"]), "witness": w}


# ---------------------------------------------------------------------------
# the dichotomy: for one signal, leaf(s) and NOT(defeater leaf(s)) split
# every timeline exactly in two
# ---------------------------------------------------------------------------

def dichotomy_check(timeline, signals, floors_list=("loose", "default")):
    checks = 0
    violations = []
    for sid in signals:
        for floors in floors_list:
            kw = dict(LOOSE) if floors == "loose" else {}
            leaf_out = evaluate_logic(
                leaf(sid, state="PRESENT", **kw), timeline, AS_OF).outcome
            not_out = evaluate_logic(
                NOT(leaf(sid, state="PRESENT", defeater=True, **kw)),
                timeline, AS_OF).outcome
            checks += 1
            if not ((leaf_out == "SATISFIED") ^ (not_out == "SATISFIED")):
                violations.append({"signal": sid, "floors": floors,
                                   "leaf": leaf_out, "not_defeater": not_out})
    return {"checks": checks, "violations": violations}


def withdrawn(sid):
    return SignalInstance(signal_id=sid, subject=SUBJECT, kind="FACT",
                          state="PRESENT", source_id="fixture",
                          confidence="HIGH", basis="VERIFIED",
                          status="WITHDRAWN")


def superseded(sid):
    return SignalInstance(signal_id=sid, subject=SUBJECT, kind="FACT",
                          state="PRESENT", source_id="fixture",
                          confidence="HIGH", basis="VERIFIED",
                          status="SUPERSEDED")


# ---------------------------------------------------------------------------
# main
# ---------------------------------------------------------------------------

def main():
    t_start = time.time()
    out = {"repo": {"slug": "NeuruhAI/lead-recipe-os",
                    "head": "7363dcb1efab4dad3e44c7408ba921b193304ff7",
                    "fetched": "2026-11-20",
                    "method": "git clone --depth 1, read-only; fresh fetch "
                    "2026-11-20 confirmed the same HEAD and byte-identical "
                    "graph.py, contracts.py, compose.py, validate.py and "
                    "recipes_canonical.py vs the vendor tree"},
           "as_of": str(AS_OF)}
    reg = load_default()
    signals = sorted(reg.signals)
    recipes = list(reg.recipes.values())
    out["registry"] = {
        "recipes": len(recipes),
        "signals": len(signals),
        "ingredients": len(reg.ingredients),
        "sources": len(reg.sources),
        "territories": len(reg.territories),
        "canonical_library": sum(1 for r in recipes if r.library == "canonical"),
        "curated_library": sum(1 for r in recipes if r.library == "curated"),
    }
    print(f"registry: {out['registry']}", flush=True)

    # --- fragment inventory: the defeater clauses as they exist, and how
    # many signals a single-node witness may not use (source-blocked)
    def defeater_detail(rs):
        rows = []
        for r in rs:
            clauses = []

            def rec(node, path):
                if node is None:
                    return
                if node.clause is not None:
                    if node.clause.defeater:
                        clauses.append({
                            "signal": node.clause.signal,
                            "decisive": node.clause.decisive,
                            "defeater": True,
                            "state": node.clause.state,
                            "cmp": node.clause.cmp,
                            "context": path})
                    return
                for i, a in enumerate(node.args):
                    rec(a, path + [f"{node.op}[{i}]"])

            rec(r.signal_logic, [])
            if clauses:
                rows.append({"recipe_id": r.recipe_id, "library": r.library,
                             "defeater_clauses": clauses})
        return rows

    from collections import Counter as _C
    op_counts = _C()
    qual_defeaters = 0
    for r in recipes:
        op_counts.update(r2.count_ops(r.signal_logic))
        for n in r2.walk(r.qualifying_logic):
            if n.clause is not None and n.clause.defeater:
                qual_defeaters += 1
    det = defeater_detail(recipes)
    by_state = Counter(s.source_state for s in reg.signals.values())
    blocked = [sid for sid, s in reg.signals.items()
               if s.source_state in BLOCKED_STATES]
    source_feasible = {sid: (sid not in blocked) for sid in signals}
    out["fragment_inventory"] = {
        "ops_in_registry_membership_logic": dict(sorted(op_counts.items())),
        "defeater_recipes": det,
        "recipes_with_defeater_clause": len(det),
        "defeater_clauses_total": sum(len(d["defeater_clauses"]) for d in det),
        "defeater_clause_signals": sorted({c["signal"] for d in det
                                           for c in d["defeater_clauses"]}),
        "defeater_clauses_decisive_and_defeater": sum(
            1 for d in det for c in d["defeater_clauses"] if c["decisive"]),
        "defeater_clauses_defeater_only": sum(
            1 for d in det for c in d["defeater_clauses"] if not c["decisive"]),
        "defeater_clauses_in_qualifying_logic": qual_defeaters,
        "signals_by_source_state": dict(sorted(by_state.items())),
        "source_blocked_signals": len(blocked),
        "source_feasible_signals": len(signals) - len(blocked),
        "composer_grammar_ops": ["ALL", "ANY", "NOT", "ABSENT", "WITHIN_DAYS",
                                 "SEQUENCE", "RECURRENCE", "NEAR", "ADJACENT"],
        "fragment_definition": "FULL-COMP: composer grammar ops, flat ALL "
        "at top, any leaf clause may carry defeater=True and/or "
        "decisive=True; composer never emits defeater, so defeater trees "
        "are hand-built by compose plus signal_logic swap, then validated",
    }
    print(f"fragment inventory: {len(det)} defeater recipes, "
          f"{out['fragment_inventory']['defeater_clauses_total']} clauses, "
          f"{len(blocked)} source-blocked signals", flush=True)

    # --- the registry's own defeater rows, evaluated: a resolved defeater
    # defeats, an unresolved one does not
    reg_rows = {}
    for d in det:
        for c in d["defeater_clauses"]:
            sid = c["signal"]
            node = NOT(leaf(sid, state="PRESENT",
                            decisive=c["decisive"], defeater=True, **LOOSE))
            reg_rows.setdefault(sid, {})[d["recipe_id"]] = {
                "present": evaluate_logic(
                    node, r2.tl([r2.present(sid)]), AS_OF).outcome,
                "evidential_absent": evaluate_logic(
                    node, r2.tl([r2.ev_absent(sid)]), AS_OF).outcome,
                "empty": evaluate_logic(node, r2.tl([]), AS_OF).outcome,
            }
    out["fragment_inventory"]["registry_defeater_rows_evaluated"] = reg_rows
    print(f"registry defeater rows evaluated: {reg_rows}", flush=True)

    # --- composer probe: 100 fresh random requests, different seed
    rng = random.Random(20261121)
    bad = 0
    compose_fail = 0
    for i in range(100):
        req = ComposeRequest(
            name=f"random probe r3 {i}", vertical="real_estate",
            target="land_parcel",
            required=rng.sample(signals, rng.randint(0, 3)),
            any_of=[rng.sample(signals, rng.randint(1, 3))]
            if rng.random() < 0.5 else [],
            negative=rng.sample(signals, rng.randint(0, 2)),
            absent=rng.sample(signals, rng.randint(0, 1)),
            within={rng.choice(signals): 30} if rng.random() < 0.3 else {},
            sequence=(rng.choice(signals), rng.choice(signals), 90)
            if rng.random() < 0.3 else None,
            recurrence=(rng.choice(signals), 2, 365)
            if rng.random() < 0.3 else None,
            near=(rng.choice(RELATIONS), 500.0) if rng.random() < 0.2 else None,
            adjacent=(rng.choice(RELATIONS), None)
            if rng.random() < 0.2 else None)
        try:
            recipe = compose(req, reg)
        except Exception:  # noqa: BLE001
            compose_fail += 1
            continue
        if r2.has_defeater(recipe.signal_logic):
            bad += 1
    out["composer_probe"] = {
        "random_compose_requests": 100, "compose_failures": compose_fail,
        "built_recipes_with_defeater": bad,
        "note": "compose plus build() has no defeater input: negatives are "
        "NOT(plain leaf); defeater trees must be hand-built",
    }
    print(f"composer probe: {out['composer_probe']}", flush=True)

    # --- defeater hinge, extended: NOT(defeater leaf) across every
    # timeline state, loose and default floors, plain NOT for comparison
    hinge = {}
    for label, defeater in (("defeater", True), ("plain", False)):
        for sid in ("ownership.government", "listing.active"):
            node_loose = NOT(leaf(sid, defeater=defeater, **LOOSE))
            node_default = NOT(leaf(sid, defeater=defeater))
            states = {
                "empty_timeline": r2.tl([]),
                "present": r2.tl([r2.present(sid)]),
                "present_lowfloor": r2.tl([r2.low_floor_present(sid)]),
                "evidential_absent": r2.tl([r2.ev_absent(sid)]),
                "conflicted": r2.tl([r2.conflicted(sid)]),
                "withdrawn": r2.tl([withdrawn(sid)]),
                "superseded": r2.tl([superseded(sid)]),
            }
            hinge[f"{label}:{sid}"] = {
                "loose": {k: evaluate_logic(node_loose, t, AS_OF).outcome
                          for k, t in states.items()},
                "default": {k: evaluate_logic(node_default, t, AS_OF).outcome
                            for k, t in states.items()},
            }
    # typed comparison defeater: gte on a NUMBER signal
    tnode = NOT(leaf("transfer.tenure_years", cmp="gte", value=15,
                     defeater=True, **LOOSE))
    hinge["typed_cmp_defeater:transfer.tenure_years"] = {
        "loose": {
            "value_20": evaluate_logic(
                tnode, r2.tl([r2.present("transfer.tenure_years", value=20)]),
                AS_OF).outcome,
            "value_5": evaluate_logic(
                tnode, r2.tl([r2.present("transfer.tenure_years", value=5)]),
                AS_OF).outcome,
            "evidential_absent": evaluate_logic(
                tnode, r2.tl([r2.ev_absent("transfer.tenure_years")]),
                AS_OF).outcome,
            "empty": evaluate_logic(tnode, r2.tl([]), AS_OF).outcome,
        }
    }
    out["defeater_hinge"] = hinge
    print(f"hinge: defeater loose on empty="
          f"{hinge['defeater:ownership.government']['loose']['empty_timeline']}, "
          f"on present={hinge['defeater:ownership.government']['loose']['present']}, "
          f"on withdrawn={hinge['defeater:ownership.government']['loose']['withdrawn']}",
          flush=True)

    # --- timelines: the round 2 battery plus the hostile ones
    full = r2.tl([r2.present(s) for s in signals])
    rfull = random.Random(20261120)
    rand_half = r2.tl([r2.present(s) for s in signals if rfull.random() < 0.5])
    mixed = r2.tl([
        r2.present("tax.delinquent"), r2.present("probate.opened"),
        r2.present("listing.active"), r2.present("deed.recorded_event"),
        r2.present("heirship.unresolved"), r2.present("death.verified"),
        r2.present("equity.estimated_pct", value=0.8),
        r2.present("transfer.tenure_years", value=20),
        r2.ev_absent("ownership.government"),
        r2.ev_absent("listing.failed_36mo"),
        r2.conflicted("tax.sale_date"),
        r2.low_floor_present("code.violation"),
        r2.low_floor_present("absentee.out_of_state"),
        r2.event("tax.delinquent", "2026-10-01"),
        r2.event("tax.delinquent", "2026-11-01"),
        r2.event("probate.opened", "2026-10-15"),
        r2.event("deed.recorded_event", "2026-11-10"),
    ])
    single = r2.tl([r2.present("tax.delinquent")])
    absent_only = r2.tl([r2.ev_absent("ownership.government"),
                         r2.ev_absent("listing.failed_36mo")])
    lowfloor_only = r2.tl([r2.low_floor_present("code.violation"),
                           r2.low_floor_present("absentee.out_of_state")])
    relations = r2.RelationContext(
        distances_m={"river": 100.0, "road": 5000.0},
        resolved_relations={"river", "road"},
        adjacent_subjects={"parcel": ["parcel:test:002"]})
    small_sigs = ["tax.delinquent", "probate.opened", "listing.active",
                  "deed.recorded_event", "heirship.unresolved",
                  "death.verified", "ownership.government", "code.violation"]
    timelines = [
        ("empty", r2.tl([]), None),
        ("empty_with_relations", r2.tl([]), relations),
        ("full_evidence", full, None),
        ("random_p0.5", rand_half, None),
        ("mixed", mixed, None),
        ("mixed_with_relations", mixed, relations),
        ("single_present", single, None),
        ("absent_only", absent_only, None),
        ("lowfloor_only", lowfloor_only, None),
        ("withdrawn_only_small", r2.tl([withdrawn(s) for s in small_sigs]), None),
        ("withdrawn_full", r2.tl([withdrawn(s) for s in signals]), None),
        ("conflicted_full", r2.tl([r2.conflicted(s) for s in signals]), None),
        ("all_absent_full", r2.tl([r2.ev_absent(s) for s in signals]), None),
        ("all_present_lowfloor_full",
         r2.tl([r2.low_floor_present(s) for s in signals]), None),
    ]

    # --- the dichotomy, exhaustively: every signal, every timeline, both
    # floor settings; exactly one of leaf(s) / NOT(defeater leaf(s)) is
    # SATISFIED in each cell
    t_dic = time.time()
    dic_total_checks = 0
    dic_violations = []
    for name, timeline, _rel in timelines:
        d = dichotomy_check(timeline, signals)
        dic_total_checks += d["checks"]
        for v in d["violations"]:
            v["timeline"] = name
            dic_violations.append(v)
    out["dichotomy"] = {
        "timelines": len(timelines),
        "signals_per_timeline": len(signals),
        "floor_settings": ["loose", "default"],
        "checks": dic_total_checks,
        "violations": dic_violations,
        "seconds": round(time.time() - t_dic, 2),
        "statement": "for every signal s and every timeline, exactly one "
        "of leaf(s, PRESENT) and NOT(leaf(s, PRESENT, defeater=True)) is "
        "SATISFIED, at fixed evidence floors",
    }
    print(f"dichotomy: {dic_total_checks} checks, "
          f"{len(dic_violations)} violations in "
          f"{out['dichotomy']['seconds']}s", flush=True)

    # --- greedy search over the FULL fragment, validity-aware decision
    cache = WitnessCache(reg)
    greedy_results = {}
    for name, timeline, rel in timelines:
        res = decide_full(timeline, signals, reg, rel, cache, source_feasible)
        greedy_results[name] = {
            "found_nodes": res["found_nodes"],
            "n_candidates": res["n_candidates"],
            "n_satisfied": res["n_satisfied"],
            "by_kind": res["by_kind"],
            "seconds": res["seconds"],
            "n_satisfied_defeater_nodes": res["n_satisfied_defeater_nodes"],
            "n_satisfied_defeater_source_feasible":
                res["n_satisfied_defeater_source_feasible"],
            "decision_valid_recipe_exists": res["decision_valid_recipe_exists"],
            "witness": res["witness"],
        }
        print(f"greedy-full {name}: sat={res['n_satisfied']} of "
              f"{res['n_candidates']} in {res['seconds']}s "
              f"defeater_sat={res['n_satisfied_defeater_nodes']} "
              f"valid_witness={res['decision_valid_recipe_exists']}", flush=True)
    out["greedy"] = greedy_results

    # --- brute-force agreement, full fragment pool and defeater-free
    # replication, on the small vocabulary
    def small_pool_full(timeline, sigs, relations=None):
        cands = candidate_nodes_full(timeline, sigs, relations)
        kinds = ("PL_loose", "AL_loose", "NOT_PL", "ABSENT_op", "NOT_DEF",
                 "NOT_DEF_DEC", "DEC_PL", "WITHIN_DAYS", "RECURRENCE",
                 "SEQUENCE")
        return [(k, n) for k, n in cands if k in kinds]

    rng2 = random.Random(777)
    trials_full = []
    deterministic = [
        ("empty", r2.tl([])),
        ("conflicted_only", r2.tl([r2.conflicted(s) for s in small_sigs])),
        ("withdrawn_only", r2.tl([withdrawn(s) for s in small_sigs])),
        ("lowfloor_only_registered",
         r2.tl([r2.low_floor_present("code.violation"),
                r2.low_floor_present("absentee.out_of_state")])),
        ("all_present_small", r2.tl([r2.present(s) for s in small_sigs])),
        ("all_absent_small", r2.tl([r2.ev_absent(s) for s in small_sigs])),
        ("all_lowfloor_small", r2.tl([r2.low_floor_present(s) for s in small_sigs])),
    ]
    t_bf = time.time()
    for label, timeline in deterministic:
        pool = small_pool_full(timeline, small_sigs)
        g = greedy_search_full(timeline, small_sigs)
        b = r2.brute_force(timeline, pool)
        trials_full.append({"trial": label, "greedy": g["found"],
                            "brute_force": b, "agree": g["found"] == b,
                            "n_satisfied": g["n_satisfied"]})
    for t in range(40):
        insts = []
        for sid in small_sigs:
            roll = rng2.random()
            if roll < 0.35:
                insts.append(r2.present(sid))
            elif roll < 0.5:
                insts.append(r2.ev_absent(sid))
            elif roll < 0.58:
                insts.append(r2.conflicted(sid))
            elif roll < 0.66:
                insts.append(r2.low_floor_present(sid))
            elif roll < 0.8:
                insts.append(r2.event(sid, f"2026-10-{rng2.randint(1, 28):02d}"))
                if rng2.random() < 0.5:
                    insts.append(r2.event(sid, f"2026-11-{rng2.randint(1, 15):02d}"))
        timeline = r2.tl(insts)
        pool = small_pool_full(timeline, small_sigs)
        g = greedy_search_full(timeline, small_sigs)
        b = r2.brute_force(timeline, pool)
        trials_full.append({"trial": t, "greedy": g["found"],
                            "brute_force": b, "agree": g["found"] == b,
                            "n_satisfied": g["n_satisfied"]})
    agree_full = sum(1 for t in trials_full if t["agree"])
    # defeater-free replication of the round 2 agreement run
    agree_plain = 0
    disagree_plain = []
    for label, timeline in deterministic[:4]:
        pool = r2.small_pool(timeline, small_sigs)
        g = r2.greedy_search(timeline, small_sigs)
        b = r2.brute_force(timeline, pool)
        if g["found"] == b:
            agree_plain += 1
        else:
            disagree_plain.append(label)
    rng3 = random.Random(777)
    for t in range(40):
        insts = []
        for sid in small_sigs:
            roll = rng3.random()
            if roll < 0.35:
                insts.append(r2.present(sid))
            elif roll < 0.5:
                insts.append(r2.ev_absent(sid))
            elif roll < 0.58:
                insts.append(r2.conflicted(sid))
            elif roll < 0.66:
                insts.append(r2.low_floor_present(sid))
            elif roll < 0.8:
                insts.append(r2.event(sid, f"2026-10-{rng3.randint(1, 28):02d}"))
                if rng3.random() < 0.5:
                    insts.append(r2.event(sid, f"2026-11-{rng3.randint(1, 15):02d}"))
        timeline = r2.tl(insts)
        pool = r2.small_pool(timeline, small_sigs)
        g = r2.greedy_search(timeline, small_sigs)
        b = r2.brute_force(timeline, pool)
        if g["found"] == b:
            agree_plain += 1
        else:
            disagree_plain.append(t)
    out["brute_force_agreement"] = {
        "vocabulary_size": len(small_sigs),
        "full_fragment": {"trials": len(trials_full), "agree": agree_full,
                          "disagree": [t for t in trials_full if not t["agree"]],
                          "all_yes": all(t["greedy"] for t in trials_full),
                          "seconds": round(time.time() - t_bf, 2)},
        "defeater_free_replication": {"trials": 44, "agree": agree_plain,
                                      "disagree": disagree_plain},
        "tree_sizes_enumerated": "ALL over subsets of size 1..3 from the "
        "per-signal node pool (plain/ABSENT/NOT/ABSENT-op/WITHIN/RECURRENCE/"
        "SEQUENCE forms, plus NOT_DEF, NOT_DEF_DEC, DEC_PL in the full run)",
        "note": "the full-fragment agreement is YES-dominated by design: "
        "the dichotomy guarantees a SATISFIED node on every timeline, so "
        "both sides answer YES; the substantive checks are the dichotomy "
        "itself and the validity-aware witness construction",
    }
    print(f"brute force agreement full: {agree_full}/{len(trials_full)}, "
          f"plain replication: {agree_plain}/44", flush=True)

    # --- 3-SAT attempt, strategy C: formula in tree with defeater
    # negation, assignment in timeline
    x1, x2, x3 = "tax.delinquent", "probate.opened", "listing.active"

    def lit_def(sid, positive, decisive=False):
        node = leaf(sid, state="PRESENT", **LOOSE)
        if positive:
            return node
        kw = dict(decisive=True) if decisive else {}
        return NOT(leaf(sid, state="PRESENT", defeater=True, **LOOSE, **kw))

    def formula_tree_def(clauses, decisive=False):
        return ALL(*[r2.ANY(*[lit_def(s, p, decisive) for s, p in c])
                     for c in clauses])

    def timeline_for_assignment(assign):
        insts = []
        for sid, val in assign.items():
            insts.append(r2.present(sid) if val else r2.ev_absent(sid))
        return r2.tl(insts)

    phi_sat = [[(x1, True), (x2, True), (x3, True)],
               [(x1, False), (x2, True), (x3, False)]]
    phi_unsat = [[(x1, p1), (x2, p2), (x3, p3)]
                 for p1 in (True, False) for p2 in (True, False)
                 for p3 in (True, False)]
    phi_neg = [[(x1, False), (x2, False), (x3, False)]]
    alpha = {x1: True, x2: True, x3: False}
    tl_alpha = timeline_for_assignment(alpha)
    strat_c = {}
    for name, phi in (("phi_sat", phi_sat), ("phi_unsat", phi_unsat)):
        tree = formula_tree_def(phi)
        tree_dec = formula_tree_def(phi, decisive=True)
        strat_c[name] = {
            "formula_tree_on_alpha_timeline": evaluate_logic(
                tree, tl_alpha, AS_OF).outcome,
            "formula_tree_decisive_on_alpha_timeline": evaluate_logic(
                tree_dec, tl_alpha, AS_OF).outcome,
            "formula_tree_on_empty_timeline": evaluate_logic(
                tree, r2.tl([]), AS_OF).outcome,
        }
    strat_c["phi_all_negative_on_empty_timeline"] = evaluate_logic(
        formula_tree_def(phi_neg), r2.tl([]), AS_OF).outcome
    strat_c["phi_all_negative_on_alpha_timeline"] = evaluate_logic(
        formula_tree_def(phi_neg), tl_alpha, AS_OF).outcome
    g_alpha = greedy_search_full(tl_alpha, signals)
    strat_c["greedy_nodes_on_alpha_timeline"] = g_alpha["found"]
    strat_c["trivial_nodes_on_alpha_timeline"] = {
        "leaf_x1_present": evaluate_logic(
            leaf(x1, state="PRESENT", **LOOSE), tl_alpha, AS_OF).outcome,
        "not_defeater_x3_absent": evaluate_logic(
            NOT(leaf(x3, state="PRESENT", defeater=True, **LOOSE)),
            tl_alpha, AS_OF).outcome,
        "not_defeater_x1_present": evaluate_logic(
            NOT(leaf(x1, state="PRESENT", defeater=True, **LOOSE)),
            tl_alpha, AS_OF).outcome,
    }
    strat_c["verdict"] = ("the formula tree itself now distinguishes SAT "
        "from UNSAT on a fixed assignment timeline (SATISFIED vs UNKNOWN); "
        "the decisive variant does not change this, because _combine_any "
        "drops decisiveness, so the outer ALL still sees a non-decisive "
        "contradiction and returns UNKNOWN; and a negative literal is true "
        "by default on the empty timeline, so the all-negative clause is "
        "SATISFIED with no assignment at all; but the decision is "
        "existential over trees, and the timeline always offers a trivial "
        "SATISFIED node, so UNSAT still answers YES")
    print(f"strategy C: phi_sat on alpha="
          f"{strat_c['phi_sat']['formula_tree_on_alpha_timeline']}, "
          f"phi_unsat on alpha="
          f"{strat_c['phi_unsat']['formula_tree_on_alpha_timeline']}, "
          f"greedy on alpha={g_alpha['found']}", flush=True)

    # --- 3-SAT attempt, strategy D: formula in timeline as clause slots,
    # assignment in tree
    clause_slots = ["deed.recorded_event", "heirship.unresolved",
                    "death.verified", "ownership.government",
                    "code.violation", "equity.estimated_pct",
                    "transfer.tenure_years", "listing.failed_36mo"]
    assert all(s in reg.signals for s in clause_slots)
    assert not (set(clause_slots) & {x1, x2, x3})

    def timeline_D(phi):
        insts = [r2.ev_absent(v) for v in (x1, x2, x3)]
        for j in range(len(phi)):
            insts.append(r2.present(clause_slots[j]))
        return r2.tl(insts)

    def assignment_tree(assign, phi):
        nodes = []
        for sid, val in assign.items():
            nodes.append(leaf(sid, state="PRESENT", **LOOSE) if val
                         else NOT(leaf(sid, state="PRESENT", defeater=True,
                                       **LOOSE)))
        for j in range(len(phi)):
            nodes.append(leaf(clause_slots[j], state="PRESENT", **LOOSE))
        return ALL(*nodes)

    alpha0 = {x1: False, x2: False, x3: False}
    strat_d = {}
    for name, phi in (("phi_sat", phi_sat), ("phi_unsat", phi_unsat)):
        tl_d = timeline_D(phi)
        strat_d[name] = {
            "clause_slots_present": len(phi),
            "reference_assignment_tree_alpha0": evaluate_logic(
                assignment_tree(alpha0, phi), tl_d, AS_OF).outcome,
            "satisfying_assignment_tree_alpha": evaluate_logic(
                assignment_tree(alpha, phi), tl_d, AS_OF).outcome,
            "greedy_nodes": greedy_search_full(tl_d, signals)["found"],
        }
    strat_d["slot_reading"] = {
        "leaf_clause_slot_present": evaluate_logic(
            leaf(clause_slots[0], state="PRESENT", **LOOSE),
            timeline_D(phi_sat), AS_OF).outcome,
        "leaf_clause_slot_absent": evaluate_logic(
            leaf(clause_slots[2], state="PRESENT", **LOOSE),
            timeline_D(phi_sat), AS_OF).outcome,
    }
    strat_d["verdict"] = ("the tree is checked against the timeline's "
        "fixed reference assignment, never against the formula: the "
        "reference assignment tree is SATISFIED for both phi_sat and "
        "phi_unsat, and a genuinely satisfying assignment tree is UNKNOWN "
        "because it disagrees with the reference; the clause slots are "
        "read only as 'present or not', which carries no clause semantics, "
        "and the tree may omit them entirely")
    print(f"strategy D: alpha0 tree on phi_sat="
          f"{strat_d['phi_sat']['reference_assignment_tree_alpha0']}, on "
          f"phi_unsat={strat_d['phi_unsat']['reference_assignment_tree_alpha0']}",
          flush=True)

    # --- 3-SAT attempt, strategy E: formula in the validity layer
    def swapped_recipe(tree, required, negative):
        req = ComposeRequest(name="validity probe", vertical="real_estate",
                             target="land_parcel", required=required,
                             negative=negative)
        recipe = compose(req, reg)
        return recipe.model_copy(update={"signal_logic": tree})

    def validate_tree(tree, required, negative, timeline):
        try:
            cand = swapped_recipe(tree, required, negative)
        except Exception as e:  # noqa: BLE001
            return {"stage": "compose", "ok": False, "error": str(e)[:200]}
        try:
            rep = validate(cand, reg)
        except Exception as e:  # noqa: BLE001
            return {"stage": "validate", "ok": False, "error": str(e)[:200]}
        return {"stage": "validate+evaluate",
                "validate_passed": bool(rep.passed),
                "failed_checks": [k for k, v in rep.checks.items()
                                  if not v.get("ok")],
                "eval_outcome": evaluate_logic(
                    cand.signal_logic, timeline, AS_OF).outcome,
                "recipe_id": cand.recipe_id}

    beta = {x1: False, x2: False, x3: False}
    strat_e = {
        "satisfying_assignment_tree_alpha": validate_tree(
            assignment_tree(alpha, phi_sat), [x1, x2, x3], [], tl_alpha),
        "nonsatisfying_assignment_tree_beta": validate_tree(
            assignment_tree(beta, phi_sat), [x1, x2, x3], [], tl_alpha),
        "formula_tree_phi_sat": validate_tree(
            formula_tree_def(phi_sat), [x1, x2, x3], [], tl_alpha),
        "formula_tree_phi_unsat": validate_tree(
            formula_tree_def(phi_unsat), [x1, x2, x3], [], tl_alpha),
    }
    strat_e["verdict"] = ("validate() takes no timeline and reads no "
        "formula: a satisfying assignment tree, a non-satisfying assignment "
        "tree, and the two formula trees all validate or fail identically "
        "on the same request shape, so the validity layer cannot gate on "
        "satisfiability either")
    print(f"strategy E: alpha validates="
          f"{strat_e['satisfying_assignment_tree_alpha'].get('validate_passed')}, "
          f"beta validates="
          f"{strat_e['nonsatisfying_assignment_tree_beta'].get('validate_passed')}",
          flush=True)

    # --- edge case: a recipe with no logic at all. evaluate_logic(None)
    # is SATISFIED by definition (META recipes), so check whether such a
    # row could validate and what the fragment definition must exclude.
    edge = {}
    try:
        empty_recipe = compose(ComposeRequest(
            name="empty edge", vertical="real_estate", target="land_parcel"),
            reg)
        edge["compose_empty_logic"] = (
            None if empty_recipe.signal_logic is None
            else str(empty_recipe.signal_logic.op))
    except Exception as e:  # noqa: BLE001
        edge["compose_empty_logic"] = f"compose refused: {str(e)[:160]}"
    base = compose(ComposeRequest(name="logic edge", vertical="real_estate",
                                  target="land_parcel",
                                  required=["tax.delinquent"]), reg)
    no_logic = base.model_copy(update={"signal_logic": None})
    try:
        rep_edge = validate(no_logic, reg)
        edge["no_logic_with_required_signal"] = {
            "validate_passed": bool(rep_edge.passed),
            "failed_checks": [k for k, v in rep_edge.checks.items()
                              if not v.get("ok")],
            "eval_outcome_on_empty_timeline": evaluate_logic(
                no_logic.signal_logic, r2.tl([]), AS_OF).outcome,
            "eval_outcome_on_full_timeline": evaluate_logic(
                no_logic.signal_logic, full, AS_OF).outcome,
        }
    except Exception as e:  # noqa: BLE001
        edge["no_logic_with_required_signal"] = {"error": str(e)[:200]}
    edge["note"] = ("a None-logic row is a META recipe, not a composer "
        "tree, and is excluded from FULL-COMP by definition; the check "
        "shows whether the exclusion matters")
    out["edge_case_no_logic"] = edge
    print(f"edge case: {edge}", flush=True)

    out["three_sat_attempt"] = {
        "variables": [x1, x2, x3],
        "assignment_alpha": alpha,
        "strategy_C_defeater_negation_formula_in_tree": strat_c,
        "strategy_D_formula_in_timeline_assignment_in_tree": strat_d,
        "strategy_E_formula_in_validity": strat_e,
        "verdict": ("all three encodings fail the equivalence, for three "
            "different structural reasons: C fails because the search is "
            "existential over trees and a trivial SATISFIED node always "
            "exists; D fails because the tree is checked against the "
            "timeline's fixed reference assignment and the clause slots "
            "carry no clause semantics; E fails because validate() takes "
            "no timeline and reads no formula"),
    }

    # --- cost comparison: greedy vs exhaustive enumeration on full vocab
    t0 = time.time()
    probe = candidate_nodes_full(full, signals)
    sample = probe[:2000]
    for _, node in sample:
        r2.eval_node(node, full)
    per_eval = (time.time() - t0) / len(sample)
    n_pool = len(probe)
    from math import comb
    out["cost"] = {
        "greedy_candidates_full_vocab": n_pool,
        "defeater_candidates_full_vocab": 4 * len(signals),
        "seconds_per_node_eval": round(per_eval, 6),
        "greedy_seconds_full_evidence":
            greedy_results["full_evidence"]["seconds"],
        "greedy_seconds_empty_timeline":
            greedy_results["empty"]["seconds"],
        "greedy_seconds_withdrawn_full":
            greedy_results["withdrawn_full"]["seconds"],
        "exhaustive_1node_seconds_est": round(n_pool * per_eval, 2),
        "exhaustive_2node_seconds_est": round(comb(n_pool, 2) * per_eval, 1),
        "exhaustive_3node_seconds_est": round(comb(n_pool, 3) * per_eval, 1),
        "note": "exhaustive 2-node and 3-node estimates are extrapolations "
        "from the measured per-evaluation cost; the greedy decision needs "
        "one pass over the node pool only, plus a bounded number of "
        "validate() calls whose results are timeline-independent and cached",
    }
    print(f"cost: {out['cost']}", flush=True)

    out["total_seconds"] = round(time.time() - t_start, 2)
    out["verdict"] = (
        "Constructive direction SUCCEEDS for the FULL fragment with "
        "defeaters, and the defeater rule makes the decision easier, not "
        "harder: for every signal and every timeline exactly one of "
        "leaf(s) and NOT(defeater leaf(s)) is SATISFIED, so a SATISFIED "
        "node always exists and node-wise greedy search decides FULL-COMP "
        "in polynomial time, with real witnesses built through compose "
        "plus signal_logic swap and validated. Hardness direction FAILS on "
        "all three defeater encodings: the formula tree can distinguish "
        "SAT from UNSAT on a fixed assignment, but the search never has "
        "to use it. Nothing here separates or collapses P and NP, and "
        "none is claimed."
    )
    dest = LAB / "data" / "p_vs_np_r3.json"
    dest.write_text(json.dumps(out, indent=2))
    print(f"wrote {dest} in {out['total_seconds']}s", flush=True)


if __name__ == "__main__":
    main()
