"""Tests for the AUDIT LAYER (the immune system's ledger).

Required coverage:
  1. hash-chain correctness (recomputed independently from the raw rows)
  2. UPDATE on audit_ledger is rejected by a SQLite trigger
  3. DELETE on audit_ledger is rejected by a SQLite trigger
  4. the verifier catches a corrupted (modified) row
  5. the verifier catches a deleted row
  6. a normal component write (job creation + state transition) appends a valid row

Plus: the HTTP surface (/audit/verify, /audit/tamper-test) and the guarantee that
the tamper test leaves the real ledger intact and verified.
"""

from __future__ import annotations

import hashlib
import json
import os
import sqlite3
import tempfile

import pytest

_TMP = tempfile.mkdtemp(prefix="jarvis-audit-test-")
os.environ["JARVIS_DB"] = os.path.join(_TMP, "test.db")
os.environ["JARVIS_MEMORY_DB"] = os.path.join(_TMP, "data", "jarvis.db")

from orchestrator import audit  # noqa: E402
from orchestrator import memory  # noqa: E402
from orchestrator import service  # noqa: E402
from orchestrator import state_machine as sm  # noqa: E402
from orchestrator.components import register_default_components  # noqa: E402
from orchestrator.db import connect, init_db  # noqa: E402
from orchestrator.events import GENESIS  # noqa: E402
from orchestrator.registry import REGISTRY  # noqa: E402


@pytest.fixture(autouse=True)
def fresh_db():
    db = os.environ["JARVIS_DB"]
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(db + suffix)
        except FileNotFoundError:
            pass
    init_db()
    audit.init_db()
    memory.init_db()
    REGISTRY.clear()
    register_default_components(REGISTRY)
    yield
    REGISTRY.clear()
    register_default_components(REGISTRY)


def canonical(obj) -> str:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), default=str)


def independent_hash(prev: str, row: dict) -> str:
    body = {
        "seq": row["seq"], "ts": row["ts"], "actor": row["actor"], "action": row["action"],
        "subject_type": row["subject_type"], "subject_id": row["subject_id"],
        "payload": json.loads(row["payload_json"]), "prev_hash": row["prev_hash"],
    }
    return hashlib.sha256((prev + canonical(body)).encode("utf-8")).hexdigest()


def seed_rows(n: int = 4) -> list[dict]:
    return [
        audit.record("TestActor", "test.write", "test_subject", str(i), {"i": i, "label": f"r{i}"})
        for i in range(n)
    ]


# --------------------------------------------------------------------------
# 1. hash chain correctness
# --------------------------------------------------------------------------

def test_chain_hashes_are_correct_and_linked():
    seed_rows(4)
    conn = connect()
    try:
        rows = [dict(r) for r in conn.execute(
            "SELECT * FROM audit_ledger ORDER BY seq ASC").fetchall()]
    finally:
        conn.close()

    assert [r["seq"] for r in rows] == [1, 2, 3, 4]
    prev = GENESIS
    for row in rows:
        assert row["prev_hash"] == prev, "each row must link to the previous row_hash"
        assert row["row_hash"] == independent_hash(prev, row), "row_hash must match the formula"
        prev = row["row_hash"]

    result = audit.verify()
    assert result["ok"] is True
    assert result["length"] == 4
    assert result["first_broken_seq"] is None
    assert result["head_hash"] == prev


def test_genesis_row_uses_64_zero_prev_hash():
    first = audit.record("TestActor", "test.first", "test_subject", "1", {"first": True})
    assert first["seq"] == 1
    assert first["prev_hash"] == "0" * 64


# --------------------------------------------------------------------------
# 2 & 3. append-only enforced by the database
# --------------------------------------------------------------------------

def test_update_on_ledger_is_rejected_by_trigger():
    seed_rows(2)
    conn = connect()
    try:
        with pytest.raises(sqlite3.IntegrityError) as excinfo:
            conn.execute("UPDATE audit_ledger SET actor = 'intruder' WHERE seq = 1")
        conn.rollback()
    finally:
        conn.close()
    assert "append-only" in str(excinfo.value)
    assert "UPDATE" in str(excinfo.value)

    conn = connect()
    try:
        actor = conn.execute("SELECT actor FROM audit_ledger WHERE seq = 1").fetchone()["actor"]
    finally:
        conn.close()
    assert actor == "TestActor"
    assert audit.verify()["ok"] is True


def test_delete_on_ledger_is_rejected_by_trigger():
    seed_rows(2)
    conn = connect()
    try:
        with pytest.raises(sqlite3.IntegrityError) as excinfo:
            conn.execute("DELETE FROM audit_ledger WHERE seq = 1")
        conn.rollback()
    finally:
        conn.close()
    assert "append-only" in str(excinfo.value)
    assert "DELETE" in str(excinfo.value)

    result = audit.verify()
    assert result["ok"] is True
    assert result["length"] == 2


def test_triggers_are_installed_in_the_database():
    conn = connect()
    try:
        names = {r["name"] for r in conn.execute(
            "SELECT name FROM sqlite_master WHERE type='trigger' AND tbl_name='audit_ledger'"
        ).fetchall()}
    finally:
        conn.close()
    assert names == {"audit_ledger_no_update", "audit_ledger_no_delete"}


# --------------------------------------------------------------------------
# 4 & 5. verifier detects corruption in a scratch copy
# --------------------------------------------------------------------------

def _scratch_copy() -> int:
    conn = connect()
    try:
        return audit._scratch_copy(conn, audit.SCRATCH)
    finally:
        conn.close()


def test_verifier_catches_modified_row():
    seed_rows(5)
    copied = _scratch_copy()
    assert copied == 5

    conn = connect()
    try:
        conn.execute(
            "UPDATE audit_scratch_demo SET payload_json = ? WHERE seq = 3",
            (canonical({"forged": True}),),
        )
        conn.commit()
        result = audit.verify_conn(conn, audit.SCRATCH)
    finally:
        conn.close()

    assert result["ok"] is False
    assert result["first_broken_seq"] == 3
    assert "modified" in result["detail"]
    # the real ledger is untouched by corrupting the scratch copy
    assert audit.verify()["ok"] is True
    assert audit.verify()["length"] == 5


def test_verifier_catches_deleted_row():
    seed_rows(5)
    _scratch_copy()

    conn = connect()
    try:
        conn.execute("DELETE FROM audit_scratch_demo WHERE seq = 3")
        conn.commit()
        result = audit.verify_conn(conn, audit.SCRATCH)
    finally:
        conn.close()

    assert result["ok"] is False
    assert result["first_broken_seq"] == 3
    assert "missing" in result["detail"] or "gap" in result["detail"]
    assert audit.verify()["ok"] is True


def test_verifier_catches_reordered_row():
    seed_rows(4)
    _scratch_copy()
    conn = connect()
    try:
        a = dict(conn.execute("SELECT * FROM audit_scratch_demo WHERE seq=2").fetchone())
        b = dict(conn.execute("SELECT * FROM audit_scratch_demo WHERE seq=3").fetchone())
        conn.execute(
            "UPDATE audit_scratch_demo SET ts=?, actor=?, action=?, subject_type=?, subject_id=?,"
            " payload_json=?, prev_hash=?, row_hash=? WHERE seq=?",
            (b["ts"], b["actor"], b["action"], b["subject_type"], b["subject_id"],
             b["payload_json"], b["prev_hash"], b["row_hash"], 2),
        )
        conn.execute(
            "UPDATE audit_scratch_demo SET ts=?, actor=?, action=?, subject_type=?, subject_id=?,"
            " payload_json=?, prev_hash=?, row_hash=? WHERE seq=?",
            (a["ts"], a["actor"], a["action"], a["subject_type"], a["subject_id"],
             a["payload_json"], a["prev_hash"], a["row_hash"], 3),
        )
        conn.commit()
        result = audit.verify_conn(conn, audit.SCRATCH)
    finally:
        conn.close()

    assert result["ok"] is False
    assert result["first_broken_seq"] == 2


# --------------------------------------------------------------------------
# 6. normal component writes append valid rows
# --------------------------------------------------------------------------

def test_component_write_appends_valid_row():
    job = service.create_job("Audited job", "test/audit", {"k": "v"}, registry=REGISTRY)
    result = service.advance(job["id"], registry=REGISTRY)

    conn = connect()
    try:
        rows = [dict(r) for r in conn.execute(
            "SELECT * FROM audit_ledger ORDER BY seq ASC").fetchall()]
    finally:
        conn.close()

    actions = [r["action"] for r in rows]
    assert "job.created" in actions
    assert "state.transition" in actions

    created = next(r for r in rows if r["action"] == "job.created")
    assert created["actor"] == "Orchestrator"
    assert created["subject_type"] == "job"
    assert created["subject_id"] == job["id"]
    assert json.loads(created["payload_json"])["source"] == "test/audit"

    transition = next(r for r in rows if r["action"] == "state.transition")
    payload = json.loads(transition["payload_json"])
    assert payload["from"] == sm.INGESTED
    assert payload["to"] == result["transition"]["to"]

    verify = audit.verify()
    assert verify["ok"] is True
    assert verify["length"] == len(rows)


def test_memory_write_appends_audit_row():
    opp = memory.create_opportunity(title="Audited memory opp", source_url="https://example.test/x")
    audit.record  # noqa: B018  (imported symbol used below)
    rows = audit.recent(limit=20)
    hit = next(r for r in rows if r["action"] == "memory.opportunity.created")
    assert hit["subject_id"] == opp["id"]
    assert hit["payload"]["source_url"] == "https://example.test/x"
    assert audit.verify()["ok"] is True


def test_legacy_events_are_mirrored_without_loss():
    from orchestrator.events import append_event

    conn = connect()
    try:
        before = conn.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
        append_event(conn, job_id=None, actor="Legacy", kind="legacy_note",
                     from_state=None, to_state=None, note="written straight to events")
        conn.commit()
        after = conn.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"]
    finally:
        conn.close()
    assert after == before + 1

    # simulate a first run of the audit layer over an existing events table
    conn = connect()
    try:
        conn.execute("DELETE FROM audit_meta WHERE key='events_mirrored_upto'")
        conn.commit()
        mirrored = audit.mirror_legacy_events(conn)
    finally:
        conn.close()

    assert mirrored == after
    verify = audit.verify()
    assert verify["ok"] is True
    assert verify["length"] == after


# --------------------------------------------------------------------------
# HTTP surface
# --------------------------------------------------------------------------

def test_http_verify_and_tamper_test_endpoints():
    from app import create_app

    app = create_app(seed=True)
    client = app.test_client()

    seed_rows(2)

    verify = client.get("/audit/verify")
    assert verify.status_code == 200
    body = verify.get_json()
    assert body["ok"] is True
    assert body["length"] >= 2
    assert body["first_broken_seq"] is None

    page = client.get("/audit")
    assert page.status_code == 200
    html = page.get_data(as_text=True)
    assert "audit_ledger_no_update" in html
    assert "APPEND-ONLY" in html
    assert "Verify chain" in html
    assert "Run tamper test" in html

    tamper = client.post("/audit/tamper-test")
    assert tamper.status_code == 200
    result = tamper.get_json()
    assert result["ok"] is True
    assert all(op["blocked"] for op in result["blocked_operations"])
    assert all("append-only" in op["error"] for op in result["blocked_operations"])
    assert result["real_ledger_after"]["ok"] is True
    assert result["real_ledger_intact"] is True

    cases = {c["case"]: c for c in result["scratch"]["cases"]}
    assert set(cases) == {"modified_row", "deleted_row", "reordered_rows"}
    for case in cases.values():
        assert case["caught"] is True
        assert case["verify"]["ok"] is False
        assert isinstance(case["verify"]["first_broken_seq"], int)

    final = client.get("/audit/verify").get_json()
    assert final["ok"] is True
    assert final["length"] == result["real_ledger_after"]["length"]


# --------------------------------------------------------------------------
# regressions found while verifying the layer end-to-end
# --------------------------------------------------------------------------

def test_ensure_repairs_partially_initialised_database():
    """A DB whose ledger table exists but whose meta table/triggers do not must
    still be repaired. (Real bug: _ensure() used to return early on the table
    alone, so audit_meta was never created and legacy events were never
    mirrored -- init_db() raised "no such table: audit_meta".)"""
    path = os.path.join(_TMP, "partial.db")
    for suffix in ("", "-wal", "-shm"):
        try:
            os.remove(path + suffix)
        except FileNotFoundError:
            pass
    raw = sqlite3.connect(path)
    raw.execute(
        """CREATE TABLE audit_ledger (
               seq INTEGER PRIMARY KEY, ts TEXT NOT NULL, actor TEXT NOT NULL,
               action TEXT NOT NULL, subject_type TEXT NOT NULL, subject_id TEXT,
               payload_json TEXT NOT NULL DEFAULT '{}', prev_hash TEXT NOT NULL,
               row_hash TEXT NOT NULL)"""
    )
    raw.commit()
    raw.close()

    old = os.environ["JARVIS_DB"]
    os.environ["JARVIS_DB"] = path
    try:
        audit.init_db()  # must not raise
        conn = connect()
        try:
            names = {
                r["name"]
                for r in conn.execute(
                    "SELECT name FROM sqlite_master WHERE type IN ('table','trigger')"
                ).fetchall()
            }
        finally:
            conn.close()
    finally:
        os.environ["JARVIS_DB"] = old

    assert "audit_meta" in names
    assert "audit_ledger_no_update" in names
    assert "audit_ledger_no_delete" in names


def test_tamper_test_succeeds_on_a_young_ledger():
    """The tamper demo must still demonstrate all three corruption cases when the
    real ledger has fewer than 3 rows, by padding only the scratch copy."""
    seed_rows(1)
    result = audit.tamper_test()
    cases = {c["case"]: c for c in result["scratch"]["cases"]}
    assert set(cases) == {"modified_row", "deleted_row", "reordered_rows"}
    assert all(c["caught"] for c in cases.values())
    assert result["scratch"]["padded_rows"] > 0
    assert result["ok"] is True
    assert result["real_ledger_intact"] is True
    assert audit.verify()["ok"] is True


def test_scratch_padding_never_touches_the_real_ledger():
    seed_rows(2)
    before = audit.verify()
    audit.tamper_test()
    after = audit.verify()
    assert after["ok"] is True
    # the tamper test appends its own start/finish rows, but never removes any
    assert after["length"] >= before["length"]
    conn = connect()
    try:
        leaked = conn.execute(
            "SELECT COUNT(*) AS n FROM audit_ledger WHERE action = 'audit.scratch.padding'"
        ).fetchone()["n"]
    finally:
        conn.close()
    assert leaked == 0, "scratch padding rows must never appear in the real ledger"


# ==========================================================================
# CANONICAL CONTRACT: {ok, length} / {ok: false, broken_at, reason}
# ==========================================================================

def test_verify_returns_the_canonical_contract_on_an_intact_chain():
    seed_rows(3)
    result = audit.verify()
    assert result["ok"] is True
    assert result["length"] == 3
    assert result["broken_at"] is None
    assert result["reason"] is None
    # the back-compatible spellings still agree
    assert result["first_broken_seq"] is None
    assert result["head_hash"] == audit.head()["row_hash"]


def test_canonical_view_publishes_the_required_field_names():
    """audit_events exposes id/timestamp/component/event_type/subject/payload."""
    seed_rows(2)
    conn = connect()
    try:
        cols = [r["name"] for r in conn.execute("PRAGMA table_info(audit_events)").fetchall()]
        row = conn.execute("SELECT * FROM audit_events ORDER BY id ASC LIMIT 1").fetchone()
        assert row["subject"] == "test_subject:0"
        assert json.loads(row["payload"]) == {"i": 0, "label": "r0"}
        assert row["row_hash"] == audit.recent(limit=10)[-1]["row_hash"]
    finally:
        conn.close()
    for required in ("id", "timestamp", "component", "event_type", "subject",
                     "payload", "prev_hash", "row_hash"):
        assert required in cols, f"audit_events must expose {required}"


# ==========================================================================
# REAL tamper injection (dev-only) — the verifier must name the exact row
# ==========================================================================

def test_dev_tamper_of_a_real_row_is_caught_at_that_exact_row():
    seed_rows(5)
    assert audit.verify()["ok"] is True

    result = audit.dev_tamper(3, field="payload_json")
    assert result["applied"] is True
    assert result["dev_only"] is True

    after = audit.verify()
    assert after["ok"] is False
    assert after["broken_at"] == 3, "the verifier must name the row that was actually mutated"
    assert "modified" in after["reason"]
    assert after["length"] == 6  # 5 real rows + the honest "tamper injected" row

    # the mutation really happened in the file, not just in the response
    conn = connect()
    try:
        payload = json.loads(
            conn.execute("SELECT payload_json FROM audit_ledger WHERE seq=3").fetchone()["payload_json"]
        )
    finally:
        conn.close()
    assert payload["tampered"] is True
    assert payload["replaced_payload"]["i"] == 2


def test_dev_tamper_of_actor_field_is_caught_too():
    seed_rows(4)
    audit.dev_tamper(2, field="actor", value="intruder")
    after = audit.verify()
    assert after["ok"] is False
    assert after["broken_at"] == 2
    assert "modified" in after["reason"]


def test_dev_deleted_row_is_caught_at_the_deleted_id():
    seed_rows(5)
    result = audit.dev_delete(3)
    assert result["applied"] is True

    after = audit.verify()
    assert after["ok"] is False
    assert after["broken_at"] == 3, "a hole must be reported where the row is missing"
    assert "missing" in after["reason"] or "gap" in after["reason"]

    conn = connect()
    try:
        gone = conn.execute("SELECT 1 FROM audit_ledger WHERE seq=3").fetchone()
    finally:
        conn.close()
    assert gone is None


def test_dev_restore_puts_the_chain_back_and_leaves_an_honest_record():
    seed_rows(4)
    before = audit.verify()
    audit.dev_tamper(2, field="payload_json")
    audit.dev_delete(3)
    assert audit.verify()["ok"] is False

    restored = audit.dev_restore()
    assert restored["restored_rows"] == [2, 3]
    after = audit.verify()
    assert after["ok"] is True
    assert after["broken_at"] is None
    # restoring never forgets what happened: the demo itself is in the ledger
    actions = [r["action"] for r in audit.recent(limit=200)]
    assert "audit.tamper.injected" in actions
    assert "audit.tamper.deleted" in actions
    assert "audit.tamper.restored" in actions
    assert after["length"] > before["length"]
    assert audit.dev_state()["tampered_rows"] == []


def test_dev_tamper_can_be_switched_off_with_an_env_flag(monkeypatch):
    seed_rows(2)
    monkeypatch.setenv("JARVIS_ALLOW_TAMPER", "0")
    result = audit.dev_tamper(1, field="payload_json")
    assert result["applied"] is False
    assert "disabled" in result["error"]
    assert audit.verify()["ok"] is True


# ==========================================================================
# HTTP: verify contract, dev-only tamper endpoint, badge flip, filters, trace
# ==========================================================================

def test_http_verify_contract_and_dev_tamper_flips_the_badge():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    client = app.test_client()

    seed_rows(4)
    body = client.get("/audit/verify").get_json()
    assert body["ok"] is True
    assert body["length"] == 4
    assert body["broken_at"] is None

    state = client.get("/audit/_tamper/state").get_json()
    assert state["dev_only"] is True and state["tampered_rows"] == []

    tampered = client.post("/audit/_tamper", json={"row_id": 2, "field": "payload_json"})
    assert tampered.status_code == 200
    payload = tampered.get_json()
    assert payload["applied"] is True and payload["dev_only"] is True
    assert payload["verify"]["ok"] is False
    assert payload["verify"]["broken_at"] == 2

    caught = client.get("/audit/verify").get_json()
    assert caught["ok"] is False
    assert caught["broken_at"] == 2
    assert caught["reason"]

    page = client.get("/audit").get_data(as_text=True)
    assert "CHAIN BROKEN AT ROW 2" in page  # the server-rendered badge is red

    fixed = client.post("/audit/_tamper/restore").get_json()
    assert fixed["restored_rows"] == [2]
    final = client.get("/audit/verify").get_json()
    assert final["ok"] is True
    assert final["broken_at"] is None
    assert "CHAIN INTACT" in client.get("/audit").get_data(as_text=True)


def test_audit_page_has_filters_trace_and_dev_only_marking():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    client = app.test_client()
    seed_rows(2)

    html = client.get("/audit").get_data(as_text=True)
    for needle in ("component", "event_type", "Apply filter", "subject",
                   "Run tamper demo", "Run tamper test", "Restore chain", "DEV-ONLY",
                   "/audit/_tamper", "CHAIN INTACT", "audit_events"):
        assert needle in html, f"audit page must render {needle!r}"

    # the provenance panel only exists for a real subject — and then shows its trail
    audit.record("Alpha", "alpha.traced", "thing", "subj-42", {"detail": "trail"})
    trace_page = client.get("/audit?subject=subj-42").get_data(as_text=True)
    assert "Provenance trail" in trace_page
    assert "subj-42" in trace_page
    assert "alpha.traced" in trace_page


def test_audit_page_filters_by_component_and_event_type():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    client = app.test_client()
    audit.record("Alpha", "alpha.did", "thing", "1", {"n": 1})
    audit.record("Beta", "beta.did", "thing", "2", {"n": 2})
    audit.record("Alpha", "alpha.other", "thing", "3", {"n": 3})

    rows = client.get("/audit/rows?component=Alpha").get_json()["rows"]
    assert [r["action"] for r in rows] == ["alpha.other", "alpha.did"]
    rows = client.get("/audit/rows?event_type=beta.did").get_json()["rows"]
    assert [r["actor"] for r in rows] == ["Beta"]
    rows = client.get("/audit/rows?component=Alpha&event_type=alpha.did").get_json()["rows"]
    assert len(rows) == 1
    page = client.get("/audit?event_type=beta.did").get_data(as_text=True)
    # the cells now also carry a data-label (the phone card layout) — same assertion,
    # tolerant of the extra attribute.
    import re as _re

    def _action_cell(action: str) -> bool:
        return _re.search(r'<td[^>]*class="action"[^>]*>' + _re.escape(action) + r"</td>", page) is not None

    assert _action_cell("beta.did")
    assert not _action_cell("alpha.did")
    assert not _action_cell("alpha.other")


def test_trace_shows_the_ordered_provenance_of_a_job():
    from app import create_app

    app = create_app(seed=False)
    app.config.update(TESTING=True)
    client = app.test_client()

    job = service.create_job("Provenance job", "test/trace", {"k": "v"}, registry=REGISTRY)
    service.advance(job["id"], registry=REGISTRY)

    trail = client.get(f"/audit/trace/{job['id']}").get_json()
    assert trail["count"] >= 2
    seqs = [e["seq"] for e in trail["events"]]
    assert seqs == sorted(seqs), "provenance must be in chain order"
    actions = [e["action"] for e in trail["events"]]
    assert "job.created" in actions
    assert "state.transition" in actions
    for event in trail["events"]:
        assert event["subject_id"] == job["id"] or job["id"] in json.dumps(event["payload"])
    assert trail["verify"]["ok"] is True

    empty = client.get("/audit/trace/does-not-exist").get_json()
    assert empty["count"] == 0 and empty["events"] == []


# ==========================================================================
# Every layer writes through the audit layer (one chain, all components)
# ==========================================================================

def test_ingestion_opportunity_verification_and_memory_all_land_in_the_chain(monkeypatch):
    from orchestrator import ingestion, opportunity, verification

    def no_network(url, **_kw):
        raise AssertionError("this test must not touch the network")

    monkeypatch.setattr(ingestion, "SOURCES", [])
    run = ingestion.run_ingest(trigger="test-audit")
    assert audit.recent(limit=5)[0]["action"] == "ingest.run"
    assert audit.recent(limit=5)[0]["subject_type"] == "ingest_run"

    # opportunity engine over stored signals (no network)
    titles = ["OpenAI ships a new agent API for developers",
              "Google expands Gemini agent tasks for teams",
              "A local LLM agent inference tool ships"]
    for i, title in enumerate(titles):
        sig = ingestion.normalize_item("hackernews", title=title,
                                       url=f"https://ex.invalid/{i}", summary="agent model tooling")
        conn = connect()
        try:
            ingestion._insert_signal(conn, sig)
            conn.commit()
        finally:
            conn.close()
    engine_run = opportunity.run_engine(actor="test-audit")
    recent_actions = [r["action"] for r in audit.recent(limit=20)]
    assert "opportunity.run" in recent_actions
    run_row = next(r for r in audit.recent(limit=20) if r["action"] == "opportunity.run")
    assert run_row["subject_type"] == "opportunity_run"
    assert run_row["subject_id"] == str(engine_run["id"])
    opps = opportunity.list_opportunities()
    assert opps, "the engine must produce an opportunity from these signals"

    # verification over a mocked fetcher (no network)
    monkeypatch.setattr(
        verification, "FETCHER",
        lambda url, **kw: {"ok": True, "http_status": 200,
                           "body": b"<html><body>agent model tooling API</body></html>",
                           "content_type": "text/html", "error": None, "error_kind": None,
                           "final_url": url, "duration_ms": 1},
    )
    vrun = verification.verify_opportunity(opps[0]["id"], trigger="test-audit")
    verdict_rows = [r for r in audit.recent(limit=50)
                    if r["action"] == "verification.verdict"]
    assert verdict_rows, "the verdict must be in the ledger"
    assert verdict_rows[0]["subject_id"] == opps[0]["id"]
    assert verdict_rows[0]["payload"]["run_id"] == vrun["id"]

    # memory store
    m_opp = memory.create_opportunity(title="Audited opp", source_url="https://example.test/a")
    memory.create_claim(opportunity_id=m_opp["id"], text="cited fact",
                        source_url="https://example.test/a", source_turn="turn-1")
    actions = {r["action"] for r in audit.recent(limit=50)}
    for action in ("memory.opportunity.created", "memory.claim.created"):
        assert action in actions

    # job pipeline
    job = service.create_job("Chained job", "test/audit", {}, registry=REGISTRY)
    service.advance(job["id"], registry=REGISTRY)

    final = audit.verify()
    assert final["ok"] is True
    actions = {r["action"] for r in audit.recent(limit=200)}
    for action in ("ingest.run", "opportunity.run", "opportunity.created",
                   "verification.verdict", "memory.opportunity.created",
                   "memory.claim.created", "job.created", "state.transition"):
        assert action in actions, f"{action} must be written through the audit layer"

    # and the legacy events table is a projection of the same writes, not a
    # second independent path: every component that reported an event also
    # produced a ledger row in the same operation.
    assert engine_run["produced"] >= 1
    conn = connect()
    try:
        subtypes = {r["kind"] for r in conn.execute("SELECT kind FROM events").fetchall()}
    finally:
        conn.close()
    assert "verification_run" in subtypes
    assert "opportunity_run" in subtypes
