Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(gates): hold the investigation ledger's replay contract in both directions (#973)

Beenu Arorac7ed1437e7c1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8df874a68..f91d39597 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -601,6 +601,21 @@ jobs:
run: python3 scripts/check_default_egress.py --self-test
- name: Default egress gate
run: python3 scripts/check_default_egress.py
+ # A different replay, and the one the claim matrix mislabelled. The gate
+ # named for "Investigation Ledger stores every step" tests the hash
+ # chain over `audit_log`, which the API middleware writes; the ledger is
+ # `investigation_events`, written by services/agents over raw asyncpg
+ # and read back by three routes no test touched. This holds the three
+ # trees that have to agree for a step to survive from the agent that
+ # took it to the analyst reading it back — the response model against
+ # the console's type, the client's requests against the router's
+ # decorators, and the writer's columns against the migration chain —
+ # each in both directions, plus the sequencing that makes "every step"
+ # mean an ordered, unduplicated one.
+ - name: Ledger replay contract gate — self-test
+ run: python3 scripts/check_ledger_replay_contract.py --self-test
+ - name: Ledger replay contract gate
+ run: python3 scripts/check_ledger_replay_contract.py
# The count claim above says how many connectors exist; this says
# whether a reader can find out how to use them. 35 of 84 had no page
# at all and the sidebar listed 34 of 96, so most connector
diff --git a/scripts/check_ledger_replay_contract.py b/scripts/check_ledger_replay_contract.py
new file mode 100644
index 000000000..67e4d15c8
--- /dev/null
+++ b/scripts/check_ledger_replay_contract.py
@@ -0,0 +1,1243 @@
+#!/usr/bin/env python3
+"""The investigation ledger's replay contract, held in both directions.
+
+Why this exists
+---------------
+
+"Investigation Ledger stores every step" is a front-page claim, and the gate
+the claim matrix named for it — ``api tests (audit_hash, audit immutability)``
+— tests a **different table**. ``services/api/tests/test_audit_hash.py``
+covers ``app.services.audit_hash`` over ``audit_log``, which the API's audit
+middleware writes. The ledger is ``investigation_runs`` /
+``investigation_events`` / ``investigation_artifacts``, created by
+``services/api/migrations/008_investigation_ledger.sql`` and written by
+``services/agents/app/investigator/ledger.py`` over raw asyncpg. Two tables
+with two writers, and only one of them was ever gated; the hash chain could
+have been perfect while every replay surface was broken.
+
+What was actually ungated: the ledger's only test covered tenant resolution
+against a stub connection, no test anywhere touched ``/replay``, ``/events``
+or ``/explain``, and the "hermetic e2e" the row cited is one Playwright spec
+in the ``screenshots`` project, which runs from a monthly cron whose job is
+to capture PNGs rather than from any pull request.
+
+Three trees have to agree for a step to survive from the agent that took it
+to the analyst reading it back, and none of them can import the others: the
+writer packages as top-level ``app`` in ``services/agents``, the reader
+packages as top-level ``app`` in ``services/api``, and the console is
+TypeScript. The contract between them is a handful of declarations agreeing
+by convention, and this tree has already shipped both halves of that failing:
+six Investigation Rail entity pivots emitted ``/attack-graph?entity=...``
+against a route that never existed, and ``EntityBaseline.peer_group_id`` was
+declared by a model no migration created, so the first query raised.
+
+Nothing is imported. The gate runs on a bare interpreter, and importing the
+API service to read a list of field names would drag in SQLAlchemy, FastAPI
+and the whole model graph.
+
+What it checks, in both directions
+----------------------------------
+
+The dominant failure shape in this repository is the one-directional gate: it
+compares A against B, never B against A, and prints OK while drift
+accumulates in the direction things actually change. The graph-schema drift
+check declared "OK" over a YAML file with 17 labels against Go with 28. So
+each of the three properties below is asserted both ways.
+
+``FIELD-*``
+ Every field of the ``EventOut`` response model is a field of the
+ ``LedgerEvent`` TypeScript interface, and the reverse. The direction that
+ drifts is a field added to the Python model that the TypeScript type never
+ hears about: it is serialised, delivered, and dropped at the boundary with
+ nothing failing. The reverse direction is a console rendering a key no
+ response carries, which reads as an empty cell rather than as a bug.
+
+``ROUTE-*``
+ Every path the ``ledgerApi`` client requests is a path the FastAPI router
+ declares, and every ledger route the router declares is either consumed
+ somewhere under ``apps/web/src`` or recorded in ``SERVER_ONLY_ROUTES``
+ with a reason. Read from the ``@router.get`` / ``@router.post`` decorators
+ and from the client's own literals, so a route renamed on one side alone
+ is a finding rather than a 404 an operator discovers.
+
+``COLUMN-*`` / ``SEQ-*``
+ Every column the three ledger tables carry is either written by the
+ ledger writer or recorded as unwritten with a reason.
+
+ Only that direction. The other one — a column the writer writes that no
+ migration creates — is held by ``scripts/check_raw_sql_columns.py``,
+ which landed while this was being written and makes the comparison
+ generically for every raw statement under ``services/*/app``, including
+ this writer's. Two gates reporting the same finding is not redundancy, it
+ is two places to keep in step, so this one delegates and says so. The
+ delegation is checked rather than asserted: if that gate stops existing
+ or stops reading the writer's tree, ``COLUMN-DELEGATION-MISSING`` fires
+ here, because a direction nobody covers must not go quiet.
+
+ What no generic column gate can say is what "stores every step" actually
+ means, so this does: the writer must stamp ``seq`` on every event it
+ appends, the schema must keep ``UNIQUE (run_id, seq)`` so a replayed
+ write conflicts instead of appending a second copy of a step, and every
+ read handler that materialises a collection of events must ``ORDER BY
+ seq`` — and not by ``ts``, which ties at the resolution the agent writes
+ it and moves backwards under a clock correction. A replay that returns
+ steps in whatever order the planner chose is not a replay, and Postgres
+ promises no order without an ``ORDER BY``.
+
+Non-vacuity
+-----------
+
+Found nothing and scanned nothing print the same word. A verdict is refused
+outright on zero parsed fields, zero parsed routes, zero parsed client paths,
+zero parsed columns, or zero event-list handlers, and the counts are printed
+on every run so a parser that quietly stopped matching is visible by reading
+rather than by trusting the exit code.
+
+What it reads
+-------------
+
+* ``services/api/app/api/v1/endpoints/investigations.py`` — Python ``ast``
+ for the ``EventOut`` model, the router decorators, and each handler's query
+ shape.
+* ``apps/web/src/lib/api.ts`` — the ``LedgerEvent`` interface and the
+ ``ledgerApi`` object, comments stripped first so a documented-but-absent
+ field cannot satisfy a requirement.
+* ``apps/web/src/**/*.ts(x)`` — which ledger routes anything actually calls.
+* ``services/agents/app/investigator/ledger.py`` — the SQL passed to
+ ``conn.execute``, by ``ast``, so a table name in a docstring is not a write.
+* ``services/api/migrations/*.sql`` — ``CREATE TABLE`` in 008 plus every
+ later ``ADD COLUMN`` against those three tables, because four of the
+ columns the writer writes arrived in migration 063.
+
+Usage
+-----
+
+::
+
+ python3 scripts/check_ledger_replay_contract.py # gate
+ python3 scripts/check_ledger_replay_contract.py --json
+ python3 scripts/check_ledger_replay_contract.py --self-test
+
+Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import json
+import re
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+# `scripts/` is on sys.path when this file is run as a program, but not when a
+# test loads it by path with importlib. gate_toolkit sits beside it either way.
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from gate_toolkit import repo_root, self_test_main # noqa: E402
+
+# ---------------------------------------------------------------------------
+# What the contract is written across
+# ---------------------------------------------------------------------------
+
+ENDPOINTS_REL = "services/api/app/api/v1/endpoints/investigations.py"
+API_TS_REL = "apps/web/src/lib/api.ts"
+WRITER_REL = "services/agents/app/investigator/ledger.py"
+CREATING_MIGRATION_REL = "services/api/migrations/008_investigation_ledger.sql"
+MIGRATIONS_DIR_REL = "services/api/migrations"
+WEB_SRC_REL = "apps/web/src"
+
+#: The response model and the TypeScript type that must carry the same fields.
+RESPONSE_MODEL = "EventOut"
+TS_INTERFACE = "LedgerEvent"
+
+#: The client object whose every request must land on a declared route.
+CLIENT_OBJECT = "ledgerApi"
+
+#: ``APIRouter(prefix=...)`` in the endpoints module. Read rather than assumed,
+#: with this as the fallback only if the constructor stops naming one.
+ROUTER_PREFIX_DEFAULT = "/investigations"
+
+#: The three tables migration 008 creates. Deliberately not "every table the
+#: writer touches": it also writes ``alerts``, ``agent_approvals`` and
+#: ``aisoc_outcome_suppressions``, which belong to other migrations and other
+#: gates.
+LEDGER_TABLES = ("investigation_runs", "investigation_events", "investigation_artifacts")
+
+#: The append-only table, the column that orders it, and the run it belongs to.
+#: ``UNIQUE (run_id, seq)`` is what makes a replayed write conflict instead of
+#: appending a second copy of a step.
+EVENTS_TABLE = "investigation_events"
+SEQUENCE_COLUMN = "seq"
+RUN_COLUMN = "run_id"
+
+#: The ORM class the API reads events through, named in the read handlers.
+EVENT_ORM = "InvestigationEvent"
+
+#: The gate that owns the other half of the column comparison — a column the
+#: writer writes that no migration creates — and the glob whose presence in
+#: its source means it still reaches this writer. Checked rather than
+#: assumed: delegating to a gate that has stopped looking is how a direction
+#: goes quiet while two files each believe the other has it.
+DELEGATE_REL = "scripts/check_raw_sql_columns.py"
+DELEGATE_SCOPE_MARKER = "services/*/app"
+
+
+# ---------------------------------------------------------------------------
+# Recorded exceptions
+# ---------------------------------------------------------------------------
+#
+# Shrink-only, and verified in both directions: an entry that stops being
+# needed fails the build rather than sitting here looking like coverage. Each
+# says why, because a bare list of names is a second place for drift to hide.
+
+#: Routes the router declares that no browser client calls, and why that is a
+#: decision rather than an oversight. Checked both ways — an entry naming a
+#: route that no longer exists, or one the console has since started calling,
+#: is a finding.
+SERVER_ONLY_ROUTES: dict[str, str] = {
+ "POST /investigations/{}/close": (
+ "closing a run is driven from the case workspace through /cases, which owns the case lifecycle; "
+ "the console never posts here directly"
+ ),
+ "GET /investigations/{}/summary.pdf": (
+ "a browser follows this as a download link rather than fetching it through the typed client, "
+ "so there is no request literal to match"
+ ),
+}
+
+#: ``(table, column)`` the schema carries and the ledger writer never writes,
+#: with the reason it is not a write. Read-only or database-populated columns
+#: are the expected shape here.
+UNWRITTEN_COLUMNS: dict[tuple[str, str], str] = {
+ ("investigation_artifacts", "blob_ref"): "reserved for object-store offload; artifacts are stored inline in content for now",
+}
+
+
+# ---------------------------------------------------------------------------
+# Findings
+# ---------------------------------------------------------------------------
+
+
+class GateError(RuntimeError):
+ """The scan itself could not run — a missing file, an unparseable source."""
+
+
+@dataclass(frozen=True)
+class Finding:
+ code: str
+ detail: str
+
+ def __str__(self) -> str:
+ return f"[{self.code}] {self.detail}"
+
+
+@dataclass
+class RouteDecl:
+ """One ``@router.<method>(path)`` declaration, normalised."""
+
+ method: str
+ path: str
+ handler: str
+
+ @property
+ def key(self) -> str:
+ return f"{self.method} {self.path}"
+
+
+@dataclass
+class EventQuery:
+ """What one router handler does with ``InvestigationEvent`` rows."""
+
+ handler: str
+ orders_by_sequence: bool
+ #: Event columns the handler orders by that are *not* ``seq``. Ordering a
+ #: replay by ``ts`` is the plausible drift and a silently wrong one:
+ #: timestamps tie at the resolution the agent writes them, and a clock
+ #: correction can move one backwards, while ``seq`` cannot.
+ other_order_columns: tuple[str, ...] = ()
+
+
+@dataclass
+class Corpus:
+ """Everything the verdict is computed from, so it can be probed directly."""
+
+ model_fields: set[str] = field(default_factory=set)
+ ts_fields: set[str] = field(default_factory=set)
+ routes: dict[str, RouteDecl] = field(default_factory=dict)
+ client_paths: set[str] = field(default_factory=set)
+ consumer_paths: set[str] = field(default_factory=set)
+ written_columns: dict[str, set[str]] = field(default_factory=dict)
+ schema_columns: dict[str, set[str]] = field(default_factory=dict)
+ created_in_migration: dict[str, str] = field(default_factory=dict)
+ unique_constraints: dict[str, set[tuple[str, ...]]] = field(default_factory=dict)
+ event_queries: list[EventQuery] = field(default_factory=list)
+ #: Whether ``DELEGATE_REL`` still covers the direction this gate hands it.
+ delegate_reads_writer: bool = False
+
+ def counts(self) -> dict[str, int]:
+ return {
+ "model_fields": len(self.model_fields),
+ "typescript_fields": len(self.ts_fields),
+ "routes": len(self.routes),
+ "client_paths": len(self.client_paths),
+ "consumer_paths": len(self.consumer_paths),
+ "written_columns": sum(len(v) for v in self.written_columns.values()),
+ "schema_columns": sum(len(v) for v in self.schema_columns.values()),
+ "event_list_handlers": len(self.event_queries),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Python: the response model, the router, the read handlers
+# ---------------------------------------------------------------------------
+
+
+def _parse_python(text: str, rel: str) -> ast.Module:
+ try:
+ return ast.parse(text)
+ except SyntaxError as exc:
+ raise GateError(f"{rel}: could not parse: {exc}") from exc
+
+
+def parse_model_fields(text: str, rel: str, class_name: str) -> set[str]:
+ """Annotated field names of one Pydantic model, by ``ast``.
+
+ A field named only in a docstring or a comment is not a field, which is
+ the whole reason this reads the tree rather than grepping it.
+ """
+ tree = _parse_python(text, rel)
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ClassDef) and node.name == class_name:
+ return {stmt.target.id for stmt in node.body if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name)}
+ raise GateError(f"{rel}: no class named {class_name}")
+
+
+def _router_prefix(tree: ast.Module) -> str:
+ """The prefix the module's ``APIRouter`` was constructed with."""
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "APIRouter"):
+ continue
+ for kw in node.keywords:
+ if kw.arg == "prefix" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
+ return kw.value.value
+ return ROUTER_PREFIX_DEFAULT
+
+
+def _normalise_path(path: str) -> str:
+ """Collapse every path parameter to ``{}``.
+
+ ``/{run_id}/events`` and ``/${runId}/events`` describe the same route and
+ have to compare equal, or the gate would only ever be able to check the
+ literal spelling each side happens to use.
+ """
+ collapsed = re.sub(r"\$?\{[^}]*\}", "{}", path)
+ return collapsed.rstrip("/") or "/"
+
+
+def parse_routes(text: str, rel: str) -> dict[str, RouteDecl]:
+ """Every route the module's router declares, keyed ``METHOD /path``.
+
+ Read from the decorators rather than from the module docstring's endpoint
+ list, which is prose and was already one route out of date.
+ """
+ tree = _parse_python(text, rel)
+ prefix = _router_prefix(tree)
+ out: dict[str, RouteDecl] = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ for decorator in node.decorator_list:
+ if not isinstance(decorator, ast.Call) or not isinstance(decorator.func, ast.Attribute):
+ continue
+ target = decorator.func.value
+ if not (isinstance(target, ast.Name) and target.id == "router"):
+ continue
+ method = decorator.func.attr.upper()
+ if method not in {"GET", "POST", "PUT", "PATCH", "DELETE"}:
+ continue
+ if not (decorator.args and isinstance(decorator.args[0], ast.Constant) and isinstance(decorator.args[0].value, str)):
+ continue
+ decl = RouteDecl(method=method, path=_normalise_path(prefix + decorator.args[0].value), handler=node.name)
+ out[decl.key] = decl
+ return out
+
+
+def _mentions_event_orm(node: ast.AST) -> bool:
+ """Whether a subtree names the event ORM class at all."""
+ return any(isinstance(inner, ast.Name) and inner.id == EVENT_ORM for inner in ast.walk(node))
+
+
+def _event_order_columns(node: ast.AST) -> set[str]:
+ """Event columns a subtree's ``order_by(...)`` calls name.
+
+ Picks up ``InvestigationEvent.seq`` directly and ``InvestigationEvent.seq
+ .asc()``, where the interesting attribute is one level in.
+ """
+ columns: set[str] = set()
+ for inner in ast.walk(node):
+ if not (isinstance(inner, ast.Call) and isinstance(inner.func, ast.Attribute) and inner.func.attr == "order_by"):
+ continue
+ for argument in inner.args:
+ for attribute in ast.walk(argument):
+ if not isinstance(attribute, ast.Attribute):
+ continue
+ owner = attribute.value
+ if isinstance(owner, ast.Name) and owner.id == EVENT_ORM:
+ columns.add(attribute.attr)
+ return columns
+
+
+def parse_event_queries(text: str, rel: str) -> list[EventQuery]:
+ """Per handler: does it read a collection of events, and how does it order them?
+
+ The unit is the handler rather than the individual query, deliberately.
+ These are chained builders — ``list_events`` assigns ``select(...)`` in one
+ statement, narrows it in a second, and appends ``order_by`` in a third —
+ so pairing an ``order_by`` with the ``select`` it belongs to would need
+ dataflow, and a gate that guesses at that is worse than one that is coarse
+ and says so. The cost of the coarseness is stated: a handler that orders
+ one event query correctly and leaves a second unordered passes here.
+
+ A handler qualifies when it both builds a ``select(InvestigationEvent)``
+ and materialises a list with ``.all()``. ``explain_step`` qualifies — its
+ ``.all()`` is over artifacts, but it does order its neighbour lookups by
+ ``seq``, which is the same property. A handler that only ever reads one
+ event by exact ``seq`` makes no ordering claim and is not asked for one.
+ """
+ tree = _parse_python(text, rel)
+ out: list[EventQuery] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
+ continue
+ selects_events = any(
+ isinstance(call, ast.Call) and isinstance(call.func, ast.Name) and call.func.id == "select" and _mentions_event_orm(call)
+ for call in ast.walk(node)
+ )
+ reads_a_collection = any(
+ isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.func.attr == "all" for call in ast.walk(node)
+ )
+ if not (selects_events and reads_a_collection):
+ continue
+ ordered_by = _event_order_columns(node)
+ out.append(
+ EventQuery(
+ handler=node.name,
+ orders_by_sequence=SEQUENCE_COLUMN in ordered_by,
+ other_order_columns=tuple(sorted(ordered_by - {SEQUENCE_COLUMN})),
+ )
+ )
+ return out
+
+
+# ---------------------------------------------------------------------------
+# TypeScript: the interface and the client
+# ---------------------------------------------------------------------------
+
+
+def _strip_ts_comments(text: str) -> str:
+ """Block and line comments, so documentation cannot satisfy a requirement.
+
+ A commented-out field is not a field either, which is the other half of
+ why this runs first.
+ """
+ without_blocks = re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)
+ return re.sub(r"^\s*//.*$", "", without_blocks, flags=re.MULTILINE)
+
+
+def _balanced_body(text: str, open_at: int) -> str:
+ """The text between ``text[open_at]`` and its matching close brace."""
+ depth, i = 1, open_at + 1
+ while i < len(text) and depth:
+ if text[i] == "{":
+ depth += 1
+ elif text[i] == "}":
+ depth -= 1
+ i += 1
+ return text[open_at + 1 : i - 1]
+
+
+def parse_ts_interface_fields(text: str, name: str) -> set[str]:
+ """Field names of one exported TypeScript interface."""
+ stripped = _strip_ts_comments(text)
+ match = re.search(rf"export\s+interface\s+{re.escape(name)}\s*(?:extends\s+[\w<>,\s]+?)?\{{", stripped)
+ if match is None:
+ raise GateError(f"{API_TS_REL}: no exported interface named {name}")
+ body = _balanced_body(stripped, match.end() - 1)
+ # Only top-level members: a nested inline object type would otherwise
+ # contribute its own keys as if they were fields of the interface.
+ fields: set[str] = set()
+ depth = 0
+ for line in body.splitlines():
+ if depth == 0:
+ member = re.match(r"\s*(\w+)\??\s*:", line)
+ if member:
+ fields.add(member.group(1))
+ depth += line.count("{") - line.count("}")
+ return fields
+
+
+def ledger_path_from_literal(literal: str) -> str | None:
+ """The ledger route a request literal addresses, or ``None``.
+
+ The discriminator is what precedes ``/investigations``: an optional base
+ URL placeholder and an optional API version prefix, and nothing else.
+ ``/api/v1/cases/${caseId}/investigations/${runId}/report.md`` is a *cases*
+ route that happens to contain the word, and crediting it here would both
+ invent a client path the router does not declare and falsely mark a
+ genuinely unconsumed route as consumed.
+ """
+ collapsed = re.sub(r"\$\{[^}]*\}", "{}", literal)
+ index = collapsed.find(ROUTER_PREFIX_DEFAULT)
+ if index < 0:
+ return None
+ if not re.fullmatch(r"(\{\})?(/api/v\d+)?", collapsed[:index]):
+ return None
+ return _normalise_path(collapsed[index:].split("?")[0].strip())
+
+
+def parse_client_paths(text: str, object_name: str) -> set[str]:
+ """Ledger paths the named client object requests.
+
+ Scoped to that object rather than to the file: ``api.ts`` is five thousand
+ lines and holds every client in the console, and a path another client
+ happens to build is not this contract's business.
+ """
+ stripped = _strip_ts_comments(text)
+ match = re.search(rf"export\s+const\s+{re.escape(object_name)}\s*=\s*\{{", stripped)
+ if match is None:
+ raise GateError(f"{API_TS_REL}: no exported const named {object_name}")
+ body = _balanced_body(stripped, match.end() - 1)
+ paths = {ledger_path_from_literal(literal) for literal in re.findall(r"[`'\"]([^`'\"]*)[`'\"]", body)}
+ return {p for p in paths if p}
+
+
+def parse_consumer_paths(sources: dict[str, str]) -> set[str]:
+ """Ledger paths anything under the web source requests.
+
+ Wider than ``ledgerApi`` on purpose. ``/timeline`` is called by
+ ``InvestigationTimeline.tsx`` through a bare ``fetch``, so a
+ consumed-or-recorded check that only read the typed client would demand a
+ reason for a route that has a caller.
+ """
+ found: set[str] = set()
+ for text in sources.values():
+ stripped = _strip_ts_comments(text)
+ for literal in re.findall(r"[`'\"]([^`'\"\n]*)[`'\"]", stripped):
+ path = ledger_path_from_literal(literal)
+ if path:
+ found.add(path)
+ return found
+
+
+# ---------------------------------------------------------------------------
+# SQL: what the writer writes, what the schema creates
+# ---------------------------------------------------------------------------
+
+
+def _strip_sql_comments(sql: str) -> str:
+ return re.sub(r"--[^\n]*", "", sql)
+
+
+def _split_top_level(text: str) -> list[str]:
+ """Split on commas at paren depth zero."""
+ parts: list[str] = []
+ depth = 0
+ current: list[str] = []
+ for char in text:
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if char == "," and depth == 0:
+ parts.append("".join(current))
+ current = []
+ else:
+ current.append(char)
+ parts.append("".join(current))
+ return [part.strip() for part in parts if part.strip()]
+
+
+def _balanced_parens(text: str, open_at: int) -> tuple[str, int]:
+ """The text inside ``text[open_at]``'s parens, and the index after them."""
+ depth, i = 1, open_at + 1
+ while i < len(text) and depth:
+ if text[i] == "(":
+ depth += 1
+ elif text[i] == ")":
+ depth -= 1
+ i += 1
+ return text[open_at + 1 : i - 1], i
+
+
+_TERMINATORS = ("WHERE", "RETURNING", "FROM")
+
+
+def _set_clause(sql: str, start: int) -> str:
+ """An ``UPDATE ... SET`` assignment list, up to the first clause that ends it."""
+ depth = 0
+ i = start
+ while i < len(sql):
+ char = sql[i]
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ elif depth == 0:
+ upper = sql[i:].upper()
+ for keyword in _TERMINATORS:
+ if upper.startswith(keyword) and (i == 0 or not sql[i - 1].isalnum()):
+ tail = sql[i + len(keyword) : i + len(keyword) + 1]
+ if not tail.isalnum() and tail != "_":
+ return sql[start:i]
+ i += 1
+ return sql[start:]
+
+
+def _executed_sql(text: str, rel: str) -> list[str]:
+ """Every SQL literal the module hands to a database call.
+
+ By ``ast``, and only the first string argument of an ``execute`` /
+ ``fetch`` / ``fetchrow`` / ``fetchval`` call, so the module docstring's
+ description of the tables is not mistaken for a write to them.
+ """
+ tree = _parse_python(text, rel)
+ statements: list[str] = []
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
+ continue
+ if node.func.attr not in {"execute", "executemany", "fetch", "fetchrow", "fetchval"}:
+ continue
+ for argument in node.args[:1]:
+ if isinstance(argument, ast.Constant) and isinstance(argument.value, str):
+ statements.append(argument.value)
+ return statements
+
+
+def parse_written_columns(text: str, rel: str, tables: tuple[str, ...]) -> dict[str, set[str]]:
+ """Columns the module's INSERT and UPDATE statements write, per table."""
+ out: dict[str, set[str]] = {table: set() for table in tables}
+ for raw in _executed_sql(text, rel):
+ sql = _strip_sql_comments(raw)
+ for match in re.finditer(r"INSERT\s+INTO\s+(\w+)\s*\(", sql, re.IGNORECASE):
+ table = match.group(1)
+ if table not in out:
+ continue
+ columns, _ = _balanced_parens(sql, match.end() - 1)
+ out[table].update(part.split()[0] for part in _split_top_level(columns))
+ for match in re.finditer(r"UPDATE\s+(\w+)\s+SET\s+", sql, re.IGNORECASE):
+ table = match.group(1)
+ if table not in out:
+ continue
+ for assignment in _split_top_level(_set_clause(sql, match.end())):
+ # The target is everything before the first `=`. Reading only
+ # that keeps `total_cost_usd = COALESCE($6, total_cost_usd)`
+ # from crediting whatever names appear inside the expression.
+ name = assignment.split("=", 1)[0].strip()
+ if re.fullmatch(r"\w+", name):
+ out[table].add(name)
+ return out
+
+
+_TABLE_CONSTRAINT_KEYWORDS = ("primary", "unique", "foreign", "check", "constraint", "exclude", "like")
+
+
+SchemaFacts = tuple[dict[str, set[str]], dict[str, str], dict[str, set[tuple[str, ...]]]]
+
+
+def parse_schema(sql_by_file: dict[str, str], tables: tuple[str, ...]) -> SchemaFacts:
+ """Columns, creating file, and unique constraints for each named table.
+
+ Reads ``CREATE TABLE`` *and* every later ``ADD COLUMN``, because half the
+ column additions in this repository are ``ALTER TABLE ... ADD COLUMN IF
+ NOT EXISTS`` in a later migration — four of the columns the ledger writer
+ writes to ``investigation_runs`` arrived in 063, so a gate reading only
+ the creating migration would report four findings against a working tree.
+ """
+ columns: dict[str, set[str]] = {table: set() for table in tables}
+ created_in: dict[str, str] = {}
+ uniques: dict[str, set[tuple[str, ...]]] = {table: set() for table in tables}
+
+ for rel, raw in sorted(sql_by_file.items()):
+ sql = _strip_sql_comments(raw)
+ for match in re.finditer(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)\s*\(", sql, re.IGNORECASE):
+ table = match.group(1)
+ if table not in columns:
+ continue
+ created_in.setdefault(table, rel)
+ body, _ = _balanced_parens(sql, match.end() - 1)
+ for fragment in _split_top_level(body):
+ head = fragment.split()[0]
+ if head.lower() in _TABLE_CONSTRAINT_KEYWORDS:
+ if head.lower() == "unique":
+ inner, _ = _balanced_parens(fragment, fragment.index("("))
+ uniques[table].add(tuple(part.split()[0] for part in _split_top_level(inner)))
+ continue
+ columns[table].add(head)
+ for match in re.finditer(r"ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(\w+)\b", sql, re.IGNORECASE):
+ table = match.group(1)
+ if table not in columns:
+ continue
+ statement = sql[match.end() :].split(";", 1)[0]
+ columns[table].update(
+ m.group(1) for m in re.finditer(r"ADD\s+COLUMN\s+(?:IF\s+NOT\s+EXISTS\s+)?(\w+)", statement, re.IGNORECASE)
+ )
+ for m in re.finditer(r"ADD\s+(?:CONSTRAINT\s+\w+\s+)?UNIQUE\s*\(", statement, re.IGNORECASE):
+ inner, _ = _balanced_parens(statement, m.end() - 1)
+ uniques[table].add(tuple(part.split()[0] for part in _split_top_level(inner)))
+ return columns, created_in, uniques
+
+
+# ---------------------------------------------------------------------------
+# Reading the tree
+# ---------------------------------------------------------------------------
+
+
+def _read(root: Path, rel: str) -> str:
+ path = root / rel
+ if not path.is_file():
+ raise GateError(f"{rel} is missing; the ledger replay contract cannot be checked")
+ return path.read_text(encoding="utf-8", errors="replace")
+
+
+def collect(root: Path) -> Corpus:
+ endpoints = _read(root, ENDPOINTS_REL)
+ api_ts = _read(root, API_TS_REL)
+ writer = _read(root, WRITER_REL)
+
+ migrations_dir = root / MIGRATIONS_DIR_REL
+ if not migrations_dir.is_dir():
+ raise GateError(f"{MIGRATIONS_DIR_REL} is missing; the ledger schema cannot be read")
+ sql_by_file = {
+ str(path.relative_to(root)): path.read_text(encoding="utf-8", errors="replace") for path in sorted(migrations_dir.glob("*.sql"))
+ }
+ if not sql_by_file:
+ raise GateError(f"{MIGRATIONS_DIR_REL} holds no .sql files; the ledger schema cannot be read")
+
+ web_src = root / WEB_SRC_REL
+ if not web_src.is_dir():
+ raise GateError(f"{WEB_SRC_REL} is missing; ledger route consumers cannot be read")
+ web_sources = {
+ str(path.relative_to(root)): path.read_text(encoding="utf-8", errors="replace")
+ for pattern in ("**/*.ts", "**/*.tsx")
+ for path in sorted(web_src.glob(pattern))
+ }
+ if not web_sources:
+ raise GateError(f"{WEB_SRC_REL} holds no TypeScript; ledger route consumers cannot be read")
+
+ delegate = root / DELEGATE_REL
+ delegate_reads_writer = delegate.is_file() and DELEGATE_SCOPE_MARKER in delegate.read_text(encoding="utf-8", errors="replace")
+
+ schema_columns, created_in, uniques = parse_schema(sql_by_file, LEDGER_TABLES)
+ return Corpus(
+ model_fields=parse_model_fields(endpoints, ENDPOINTS_REL, RESPONSE_MODEL),
+ ts_fields=parse_ts_interface_fields(api_ts, TS_INTERFACE),
+ routes=parse_routes(endpoints, ENDPOINTS_REL),
+ client_paths=parse_client_paths(api_ts, CLIENT_OBJECT),
+ consumer_paths=parse_consumer_paths(web_sources),
+ written_columns=parse_written_columns(writer, WRITER_REL, LEDGER_TABLES),
+ schema_columns=schema_columns,
+ created_in_migration=created_in,
+ unique_constraints=uniques,
+ event_queries=parse_event_queries(endpoints, ENDPOINTS_REL),
+ delegate_reads_writer=delegate_reads_writer,
+ )
+
+
+# ---------------------------------------------------------------------------
+# The verdict
+# ---------------------------------------------------------------------------
+
+
+def _vacuity(corpus: Corpus) -> list[Finding]:
+ """Refusals for a corpus that credits nothing.
+
+ Each of these is a state in which every comparison below would pass over
+ an empty set, which is the failure this repository has shipped most often.
+ """
+ out: list[Finding] = []
+ if not corpus.model_fields:
+ out.append(Finding("EMPTY-MODEL", f"{ENDPOINTS_REL}: {RESPONSE_MODEL} parsed with no fields"))
+ if not corpus.ts_fields:
+ out.append(Finding("EMPTY-TS", f"{API_TS_REL}: {TS_INTERFACE} parsed with no fields"))
+ if not corpus.routes:
+ out.append(Finding("EMPTY-ROUTES", f"{ENDPOINTS_REL}: no router decorators parsed"))
+ if not corpus.client_paths:
+ out.append(Finding("EMPTY-CLIENT", f"{API_TS_REL}: {CLIENT_OBJECT} parsed with no request paths"))
+ for table in LEDGER_TABLES:
+ if not corpus.schema_columns.get(table):
+ out.append(Finding("EMPTY-SCHEMA", f"{table}: no columns parsed from {MIGRATIONS_DIR_REL}"))
+ if not corpus.written_columns.get(table):
+ out.append(Finding("EMPTY-WRITER", f"{table}: no columns parsed from {WRITER_REL}"))
+ if not corpus.event_queries:
+ out.append(Finding("EMPTY-HANDLERS", f"{ENDPOINTS_REL}: no handler parsed as reading more than one {EVENT_ORM}"))
+ return out
+
+
+def _field_findings(corpus: Corpus) -> list[Finding]:
+ out: list[Finding] = []
+ for name in sorted(corpus.model_fields - corpus.ts_fields):
+ out.append(
+ Finding(
+ "FIELD-PY-NOT-IN-TS",
+ f"{RESPONSE_MODEL}.{name} is serialised to the console and {TS_INTERFACE} does not declare it, "
+ f"so every replay drops it silently at the boundary",
+ )
+ )
+ for name in sorted(corpus.ts_fields - corpus.model_fields):
+ out.append(
+ Finding(
+ "FIELD-TS-NOT-IN-PY",
+ f"{TS_INTERFACE}.{name} is read by the console and {RESPONSE_MODEL} never sends it, "
+ f"so the replay view renders it as permanently absent",
+ )
+ )
+ return out
+
+
+def _route_findings(corpus: Corpus) -> list[Finding]:
+ out: list[Finding] = []
+ declared = {decl.path for decl in corpus.routes.values()}
+
+ for path in sorted(corpus.client_paths - declared):
+ out.append(
+ Finding(
+ "ROUTE-CLIENT-ORPHAN",
+ f"{CLIENT_OBJECT} requests {path} and the router declares no such route — the console would 404 here",
+ )
+ )
+
+ for key, decl in sorted(corpus.routes.items()):
+ consumed = decl.path in corpus.client_paths or any(path == decl.path for path in corpus.consumer_paths)
+ if consumed or key in SERVER_ONLY_ROUTES:
+ continue
+ out.append(
+ Finding(
+ "ROUTE-UNCONSUMED",
+ f"{key} (handler {decl.handler}) is declared and nothing under {WEB_SRC_REL} calls it; "
+ f"wire it or record it in SERVER_ONLY_ROUTES with a reason",
+ )
+ )
+
+ # Both directions on the recorded list, so an entry cannot outlive its need.
+ for key in sorted(SERVER_ONLY_ROUTES):
+ if key not in corpus.routes:
+ out.append(Finding("ROUTE-STALE-EXEMPTION", f"SERVER_ONLY_ROUTES names {key} and the router no longer declares it"))
+ continue
+ path = corpus.routes[key].path
+ if path in corpus.client_paths or path in corpus.consumer_paths:
+ out.append(
+ Finding(
+ "ROUTE-STALE-EXEMPTION",
+ f"SERVER_ONLY_ROUTES excuses {key} as server-only and the console now calls it; drop the entry",
+ )
+ )
+ return out
+
+
+def _column_findings(corpus: Corpus) -> list[Finding]:
+ out: list[Finding] = []
+
+ # The delegated direction has to be covered by somebody. If the gate that
+ # owns it is gone or has narrowed away from this writer, that is a gap in
+ # this contract even though the check lives elsewhere.
+ if not corpus.delegate_reads_writer:
+ out.append(
+ Finding(
+ "COLUMN-DELEGATION-MISSING",
+ f"{DELEGATE_REL} no longer reads {DELEGATE_SCOPE_MARKER}, so nothing checks that a column "
+ f"{WRITER_REL} writes is a column some migration creates; bring that direction back here",
+ )
+ )
+
+ for table in LEDGER_TABLES:
+ written = corpus.written_columns.get(table, set())
+ schema = corpus.schema_columns.get(table, set())
+ for column in sorted(schema - written):
+ if (table, column) in UNWRITTEN_COLUMNS:
+ continue
+ out.append(
+ Finding(
+ "COLUMN-UNWRITTEN",
+ f"{table}.{column} exists in the schema and {WRITER_REL} never writes it; "
+ f"write it or record it in UNWRITTEN_COLUMNS with a reason",
+ )
+ )
+ for (table, column), reason in sorted(UNWRITTEN_COLUMNS.items()):
+ if column not in corpus.schema_columns.get(table, set()):
+ out.append(
+ Finding(
+ "COLUMN-STALE-EXEMPTION",
+ f"UNWRITTEN_COLUMNS names {table}.{column} ({reason}) and the schema has no such column",
+ )
+ )
+ elif column in corpus.written_columns.get(table, set()):
+ out.append(
+ Finding(
+ "COLUMN-STALE-EXEMPTION",
+ f"UNWRITTEN_COLUMNS excuses {table}.{column} as unwritten and the writer now writes it",
+ )
+ )
+ return out
+
+
+def _sequence_findings(corpus: Corpus) -> list[Finding]:
+ """The assertions that make "every step" mean an ordered, unduplicated one."""
+ out: list[Finding] = []
+
+ if SEQUENCE_COLUMN not in corpus.written_columns.get(EVENTS_TABLE, set()):
+ out.append(
+ Finding(
+ "SEQ-UNSTAMPED",
+ f"{WRITER_REL} appends to {EVENTS_TABLE} without writing {SEQUENCE_COLUMN}, so the steps carry no order to replay",
+ )
+ )
+
+ creating = corpus.created_in_migration.get(EVENTS_TABLE)
+ if creating != CREATING_MIGRATION_REL:
+ out.append(
+ Finding(
+ "SEQ-SCHEMA-MOVED",
+ f"{EVENTS_TABLE} is created in {creating or 'no migration this gate read'} and this gate was written against "
+ f"{CREATING_MIGRATION_REL}; point it at the new creating migration deliberately",
+ )
+ )
+
+ expected = (RUN_COLUMN, SEQUENCE_COLUMN)
+ if expected not in corpus.unique_constraints.get(EVENTS_TABLE, set()):
+ out.append(
+ Finding(
+ "SEQ-NOT-UNIQUE",
+ f"{EVENTS_TABLE} has no UNIQUE {expected} constraint, so a replayed write appends a second copy of a step "
+ f"instead of conflicting, and the ledger reports a run that never happened that way",
+ )
+ )
+
+ for query in corpus.event_queries:
+ if not query.orders_by_sequence:
+ out.append(
+ Finding(
+ "SEQ-UNORDERED-READ",
+ f"{ENDPOINTS_REL}: {query.handler} reads a collection of {EVENT_ORM} rows with no ORDER BY {SEQUENCE_COLUMN} — "
+ f"Postgres promises no order without one, so the replay is a set of steps rather than a sequence",
+ )
+ )
+ if query.other_order_columns:
+ out.append(
+ Finding(
+ "SEQ-ORDERED-BY-CLOCK",
+ f"{ENDPOINTS_REL}: {query.handler} orders {EVENT_ORM} rows by {list(query.other_order_columns)} — "
+ f"only {SEQUENCE_COLUMN} is monotonic within a run; timestamps tie at the resolution the agent writes "
+ f"them and a clock correction can move one backwards",
+ )
+ )
+ return out
+
+
+def evaluate(corpus: Corpus) -> list[Finding]:
+ vacuous = _vacuity(corpus)
+ if vacuous:
+ # A corpus that credits nothing cannot also render a drift verdict:
+ # every comparison below would pass over an empty set and the two
+ # kinds of failure would be indistinguishable in the output.
+ return vacuous
+ return _field_findings(corpus) + _route_findings(corpus) + _column_findings(corpus) + _sequence_findings(corpus)
+
+
+def exit_status(findings: list[Finding]) -> int:
+ """0 clean, 1 drift, 2 the scan itself could not run.
+
+ A corpus that parsed nothing is the third case, not the second: there is
+ no drift to report because nothing was compared, and rounding it to 1
+ would have the gate claim it found a disagreement it never looked for.
+ """
+ if not findings:
+ return 0
+ return 2 if any(finding.code.startswith("EMPTY-") for finding in findings) else 1
+
+
+# ---------------------------------------------------------------------------
+# Self-test
+# ---------------------------------------------------------------------------
+
+
+def _probe_corpus() -> Corpus:
+ """A minimal corpus that passes, so each injection below changes one thing.
+
+ Built *from* the recorded exception lists rather than beside them: a probe
+ that hard-coded its own route set would start reporting stale exemptions
+ the moment somebody added a legitimate one, and the temptation would then
+ be to weaken the check rather than the probe.
+ """
+ routes = {"GET /investigations/{}/replay": RouteDecl("GET", "/investigations/{}/replay", "replay_run")}
+ for key in SERVER_ONLY_ROUTES:
+ method, path = key.split(" ", 1)
+ routes[key] = RouteDecl(method, path, f"{path.strip('/').replace('/', '_')}_handler")
+
+ columns = {table: {"id", RUN_COLUMN, SEQUENCE_COLUMN} for table in LEDGER_TABLES}
+ schema = {table: set(cols) for table, cols in columns.items()}
+ for table, column in UNWRITTEN_COLUMNS:
+ schema[table].add(column)
+
+ return Corpus(
+ model_fields={"id", "seq", "input_hash"},
+ ts_fields={"id", "seq", "input_hash"},
+ routes=routes,
+ client_paths={"/investigations/{}/replay"},
+ consumer_paths={"/investigations/{}/replay"},
+ written_columns=columns,
+ schema_columns=schema,
+ created_in_migration=dict.fromkeys(LEDGER_TABLES, CREATING_MIGRATION_REL),
+ unique_constraints={table: {(RUN_COLUMN, SEQUENCE_COLUMN)} for table in LEDGER_TABLES},
+ event_queries=[EventQuery("replay_run", orders_by_sequence=True)],
+ delegate_reads_writer=True,
+ )
+
+
+def _self_test_cases() -> list[tuple[str, bool]]:
+ """Injected drift for each property, in both directions.
+
+ A gate that has never failed is not known to work, and the shapes it must
+ catch are cheap to construct — so they are constructed here rather than
+ left to whoever next changes the tree.
+ """
+ cases: list[tuple[str, bool]] = []
+
+ def codes(mutate) -> set[str]:
+ corpus = _probe_corpus()
+ mutate(corpus)
+ return {finding.code for finding in evaluate(corpus)}
+
+ cases.append(("a clean corpus is clean", evaluate(_probe_corpus()) == []))
+
+ # 1. Field parity, both ways.
+ cases.append(
+ (
+ "a field added to the response model and not to TypeScript is caught",
+ "FIELD-PY-NOT-IN-TS" in codes(lambda c: c.model_fields.add("output_hash")),
+ )
+ )
+ cases.append(
+ (
+ "a field renamed on the Python side alone is caught in both directions",
+ codes(lambda c: (c.model_fields.discard("input_hash"), c.model_fields.add("inputHash")))
+ >= {"FIELD-PY-NOT-IN-TS", "FIELD-TS-NOT-IN-PY"},
+ )
+ )
+ cases.append(
+ (
+ "a field TypeScript reads and no response sends is caught",
+ "FIELD-TS-NOT-IN-PY" in codes(lambda c: c.ts_fields.add("pivot_path")),
+ )
+ )
+
+ # 2. Route parity, both ways.
+ cases.append(
+ (
+ "a client request against a route the router never declares is caught",
+ "ROUTE-CLIENT-ORPHAN" in codes(lambda c: c.client_paths.add("/investigations/{}/attack-graph")),
+ )
+ )
+ cases.append(
+ (
+ "deleting one route decorator while the client still calls it is caught",
+ "ROUTE-CLIENT-ORPHAN" in codes(lambda c: c.routes.pop("GET /investigations/{}/replay")),
+ )
+ )
+ cases.append(
+ (
+ "a declared route nothing calls and nothing records is caught",
+ "ROUTE-UNCONSUMED"
+ in codes(
+ lambda c: c.routes.__setitem__(
+ "GET /investigations/{}/orphan", RouteDecl("GET", "/investigations/{}/orphan", "orphan_handler")
+ )
+ ),
+ )
+ )
+ cases.append(
+ (
+ "a recorded server-only route the console has started calling is caught",
+ "ROUTE-STALE-EXEMPTION"
+ in codes(lambda c: c.consumer_paths.update(corpus_routes.path for corpus_routes in _probe_corpus().routes.values())),
+ )
+ )
+
+ # 3. Writer/schema parity and the sequencing assertions.
+ cases.append(
+ (
+ "a schema column the writer never writes is caught",
+ "COLUMN-UNWRITTEN" in codes(lambda c: c.schema_columns[EVENTS_TABLE].add("signed_by")),
+ )
+ )
+ cases.append(
+ (
+ "losing the gate this one delegates the other column direction to is caught",
+ "COLUMN-DELEGATION-MISSING" in codes(lambda c: setattr(c, "delegate_reads_writer", False)),
+ )
+ )
+ cases.append(
+ (
+ f"{DELEGATE_REL} is present and still reads {DELEGATE_SCOPE_MARKER}",
+ (repo_root() / DELEGATE_REL).is_file()
+ and DELEGATE_SCOPE_MARKER in (repo_root() / DELEGATE_REL).read_text(encoding="utf-8", errors="replace"),
+ )
+ )
+ cases.append(
+ (
+ "a recorded unwritten column the writer has started writing is caught",
+ "COLUMN-STALE-EXEMPTION" in codes(lambda c: [c.written_columns[table].add(column) for table, column in UNWRITTEN_COLUMNS]),
+ )
+ )
+ cases.append(
+ (
+ "an event append with no sequence number is caught",
+ "SEQ-UNSTAMPED" in codes(lambda c: c.written_columns[EVENTS_TABLE].discard("seq")),
+ )
+ )
+ cases.append(
+ (
+ "dropping UNIQUE (run_id, seq) is caught",
+ "SEQ-NOT-UNIQUE" in codes(lambda c: c.unique_constraints[EVENTS_TABLE].clear()),
+ )
+ )
+ cases.append(
+ (
+ "a replay handler that reads a collection of steps with no ORDER BY seq is caught",
+ "SEQ-UNORDERED-READ" in codes(lambda c: c.event_queries.__setitem__(0, EventQuery("replay_run", orders_by_sequence=False))),
+ )
+ )
+ by_clock = EventQuery("replay_run", orders_by_sequence=True, other_order_columns=("ts",))
+ cases.append(
+ (
+ "a replay handler that orders steps by the clock instead of the sequence is caught",
+ "SEQ-ORDERED-BY-CLOCK" in codes(lambda c: c.event_queries.__setitem__(0, by_clock)),
+ )
+ )
+ cases.append(
+ (
+ "ordering by the clock is read off the source, not assumed",
+ parse_event_queries(
+ "async def replay(db):\n"
+ " q = select(InvestigationEvent).order_by(InvestigationEvent.ts.asc())\n"
+ " return (await db.execute(q)).scalars().all()\n",
+ "probe.py",
+ )
+ == [EventQuery("replay", orders_by_sequence=False, other_order_columns=("ts",))],
+ )
+ )
+
+ # 4. Non-vacuity: every corpus that credits nothing is refused.
+ for label, mutate, code in (
+ ("no model fields", lambda c: c.model_fields.clear(), "EMPTY-MODEL"),
+ ("no TypeScript fields", lambda c: c.ts_fields.clear(), "EMPTY-TS"),
+ ("no routes and no client paths", lambda c: (c.routes.clear(), c.client_paths.clear()), "EMPTY-ROUTES"),
+ ("no parsed schema columns", lambda c: c.schema_columns[EVENTS_TABLE].clear(), "EMPTY-SCHEMA"),
+ ("no parsed writer columns", lambda c: c.written_columns[EVENTS_TABLE].clear(), "EMPTY-WRITER"),
+ ("no event-list handlers", lambda c: c.event_queries.clear(), "EMPTY-HANDLERS"),
+ ):
+ cases.append((f"a corpus with {label} is refused rather than called clean", code in codes(mutate)))
+
+ # 5. The parsers themselves, on the shapes that would make them lie.
+ cases.append(
+ (
+ "a table named only in a docstring is not parsed as a write",
+ parse_written_columns('"""Writes investigation_events (id, seq)."""\n', "probe.py", LEDGER_TABLES)[EVENTS_TABLE] == set(),
+ )
+ )
+ cases.append(
+ (
+ "a COALESCE self-reference credits the target column and nothing inside the expression",
+ parse_written_columns(
+ 'conn.execute("UPDATE investigation_runs SET total_cost_usd = COALESCE($1, total_cost_usd) WHERE id = $2")\n',
+ "probe.py",
+ LEDGER_TABLES,
+ )["investigation_runs"]
+ == {"total_cost_usd"},
+ )
+ )
+ cases.append(
+ (
+ "a cases route containing the word investigations is not a ledger path",
+ ledger_path_from_literal("/api/v1/cases/${caseId}/investigations/${runId}/report.md") is None,
+ )
+ )
+ cases.append(
+ (
+ "a bare fetch against a base-URL variable is a ledger path",
+ ledger_path_from_literal("${apiBase}/investigations/${runId}/timeline") == "/investigations/{}/timeline",
+ )
+ )
+ cases.append(
+ (
+ "a documented-but-absent TypeScript field is not a field",
+ parse_ts_interface_fields("export interface Probe {\n // ghost: string;\n real: number;\n}\n", "Probe") == {"real"},
+ )
+ )
+ cases.append(
+ (
+ "a single-event read with no ORDER BY is not demanded to have one",
+ parse_event_queries(
+ "async def focus(db):\n"
+ " q = select(InvestigationEvent).where(InvestigationEvent.seq == step)\n"
+ " return (await db.execute(q)).scalar_one_or_none()\n",
+ "probe.py",
+ )
+ == [],
+ )
+ )
+
+ return cases
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--repo-root", type=Path, default=None, help="tree to render a verdict about (defaults to git)")
+ parser.add_argument("--json", action="store_true", dest="as_json", help="machine-readable findings + counts")
+ parser.add_argument("--self-test", action="store_true", help="prove the gate still detects what it claims")
+ args = parser.parse_args(argv)
+
+ if args.self_test:
+ return self_test_main(Path(__file__).name, extra=_self_test_cases())
+
+ root = args.repo_root or repo_root()
+ try:
+ corpus = collect(root)
+ except GateError as exc:
+ print(f"UNABLE: {exc}")
+ return 2
+
+ findings = evaluate(corpus)
+ counts = corpus.counts()
+ status = exit_status(findings)
+
+ if args.as_json:
+ print(json.dumps({"counts": counts, "findings": [{"code": f.code, "detail": f.detail} for f in findings]}, indent=2))
+ return status
+
+ scanned = ", ".join(f"{value} {name.replace('_', ' ')}" for name, value in counts.items())
+ if findings:
+ print(f"FAIL: the investigation ledger's replay contract disagrees across trees ({len(findings)} finding(s))")
+ for finding in findings:
+ print(f" - {finding}")
+ print(f"\nscanned: {scanned}")
+ return status
+
+ print("OK: the investigation ledger's replay contract agrees across its three trees")
+ print(f" {scanned}")
+ print(
+ f" {len(SERVER_ONLY_ROUTES)} route(s) recorded server-only, "
+ f"{len(UNWRITTEN_COLUMNS)} column(s) recorded unwritten, each with a reason"
+ )
+ print(f" a column written but never created is {DELEGATE_REL}'s direction, and that gate still reads {DELEGATE_SCOPE_MARKER}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/tests/test_check_ledger_replay_contract.py b/scripts/tests/test_check_ledger_replay_contract.py
new file mode 100644
index 000000000..97d0f222e
--- /dev/null
+++ b/scripts/tests/test_check_ledger_replay_contract.py
@@ -0,0 +1,497 @@
+"""The ledger replay-contract gate detects what it claims, and only that.
+
+Proven against each of the three properties it holds, in both directions,
+against the parser shapes that would make it lie, and against the corpora it
+has to refuse rather than call clean.
+
+The near misses matter as much as the hits: a cases route that happens to
+contain the word "investigations", a ``COALESCE`` that names its own target,
+a field documented in a comment, and a handler that reads exactly one event
+by sequence number. A gate that fires on any of those is a nuisance somebody
+will switch off.
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+GATE = REPO_ROOT / "scripts" / "check_ledger_replay_contract.py"
+
+
+def _load():
+ spec = importlib.util.spec_from_file_location("check_ledger_replay_contract", GATE)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+MODULE = _load()
+
+
+def _codes(mutate) -> set[str]:
+ """Finding codes the gate reports for the probe corpus after ``mutate``.
+
+ Callers bind the result before asserting on it. ``mutate`` changes the
+ corpus, and a call with a side effect inside an ``assert`` disappears
+ under ``python -O`` along with the assertion — which would leave every
+ injection test here passing without injecting anything.
+ """
+ corpus = MODULE._probe_corpus()
+ mutate(corpus)
+ return {finding.code for finding in MODULE.evaluate(corpus)}
+
+
+# ---------------------------------------------------------------------------
+# The baseline the injections are measured against
+# ---------------------------------------------------------------------------
+
+
+def test_the_probe_corpus_is_clean() -> None:
+ """Every case below asserts a *change*, so the baseline has to be silent."""
+ assert MODULE.evaluate(MODULE._probe_corpus()) == []
+
+
+def test_the_probe_corpus_is_built_from_the_recorded_lists() -> None:
+ """A probe kept beside the lists would drift from them.
+
+ Every recorded server-only route has to appear as a declared route in the
+ probe, or the probe reports its own exemptions as stale and the pressure
+ is to weaken the check instead of the fixture.
+ """
+ corpus = MODULE._probe_corpus()
+ assert set(MODULE.SERVER_ONLY_ROUTES) <= set(corpus.routes)
+ assert corpus.delegate_reads_writer
+ for table, column in MODULE.UNWRITTEN_COLUMNS:
+ assert column in corpus.schema_columns[table]
+ assert column not in corpus.written_columns[table]
+
+
+# ---------------------------------------------------------------------------
+# Property 1 — field parity
+# ---------------------------------------------------------------------------
+
+
+def test_a_field_added_to_the_response_model_alone_is_caught() -> None:
+ """The direction that drifts: the model grows, TypeScript does not hear."""
+ reported = _codes(lambda c: c.model_fields.add("groundedness"))
+ assert "FIELD-PY-NOT-IN-TS" in reported
+
+
+def test_a_field_added_to_typescript_alone_is_caught() -> None:
+ reported = _codes(lambda c: c.ts_fields.add("pivot_path"))
+ assert "FIELD-TS-NOT-IN-PY" in reported
+
+
+def test_a_rename_on_one_side_is_reported_in_both_directions() -> None:
+ """``input_hash`` becoming ``inputHash`` is a loss *and* an absence."""
+
+ def rename(corpus) -> None:
+ corpus.model_fields.discard("input_hash")
+ corpus.model_fields.add("inputHash")
+
+ assert _codes(rename) >= {"FIELD-PY-NOT-IN-TS", "FIELD-TS-NOT-IN-PY"}
+
+
+# ---------------------------------------------------------------------------
+# Property 2 — route parity
+# ---------------------------------------------------------------------------
+
+
+def test_a_client_request_with_no_matching_route_is_caught() -> None:
+ """The shape this repository shipped: six pivots against ``/attack-graph``."""
+ reported = _codes(lambda c: c.client_paths.add("/investigations/{}/attack-graph"))
+ assert "ROUTE-CLIENT-ORPHAN" in reported
+
+
+def test_deleting_a_route_the_client_still_calls_is_caught() -> None:
+ reported = _codes(lambda c: c.routes.pop("GET /investigations/{}/replay"))
+ assert "ROUTE-CLIENT-ORPHAN" in reported
+
+
+def test_a_declared_route_nothing_calls_and_nothing_records_is_caught() -> None:
+ def add_orphan(corpus) -> None:
+ corpus.routes["GET /investigations/{}/orphan"] = MODULE.RouteDecl("GET", "/investigations/{}/orphan", "orphan_handler")
+
+ assert "ROUTE-UNCONSUMED" in _codes(add_orphan)
+
+
+def test_a_route_consumed_outside_the_typed_client_still_counts() -> None:
+ """``/timeline`` is called through a bare ``fetch``, and that is a caller.
+
+ A consumed-or-recorded check that only read ``ledgerApi`` would demand a
+ written reason for a route that has one.
+ """
+
+ def add_fetch_only(corpus) -> None:
+ corpus.routes["GET /investigations/{}/timeline"] = MODULE.RouteDecl("GET", "/investigations/{}/timeline", "get_timeline")
+ corpus.consumer_paths.add("/investigations/{}/timeline")
+
+ assert "ROUTE-UNCONSUMED" not in _codes(add_fetch_only)
+
+
+def test_a_recorded_exemption_the_router_dropped_is_caught() -> None:
+ key = next(iter(MODULE.SERVER_ONLY_ROUTES))
+ reported = _codes(lambda c: c.routes.pop(key))
+ assert "ROUTE-STALE-EXEMPTION" in reported
+
+
+def test_a_recorded_exemption_the_console_started_calling_is_caught() -> None:
+ def start_calling(corpus) -> None:
+ for key in MODULE.SERVER_ONLY_ROUTES:
+ corpus.consumer_paths.add(corpus.routes[key].path)
+
+ assert "ROUTE-STALE-EXEMPTION" in _codes(start_calling)
+
+
+# ---------------------------------------------------------------------------
+# Property 3 — writer / schema parity and sequencing
+# ---------------------------------------------------------------------------
+
+
+def test_a_schema_column_the_writer_never_writes_is_caught() -> None:
+ """The direction no generic raw-SQL gate makes, because it cannot know
+ which writer a table belongs to."""
+ reported = _codes(lambda c: c.schema_columns[MODULE.EVENTS_TABLE].add("signed_by"))
+ assert "COLUMN-UNWRITTEN" in reported
+
+
+def test_the_other_column_direction_is_delegated_to_a_gate_that_exists() -> None:
+ """A column the writer writes and no migration creates is held elsewhere.
+
+ ``check_raw_sql_columns.py`` makes that comparison generically over every
+ raw statement under ``services/*/app``, this writer's included, so
+ duplicating it here would be two places to keep in step rather than two
+ checks. Measured on this tree: dropping ``investigation_events.input_hash``
+ from migration 008 exits 1 there.
+ """
+ delegate = REPO_ROOT / MODULE.DELEGATE_REL
+ assert delegate.is_file(), f"{MODULE.DELEGATE_REL} is gone and this gate is delegating to nothing"
+ assert MODULE.DELEGATE_SCOPE_MARKER in delegate.read_text(encoding="utf-8")
+
+
+def test_losing_the_delegate_is_a_finding_rather_than_a_silence() -> None:
+ """A direction nobody covers must not go quiet because two files each
+ believed the other had it."""
+ reported = _codes(lambda c: setattr(c, "delegate_reads_writer", False))
+ assert "COLUMN-DELEGATION-MISSING" in reported
+
+
+def test_a_recorded_unwritten_column_the_writer_started_writing_is_caught() -> None:
+ def start_writing(corpus) -> None:
+ for table, column in MODULE.UNWRITTEN_COLUMNS:
+ corpus.written_columns[table].add(column)
+
+ assert "COLUMN-STALE-EXEMPTION" in _codes(start_writing)
+
+
+def test_an_event_appended_without_a_sequence_number_is_caught() -> None:
+ reported = _codes(lambda c: c.written_columns[MODULE.EVENTS_TABLE].discard("seq"))
+ assert "SEQ-UNSTAMPED" in reported
+
+
+def test_dropping_the_run_and_sequence_uniqueness_is_caught() -> None:
+ """Without it a replayed write appends a second copy instead of conflicting."""
+ reported = _codes(lambda c: c.unique_constraints[MODULE.EVENTS_TABLE].clear())
+ assert "SEQ-NOT-UNIQUE" in reported
+
+
+def test_moving_the_creating_migration_is_caught_rather_than_followed() -> None:
+ def move(corpus) -> None:
+ corpus.created_in_migration[MODULE.EVENTS_TABLE] = "services/api/migrations/999_elsewhere.sql"
+
+ assert "SEQ-SCHEMA-MOVED" in _codes(move)
+
+
+def test_a_collection_read_with_no_ordering_is_caught() -> None:
+ def unorder(corpus) -> None:
+ corpus.event_queries[0] = MODULE.EventQuery("replay_run", orders_by_sequence=False)
+
+ assert "SEQ-UNORDERED-READ" in _codes(unorder)
+
+
+def test_ordering_a_replay_by_the_clock_is_caught() -> None:
+ """``ts`` ties at write resolution and moves under a clock correction."""
+
+ def by_clock(corpus) -> None:
+ corpus.event_queries[0] = MODULE.EventQuery("replay_run", orders_by_sequence=False, other_order_columns=("ts",))
+
+ assert _codes(by_clock) >= {"SEQ-UNORDERED-READ", "SEQ-ORDERED-BY-CLOCK"}
+
+
+# ---------------------------------------------------------------------------
+# Non-vacuity
+# ---------------------------------------------------------------------------
+
+
+def test_every_empty_corpus_is_refused_rather_than_called_clean() -> None:
+ """Found nothing and scanned nothing must not print the same word."""
+ table = MODULE.EVENTS_TABLE
+ for mutate, code in (
+ (lambda c: c.model_fields.clear(), "EMPTY-MODEL"),
+ (lambda c: c.ts_fields.clear(), "EMPTY-TS"),
+ (lambda c: c.routes.clear(), "EMPTY-ROUTES"),
+ (lambda c: c.client_paths.clear(), "EMPTY-CLIENT"),
+ (lambda c: c.schema_columns[table].clear(), "EMPTY-SCHEMA"),
+ (lambda c: c.written_columns[table].clear(), "EMPTY-WRITER"),
+ (lambda c: c.event_queries.clear(), "EMPTY-HANDLERS"),
+ ):
+ assert code in _codes(mutate), code
+
+
+def test_a_vacuous_corpus_exits_two_rather_than_one() -> None:
+ """Nothing was compared, so there is no disagreement to report as one."""
+ corpus = MODULE._probe_corpus()
+ corpus.model_fields.clear()
+ assert MODULE.exit_status(MODULE.evaluate(corpus)) == 2
+
+ drifted = MODULE._probe_corpus()
+ drifted.model_fields.add("groundedness")
+ assert MODULE.exit_status(MODULE.evaluate(drifted)) == 1
+ assert MODULE.exit_status([]) == 0
+
+
+def test_a_vacuous_corpus_reports_only_the_refusal() -> None:
+ """A drift verdict over an empty set would be indistinguishable from a clean one."""
+ corpus = MODULE._probe_corpus()
+ corpus.model_fields.clear()
+ assert {finding.code for finding in MODULE.evaluate(corpus)} == {"EMPTY-MODEL"}
+
+
+# ---------------------------------------------------------------------------
+# The parsers, on the shapes that would make them lie
+# ---------------------------------------------------------------------------
+
+
+def test_a_table_named_only_in_a_docstring_is_not_a_write() -> None:
+ source = '"""Appends to investigation_events (id, run_id, seq)."""\n'
+ parsed = MODULE.parse_written_columns(source, "probe.py", MODULE.LEDGER_TABLES)
+ assert parsed[MODULE.EVENTS_TABLE] == set()
+
+
+def test_an_insert_column_list_is_read_and_the_values_are_not() -> None:
+ source = (
+ "async def go(conn):\n"
+ ' await conn.execute("""\n'
+ " INSERT INTO investigation_events (id, run_id, seq, payload)\n"
+ " VALUES ($1, $2, $3, $4::jsonb)\n"
+ ' """)\n'
+ )
+ parsed = MODULE.parse_written_columns(source, "probe.py", MODULE.LEDGER_TABLES)
+ assert parsed[MODULE.EVENTS_TABLE] == {"id", "run_id", "seq", "payload"}
+
+
+def test_an_update_credits_the_assignment_target_and_not_the_expression() -> None:
+ """``COALESCE($6, total_cost_usd)`` must not credit anything it reads."""
+ source = (
+ "async def go(conn):\n"
+ ' await conn.execute("""\n'
+ " UPDATE investigation_runs\n"
+ " SET total_cost_usd = COALESCE($2, total_cost_usd),\n"
+ " status = CASE WHEN $3 THEN 'closed' ELSE status END\n"
+ " WHERE id = $1 AND tenant_id = $4\n"
+ ' """)\n'
+ )
+ parsed = MODULE.parse_written_columns(source, "probe.py", MODULE.LEDGER_TABLES)
+ assert parsed["investigation_runs"] == {"total_cost_usd", "status"}
+
+
+def test_a_write_to_a_table_outside_the_ledger_is_ignored() -> None:
+ """The writer also updates ``alerts``; that belongs to another gate."""
+ source = 'async def go(conn):\n await conn.execute("UPDATE alerts SET disposition = $1 WHERE id = $2")\n'
+ parsed = MODULE.parse_written_columns(source, "probe.py", MODULE.LEDGER_TABLES)
+ assert all(columns == set() for columns in parsed.values())
+
+
+def test_a_later_add_column_counts_as_created() -> None:
+ """Four of the columns the writer writes arrived in migration 063.
+
+ A gate reading only the creating migration would report four findings
+ against a tree that works.
+ """
+ files = {
+ "008.sql": "CREATE TABLE IF NOT EXISTS investigation_runs (\n id UUID PRIMARY KEY,\n status VARCHAR(20) NOT NULL\n);\n",
+ "063.sql": "ALTER TABLE investigation_runs\n ADD COLUMN IF NOT EXISTS measured_call_count INTEGER NOT NULL DEFAULT 0;\n",
+ }
+ columns, created_in, _uniques = MODULE.parse_schema(files, MODULE.LEDGER_TABLES)
+ assert columns["investigation_runs"] == {"id", "status", "measured_call_count"}
+ assert created_in["investigation_runs"] == "008.sql"
+
+
+def test_a_table_constraint_is_not_read_as_a_column() -> None:
+ files = {
+ "008.sql": (
+ "CREATE TABLE IF NOT EXISTS investigation_events (\n"
+ " id UUID PRIMARY KEY,\n"
+ " run_id UUID NOT NULL REFERENCES investigation_runs(id) ON DELETE CASCADE,\n"
+ " seq INTEGER NOT NULL,\n"
+ " UNIQUE (run_id, seq)\n"
+ ");\n"
+ ),
+ }
+ columns, _created_in, uniques = MODULE.parse_schema(files, MODULE.LEDGER_TABLES)
+ assert columns[MODULE.EVENTS_TABLE] == {"id", "run_id", "seq"}
+ assert uniques[MODULE.EVENTS_TABLE] == {("run_id", "seq")}
+
+
+def test_a_comment_on_column_statement_does_not_create_a_column() -> None:
+ """``063`` repeats every column name in prose, and that is the point of it."""
+ files = {
+ "063.sql": (
+ "-- ALTER TABLE investigation_runs ADD COLUMN IF NOT EXISTS ghost INTEGER;\n"
+ "COMMENT ON COLUMN investigation_runs.total_cost_usd IS 'Measured cost only.';\n"
+ ),
+ }
+ columns, _created_in, _uniques = MODULE.parse_schema(files, MODULE.LEDGER_TABLES)
+ assert columns["investigation_runs"] == set()
+
+
+def test_a_cases_route_containing_the_word_investigations_is_not_a_ledger_path() -> None:
+ """``/cases/${caseId}/investigations/${runId}/report.md`` is a cases route.
+
+ Crediting it would invent a client path the router does not declare *and*
+ mark a genuinely unconsumed route as consumed — a finding in one direction
+ and a missed finding in the other, from one mistake.
+ """
+ assert MODULE.ledger_path_from_literal("/api/v1/cases/${caseId}/investigations/${runId}/report.md") is None
+
+
+def test_a_base_url_variable_and_a_version_prefix_are_both_accepted() -> None:
+ assert MODULE.ledger_path_from_literal("${apiBase}/investigations/${runId}/timeline") == "/investigations/{}/timeline"
+ assert MODULE.ledger_path_from_literal("/api/v1/investigations/${runId}/replay") == "/investigations/{}/replay"
+ assert MODULE.ledger_path_from_literal("/api/v1/investigations") == "/investigations"
+
+
+def test_a_query_string_is_not_part_of_the_path() -> None:
+ assert MODULE.ledger_path_from_literal("/api/v1/investigations/${runId}/explain?step=3") == "/investigations/{}/explain"
+
+
+def test_a_documented_or_commented_out_typescript_field_is_not_a_field() -> None:
+ source = "export interface Probe {\n /** documented */\n real: number;\n // ghost: string;\n}\n"
+ assert MODULE.parse_ts_interface_fields(source, "Probe") == {"real"}
+
+
+def test_a_nested_inline_object_does_not_contribute_its_keys() -> None:
+ source = "export interface Probe {\n outer: {\n inner: string;\n };\n flat: number;\n}\n"
+ assert MODULE.parse_ts_interface_fields(source, "Probe") == {"outer", "flat"}
+
+
+def test_an_optional_typescript_field_is_still_a_field() -> None:
+ assert MODULE.parse_ts_interface_fields("export interface Probe {\n maybe?: string;\n}\n", "Probe") == {"maybe"}
+
+
+def test_the_router_prefix_is_read_from_the_constructor() -> None:
+ source = (
+ 'router = APIRouter(prefix="/investigations", tags=["investigations"])\n'
+ "\n\n"
+ '@router.get("/{run_id}/replay")\n'
+ "async def replay_run(run_id):\n"
+ " return []\n"
+ )
+ assert set(MODULE.parse_routes(source, "probe.py")) == {"GET /investigations/{}/replay"}
+
+
+def test_a_decorator_from_another_object_is_not_a_route() -> None:
+ """``@app.get`` and ``@other_router.get`` are not this router's surface."""
+ source = 'router = APIRouter(prefix="/investigations")\n\n\[email protected]("/elsewhere")\nasync def elsewhere():\n return []\n'
+ assert MODULE.parse_routes(source, "probe.py") == {}
+
+
+def test_a_single_event_read_is_not_asked_for_an_ordering() -> None:
+ """``explain_step``'s focal lookup is by exact ``seq`` and needs no order."""
+ source = (
+ "async def focus(db):\n"
+ " q = select(InvestigationEvent).where(InvestigationEvent.seq == step)\n"
+ " return (await db.execute(q)).scalar_one_or_none()\n"
+ )
+ assert MODULE.parse_event_queries(source, "probe.py") == []
+
+
+def test_an_ordering_appended_in_a_later_statement_is_still_found() -> None:
+ """These are chained builders; ``list_events`` orders three statements on."""
+ source = (
+ "async def stream(db):\n"
+ " q = select(InvestigationEvent).where(InvestigationEvent.run_id == run_id)\n"
+ " q = q.where(InvestigationEvent.seq > since)\n"
+ " q = q.order_by(InvestigationEvent.seq.asc()).limit(limit)\n"
+ " return (await db.execute(q)).scalars().all()\n"
+ )
+ assert MODULE.parse_event_queries(source, "probe.py") == [MODULE.EventQuery("stream", orders_by_sequence=True)]
+
+
+def test_ordering_by_a_non_sequence_column_is_read_off_the_source() -> None:
+ source = (
+ "async def replay(db):\n"
+ " q = select(InvestigationEvent).order_by(InvestigationEvent.ts.asc())\n"
+ " return (await db.execute(q)).scalars().all()\n"
+ )
+ parsed = MODULE.parse_event_queries(source, "probe.py")
+ assert parsed == [MODULE.EventQuery("replay", orders_by_sequence=False, other_order_columns=("ts",))]
+
+
+def test_an_ordering_on_another_model_is_not_attributed_to_events() -> None:
+ """``list_artifacts`` orders by ``InvestigationArtifact.created_at``."""
+ source = (
+ "async def artifacts(db):\n"
+ " q = select(InvestigationEvent).order_by(InvestigationEvent.seq.asc())\n"
+ " a = select(InvestigationArtifact).order_by(InvestigationArtifact.created_at.asc())\n"
+ " return (await db.execute(q)).scalars().all(), (await db.execute(a)).scalars().all()\n"
+ )
+ parsed = MODULE.parse_event_queries(source, "probe.py")
+ assert parsed == [MODULE.EventQuery("artifacts", orders_by_sequence=True, other_order_columns=())]
+
+
+def test_the_client_object_is_read_and_its_neighbours_are_not() -> None:
+ """``api.ts`` holds every client in the console; only one owns this contract."""
+ source = (
+ "export const ledgerApi = {\n"
+ " replay: (runId: string) => request(`/api/v1/investigations/${runId}/replay`),\n"
+ "};\n"
+ "\n"
+ "export const otherApi = {\n"
+ " nope: (runId: string) => request(`/api/v1/investigations/${runId}/invented`),\n"
+ "};\n"
+ )
+ assert MODULE.parse_client_paths(source, "ledgerApi") == {"/investigations/{}/replay"}
+
+
+# ---------------------------------------------------------------------------
+# Reading a tree
+# ---------------------------------------------------------------------------
+
+
+def test_a_missing_subject_is_a_refusal_and_not_a_verdict() -> None:
+ """Every content directory absent is the scratch-tree shape."""
+ try:
+ MODULE.collect(REPO_ROOT / "scripts")
+ except MODULE.GateError as exc:
+ assert "missing" in str(exc)
+ else: # pragma: no cover - the point of the test
+ raise AssertionError("collect() rendered a verdict about a tree with no subject")
+
+
+def test_the_gate_answers_the_self_test_flag() -> None:
+ result = subprocess.run([sys.executable, str(GATE), "--self-test"], capture_output=True, text=True)
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_the_live_repository_is_clean() -> None:
+ """The contract this gate exists for, asserted against the real tree."""
+ result = subprocess.run([sys.executable, str(GATE)], capture_output=True, text=True)
+ assert result.returncode == 0, result.stdout + result.stderr
+
+
+def test_the_json_verdict_carries_the_counts_it_was_based_on() -> None:
+ """A verdict with no counts cannot be audited for having scanned anything."""
+ import json
+
+ result = subprocess.run([sys.executable, str(GATE), "--json"], capture_output=True, text=True)
+ assert result.returncode == 0, result.stdout + result.stderr
+ payload = json.loads(result.stdout)
+ assert payload["findings"] == []
+ assert all(value > 0 for value in payload["counts"].values()), payload["counts"]
diff --git a/services/api/tests/test_investigation_replay.py b/services/api/tests/test_investigation_replay.py
new file mode 100644
index 000000000..4eaf06228
--- /dev/null
+++ b/services/api/tests/test_investigation_replay.py
@@ -0,0 +1,495 @@
+"""The investigation ledger's read side: /replay, /events and /explain.
+
+"Investigation Ledger stores every step" is a front-page claim, and the gate
+the claim matrix named for it — ``api tests (audit_hash, audit immutability)``
+— covers a different table. ``test_audit_hash.py`` tests the hash chain over
+``audit_log``, which the API's audit middleware writes. The ledger is
+``investigation_events``, written by ``services/agents/app/investigator/
+ledger.py`` over raw asyncpg, and its only test covered tenant resolution
+against a stub connection. No test in this directory touched ``/replay``,
+``/events`` or ``/explain`` at all, and the "hermetic e2e" the row cited is a
+single Playwright spec in the ``screenshots`` project, run from a monthly cron
+whose job is to capture PNGs rather than from any pull request.
+
+Why the stub declines to sort
+-----------------------------
+
+``_Session`` returns rows in the order the *emitted SQL asks for* and, when
+the statement carries no ``ORDER BY``, in the order the fixture stored them —
+which is deliberately not sequence order. That is not a trick to make a test
+fail; it is the guarantee Postgres actually gives. A query with no ``ORDER BY``
+may return rows in any order at all, and in practice the order changes with
+the plan, the page layout and whether a sequential scan went parallel. So a
+replay handler that loses its ``ORDER BY seq`` keeps passing every test that
+asserts on a *set* of steps and starts serving an investigation whose steps
+are in the wrong order — which is precisely what "stores every step" must not
+be allowed to mean.
+
+Removing ``.order_by(InvestigationEvent.seq.asc())`` from ``replay_run`` turns
+this file red. The parity gate ``scripts/check_ledger_replay_contract.py``
+catches the same edit structurally; both are here because the gate reads the
+source and this reads what the route serves.
+"""
+
+from __future__ import annotations
+
+import re
+import uuid
+from datetime import UTC, datetime
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from app.api.v1.deps import CurrentUser, get_current_user
+from app.api.v1.endpoints.investigations import EventOut
+from app.api.v1.endpoints.investigations import router as investigations_router
+from app.db.rls import get_tenant_db
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+TENANT = uuid.UUID("aaaaaaaa-0000-0000-0000-00000000ledg".replace("ledg", "1ed9"))
+RUN_ID = uuid.UUID("bbbbbbbb-0000-0000-0000-000000000001")
+
+#: The sequence numbers the fixture holds, and the order it holds them in.
+#: Scrambled on purpose — see the module docstring. If this were already
+#: sorted, a handler that dropped its ORDER BY would still look correct.
+STORED_ORDER = (3, 1, 5, 2, 4)
+
+
+# ---------------------------------------------------------------------------
+# Rows
+# ---------------------------------------------------------------------------
+
+
+def _event(seq: int) -> SimpleNamespace:
+ """One ``investigation_events`` row, as the ORM would hand it over."""
+ return SimpleNamespace(
+ id=uuid.UUID(int=seq),
+ run_id=RUN_ID,
+ seq=seq,
+ ts=datetime(2026, 5, 1, 12, 0, seq, tzinfo=UTC),
+ kind="llm_response",
+ agent="aisoc-investigation",
+ summary=f"step {seq}",
+ payload={"step": seq},
+ input_hash=f"in-{seq}",
+ output_hash=f"out-{seq}",
+ duration_ms=seq * 100,
+ )
+
+
+def _run() -> SimpleNamespace:
+ return SimpleNamespace(
+ id=RUN_ID,
+ tenant_id=TENANT,
+ case_id="INC-LEDGER-001",
+ status="completed",
+ model_used="llama3.2:3b",
+ iterations=5,
+ total_tokens=4096,
+ total_cost_usd=0.0,
+ measured_call_count=0,
+ estimated_cost_usd=0.0,
+ estimated_call_count=0,
+ unpriced_call_count=5,
+ started_at=datetime(2026, 5, 1, 12, 0, tzinfo=UTC),
+ completed_at=datetime(2026, 5, 1, 12, 5, tzinfo=UTC),
+ error=None,
+ alert_summary="Impossible travel on a privileged account",
+ )
+
+
+def _artifact(event_seq: int) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=uuid.UUID(int=1000 + event_seq),
+ run_id=RUN_ID,
+ event_id=uuid.UUID(int=event_seq),
+ kind="llm_response",
+ content="the literal model transcript",
+ blob_ref=None,
+ sha256="f" * 64,
+ size_bytes=28,
+ created_at=datetime(2026, 5, 1, 12, 0, event_seq, tzinfo=UTC),
+ )
+
+
+# ---------------------------------------------------------------------------
+# The stubbed database
+# ---------------------------------------------------------------------------
+
+#: ``investigation_events.seq <op> :bound`` as SQLAlchemy renders it.
+_SEQ_PREDICATE = re.compile(r"investigation_events\.seq\s*(<=|>=|<|>|=)\s*:(\w+)")
+_LIMIT = re.compile(r"LIMIT\s*:(\w+)")
+
+_OPERATORS: dict[str, Any] = {
+ "<": lambda value, bound: value < bound,
+ "<=": lambda value, bound: value <= bound,
+ ">": lambda value, bound: value > bound,
+ ">=": lambda value, bound: value >= bound,
+ "=": lambda value, bound: value == bound,
+}
+
+
+class _Result:
+ """Enough of SQLAlchemy's ``Result`` for the four shapes these routes use."""
+
+ def __init__(self, rows: list[Any]) -> None:
+ self._rows = rows
+
+ def scalars(self) -> _Result:
+ return self
+
+ def all(self) -> list[Any]:
+ return list(self._rows)
+
+ def scalar_one_or_none(self) -> Any:
+ return self._rows[0] if self._rows else None
+
+ def scalar_one(self) -> Any:
+ if not self._rows:
+ raise AssertionError("scalar_one() on an empty result")
+ return self._rows[0]
+
+
+class _Session:
+ """Answers the ledger read queries the way Postgres would.
+
+ Specifically: it applies the predicates, the ordering and the limit the
+ *emitted statement* carries, and applies no ordering the statement does
+ not ask for. A handler gets back what its own SQL described, which is the
+ only way a test can tell a replay from a bag of steps.
+ """
+
+ def __init__(
+ self,
+ *,
+ run: SimpleNamespace | None,
+ events: list[SimpleNamespace] | None = None,
+ artifacts: list[SimpleNamespace] | None = None,
+ ) -> None:
+ self.run = run
+ self.events = events if events is not None else [_event(seq) for seq in STORED_ORDER]
+ self.artifacts = artifacts or []
+ self.statements: list[tuple[str, dict[str, Any]]] = []
+
+ async def execute(self, statement: Any) -> _Result:
+ sql = " ".join(str(statement).split())
+ params = dict(statement.compile().params)
+ self.statements.append((sql, params))
+
+ # Order matters: the count statement wraps the event select in a
+ # subquery, so it names `investigation_events` too.
+ if "count(" in sql:
+ return _Result([len(self._events(sql, params))])
+ if "FROM investigation_runs" in sql:
+ return _Result([self.run] if self.run is not None else [])
+ if "FROM investigation_artifacts" in sql:
+ return _Result(list(self.artifacts))
+ if "FROM investigation_events" in sql:
+ return _Result(self._events(sql, params))
+ if "aisoc_run_costs" in sql:
+ return _Result([])
+ raise AssertionError(f"the stub was asked something it does not model: {sql}")
+
+ def _events(self, sql: str, params: dict[str, Any]) -> list[SimpleNamespace]:
+ rows = list(self.events)
+
+ for operator, bound_name in _SEQ_PREDICATE.findall(sql):
+ bound = params.get(bound_name)
+ if bound is None:
+ continue
+ rows = [row for row in rows if _OPERATORS[operator](row.seq, bound)]
+
+ # No ORDER BY, no ordering. This is the whole point of the fixture.
+ if "ORDER BY investigation_events.seq" in sql:
+ rows.sort(key=lambda row: row.seq, reverse="ORDER BY investigation_events.seq DESC" in sql)
+
+ limit = _LIMIT.search(sql)
+ if limit:
+ rows = rows[: params[limit.group(1)]]
+ return rows
+
+ def statement_for(self, table: str) -> str:
+ """The last statement issued against ``table``, for diagnostics."""
+ for sql, _params in reversed(self.statements):
+ if f"FROM {table}" in sql and "count(" not in sql:
+ return sql
+ raise AssertionError(f"no statement was issued against {table}")
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def _user(*, scopes: list[str] | None = None) -> CurrentUser:
+ return CurrentUser(
+ user_id=uuid.uuid4(),
+ tenant_id=TENANT,
+ role="tenant_admin",
+ scopes=["*"] if scopes is None else scopes,
+ )
+
+
+def _client(session: _Session, *, user: CurrentUser | None = None) -> TestClient:
+ app = FastAPI()
+ app.include_router(investigations_router, prefix="/api/v1")
+
+ async def _db() -> Any:
+ yield session
+
+ app.dependency_overrides[get_tenant_db] = _db
+ app.dependency_overrides[get_current_user] = lambda: user or _user()
+ return TestClient(app)
+
+
+def session() -> _Session:
+ return _Session(run=_run())
+
+
+def client(session: _Session) -> TestClient:
+ return _client(session)
+
+
+_REPLAY = f"/api/v1/investigations/{RUN_ID}/replay"
+_EVENTS = f"/api/v1/investigations/{RUN_ID}/events"
+_EXPLAIN = f"/api/v1/investigations/{RUN_ID}/explain"
+
+
+# ---------------------------------------------------------------------------
+# Ordering — the property the claim rests on
+# ---------------------------------------------------------------------------
+
+
+class TestReplayIsOrderedBySequence:
+ def test_steps_come_back_in_sequence_order_not_storage_order(self, client: TestClient) -> None:
+ """The assertion that goes red when ``ORDER BY seq`` leaves the handler.
+
+ The fixture holds the steps as 3, 1, 5, 2, 4. A replay that does not
+ order them serves them that way, and an analyst reading the run sees
+ the agent reach a conclusion before it gathered the evidence.
+ """
+ body = client.get(_REPLAY).json()
+
+ assert [step["seq"] for step in body] == [1, 2, 3, 4, 5]
+ assert [step["seq"] for step in body] != list(STORED_ORDER)
+
+ def test_the_emitted_statement_orders_by_seq_ascending(self, session: _Session, client: TestClient) -> None:
+ """Names the cause when the test above fails, rather than the symptom."""
+ client.get(_REPLAY)
+
+ assert "ORDER BY investigation_events.seq ASC" in session.statement_for("investigation_events")
+
+ def test_the_paginated_stream_is_ordered_too(self, client: TestClient) -> None:
+ """``/events`` is what a tailing client reads; out of order it cannot tail."""
+ body = client.get(_EVENTS).json()
+
+ assert [step["seq"] for step in body["items"]] == [1, 2, 3, 4, 5]
+
+ def test_a_replay_of_one_step_is_still_a_replay(self, client: TestClient) -> None:
+ """Guards the degenerate case a sort would pass trivially."""
+ body = client.get(_REPLAY, params={"max_events": 1}).json()
+
+ assert [step["seq"] for step in body] == [1]
+
+
+# ---------------------------------------------------------------------------
+# Bounds
+# ---------------------------------------------------------------------------
+
+
+class TestReplayHonoursItsBound:
+ def test_max_events_truncates_and_keeps_the_earliest_steps(self, client: TestClient) -> None:
+ """Truncation has to take the *first* steps, which needs the ordering.
+
+ An unordered query truncated to two would hand back steps 3 and 1 and
+ call them the start of the investigation.
+ """
+ body = client.get(_REPLAY, params={"max_events": 2}).json()
+
+ assert [step["seq"] for step in body] == [1, 2]
+
+ def test_the_bound_reaches_the_query_rather_than_the_serialiser(self, session: _Session, client: TestClient) -> None:
+ client.get(_REPLAY, params={"max_events": 3})
+
+ sql, params = session.statements[-1]
+ limit = _LIMIT.search(sql)
+ assert limit is not None, f"the replay query carries no LIMIT: {sql}"
+ assert params[limit.group(1)] == 3
+
+ def test_the_default_bound_is_applied_when_none_is_asked_for(self, session: _Session, client: TestClient) -> None:
+ """A replay with no bound at all would stream an unbounded response."""
+ client.get(_REPLAY)
+
+ sql, params = session.statements[-1]
+ limit = _LIMIT.search(sql)
+ assert limit is not None
+ assert params[limit.group(1)] == 10000
+
+ @pytest.mark.parametrize("max_events", [0, -1, 50001])
+ def test_a_bound_outside_the_declared_range_is_refused(self, client: TestClient, max_events: int) -> None:
+ assert client.get(_REPLAY, params={"max_events": max_events}).status_code == 422
+
+ @pytest.mark.parametrize("limit", [0, 1001])
+ def test_the_event_page_size_is_bounded_the_same_way(self, client: TestClient, limit: int) -> None:
+ assert client.get(_EVENTS, params={"limit": limit}).status_code == 422
+
+
+class TestEventCursor:
+ def test_since_returns_only_later_steps_and_reports_the_next_cursor(self, client: TestClient) -> None:
+ body = client.get(_EVENTS, params={"since": 2}).json()
+
+ assert [step["seq"] for step in body["items"]] == [3, 4, 5]
+ assert body["since"] == 2
+ assert body["next_seq"] == 5
+
+ def test_total_counts_the_matching_rows_not_the_returned_page(self, client: TestClient) -> None:
+ """A total equal to the page size tells a tailing client nothing."""
+ body = client.get(_EVENTS, params={"limit": 2}).json()
+
+ assert [step["seq"] for step in body["items"]] == [1, 2]
+ assert body["total"] == 5
+
+ def test_an_exhausted_cursor_reports_no_next_seq(self, client: TestClient) -> None:
+ body = client.get(_EVENTS, params={"since": 5}).json()
+
+ assert body["items"] == []
+ assert body["next_seq"] is None
+
+
+# ---------------------------------------------------------------------------
+# The response contract
+# ---------------------------------------------------------------------------
+
+
+class TestServedFieldsAreExactlyTheModel:
+ def test_replay_serves_every_event_field_and_no_others(self, client: TestClient) -> None:
+ """Pins the response against ``EventOut`` rather than a hand-typed list.
+
+ ``scripts/check_ledger_replay_contract.py`` holds ``EventOut`` against
+ the console's ``LedgerEvent``; this holds the served document against
+ ``EventOut``. Between them a field cannot be added to the model and
+ dropped on the way out, or renamed in one place only.
+ """
+ step = client.get(_REPLAY).json()[0]
+
+ assert set(step) == set(EventOut.model_fields)
+
+ def test_the_hashes_that_make_a_step_auditable_are_served(self, client: TestClient) -> None:
+ """``input_hash``/``output_hash`` are what tie a step to its evidence."""
+ step = client.get(_REPLAY).json()[0]
+
+ assert step["input_hash"] == "in-1"
+ assert step["output_hash"] == "out-1"
+ assert step["payload"] == {"step": 1}
+
+ def test_the_event_page_serves_the_same_shape(self, client: TestClient) -> None:
+ body = client.get(_EVENTS).json()
+
+ assert set(body) == {"items", "total", "since", "next_seq"}
+ assert set(body["items"][0]) == set(EventOut.model_fields)
+
+
+# ---------------------------------------------------------------------------
+# Explain
+# ---------------------------------------------------------------------------
+
+
+class TestExplainStep:
+ def test_it_renders_the_step_with_the_decisions_either_side(self, session: _Session) -> None:
+ session.artifacts = [_artifact(3)]
+ body = _client(session).get(_EXPLAIN, params={"step": 3}).json()
+
+ assert body["focus"]["seq"] == 3
+ assert body["previous"]["seq"] == 2
+ assert body["next"]["seq"] == 4
+
+ def test_the_neighbours_are_the_adjacent_steps_not_arbitrary_ones(self, session: _Session) -> None:
+ """The prev/next lookups order by ``seq`` in opposite directions.
+
+ With the fixture stored as 3, 1, 5, 2, 4 an unordered ``LIMIT 1`` would
+ answer with whichever row came first, so this is the same ordering
+ property as replay, asserted where it is easiest to get wrong.
+ """
+ body = _client(session).get(_EXPLAIN, params={"step": 4}).json()
+
+ assert body["previous"]["seq"] == 3
+ assert body["next"]["seq"] == 5
+
+ def test_the_first_step_has_no_previous_and_the_last_has_no_next(self, session: _Session) -> None:
+ first = _client(session).get(_EXPLAIN, params={"step": 1}).json()
+ last = _client(session).get(_EXPLAIN, params={"step": 5}).json()
+
+ assert first["previous"] is None
+ assert first["next"]["seq"] == 2
+ assert last["previous"]["seq"] == 4
+ assert last["next"] is None
+
+ def test_the_transcript_attached_to_the_step_is_inlined(self, session: _Session) -> None:
+ session.artifacts = [_artifact(2)]
+ body = _client(session).get(_EXPLAIN, params={"step": 2}).json()
+
+ assert [artifact["content"] for artifact in body["artifacts"]] == ["the literal model transcript"]
+
+ def test_a_step_the_run_never_took_is_a_404(self, session: _Session) -> None:
+ response = _client(session).get(_EXPLAIN, params={"step": 99})
+
+ assert response.status_code == 404
+ assert "seq=99" in response.json()["detail"]
+
+ def test_the_step_is_required(self, client: TestClient) -> None:
+ assert client.get(_EXPLAIN).status_code == 422
+
+
+# ---------------------------------------------------------------------------
+# Authorization and the missing run
+# ---------------------------------------------------------------------------
+
+
+class TestAccessControl:
+ """Every read here is a step an agent took inside somebody's estate."""
+
+ @pytest.mark.parametrize("url", [_REPLAY, _EVENTS, _EXPLAIN])
+ def test_a_run_that_is_not_this_tenants_is_a_404_not_an_empty_list(self, url: str) -> None:
+ """An empty replay reads as "the agent did nothing", which is a lie.
+
+ ``_fetch_run`` filters on the authenticated tenant, so a run belonging
+ to somebody else is indistinguishable from one that does not exist —
+ and both must refuse rather than answer with zero steps.
+ """
+ response = _client(_Session(run=None)).get(url, params={"step": 1})
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "Investigation run not found"
+
+ @pytest.mark.parametrize("url", [_REPLAY, _EVENTS, _EXPLAIN])
+ def test_a_caller_without_cases_read_is_refused(self, session: _Session, url: str) -> None:
+ response = _client(session, user=_user(scopes=[])).get(url, params={"step": 1})
+
+ assert response.status_code == 403
+ assert "cases:read" in response.json()["detail"]
+
+ @pytest.mark.parametrize("url", [_REPLAY, _EVENTS, _EXPLAIN])
+ def test_authorization_is_checked_before_the_database_is_touched(self, session: _Session, url: str) -> None:
+ """A refused caller must not be able to make the route run a query."""
+ _client(session, user=_user(scopes=[])).get(url, params={"step": 1})
+
+ assert session.statements == []
+
+ @pytest.mark.parametrize("url", [_REPLAY, _EVENTS, _EXPLAIN])
+ def test_a_read_only_scope_is_enough(self, session: _Session, url: str) -> None:
+ response = _client(session, user=_user(scopes=["cases:read"])).get(url, params={"step": 1})
+
+ assert response.status_code == 200
+
+ def test_the_run_is_resolved_against_the_callers_tenant(self, session: _Session, client: TestClient) -> None:
+ """Without the tenant predicate any authenticated caller reads any run."""
+ client.get(_REPLAY)
+
+ sql, params = session.statements[0]
+ assert "FROM investigation_runs" in sql
+ assert "investigation_runs.tenant_id" in sql
+ assert TENANT in params.values()