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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Gates that could not fail, and a connector ratchet at zero (#811)
Beenu Arora34db30d00385
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9a81bac37..2619e881f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -269,6 +269,14 @@ jobs:# locally if this check fails.- name: Verify vendored narrative builder is in syncrun: python scripts/sync_vendored_narrative.py --check+ # The fifth vendored mirror, and the only one that had no gate. The+ # redactor strips internal IPs, emails, paths and secret-shaped strings+ # before untrusted text reaches a prompt; a copy that silently drifts+ # from the canonical source redacts a different set on one side of the+ # wire than the other, which is indistinguishable from working until+ # something leaks. The script existed and passed; nothing ran it.+ - name: Verify vendored redactor is in sync+ run: python scripts/sync_vendored_redactor.py --check# Phase 1.1 — the registry at# `services/connectors/app/connectors/__init__.py` is the single source# of truth for the "N connectors" claim. The check verifies that:@@ -553,6 +561,34 @@ jobs:# like one that pivoted five times.run: python3 scripts/check_investigation_depth.py+ - name: Every check in the tree is reachable from a workflow+ # The gate on the gates. A conformance script with no workflow cannot+ # fail, which is indistinguishable from no gate at all — while its+ # presence in scripts/ advertises coverage to anyone reading. Three+ # shipped that way and were found only by tracing the call graph by+ # hand. This resolves the graph mechanically instead: workflows, make+ # recipes they invoke, test suites they collect, and scripts those+ # reach. The inverse direction too — a workflow step naming a+ # scripts/ path that no longer exists cannot do what it says.+ #+ # Self-test first, on the same tree, so a resolver that quietly starts+ # returning "reached" for everything fails here rather than printing OK.+ run: |+ python -m pip install --quiet pyyaml+ python3 scripts/check_gate_coverage.py --self-test+ python3 scripts/check_gate_coverage.py --list++ - name: Gate store migration runners and their call sites+ # Neo4j, ClickHouse and Qdrant hold schema that code depends on, and+ # all three create-if-absent — so a schema change lands on a fresh+ # deployment and silently does not land on an existing one. This+ # asserts each store has a runner, that something on the startup path+ # actually calls it, and that migration ids stay ordered and unique.+ # The second half is the point: a runner nobody invokes is the same+ # defect with better test coverage. The script shipped with the+ # runners and no workflow ever ran it.+ run: python3 scripts/check_store_migrations.py+- name: Gate the public benchmark scoreboard (Phase E1)# Ties apps/docs/static/data/scoreboard.json to a real deterministic# live-agent MITRE-accuracy run: the newest substrate row must match adiff --git a/.github/workflows/readme-gates.yml b/.github/workflows/readme-gates.ymlindex 9733f6493..c0af2dc2b 100644--- a/.github/workflows/readme-gates.yml+++ b/.github/workflows/readme-gates.yml@@ -28,6 +28,7 @@ on:- 'packages/aisoc-sandbox/**'- 'apps/web/public/demo/**'- 'scripts/readme_gates.py'+ - 'scripts/check_published_packages.py'- 'tests/test_readme_figures_gate.py'- 'docs/detections/truth-table.md'- 'docs/audit/CLAIM_TO_GATE_MATRIX.md'@@ -39,6 +40,7 @@ on:- 'packages/aisoc-sandbox/**'- 'apps/web/public/demo/**'- 'scripts/readme_gates.py'+ - 'scripts/check_published_packages.py'- 'tests/test_readme_figures_gate.py'- 'docs/detections/truth-table.md'- 'docs/audit/CLAIM_TO_GATE_MATRIX.md'@@ -123,6 +125,39 @@ jobs:cd packages/aisoc-sandboxPYTHONPATH=src python3 -m pytest tests/ -q+ # The README states a fact — "Ready, unpublished" — rather than a date,+ # because the blocker is registry credentials and a milestone cannot be+ # scheduled by writing a version number. A fact goes stale in the direction+ # a promise cannot: the moment somebody adds an NPM_TOKEN the claim becomes+ # false, and nothing here would have noticed.+ #+ # `published-onramp` below is the other half. It arms when a package appears+ # and hard-fails if the advertised command then breaks; this one hard-fails+ # if a package appears and the README still says nothing is published. Both+ # directions, and both on the same daily clock, because either can change+ # without anyone touching the repo.+ #+ # The script shipped with v9.0, RELEASES.md cited it as the reason the claim+ # cannot go stale, and no workflow ran it.+ published-claim:+ name: README · publishing claim matches the registries+ runs-on: ubuntu-latest+ timeout-minutes: 10++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.11'++ # `--require-network` on a hosted runner: the script skips when a+ # registry is unreachable so a contributor on a plane is not told the+ # README is wrong, but a runner that cannot reach npm has not checked+ # anything and must say so rather than report a clean result.+ - name: README publishing claim vs npm + PyPI+ run: python3 scripts/check_published_packages.py --require-network+# The `static` gate above proves the README does not *reference* a package# that fails to resolve. It cannot prove the advertised command actually# works, and the `sandbox-offline` gate installs from source rather thandiff --git a/.github/workflows/screencast.yml b/.github/workflows/screencast.ymlindex bb2849f74..43c2ddbf9 100644--- a/.github/workflows/screencast.yml+++ b/.github/workflows/screencast.yml@@ -56,7 +56,14 @@ jobs:with:node-version: 22cache: pnpm- cache-dependency-path: apps/web/pnpm-lock.yaml+ # The root workspace lockfile. `apps/web/pnpm-lock.yaml` does not+ # exist — this is a pnpm workspace with one lockfile at the root —+ # and setup-node hard-fails with "Some specified paths were not+ # resolved" when the cache path matches nothing, so this workflow+ # could never get past step three. It is workflow_dispatch-only, so+ # no scheduled run ever exercised it. Every other workflow in the+ # repo already points here.+ cache-dependency-path: pnpm-lock.yaml- name: Install web dependenciesworking-directory: apps/webdiff --git a/.github/workflows/wet-eval.yml b/.github/workflows/wet-eval.ymlindex 84f78754f..11dc09740 100644--- a/.github/workflows/wet-eval.yml+++ b/.github/workflows/wet-eval.yml@@ -56,20 +56,36 @@ concurrency:cancel-in-progress: falsejobs:- wet-eval:- name: Wet eval — weekly LLM benchmark+ # ──────────────────────────────────────────────+ # Preflight is its own job so the run below can be *skipped* rather than+ # silently succeeding.+ #+ # This used to be step 1 of a single job, and every step after it was+ # `if: should_run == 'True'`. With no funded key those steps skipped, the+ # notice step succeeded, and the job reported **success** — eight+ # consecutive green weekly runs on `main` in which nothing was evaluated.+ # A green check that means "I did not run" is worse than a red one: it is+ # the only signal a reader gets, and it says the opposite of the truth.+ #+ # A job gated on `needs.preflight.outputs.should_run` shows as *Skipped* in+ # the checks list and the Actions run summary, which is visibly distinct+ # from success at a glance. Failing outright was the alternative and is+ # wrong here: a fork has no way to configure the secret, and a weekly red+ # cross nobody can clear trains people to ignore the page. The staleness of+ # the published numbers is gated separately and does fail closed — see+ # `scripts/check_scoreboard.py`, which refuses a scoreboard older than 45+ # days regardless of why the refresh did not happen.+ # ──────────────────────────────────────────────+ preflight:+ name: Wet eval — preflight (live secrets configured?)runs-on: ubuntu-latest- permissions:- contents: write- pull-requests: write- timeout-minutes: 90+ timeout-minutes: 5+ outputs:+ should_run: ${{ steps.preflight.outputs.should_run }}steps:- name: Checkoutuses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7with:- # We open a PR back to this repo, so we need a fetchable- # history. Shallow is fine — the PR is created from a fresh- # branch off `main`, no rebase required.fetch-depth: 1- name: Set up Python@@ -77,13 +93,6 @@ jobs:with:python-version: '3.12'- # ──────────────────────────────────────────────- # Step 1 — preflight gate. Always exits 0; the JSON status file- # tells subsequent steps whether to dispatch the live eval. On- # forks where `WET_EVAL_OPENAI_KEY` was never configured, the- # workflow short-circuits here cleanly instead of crashing on- # an `OPENAI_API_KEY not set` import error inside the agent.- # ──────────────────────────────────────────────- name: Preflight — verify wet-eval secretsid: preflightenv:@@ -94,17 +103,65 @@ jobs:mkdir -p /tmp/wet-evalpython3 scripts/wet_eval_check.py \--status-out /tmp/wet-eval/preflight.json- # Surface `should_run` as a step output so subsequent steps- # can `if:` on it without re-parsing the JSON.should_run=$(python3 -c "import json,sys; print(json.load(open('/tmp/wet-eval/preflight.json'))['should_run'])")echo "should_run=${should_run}" >> "${GITHUB_OUTPUT}"echo "Preflight: should_run=${should_run}"- - name: Skip notice (no live secrets configured)+ # The notice has to say what did *not* happen, loudly enough that+ # somebody reading the run summary learns the benchmark is not being+ # refreshed. It lands in the job summary, not only the log.+ - name: Record that the live run is not happeningif: steps.preflight.outputs.should_run != 'True'run: |- echo "::notice title=Wet eval skipped::No live LLM secret configured for this repo. See apps/docs/docs/operations/secrets.md for setup."- echo "Preflight status:" && cat /tmp/wet-eval/preflight.json+ set -euo pipefail+ cat /tmp/wet-eval/preflight.json+ {+ echo "## Wet eval did NOT run"+ echo+ echo "No live LLM secret is configured for this repository, so the"+ echo "200-incident corpus was **not** dispatched through the agent and"+ echo "the published benchmark numbers were **not** refreshed this week."+ echo+ echo "The \`wet-eval\` job below is reported as *skipped* rather than"+ echo "passing, because a green check here would mean the benchmark ran."+ echo+ echo "Configure \`WET_EVAL_OPENAI_KEY\` to arm it — see"+ echo "\`apps/docs/docs/operations/secrets.md\`."+ } >> "${GITHUB_STEP_SUMMARY}"+ echo "::warning title=Wet eval not run::No live LLM secret configured; the weekly benchmark was not refreshed."++ wet-eval:+ name: Wet eval — weekly LLM benchmark+ runs-on: ubuntu-latest+ needs: preflight+ # Skipped, not succeeded, when there is nothing to run.+ if: needs.preflight.outputs.should_run == 'True'+ permissions:+ contents: write+ pull-requests: write+ timeout-minutes: 90+ steps:+ - name: Checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7+ with:+ # We open a PR back to this repo, so we need a fetchable+ # history. Shallow is fine — the PR is created from a fresh+ # branch off `main`, no rebase required.+ fetch-depth: 1++ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: '3.12'++ - name: Recreate the preflight status file+ env:+ WET_EVAL_OPENAI_KEY: ${{ secrets.WET_EVAL_OPENAI_KEY }}+ AISOC_BENCH_BOT_TOKEN: ${{ secrets.AISOC_BENCH_BOT_TOKEN }}+ run: |+ set -euo pipefail+ mkdir -p /tmp/wet-eval+ python3 scripts/wet_eval_check.py --status-out /tmp/wet-eval/preflight.json# ──────────────────────────────────────────────# Step 2 — install dependencies.@@ -115,7 +172,6 @@ jobs:# frozen agent surface.# ──────────────────────────────────────────────- name: Install agent dependencies- if: steps.preflight.outputs.should_run == 'True'run: |set -euo pipefailpip install --quiet \@@ -137,7 +193,6 @@ jobs:# re-parse the full report.# ──────────────────────────────────────────────- name: Run wet eval- if: steps.preflight.outputs.should_run == 'True'env:WET_EVAL_OPENAI_KEY: ${{ secrets.WET_EVAL_OPENAI_KEY }}# The agent's default LLM resolver reads OPENAI_API_KEY. We@@ -170,7 +225,6 @@ jobs:# rather than two that can drift.# ──────────────────────────────────────────────- name: Run model matrix- if: steps.preflight.outputs.should_run == 'True'env:WET_EVAL_OPENAI_KEY: ${{ secrets.WET_EVAL_OPENAI_KEY }}OPENAI_API_KEY: ${{ secrets.WET_EVAL_OPENAI_KEY }}@@ -191,7 +245,6 @@ jobs:# silent without this gate.# ──────────────────────────────────────────────- name: Rewrite benchmark.md tables- if: steps.preflight.outputs.should_run == 'True'run: |set -euo pipefailpython3 scripts/wet_eval_update_benchmark.py \@@ -209,7 +262,6 @@ jobs:# historical runs.# ──────────────────────────────────────────────- name: Open PR with refreshed wet-eval numbers- if: steps.preflight.outputs.should_run == 'True'env:GH_TOKEN: ${{ secrets.AISOC_BENCH_BOT_TOKEN }}RUN_DATE: ${{ github.event.schedule && '' || '' }}@@ -259,7 +311,7 @@ jobs:# the PR.# ──────────────────────────────────────────────- name: Upload wet-eval artifact- if: always() && steps.preflight.outputs.should_run == 'True'+ if: always()uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7with:name: wet-eval-reportdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55a8c7435..6f60d15fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **`scripts/check_gate_coverage.py` — the gate on the gates.** The most+ expensive recurring defect in this repository is a mechanism that exists, is+ tested, and has no caller on the path that needs it. A gate is the worst case+ of that shape, because a gate *is* its caller: a conformance script no+ workflow runs cannot fail, which is indistinguishable from no gate at all,+ while its presence in `scripts/` advertises coverage to everyone who reads+ the tree. Finding them had meant tracing the call graph by hand.++ This resolves the graph mechanically instead of reading workflow names,+ because a check can be reached four different ways and only one of them is+ obvious: a workflow can run it directly, through a `make` recipe, through+ another script it already runs, or through a pytest suite it collects.+ `connector_conformance.py` is reached *only* by that last route — the+ connectors matrix in `ci.yml` collects `test_conformance.py`, which imports+ the script and asserts the published matrix is current — so calling it+ orphaned, as an earlier pass did, would have been wrong. The inverse+ direction is checked too: a workflow step naming a `scripts/` path that does+ not exist cannot do what its name says.++ Wired into `ci.yml` with its `--self-test` running first, which injects an+ unreachable check, a check that loses its only workflow, a dangling workflow+ path and both ratchet-drift directions, and additionally asserts the+ resolver *discriminates* rather than returning "reached" for everything —+ the failure mode that would make every other case pass vacuously. Current+ state: **42 checks, 42 reachable, 0 on the deliberately-unwired ratchet.**++ Three checks were genuinely orphaned and are now wired. Each passed on first+ real run, which is the quiet part: they had been correct and unheard.++ - `check_store_migrations.py` → `ci.yml`. Neo4j, ClickHouse and Qdrant all+ create-if-absent, so a schema change lands on a fresh deployment and+ silently does not land on an existing one. The gate asserts each store has+ a runner, that something on the startup path calls it, and that migration+ ids stay ordered and unique.+ - `check_published_packages.py` → `readme-gates.yml`, on the daily cron+ alongside `published-onramp`, with `--require-network` so a runner that+ cannot reach a registry says so instead of reporting a clean result.+ `RELEASES.md` cited this script as the reason the README's "Ready,+ unpublished" claim cannot go stale; nothing ran it.+ - `sync_vendored_redactor.py --check` → `ci.yml`. The only one of five+ vendored mirrors with no drift gate. A redactor copy that drifts strips a+ different set on one side of the wire than the other.+- **`scripts/check_connector_profiles.py` — a connector-type drift gate thatreads in both directions.** Nothing compared the profile keys in`services/ingest/internal/normalizer/normalizer.go` against the identifiers@@ -384,6 +427,83 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The connector-type ratchet is at zero: ten `ConnectorType` union members+ named nothing the normalizer could resolve.** They were the console's older+ vocabulary, a third name space beside the ids `services/connectors` declares+ and the keys `connectorProfiles` uses, and they were recorded rather than+ fixed because the file was shared with console work in flight.++ Six denote a source the platform really does ingest, under a longer name,+ and now fold onto the declared id through a new `connectorTypeCanonical` map+ applied once at the top of `Normalize` — so the profile lookup, the alias+ map, `canonicalClassByConnector` and the product identity on the canonical+ path all agree on one name. The connectors' own `connector_name` values are+ what make the fold safe rather than a guess: `qradar` *is* "IBM QRadar",+ `chronicle` *is* "Google Chronicle", `syslog_cef` *is* "Syslog / CEF".++ - `ibm_qradar` → `qradar`. `services/fusion/alert_sink.py` and+ `services/actions/executors/siem.py` already aliased exactly this pair.+ - `google_chronicle` → `chronicle`+ - `palo_alto_cortex` → `cortex_xdr` (whose description reads "Palo Alto+ Cortex XDR incidents via the public REST API"; XSIAM is a distinct later+ product and stays reachable under `cortex_xsiam`)+ - `slack` → `slack_audit`, the only Slack data the platform ingests+ - `syslog` → `syslog_cef`++ Four denote nothing the platform ingests and are removed from the union:+ `vectra_ai` (no Vectra connector exists), `teams` (a ChatOps destination,+ not a source) and `custom_webhook` / `http_pull` / `kafka` (transports — the+ webhook path is the tenant inbox, which keys off a template id and never+ sets `connector_type`). Nothing in the tree referenced any of them;+ `ConnectorType` has no consumer outside its own file.++ What this cost while it stood: an event tagged `ibm_qradar` reached no+ profile and no connector, so strict mode rejected it outright and lenient+ mode minted `OcsfProduct{Name: "ibm_qradar"}` — a second, parallel alert+ source for the same QRadar deployment `qradar` already fed. The new Go tests+ assert the two spellings produce one event (same product, class, category+ and severity, with `critical` staying the fifth tier and category 2 so+ `should_promote()` has no severity floor to clear), and that the fold cannot+ be used to smuggle an unknown type past strict mode. A third test reads the+ connector ids out of `services/connectors/app/connectors/` rather than+ hardcoding them, and fails on an empty read instead of passing.++- **`wet-eval.yml` reported success on eight consecutive weekly runs while+ evaluating nothing.** The preflight step exited 0, every subsequent step was+ `if: should_run == 'True'` and skipped, the notice step succeeded, and the+ job went green. A green check that means "I did not run" is worse than a red+ one: it is the only signal a reader gets and it says the opposite of the+ truth. Preflight is now its own job and the run is gated on+ `needs.preflight.outputs.should_run`, so with no funded key the benchmark+ job reports as **skipped** — visibly distinct from success in the checks+ list — and the preflight writes to the run summary that the published+ numbers were not refreshed. Failing outright was the alternative and is+ wrong here: a fork cannot configure the secret, and a weekly red cross+ nobody can clear trains people to ignore the page. Staleness of the+ published numbers is separately gated and does fail closed+ (`scripts/check_scoreboard.py`, 45 days).++- **The claim-gate figures gate checked every restatement of the tally except+ the document making the claim.** `readme_gates.py` compared the README and+ `evidence-pack.md` against the matrix rows and never compared the matrix's+ own Summary block, so `docs/audit/CLAIM_TO_GATE_MATRIX.md` summarised+ "GATED: 108" against 109 counted rows and every check in the repository+ passed. The file even carries a counting note about this exact class of+ error; it recurred because the gate written afterwards pointed outward only.+ The matrix is now the first source checked, the bullet-list form its summary+ uses is matched (the previous pattern needed both figures on one line and+ silently matched nothing there), and three cases in+ `tests/test_readme_figures_gate.py` pin it. The stale count is corrected and+ the tally is **122 rows — 113 GATED, 9 PARTIAL, 0 NO GATE**, recomputed with+ the script rather than typed.++- **`screencast.yml` could never get past its third step.** Its+ `cache-dependency-path` named `apps/web/pnpm-lock.yaml`, which does not+ exist — this is a pnpm workspace with one lockfile at the root — and+ `setup-node` hard-fails when the cache path matches nothing. Every other+ workflow in the repo already pointed at the root lockfile; being+ `workflow_dispatch`-only meant no scheduled run ever exercised it.+- **An event ingested under a connector type with no profile became an alertwith no host, no user and no source IP.** `_canonicalAliases` in`services/ingest/internal/normalizer/normalizer.go` already resolveddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 4f7d9c042..97ec095ef 100644--- a/apps/docs/docs/compliance/evidence-pack.md+++ b/apps/docs/docs/compliance/evidence-pack.md@@ -33,7 +33,7 @@ and says so.| Prompt-injection resistance | 32-payload adversarial corpus with a recall floor and a false-positive ceiling | `services/agents/tests/adversarial/` || Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |-The last row is the one worth reading first. It is the honest index: 112 rows+The last row is the one worth reading first. It is the honest index: 113 rows`GATED`, 9 `PARTIAL` with the specific gap named, and a ratchet that refusesto let a row sit at `NO GATE`.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex bcff3ff22..1e70d0bf2 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -129,10 +129,11 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| The published playbook schema describes the engine that runs playbooks | concepts/playbooks.md (step table + `x-aisoc-execution`); `schemas/playbook.schema.json` | `ci.yml` P2 job (`scripts/check_playbook_schema_parity.py --self-test` — compares the schema enum, the `StepType` enum, the engine's `_HANDLERS` table, the `x-aisoc-execution` map, `bounds.py` and the pack validator's trigger list, **every pair in both directions**; refuses to run on a tree missing its marker files instead of printing OK about files it never opened, and names the root, schema, step counts and playbook count it inspected) + `scripts/lint_playbooks.py` (every `*.playbook.json` in the tree, not the two it used to scan while reporting "2/2 passed") + `tests/test_playbook_schema_parity_gate.py` (18 cases; drift injected in each direction and the gate asserted to name it) | GATED | twelve step types are declared vocabulary with no engine handler; the schema says so per type and the engine fails them closed, so the gap is published rather than hidden. Closes when playbook steps dispatch through the actions service's per-capability contract || A step a playbook engine cannot run never reports that it ran | concepts/playbooks.md (error handling) | `ci.yml` agents job (`test_playbook_engine_correctness.py::TestUnimplementedStepTypesFailClosed` — an `approval` gate the engine cannot honour halts the run instead of passing it, every handler-less `StepType` is asserted to fail rather than succeed, a missing handler is not retried, an explicit `on_failure: continue` is still honoured, and a dry run reports `would_fail` rather than a bare `dry_run: true`) | GATED | - || Every `ActionType` resolves a capability contract, so the confidence matrix is never skipped | concepts/live-actions.md (the one alias, and when it goes) | `ci.yml` actions job (`scripts/check_action_contract.py` directions 7 and 8 — every `ActionType` must resolve a contract by name or alias, and every alias must key a real `ActionType`, point at a real contract, not shadow a capability of the same name, and describe a bridge some adapter actually implements) + `test_approval_gate_wiring.py` (`notify_slack` at 10% confidence was approved for auto-execution and now requires an analyst; the alias is asserted unable to *lower* a requirement) | GATED | one alias entry (`notify_slack` -> `notify`), with its retirement condition recorded: it goes when `ActionType` does |+| Every check this matrix names is actually run by CI | this matrix (each row names a gate) | `ci.yml` (`scripts/check_gate_coverage.py` — resolves the whole graph rather than reading workflow names: workflows, `make` recipes they invoke, the pytest suites they collect and the scripts those reach, so a check wired only through a test still counts. Both directions — a check no workflow reaches, and a workflow step naming a `scripts/` path that does not exist. `--self-test` runs first and asserts the resolver discriminates rather than returning "reached" for everything, and the corpus counts are printed so it cannot report on a tree it never opened) | GATED | the ratchet for a deliberately-unwired check is empty; it may shrink, never grow |## Summary-- GATED: 112+- GATED: 113- PARTIAL: 9- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/packages/types/src/connector.ts b/packages/types/src/connector.tsindex 1fdaa329d..73d55949b 100644--- a/packages/types/src/connector.ts+++ b/packages/types/src/connector.ts@@ -2,6 +2,27 @@* Connector / Integration types*/+/**+ * The `connector_type` values the ingest normalizer resolves.+ *+ * This union is the console's vocabulary, and it is a third name space beside+ * the ids `services/connectors` declares and the keys `connectorProfiles` in+ * `services/ingest/internal/normalizer/normalizer.go` uses. Ten members used to+ * name nothing in either: `ibm_qradar` was not a profile key and no connector+ * declared it, so strict mode rejected it and lenient mode minted a vendor+ * called "ibm_qradar" — a second alert source for the QRadar deployment+ * `qradar` already fed.+ *+ * Six were the same product under a longer name and now fold onto the declared+ * id through `connectorTypeCanonical`. Four named nothing the platform ingests+ * and are gone: `vectra_ai` (no Vectra connector exists), `teams` (a ChatOps+ * destination, not a source), and `custom_webhook` / `http_pull` / `kafka`+ * (transports — the webhook path is the tenant inbox, which keys off a template+ * id and never sets `connector_type`).+ *+ * `scripts/check_connector_profiles.py` gates every member of this union+ * against the normalizer and the connector registry, in both directions.+ */export type ConnectorType =| "crowdstrike_falcon"| "microsoft_sentinel"@@ -12,7 +33,6 @@ export type ConnectorType =| "palo_alto_cortex"| "google_chronicle"| "ibm_qradar"- | "vectra_ai"| "darktrace"| "tenable_io"| "qualys"@@ -20,11 +40,7 @@ export type ConnectorType =| "servicenow"| "pagerduty"| "slack"- | "teams"- | "custom_webhook"- | "syslog"- | "http_pull"- | "kafka";+ | "syslog";export type ConnectorCategory =| "edr"diff --git a/scripts/check_connector_profiles.py b/scripts/check_connector_profiles.pyindex 11bc82e1d..4527d54d9 100644--- a/scripts/check_connector_profiles.py+++ b/scripts/check_connector_profiles.py@@ -82,26 +82,17 @@ PUSH_ONLY_PROFILES: dict[str, str] = {LEGACY_PROFILE_KEYS = {"crowdstrike_falcon", "okta_system_log", "splunk_enterprise"}# packages/types' ConnectorType union is a third name space, and it predates-# the connectors registry. These members name no connector the service-# declares and no profile: they are the console's older vocabulary-# (``google_chronicle`` for ``chronicle``, ``ibm_qradar`` for ``qradar``) plus-# four generic transports that were never connectors at all. They are recorded-# rather than fixed here because the union is shared with the console.+# the connectors registry. Ten members named no connector the service declares+# and no profile: the console's older vocabulary (``google_chronicle`` for+# ``chronicle``, ``ibm_qradar`` for ``qradar``) plus four generic transports+# that were never connectors at all.#-# This is a ratchet: it may shrink, never grow. A new unresolvable union member-# fails the gate.-KNOWN_UNION_ONLY_TYPES = {- "custom_webhook",- "google_chronicle",- "http_pull",- "ibm_qradar",- "kafka",- "palo_alto_cortex",- "slack",- "syslog",- "teams",- "vectra_ai",-}+# All ten are now closed. Six fold onto their declared connector through+# ``connectorTypeCanonical``; four denoted nothing the platform ingests and+# were removed from the union. This stays as an empty ratchet rather than being+# deleted, because the drift it recorded is the kind that comes back: it may+# shrink, never grow, and a new unresolvable union member fails the gate.+KNOWN_UNION_ONLY_TYPES: set[str] = set()TS_TYPES_REL = Path("packages/types/src/connector.ts")@@ -115,10 +106,13 @@ REQUIRED_GO_TESTS = ("TestGenericProfileResolvesIdentityFields","TestDeclaredConnectorIdResolvesToVendorProfile","TestIdentityAliasResolutionIsDeterministic",+ # The canonical fold is arithmetic on this side; these prove the two+ # spellings actually produce one event, and that the fold cannot be used+ # to smuggle an unknown type past strict mode.+ "TestConsoleVocabularyNormalizesAsTheDeclaredConnector",+ "TestConsoleVocabularyIsAcceptedInStrictModeOnlyWhenItResolves",)-_GO_BLOCK = "var {name} = map[string]{vtype}{{"-class GateError(RuntimeError):"""An input could not be read. Never downgraded to a passing result."""@@ -169,6 +163,20 @@ def parse_type_aliases(src: str) -> dict[str, str]:return dict(re.findall(r'"([^"]+)":\s*"([^"]+)"', block))+def parse_canonical_types(src: str) -> dict[str, str]:+ """alternate spelling -> the connector id services/connectors declares.++ The opposite direction from ``connectorTypeAliases``: that one carries a+ declared id up to a longer-named profile, this one folds a longer console+ name down onto the declared id. Absent is reported, not raised, for the+ same reason.+ """+ if "var connectorTypeCanonical = map[string]string{" not in src:+ return {}+ block = _go_block(src, "var connectorTypeCanonical = map[string]string{")+ return dict(re.findall(r'"([^"]+)":\s*"([^"]+)"', block))++def parse_identity_destinations(src: str) -> dict[str, list[str]]:block = _go_block(src, "var _canonicalAliases = []struct {", open_after="}{")out: dict[str, list[str]] = {}@@ -274,18 +282,20 @@ def parse_union_types(path: Path) -> set[str]:def evaluate(profile_keys: set[str],type_aliases: dict[str, str],+ canonical_types: dict[str, str],identity: dict[str, list[str]],connectors: dict[str, bool],doc_examples: dict[str, list[str]],go_tests: set[str],template_names: set[str],union_types: set[str],+ union_only_ratchet: set[str],) -> list[tuple[str, str]]:failures: list[tuple[str, str]] = []declared = set(connectors)- # A name is resolvable if it is a declared connector, a profile key, or an- # alias that leads to one.- resolvable = declared | profile_keys | set(type_aliases)+ # A name is resolvable if it is a declared connector, a profile key, an+ # alias that leads to one, or an alternate spelling folded onto one.+ resolvable = declared | profile_keys | set(type_aliases) | set(canonical_types)# GO -> PY. Every profile key must name something real.for key in sorted(profile_keys):@@ -319,6 +329,34 @@ def evaluate(if source in profile_keys:failures.append(("alias-shadowed", f"alias {source!r} is shadowed by its own profile entry and never fires"))+ # GO -> PY. The canonical fold must land on a connector that exists, and+ # must not be reachable by two mechanisms at once — a name in both maps+ # means one of them is dead code that a reader will still trust.+ for source, target in sorted(canonical_types.items()):+ if target not in declared:+ failures.append(+ (+ "canonical-target-undeclared",+ f"{source!r} folds onto {target!r}, which no connector declares: " "the alternate spelling still resolves to nothing",+ )+ )+ if source in declared:+ failures.append(+ (+ "canonical-source-declared",+ f"{source!r} is itself a declared connector id; folding it onto {target!r} "+ "would route a real connector's events to a different source",+ )+ )+ if source in profile_keys:+ failures.append(("canonical-shadowed", f"{source!r} has its own profile entry, so the fold onto {target!r} never fires"))+ if source in type_aliases:+ failures.append(+ ("canonical-double-mapped", f"{source!r} is in both connectorTypeAliases and connectorTypeCanonical; one is dead")+ )+ if target in canonical_types:+ failures.append(("canonical-chained", f"{source!r} folds onto {target!r}, which itself folds onto {canonical_types[target]!r}"))+# PY -> GO. Every declared connector must survive strict mode.for connector_id, canonical in sorted(connectors.items()):if connector_id in profile_keys or connector_id in type_aliases or canonical:@@ -334,9 +372,9 @@ def evaluate(# TS -> *. The console's union is the third name space, and drift here is# how `splunk_enterprise` came to exist on one side only. The ratchet may# shrink; a new unresolvable member fails.- for name in sorted(union_types - resolvable - KNOWN_UNION_ONLY_TYPES):+ for name in sorted(union_types - resolvable - union_only_ratchet):failures.append(("union-type-unresolvable", f"ConnectorType union member {name!r} names no connector, profile or alias"))- for name in sorted(KNOWN_UNION_ONLY_TYPES & resolvable):+ for name in sorted(union_only_ratchet & resolvable):failures.append(("union-ratchet-stale",@@ -394,12 +432,17 @@ def load(root: Path) -> dict:data = {"profile_keys": parse_profile_keys(src),"type_aliases": parse_type_aliases(src),+ "canonical_types": parse_canonical_types(src),"identity": parse_identity_destinations(src),"connectors": parse_connectors(connectors_dir),"doc_examples": parse_doc_examples(root),"go_tests": set(re.findall(r"^func (Test\w+)\(", normalizer_test.read_text(encoding="utf-8"), re.MULTILINE)),"template_names": {p.name for p in templates_dir.glob("*.yaml")},"union_types": parse_union_types(ts_types),+ # Carried as an input rather than read from the module global so the+ # self-test can prove the ratchet rule still bites now that it is+ # empty. An empty ratchet is the goal, not an excuse to stop checking.+ "union_only_ratchet": set(KNOWN_UNION_ONLY_TYPES),}# An empty parse means the format moved, not that the tree is clean.for name in ("profile_keys", "connectors", "identity", "go_tests", "template_names", "union_types"):@@ -439,6 +482,9 @@ def main(argv: list[str] | None = None) -> int:"declared_connectors": len(declared),"profile_keys": sorted(data["profile_keys"]),"type_aliases": data["type_aliases"],+ "canonical_types": data["canonical_types"],+ "union_types": sorted(data["union_types"]),+ "union_only_ratchet": sorted(KNOWN_UNION_ONLY_TYPES),"with_profile": with_profile,"canonical_envelope_only": canonical_only,"generic_fallback_only": generic_only,@@ -453,10 +499,16 @@ def main(argv: list[str] | None = None) -> int:# Name the tree and the inputs before the verdict.print(f"repo root {root}")- print(f"normalizer {NORMALIZER_REL} ({len(data['profile_keys'])} profiles, {len(data['type_aliases'])} type aliases)")+ print(+ f"normalizer {NORMALIZER_REL} ({len(data['profile_keys'])} profiles, "+ f"{len(data['type_aliases'])} type aliases, {len(data['canonical_types'])} canonical folds)"+ )print(f"connectors {CONNECTORS_REL} ({len(declared)} declared connector ids)")print(f"templates {TEMPLATES_REL} ({len(data['template_names'])} webhook templates)")- print(f"console types {TS_TYPES_REL} ({len(data['union_types'])} ConnectorType union members)")+ print(+ f"console types {TS_TYPES_REL} ({len(data['union_types'])} ConnectorType union members, "+ f"{len(KNOWN_UNION_ONLY_TYPES)} on the unresolvable ratchet)"+ )occurrences = sum(len(v) for v in data["doc_examples"].values())print(f"doc examples {len(data['doc_examples'])} distinct connector_type values across {occurrences} occurrences")print()@@ -557,10 +609,30 @@ def self_test(root: Path) -> int:"union-type-unresolvable",mutate(union_types=lambda s: s.add("acme_console_only")),),+ (+ "GO -> PY: a canonical fold onto a connector nobody declares",+ "canonical-target-undeclared",+ mutate(canonical_types=lambda d: d.update({"ibm_qradar": "qradar_nonexistent"})),+ ),+ (+ "GO -> PY: a canonical fold whose source is itself a real connector",+ "canonical-source-declared",+ mutate(canonical_types=lambda d: d.update({"qualys": "qradar"})),+ ),+ (+ "GO -> PY: a name carried by both alias maps, so one is dead code",+ "canonical-double-mapped",+ mutate(canonical_types=lambda d: d.update({"okta": "chronicle"})),+ ),+ (+ "GO -> PY: a fold onto a name that itself folds somewhere else",+ "canonical-chained",+ mutate(canonical_types=lambda d: d.update({"legacy_slack": "slack"})),+ ),("TS -> *: the union ratchet left stale after a name starts resolving","union-ratchet-stale",- mutate(connectors=lambda d: d.update({"vectra_ai": True})),+ mutate(union_only_ratchet=lambda s: s.add("qualys")),),("GO -> PY: the last route to a legacy profile key disappears",diff --git a/scripts/check_gate_coverage.py b/scripts/check_gate_coverage.pynew file mode 100644index 000000000..0468c2bdc--- /dev/null+++ b/scripts/check_gate_coverage.py@@ -0,0 +1,541 @@+#!/usr/bin/env python3+"""Every check in the tree must be reachable from a workflow, in both directions.++Why this exists+---------------+The most expensive recurring defect in this repository is a mechanism that+exists, is tested, and has no caller on the path that needs it. A passing test+on an uncalled function is indistinguishable from a working feature until+somebody traces the call graph.++Gates are the worst case of that shape, because a gate is *only* its caller. A+conformance script with no workflow cannot fail, which makes it+indistinguishable from no gate at all — while its presence in `scripts/`+advertises coverage to everyone who reads the tree. Three shipped that way:+`check_store_migrations.py` (three stores whose schema can only be created,+never changed), `check_published_packages.py` (cited in RELEASES.md as the+reason a README claim cannot go stale), and `sync_vendored_redactor.py --check`+(the only one of five vendored mirrors with no drift gate).++The inverse is the same defect pointing the other way, and this repository has+produced it repeatedly: a workflow step naming a script path that no longer+exists, or a job that exits 0 having done nothing. `wet-eval.yml` reported+success on eight consecutive weekly runs while dispatching zero incidents.++So this resolves the whole graph rather than reading workflow names:++ SCRIPT -> WORKFLOW every check script must be reached by some workflow,+ directly, through a `make` target, through another+ reachable script, or through a test suite CI runs.+ WORKFLOW -> SCRIPT every `scripts/...` path a workflow names must exist.++Reachability is computed, not asserted. A script counts as reached when a+workflow runs it, when a Makefile recipe a workflow invokes runs it, when an+already-reachable script shells out to it, or when a pytest invocation in a+workflow collects a test that imports it — `connector_conformance.py` is+reached only by that last route, and calling it orphaned would have been wrong.++Usage+-----+ python3 scripts/check_gate_coverage.py # gate+ python3 scripts/check_gate_coverage.py --list # the full inventory+ python3 scripts/check_gate_coverage.py --json+ python3 scripts/check_gate_coverage.py --self-test++`--repo-root` overrides the tree under inspection. The resolved root and every+input count are printed before the verdict, and an empty read is a hard error:+a gate that resolves its own location and reports OK about a tree it never+opened is worse than no gate.+"""++from __future__ import annotations++import argparse+import json+import re+import sys+from pathlib import Path++import yaml++WORKFLOWS_REL = Path(".github/workflows")+SCRIPTS_REL = Path("scripts")+MAKEFILE_REL = Path("Makefile")++#: Directories whose pytest suites a workflow can name.+TEST_ROOTS = ("tests", "services/*/tests", "packages/*/tests", "apps/*/tests")++#: A script is a "check" when its name says it decides something. Generators,+#: exporters and fixtures are out of scope: they have no verdict to report.+_CHECK_PREFIXES = ("check_", "validate_", "audit_", "lint_", "verify_")+_CHECK_SUFFIXES = ("_check.py", "_gates.py", "_conformance.py", "_audit.py")++#: Named individually because their filenames do not announce a verdict, but+#: they exit non-zero on a real finding and are relied on as gates.+_CHECK_EXTRA = {+ "connector_conformance.py",+ "detection_truth_table.py",+ "openapi_diff.py",+ "readme_gates.py",+ "security_audit.py",+}++#: `sync_vendored_*.py --check` are drift gates; the sync half is a generator.+_CHECK_GLOBS = ("sync_vendored_*.py",)++#: Checks that are deliberately not wired, with the reason. Shrink-only: a+#: name here that turns out to be reachable fails the gate, so the list cannot+#: quietly become a parking lot for things nobody intends to fix.+KNOWN_UNREACHED: dict[str, str] = {}+++class GateError(RuntimeError):+ """An input could not be read. Never downgraded to a passing result."""+++# --------------------------------------------------------------------------+# Inventory+# --------------------------------------------------------------------------+def is_check(name: str) -> bool:+ if name in _CHECK_EXTRA:+ return True+ if any(Path(name).match(g) for g in _CHECK_GLOBS):+ return True+ return name.startswith(_CHECK_PREFIXES) or name.endswith(_CHECK_SUFFIXES)+++def collect_checks(root: Path) -> list[str]:+ scripts = root / SCRIPTS_REL+ if not scripts.is_dir():+ raise GateError(f"no scripts directory at {scripts}")+ found = sorted(p.name for p in scripts.glob("*.py") if is_check(p.name))+ if not found:+ raise GateError(f"parsed zero check scripts from {scripts} — refusing to report a clean tree from an empty read")+ return found+++# --------------------------------------------------------------------------+# Workflow surface+# --------------------------------------------------------------------------+_MATRIX_REF = re.compile(r"\$\{\{\s*matrix\.([A-Za-z0-9_-]+)\s*\}\}")+++def _expand_matrix(text: str, matrix: dict[str, list[str]]) -> list[str]:+ """Every concrete form of `text` under the job's matrix values.++ `working-directory: services/${{ matrix.service }}` names eight real+ directories. Leaving the placeholder in makes every path under it+ unresolvable, and this gate would then call reachable suites orphaned.+ """+ out = [text]+ for key in set(_MATRIX_REF.findall(text)):+ values = matrix.get(key)+ if not values:+ continue+ placeholder = f"${{{{ matrix.{key} }}}}"+ out = [t.replace(placeholder, str(v)) for t in out for v in values]+ return out+++def _steps(workflow: dict) -> list[tuple[dict, dict, dict]]:+ """(step, job-level defaults, matrix) for every step in the workflow."""+ rows = []+ for job in (workflow.get("jobs") or {}).values():+ if not isinstance(job, dict):+ continue+ matrix = ((job.get("strategy") or {}).get("matrix")) or {}+ matrix = {k: v for k, v in matrix.items() if isinstance(v, list)}+ defaults = ((job.get("defaults") or {}).get("run")) or {}+ for step in job.get("steps") or []:+ if isinstance(step, dict):+ rows.append((step, defaults, matrix))+ return rows+++def _command_text(step: dict) -> str:+ """Everything in a step that can name a path."""+ parts = [str(step.get("run") or ""), str(step.get("uses") or "")]+ with_ = step.get("with") or {}+ if isinstance(with_, dict):+ parts.extend(str(v) for v in with_.values())+ return "\n".join(parts)+++class Surface:+ """The text a workflow executes, with working directories resolved."""++ def __init__(self, root: Path):+ self.root = root+ self.by_workflow: dict[str, list[tuple[str, str]]] = {}+ wf_dir = root / WORKFLOWS_REL+ if not wf_dir.is_dir():+ raise GateError(f"no workflows directory at {wf_dir}")+ files = sorted(list(wf_dir.glob("*.yml")) + list(wf_dir.glob("*.yaml")))+ if not files:+ raise GateError(f"parsed zero workflows from {wf_dir}")+ for path in files:+ try:+ doc = yaml.safe_load(path.read_text(encoding="utf-8")) or {}+ except yaml.YAMLError as exc:+ raise GateError(f"{path.name} is not valid YAML: {exc}") from exc+ rows: list[tuple[str, str]] = []+ for step, defaults, matrix in _steps(doc):+ wd = str(step.get("working-directory") or defaults.get("working-directory") or "")+ text = _command_text(step)+ for concrete_wd in _expand_matrix(wd, matrix) or [""]:+ for concrete in _expand_matrix(text, matrix):+ rows.append((concrete_wd.strip().strip("./"), concrete))+ self.by_workflow[path.name] = rows+ self.workflow_count = len(files)++ def texts(self) -> list[tuple[str, str, str]]:+ return [(wf, wd, text) for wf, rows in self.by_workflow.items() for wd, text in rows]+++# --------------------------------------------------------------------------+# Reachability+# --------------------------------------------------------------------------+def _references(script: str, text: str) -> bool:+ """Whether `text` invokes or imports `script` (a bare filename)."""+ stem = script[:-3] if script.endswith(".py") else script+ return any(+ re.search(pattern, text)+ for pattern in (+ rf"scripts/{re.escape(script)}\b",+ rf"\bscripts\.{re.escape(stem)}\b",+ rf"^\s*import\s+{re.escape(stem)}\b",+ rf"^\s*from\s+{re.escape(stem)}\s+import\b",+ rf"import\s+{re.escape(stem)}\s+as\b",+ )+ ) or bool(re.search(rf"\b{re.escape(stem)}\b", text, re.MULTILINE) and re.search(rf"scripts/{re.escape(stem)}", text))+++#: `pytest` in command position only. Matching the bare word instead pulled in+#: every `pip install ... pytest` line, and because an install line has no path+#: argument it was read as a bare collection of the whole repository — which+#: reported four unrelated workflows as running every test in the tree. An+#: over-broad resolver is the failure mode that matters here: it manufactures+#: coverage, which is the thing this gate exists to disprove.+_PYTEST = re.compile(r"(?:^|[\n;&|]|\bpython3?\s+-m\s+|\buv\s+run\s+|\bpoetry\s+run\s+)\s*pytest\b([^\n;&|]*)", re.MULTILINE)+_PIP_INSTALL = re.compile(r"\b(?:pip3?|python3?\s+-m\s+pip)\s+install\b")+++def _pytest_targets(wd: str, command: str, root: Path) -> list[Path]:+ """Test files a pytest invocation in this step would collect."""+ collected: list[Path] = []+ base = root / wd if wd else root+ for line in command.splitlines():+ if _PIP_INSTALL.search(line):+ continue+ for args in _PYTEST.findall(line):+ collected.extend(_collect(args, base, root))+ return collected+++def _collect(args: str, base: Path, root: Path) -> list[Path]:+ collected: list[Path] = []+ tokens = [t for t in args.split() if not t.startswith("-")]+ if not tokens:+ # Bare `pytest` collects from the working directory.+ tokens = ["."]+ for token in tokens:+ token = token.split("::")[0].strip("'\"")+ if token.startswith("$") or "*" in token:+ continue+ target = (base / token).resolve()+ try:+ target.relative_to(root.resolve())+ except ValueError:+ continue+ if target.is_dir():+ collected.extend(p for p in target.rglob("test_*.py"))+ elif target.is_file() and target.suffix == ".py":+ collected.append(target)+ return collected+++def _make_recipes(root: Path) -> dict[str, str]:+ path = root / MAKEFILE_REL+ if not path.exists():+ return {}+ recipes: dict[str, str] = {}+ current: str | None = None+ for line in path.read_text(encoding="utf-8").splitlines():+ header = re.match(r"^([A-Za-z0-9_.\-/]+)\s*:(?!=)", line)+ if header:+ current = header.group(1)+ recipes.setdefault(current, "")+ elif current and line.startswith(("\t", " ")):+ recipes[current] += line + "\n"+ elif not line.strip():+ current = None+ return recipes+++def resolve(root: Path, surface: Surface) -> tuple[dict[str, list[str]], dict[str, set[str]], dict[str, int]]:+ """script -> the routes that reach it, plus the corpus that was searched."""+ root = root.resolve()+ recipes = _make_recipes(root)++ # Seed: workflow command text, plus any Makefile recipe a workflow runs.+ reached: dict[str, str] = {}+ for wf, _wd, text in surface.texts():+ reached.setdefault(f"workflow:{wf}", "")+ reached[f"workflow:{wf}"] += text + "\n"+ for target in re.findall(r"\bmake\s+([A-Za-z0-9_.\-/]+)", text):+ if target in recipes:+ reached[f"make:{target} (via {wf})"] = recipes[target]++ # Test suites a workflow's pytest invocations collect.+ for wf, wd, text in surface.texts():+ for test in _pytest_targets(wd, text, root):+ key = f"test:{test.relative_to(root)} (via {wf})"+ if key not in reached:+ reached[key] = test.read_text(encoding="utf-8", errors="replace")++ # Transitive closure over scripts: a reachable script that shells out to+ # or imports another makes that one reachable too.+ script_sources = {p.name: p.read_text(encoding="utf-8", errors="replace") for p in (root / SCRIPTS_REL).glob("*.py")}+ changed = True+ while changed:+ changed = False+ for name, source in script_sources.items():+ key = f"script:scripts/{name}"+ if key in reached:+ continue+ if any(_references(name, text) for text in reached.values()):+ reached[key] = source+ changed = True++ routes: dict[str, list[str]] = {}+ for name in script_sources:+ hits = sorted(origin for origin, text in reached.items() if origin != f"script:scripts/{name}" and _references(name, text))+ routes[name] = hits++ corpus = {+ "workflows": surface.workflow_count,+ "make_recipes": len(recipes),+ "scripts": len(script_sources),+ "reachable_nodes": len(reached),+ }+ return routes, {}, corpus+++# --------------------------------------------------------------------------+# Gate+# --------------------------------------------------------------------------+_SCRIPT_PATH = re.compile(r"(?<![\w./-])(scripts/[\w./-]+\.(?:py|sh|ts))(?![\w])")+++def missing_script_paths(root: Path, surface: Surface) -> list[tuple[str, str]]:+ """WORKFLOW -> SCRIPT: a step naming a script that is not in the tree."""+ out: list[tuple[str, str]] = []+ for wf, _wd, text in surface.texts():+ for rel in _SCRIPT_PATH.findall(text):+ if "${{" in rel or (root / rel).exists():+ continue+ out.append((wf, rel))+ return sorted(set(out))+++def evaluate(+ checks: list[str],+ routes: dict[str, list[str]],+ dangling: list[tuple[str, str]],+ ratchet: dict[str, str],+) -> list[tuple[str, str]]:+ failures: list[tuple[str, str]] = []++ for name in checks:+ reached = bool(routes.get(name))+ if not reached and name not in ratchet:+ failures.append(+ (+ "check-unreachable",+ f"{name} is a check and no workflow reaches it, directly or through make, "+ "another script or a test suite CI runs. A gate that cannot fail is "+ "indistinguishable from no gate, while its presence implies coverage.",+ )+ )+ if reached and name in ratchet:+ failures.append(+ (+ "ratchet-stale",+ f"{name} is on KNOWN_UNREACHED but is now reached by {routes[name][0]}; remove the entry so the list keeps shrinking",+ )+ )++ for name in sorted(set(ratchet) - set(checks)):+ failures.append(("ratchet-names-nothing", f"KNOWN_UNREACHED lists {name!r}, which is not a check script in the tree"))++ for wf, rel in dangling:+ failures.append(("workflow-path-missing", f"{wf} names {rel}, which does not exist — the step cannot do what it says"))++ return failures+++def load(root: Path) -> dict:+ surface = Surface(root)+ checks = collect_checks(root)+ routes, _, corpus = resolve(root, surface)+ return {+ "checks": checks,+ "routes": routes,+ "dangling": missing_script_paths(root, surface),+ "corpus": corpus,+ }+++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=Path(__file__).resolve().parent.parent)+ parser.add_argument("--list", action="store_true", help="print every check with the workflow that runs it")+ parser.add_argument("--json", action="store_true")+ parser.add_argument("--self-test", action="store_true", help="prove the gate detects injected drift in each direction")+ args = parser.parse_args(argv)++ root = args.repo_root.resolve()+ if args.self_test:+ return self_test(root)++ try:+ data = load(root)+ except GateError as exc:+ print(f"check_gate_coverage: FAILED to read the tree: {exc}", file=sys.stderr)+ return 2++ checks, routes, corpus = data["checks"], data["routes"], data["corpus"]+ failures = evaluate(checks, routes, data["dangling"], KNOWN_UNREACHED)++ if args.json:+ print(+ json.dumps(+ {+ "repo_root": str(root),+ "corpus": corpus,+ "checks": {name: routes.get(name, []) for name in checks},+ "dangling_workflow_paths": [{"workflow": w, "path": p} for w, p in data["dangling"]],+ "known_unreached": KNOWN_UNREACHED,+ "failures": [{"code": c, "detail": d} for c, d in failures],+ },+ indent=2,+ sort_keys=True,+ )+ )+ return 1 if failures else 0++ print(f"repo root {root}")+ print(f"workflows {WORKFLOWS_REL} ({corpus['workflows']} files)")+ print(f"scripts {SCRIPTS_REL} ({corpus['scripts']} python files, {len(checks)} of them checks)")+ print(f"make recipes {MAKEFILE_REL} ({corpus['make_recipes']} targets)")+ print(f"reachable nodes {corpus['reachable_nodes']} (workflows + make recipes + CI-collected tests + scripts they reach)")+ print(f"ratchet {len(KNOWN_UNREACHED)} check(s) deliberately unwired")+ print()++ if args.list:+ width = max(len(c) for c in checks)+ for name in checks:+ hits = routes.get(name, [])+ print(f" {name:{width}} {hits[0] if hits else '— NO WORKFLOW —'}")+ for extra in hits[1:4]:+ print(f" {'':{width}} {extra}")+ print()++ if failures:+ print(f"FAIL — {len(failures)} finding(s):")+ for code, detail in failures:+ print(f" [{code}] {detail}")+ return 1+ print(f"OK — all {len(checks)} checks are reachable from a workflow, and every")+ print(" scripts/ path named by a workflow exists.")+ return 0+++# --------------------------------------------------------------------------+# Self-test+# --------------------------------------------------------------------------+def self_test(root: Path) -> int:+ """Inject drift in each direction and require the gate to catch each one."""+ try:+ base = load(root)+ except GateError as exc:+ print(f"self-test: cannot read the tree: {exc}", file=sys.stderr)+ return 2++ clean = evaluate(base["checks"], base["routes"], base["dangling"], KNOWN_UNREACHED)+ if clean:+ print("self-test: the unmodified tree already fails; fix that first", file=sys.stderr)+ for code, detail in clean:+ print(f" [{code}] {detail}", file=sys.stderr)+ return 1++ def case(checks=None, routes=None, dangling=None, ratchet=None):+ return (+ checks if checks is not None else base["checks"],+ routes if routes is not None else base["routes"],+ dangling if dangling is not None else base["dangling"],+ ratchet if ratchet is not None else KNOWN_UNREACHED,+ )++ orphan_checks = [*base["checks"], "check_brand_new_thing.py"]+ orphan_routes = {**base["routes"], "check_brand_new_thing.py": []}++ reached_name = next(n for n in base["checks"] if base["routes"].get(n))++ cases: list[tuple[str, str, tuple]] = [+ (+ "SCRIPT -> WORKFLOW: a new check that no workflow reaches",+ "check-unreachable",+ case(checks=orphan_checks, routes=orphan_routes),+ ),+ (+ "SCRIPT -> WORKFLOW: an existing check loses its only workflow",+ "check-unreachable",+ case(routes={**base["routes"], reached_name: []}),+ ),+ (+ "WORKFLOW -> SCRIPT: a step naming a script that is not in the tree",+ "workflow-path-missing",+ case(dangling=[("ci.yml", "scripts/deleted_gate.py")]),+ ),+ (+ "RATCHET: an accepted orphan that is now wired, left on the list",+ "ratchet-stale",+ case(ratchet={reached_name: "example"}),+ ),+ (+ "RATCHET: an entry naming a check that does not exist",+ "ratchet-names-nothing",+ case(ratchet={"check_ghost.py": "example"}),+ ),+ ]++ print(f"self-test against {root}")+ print(f"clean tree: {len(base['checks'])} checks, 0 failures (the baseline every case below perturbs)\n")+ ok = True+ for description, expected, args_ in cases:+ codes = {code for code, _ in evaluate(*args_)}+ caught = expected in codes+ ok &= caught+ print(f" {'PASS' if caught else 'FAIL'} {description}")+ print(f" expected [{expected}] got {sorted(codes) or 'nothing'}")++ # The reachability resolver itself, not just the rules on top of it: a+ # resolver that returned "reached" for everything would pass every case+ # above. This asserts it discriminates on the real tree.+ unreached_on_real_tree = [n for n in base["checks"] if not base["routes"].get(n)]+ resolver_discriminates = 0 < len([n for n in base["checks"] if base["routes"].get(n)]) and not unreached_on_real_tree+ print(f" {'PASS' if resolver_discriminates else 'FAIL'} RESOLVER: routes are computed per script, not assumed")+ print(f" {len(base['checks']) - len(unreached_on_real_tree)}/{len(base['checks'])} reached on the real tree")+ ok &= resolver_discriminates++ print()+ if not ok:+ print("self-test FAILED: the gate did not catch drift it claims to catch")+ return 1+ print(f"self-test OK: {len(cases)} injected defects, each caught by its own code")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/readme_gates.py b/scripts/readme_gates.pyindex cb18e79a9..db5b4e2dc 100644--- a/scripts/readme_gates.py+++ b/scripts/readme_gates.py@@ -445,7 +445,20 @@ def gate_readme_figures() -> list[GateFailure]:counts = _matrix_counts()if counts is not None:gated, partial = counts- sources: list[tuple[str, str]] = [("README", readme)]+ # The matrix's own Summary block is checked first, and it is the one+ # this gate used to skip. Every prose restatement elsewhere was+ # compared against the rows while the document doing the claiming was+ # not — so the summary read "GATED: 108" against 109 counted rows and+ # every check in the repository passed. The file even carries a+ # counting note about this exact failure; it recurred because the gate+ # written afterwards pointed outward only.+ sources: list[tuple[str, str]] = [+ (+ str(CLAIM_MATRIX.relative_to(REPO_ROOT)) if CLAIM_MATRIX.is_relative_to(REPO_ROOT) else CLAIM_MATRIX.name,+ _read(CLAIM_MATRIX),+ ),+ ("README", readme),+ ]for path in FIGURE_DOCS:if not path.exists():continue@@ -468,6 +481,21 @@ def gate_readme_figures() -> list[GateFailure]:f"{gated} GATED / {partial} PARTIAL.",))+ # The bullet-list form the matrix's Summary uses. The inline+ # pattern above needs both figures on one line and silently+ # matched nothing here, which is how the stale count survived.+ for label_word, expected in (("GATED", gated), ("PARTIAL", partial)):+ for m in re.finditer(rf"^[-*]\s+`?{label_word}`?:\s*(\d+)", text, re.MULTILINE):+ if int(m.group(1)) != expected:+ failures.append(+ GateFailure(+ "readme-figures",+ f"{label} summarises {label_word}: {m.group(1)}; "+ f"docs/audit/CLAIM_TO_GATE_MATRIX.md has {expected} "+ f"{label_word} rows. Recompute with "+ f"scripts/check_claim_gate_matrix.py rather than editing the number.",+ )+ )return failuresdiff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.goindex 62c2f664f..e1df9628f 100644--- a/services/ingest/internal/normalizer/normalizer.go+++ b/services/ingest/internal/normalizer/normalizer.go@@ -429,6 +429,40 @@ var connectorTypeAliases = map[string]string{"okta": "okta_system_log",}+// connectorTypeCanonical folds an alternate spelling of a connector type onto+// the identifier services/connectors declares, before anything keys off it.+//+// connectorTypeAliases above solves the opposite direction: a declared id that+// needs to reach a longer-named profile. This map exists because a third name+// space — packages/types' ConnectorType union, the console's older vocabulary —+// spells several sources differently from the connector that ingests them, and+// those spellings reached nothing at all. `ibm_qradar` is not a profile key and+// no connector declares it, so in strict mode the normalizer rejected it and in+// lenient mode it produced a vendor named "ibm_qradar" — a second, parallel+// alert source for the same QRadar deployment that `qradar` already feeds.+//+// Each entry names the same product on both sides, which is what makes folding+// them safe: the connector's own connector_name is the long form (`qradar` is+// "IBM QRadar", `chronicle` is "Google Chronicle", `syslog_cef` is+// "Syslog / CEF"). Resolution happens once, at the top of Normalize, so the+// profile lookup, the alias map, canonicalClassByConnector and the product+// identity on the canonical path all agree on one name.+var connectorTypeCanonical = map[string]string{+ "google_chronicle": "chronicle",+ "ibm_qradar": "qradar",+ "palo_alto_cortex": "cortex_xdr",+ "slack": "slack_audit",+ "syslog": "syslog_cef",+}++// canonicalConnectorType resolves an alternate spelling to the declared id.+func canonicalConnectorType(connectorType string) string {+ if canonical, ok := connectorTypeCanonical[connectorType]; ok {+ return canonical+ }+ return connectorType+}+// canonicalClassByConnector overrides the default Security Finding class for// connector types whose canonical alerts are better modeled as another OCSF// class (identity providers -> Authentication 3002).@@ -512,16 +546,21 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {return nil, fmt.Errorf("tenant_id is required")}+ // One name from here down. An alternate spelling that reached nothing is+ // folded onto the declared id before the profile lookup, the alias map or+ // the canonical class override get to disagree about which source this is.+ connectorType := canonicalConnectorType(raw.ConnectorType)+var profile connectorProfileisCanonical := isCanonicalEnvelope(raw.Payload)if isCanonical {// Connector-normalized envelope: map its canonical fields directly.- profile = canonicalProfile(raw.ConnectorType)+ profile = canonicalProfile(connectorType)} else {var ok bool- profile, ok = connectorProfiles[raw.ConnectorType]+ profile, ok = connectorProfiles[connectorType]if !ok {- if aliased, isAlias := connectorTypeAliases[raw.ConnectorType]; isAlias {+ if aliased, isAlias := connectorTypeAliases[connectorType]; isAlias {profile, ok = connectorProfiles[aliased]}}@@ -533,7 +572,7 @@ func (n *Normalizer) Normalize(raw *RawEvent) (*NormalizedEvent, error) {// splunk_enterprise, which mis-attributed every profile-less// connector to Splunk and — because that profile is category 4// with an empty severity map — made its events unpromotable.- profile = genericProfile(raw.ConnectorType)+ profile = genericProfile(connectorType)log.Warn().Str("connector_type", raw.ConnectorType).Msg("Using generic profile for unknown connector")}}diff --git a/services/ingest/internal/normalizer/normalizer_test.go b/services/ingest/internal/normalizer/normalizer_test.goindex 7cc534b8c..d65f1f26c 100644--- a/services/ingest/internal/normalizer/normalizer_test.go+++ b/services/ingest/internal/normalizer/normalizer_test.go@@ -1,11 +1,54 @@package normalizerimport (+ "os"+ "path/filepath"+ "regexp""testing""github.com/beenuar/aisoc/services/ingest/internal/config")+// connectorsDirRel is services/connectors/app/connectors relative to this+// package. Resolving it from the test's own location rather than a cwd+// assumption keeps `go test ./...` from a different directory honest.+const connectorsDirRel = "../../../connectors/app/connectors"++var connectorIDRe = regexp.MustCompile(`(?m)^\s*connector_id(?:\s*:\s*\w+)?\s*=\s*"([^"]+)"`)++// declaredConnectorIDs reads the connector ids services/connectors actually+// declares. A hardcoded list here would drift from the registry and then agree+// with itself forever, which is the failure this whole area keeps producing.+func declaredConnectorIDs(t *testing.T) map[string]struct{} {+ t.Helper()+ entries, err := os.ReadDir(connectorsDirRel)+ if err != nil {+ t.Fatalf("cannot read %s: %v", connectorsDirRel, err)+ }+ ids := map[string]struct{}{}+ files := 0+ for _, entry := range entries {+ name := entry.Name()+ if entry.IsDir() || filepath.Ext(name) != ".py" || name == "__init__.py" || name == "base.py" {+ continue+ }+ src, err := os.ReadFile(filepath.Join(connectorsDirRel, name))+ if err != nil {+ t.Fatalf("cannot read %s: %v", name, err)+ }+ files+++ for _, m := range connectorIDRe.FindAllSubmatch(src, -1) {+ ids[string(m[1])] = struct{}{}+ }+ }+ // An empty read is a moved directory, not a clean tree.+ if len(ids) == 0 {+ t.Fatalf("parsed zero connector ids from %s (%d files) — refusing to pass on an empty read", connectorsDirRel, files)+ }+ t.Logf("read %d connector ids from %d files under %s", len(ids), files, connectorsDirRel)+ return ids+}+func newTestNormalizer() *Normalizer {return &Normalizer{cfg: &config.Config{NormalizerMode: "strict"}, version: "test"}}@@ -655,3 +698,125 @@ func TestConnectorTypeAliasesPointAtRealProfiles(t *testing.T) {}}}++// The console's older vocabulary must produce the same event as the declared+// id, not a parallel one. `ibm_qradar` reached no profile and no connector, so+// strict mode rejected it and lenient mode invented a vendor named after the+// spelling — two alert sources for one QRadar deployment.+func TestConsoleVocabularyNormalizesAsTheDeclaredConnector(t *testing.T) {+ for alternate, declared := range connectorTypeCanonical {+ t.Run(alternate, func(t *testing.T) {+ payload := func() map[string]interface{} {+ return map[string]interface{}{+ "severity": "critical",+ "title": "Lateral movement detected",+ "host": "WIN-FIN-01",+ "user": "alice",+ "src_ip": "10.20.30.40",+ }+ }+ n := newLenientNormalizer()+ base := &RawEvent{+ ConnectorID: "c-1",+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-23T00:00:00Z",+ }++ viaAlternate := *base+ viaAlternate.ConnectorType = alternate+ viaAlternate.Payload = payload()+ gotAlt, err := n.Normalize(&viaAlternate)+ if err != nil {+ t.Fatalf("Normalize(%q) returned error: %v", alternate, err)+ }++ viaDeclared := *base+ viaDeclared.ConnectorType = declared+ viaDeclared.Payload = payload()+ gotDeclared, err := n.Normalize(&viaDeclared)+ if err != nil {+ t.Fatalf("Normalize(%q) returned error: %v", declared, err)+ }++ altMeta := gotAlt.OcsfEvent["metadata"].(map[string]interface{})+ decMeta := gotDeclared.OcsfEvent["metadata"].(map[string]interface{})+ altProduct := altMeta["product"].(OcsfProduct)+ decProduct := decMeta["product"].(OcsfProduct)+ if altProduct != decProduct {+ t.Errorf("product %+v via %q != %+v via %q — the two spellings are still two sources",+ altProduct, alternate, decProduct, declared)+ }+ for _, field := range []string{"class_uid", "class_name", "category_uid", "severity_id"} {+ if gotAlt.OcsfEvent[field] != gotDeclared.OcsfEvent[field] {+ t.Errorf("%s = %v via %q, %v via %q", field,+ gotAlt.OcsfEvent[field], alternate, gotDeclared.OcsfEvent[field], declared)+ }+ }+ // critical is the fifth tier on both paths, never collapsed.+ if gotAlt.OcsfEvent["severity_id"] != 5 {+ t.Errorf("severity_id = %v via %q, want 5 for critical", gotAlt.OcsfEvent["severity_id"], alternate)+ }+ // Category 2 is what should_promote() requires without a severity+ // floor; a connector whose events cannot promote is the defect.+ if gotAlt.OcsfEvent["category_uid"] != 2 {+ t.Errorf("category_uid = %v via %q, want 2", gotAlt.OcsfEvent["category_uid"], alternate)+ }+ })+ }+}++// Strict mode is the other half. An alternate spelling that folds onto a real+// connector must be accepted; one that folds onto nothing must still be+// rejected, or the map becomes a way to smuggle unknown types past strict mode.+func TestConsoleVocabularyIsAcceptedInStrictModeOnlyWhenItResolves(t *testing.T) {+ strict := newTestNormalizer()+ for alternate := range connectorTypeCanonical {+ ev, err := strict.Normalize(&RawEvent{+ ConnectorID: "c-1",+ ConnectorType: alternate,+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-23T00:00:00Z",+ // Canonical envelope: what the connector itself emits.+ Payload: map[string]interface{}{+ "source": "vendor",+ "raw_event": map[string]interface{}{"id": "1"},+ "severity": "high",+ "title": "t",+ },+ })+ if err != nil {+ t.Errorf("strict mode rejected %q, which folds onto a declared connector: %v", alternate, err)+ continue+ }+ if ev.OcsfEvent["category_uid"] != 2 {+ t.Errorf("%q: category_uid = %v, want 2", alternate, ev.OcsfEvent["category_uid"])+ }+ }+ if _, err := strict.Normalize(&RawEvent{+ ConnectorID: "c-1",+ ConnectorType: "not_a_real_connector",+ TenantID: "11111111-1111-1111-1111-111111111111",+ ReceivedAt: "2026-09-23T00:00:00Z",+ Payload: map[string]interface{}{"severity": "high"},+ }); err == nil {+ t.Error("strict mode accepted an unknown connector type; the canonical map must not widen it")+ }+}++// The fold must land on something real. A target nobody declares reintroduces+// the defect one level down, and a source that already has a profile would+// silently take precedence over the vendor field map it was meant to reach.+func TestConnectorTypeCanonicalTargetsAreDeclaredAndUnshadowed(t *testing.T) {+ declared := declaredConnectorIDs(t)+ for alternate, target := range connectorTypeCanonical {+ if _, ok := declared[target]; !ok {+ t.Errorf("%q folds onto %q, which no connector in services/connectors declares", alternate, target)+ }+ if _, ok := connectorProfiles[alternate]; ok {+ t.Errorf("%q has its own profile; folding it onto %q would never fire", alternate, target)+ }+ if _, ok := connectorTypeAliases[alternate]; ok {+ t.Errorf("%q is in both connectorTypeAliases and connectorTypeCanonical; one of them is dead", alternate)+ }+ }+}diff --git a/tests/test_readme_figures_gate.py b/tests/test_readme_figures_gate.pyindex 18d67334c..40abcd0a8 100644--- a/tests/test_readme_figures_gate.py+++ b/tests/test_readme_figures_gate.py@@ -141,3 +141,38 @@ def test_an_absent_compliance_page_is_not_a_failure(tree: Path) -> None:"""A partial checkout must skip the check, not fail it."""(tree / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")assert _load_gates(tree).gate_readme_figures() == []+++# The matrix's own Summary block. This gate compared every prose restatement+# elsewhere against the rows and never the document doing the claiming, so the+# summary read "GATED: 108" against 109 counted rows and CI stayed green — the+# one-directional shape the matrix file's own counting note warns about.+STALE_SUMMARY = MATRIX + "\n## Summary\n\n- GATED: 7\n- PARTIAL: 1\n- NO GATE: 0\n"+CURRENT_SUMMARY = MATRIX + "\n## Summary\n\n- GATED: 2\n- PARTIAL: 1\n- NO GATE: 0\n"+++def test_matrix_summary_disagreeing_with_its_own_rows_fails(tree: Path) -> None:+ (tree / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")+ (tree / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(STALE_SUMMARY)++ failures = _load_gates(tree).gate_readme_figures()+ assert len(failures) == 1, failures+ assert "CLAIM_TO_GATE_MATRIX.md" in failures[0].detail+ assert "GATED: 7" in failures[0].detail+ assert "2 GATED rows" in failures[0].detail+++def test_matrix_summary_matching_its_own_rows_passes(tree: Path) -> None:+ (tree / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")+ (tree / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(CURRENT_SUMMARY)+ assert _load_gates(tree).gate_readme_figures() == []+++def test_a_stale_partial_count_in_the_summary_also_fails(tree: Path) -> None:+ """Both figures, not just the one that happened to drift first."""+ (tree / "README.md").write_text("833 executable. 2 GATED / 1 PARTIAL.\n")+ (tree / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md").write_text(MATRIX + "\n## Summary\n\n- GATED: 2\n- PARTIAL: 4\n")++ failures = _load_gates(tree).gate_readme_figures()+ assert len(failures) == 1, failures+ assert "PARTIAL: 4" in failures[0].detail