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
Five gates said OK over nothing; the probe that found them is now a gate (#823)
Beenu Aroraf3348223a8f5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9585e4eab..0ca7b1293 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -681,6 +681,37 @@ jobs:python3 scripts/check_gate_coverage.py --listpython3 -m pytest tests/test_gate_coverage_classifier.py -q+ - name: No check may report OK over a repository with no content+ # The gate on the gates, the other axis. Reachability says a check can+ # fail; this says it does, when there is nothing there to be clean.+ # Copying scripts/ into an empty git repository and running every+ # wired check found five reporting OK over a tree with no content —+ # the detection validator certifying zero rules valid, a dashboard+ # check that failed on an empty directory and passed on a missing one,+ # `OK: 0 published Go module path(s)`, every self-link healthy over+ # zero files, and a health-probe audit printing a table header. Found+ # nothing and scanned nothing print the same word.+ #+ # That probe was a one-off, so the next gate written could reintroduce+ # the defect freely. This is the same probe, permanent: each check is+ # run the way a workflow runs it, inside a repository holding only+ # scripts/, and must not exit 0. Exceptions are recorded with the+ # disposition they are excused for and checked in both directions, so+ # an entry that stops being needed fails the build.+ #+ # It also holds the two properties that produced those five: a root+ # resolved through git rather than from __file__ (two levels above the+ # script is whatever happens to be there), and a --self-test a+ # contributor can run before CI does.+ #+ # The inventory comes from check_gate_coverage.py above. A second+ # scanner here would drift the first time either one learned something+ # the other had not.+ run: |+ python3 scripts/check_gate_contract.py --self-test+ python3 scripts/check_gate_contract.py --list+ python3 -m pytest tests/test_gate_contract.py -q+- 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 freshdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e1ddc369..81ae91818 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **No gate may report OK over a repository with no content, and it is a CI+ gate now rather than a probe somebody happened to run once.** Copying+ `scripts/` into an empty git repository and running every wired check there+ found five reporting OK over a tree holding nothing — the detection+ validator behind the rule count on the front page certifying zero rules as+ valid, a dashboard check that failed on an *empty* directory and passed on a+ *missing* one, `OK: 0 published Go module path(s)`, every self-link healthy+ over zero files, and a health-probe audit printing a table header and+ exiting 0. Those five were fixed; the probe that found them was a one-off,+ so the next gate written could reintroduce the defect freely.++ `scripts/check_gate_contract.py` is that probe made permanent. It runs all+ 69 inventoried checks the way a workflow runs each one, inside a git+ repository holding only `scripts/`, and requires each to exit non-zero.+ Three things make the result mean something:++ - **The inventory is not written here.** It comes from+ `check_gate_coverage.py`, which already resolves the workflow-to-check+ graph structurally. A second scanner would drift the first time either+ one learned something the other had not.+ - **A failure the empty tree did not cause is INCONCLUSIVE, not a pass.**+ An argparse usage error, or an import of a module the repository does not+ supply, means the gate was never exercised — crediting that as a refusal+ would be the same defect one level up. Whether a missing module is the+ repository's own is read from `git ls-files`, so `No module named 'app'`+ counts as the empty tree working and `No module named 'structlog'` does+ not.+ - **Every way CI runs a script is probed, and the worst result decides.**+ Four subcommands under one name are four gates; excusing the set because+ the first refused is how the others stay hidden. Only invocations+ carrying a declared verdict flag are probed, so the generator half of a+ script that is both generator and gate is not mistaken for one.++ Exceptions are recorded with the disposition they are excused for and+ checked in both directions, so an entry naming a check that no longer+ exists fails, and so does one whose gate has started behaving differently.+ Four are recorded: `wet_eval_check.py` (reads two environment variables and+ no repository content), `security_audit.py`'s `validate-ignores` arm (its+ entire subject is a file inside `scripts/`, the one directory the scratch+ tree must keep), and `openapi_diff.py` / `wet_eval_update_benchmark.py`+ (both inputs named on the command line, one of them built outside the+ checkout).++- **Every check resolves its repository root from git, and every check+ carries a `--self-test`.** Sixty of the sixty-nine derived a root from+ `Path(__file__).resolve().parent.parent` — whatever happens to sit two+ levels above the script — which is how a gate prints a confident OK about a+ tree it never opened, and only a deliberate run from another directory+ catches it. Fifty-four had no self-test at all. Both are now properties the+ contract gate enforces, with empty exception lists.++ `scripts/gate_toolkit.py` holds the single implementation of both. Five+ near-identical copies of the git resolution had already accumulated across+ `scripts/`, which is how the sixth gets written subtly differently.++ Two things this turned up. `check_gate_coverage.py` decided whether a script+ inspects the repository partly by looking for `Path(__file__)` — the very+ idiom being migrated away from — so moving six gates onto the shared+ resolver silently dropped them out of the inventory, and deleting their+ workflow steps would then have gone unnoticed. And the first spelling of the+ root-resolution property matched `repo_root` anywhere in the file, which+ `check_gate_coverage.py` emits as a JSON key: a gate rooted at `__file__`+ read as compliant on the strength of a dictionary key in its own output.+ Both are read from the syntax tree now.+- **The 153 Python files that belong to no manifest tree are type-checked, andfive gates that reported OK over nothing now fail.** Giving all twenty treesa `[tool.mypy]` table still left `scripts/`, `tests/`, `tools/` and@@ -1225,6 +1290,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **`check_route_tenant_scope.py` reported OK having scanned zero routes.** It+ refused a tree with no `services/` directory, which is not how a scan loses+ its corpus: a renamed package, a changed decorator spelling or a walk that+ stops descending all leave the directory in place. Against a `services/`+ tree with no routes in it the gate printed `scanned 0 routes across 0 files`+ and then `OK: every route taking a tenant identifier authenticates` — the+ same sentence CI shows on a real pass. It now exits 2, and `--self-test`+ carries the case. Naming the count was only half the fix: the number was+ already printed, directly above the clean verdict.++- **The dependency audit reported success over a tree with no manifests.**+ `security_audit.py`'s pnpm, python and go arms each discovered zero targets+ and printed `0 findings`, which is the sentence a clean audit of twenty+ services prints. The file already treated an unscanned service as a failure+ rather than a warning — the gap was that a corpus of zero was never+ *unscanned*, just empty. All three now record a coverage gap when discovery+ finds nothing, and `validate-ignores` refuses a missing policy file instead+ of reporting `Validated 0 ignore entries` and exiting 0. `get_repo_root()`+ also stopped falling back to `Path.cwd()`, which meant a run from anywhere+ else audited whatever manifests happened to be under it.+- **Four tests failed on a clean checkout and belonged to nobody.** A suitewith known-failing tests teaches everyone to skim past red, so each is noweither fixed or skipped with a reason that says what to do about it.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0a9c9c6d8..60990ce9c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -205,6 +205,52 @@ fails the build rather than outliving the code it excused.- Maintain or improve test coverage- Run the full test suite before submitting a PR+### Writing a CI gate++A gate under `scripts/` is only worth the tree it opened. The useful question+to ask of one is not "does it flag the right things" but **"what does it+credit as clean, and could it credit something it never actually opened?"**+Running every wired check inside an empty git repository once found five+reporting OK over a repository containing nothing — including the detection+validator behind the rule count on the front page.++Four properties are enforced by `scripts/check_gate_contract.py`, which runs+in `ci.yml :: python-test`:++1. **Resolve the root from git.** Use `gate_toolkit.repo_root()`.+ `Path(__file__).resolve().parent.parent` is whatever happens to sit two+ levels above the script, so a copy run from elsewhere scans that other+ tree and prints a confident OK about a checkout nobody asked about.+2. **Print what was scanned, including a count.** *Found nothing* and+ *scanned nothing* are different results that print the same word.+3. **Fail closed on an empty or unreadable read.** Zero files walked is not+ zero violations found; it usually means a broken glob, a renamed package+ or a wrong root. Exit non-zero and say which.+4. **Carry a `--self-test`.** For a gate with nothing bespoke to prove, one+ statement below the imports is enough:++ ```python+ from gate_toolkit import repo_root, self_test_if_requested++ self_test_if_requested(__file__)+ ```++ Where the gate enforces a specific rule, inject a violation of that rule+ and assert it is caught — a gate nobody has seen fail is indistinguishable+ from one that cannot.++Run both gates on the gates before pushing:++```bash+python3 scripts/check_gate_coverage.py # every check is reachable from a workflow+python3 scripts/check_gate_contract.py # no check reports OK over an empty tree+```++Exceptions to the empty-tree rule are recorded in+`EMPTY_TREE_EXCEPTIONS` with the disposition they are excused for, and are+checked in both directions — an entry naming a check that no longer exists+fails, and so does one whose gate has started behaving differently.+### Public eval harnessAnything that touches the agent (`services/agents/`), the orchestratordiff --git a/ROADMAP.md b/ROADMAP.mdindex 4abf8c08b..830c027f7 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -44,7 +44,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.-The claim-to-gate matrix stands at **132 rows — 124 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).+The claim-to-gate matrix stands at **134 rows — 126 GATED / 8 PARTIAL / 0 NO GATE** — **every product claim is backed by a failing test** and the ratchet (`MAX_NO_GATE=0`) forbids any regression. The 8 remaining PARTIAL rows are honest, named deferrals; none was relabelled without building the gate it names. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).## v4.0 — Shippeddiff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.mdindex 78c874195..e4e845171 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: 124 rows+The last row is the one worth reading first. It is the honest index: 126 rows`GATED`, 8 `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 f32dcae63..fedcccccb 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -140,10 +140,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| 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 || What counts as a check is decided by what a script does, not what it is named | `scripts/check_gate_coverage.py` (the inventory it reports on) | `ci.yml` (three structural signals, all read from the tree: a declared verdict flag, an exit status derived from findings the script accumulates, and a workflow job whose output another job branches on. The first two are intrinsic, so an uncalled gate is still inventoried and the `SCRIPT -> WORKFLOW` direction is not vacuous. The classifier is also checked in reverse — a script CI runs with `--check` that the classifier does not inventory fails as `classifier-blind-spot`) + `tests/test_gate_coverage_classifier.py` (10 cases, including a gate planted under a name no convention would reveal, and a generator that aborts on an empty read asserted *not* to be a check) | GATED | - |+| No check reports OK over a repository with no content | every row above (a gate that credits an empty tree proves nothing about a full one) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — runs all 69 inventoried checks the way a workflow runs each one, inside a git repository holding only `scripts/`, and requires a non-zero exit. A run that failed for a reason the empty tree did not cause — an argparse usage error, or an import of a module the repository does not supply — is INCONCLUSIVE and fails rather than counting as a refusal, so the gate cannot credit a failure it did not cause. Exceptions are recorded with the disposition they are excused for and checked in both directions: an entry naming nothing, and an entry whose gate has started behaving differently, both fail) + `tests/test_gate_contract.py` (41 cases) | GATED | 4 recorded exceptions; the probe cannot pose the question to a gate whose only input is a path named on the command line, or one that lives inside `scripts/` |+| Every check resolves its root from git and carries a `--self-test` | `scripts/` (the gates themselves) | `ci.yml :: python-test` (`scripts/check_gate_contract.py` — a check that derives a repository root from `__file__` without consulting git fails as `root-from-file`, and one that declares no `--self-test` fails as `no-self-test`. Both read from the syntax tree: the first spelling matched `repo_root` anywhere in the text and `check_gate_coverage.py` emits it as a JSON key, so a non-compliant gate read as compliant on the strength of a dictionary key in its own output. Both exception lists are empty — all 69 comply — and an entry added to either must carry a reason) | GATED | - |## Summary-- GATED: 124+- GATED: 126- PARTIAL: 8- 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/scripts/audit_health_probes.py b/scripts/audit_health_probes.pyindex 13b35f631..b6c21e109 100644--- a/scripts/audit_health_probes.py+++ b/scripts/audit_health_probes.py@@ -38,7 +38,15 @@ import argparseimport pathlibimport sys-REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent+# `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(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SERVICES_DIR = REPO_ROOT / "services"diff --git a/scripts/audit_managed_tenants.py b/scripts/audit_managed_tenants.pyindex d50aa18e5..23a6f241c 100644--- a/scripts/audit_managed_tenants.py+++ b/scripts/audit_managed_tenants.py@@ -31,7 +31,15 @@ from pathlib import Pathimport yaml-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()TENANT_DIR = REPO_ROOT / "infra" / "fly" / "managed" / "tenants"SLUG_RE = re.compile(r"^[a-z0-9-]{2,32}$")diff --git a/scripts/audit_prometheus_targets.py b/scripts/audit_prometheus_targets.pyindex 272c91038..4d93c17e5 100755--- a/scripts/audit_prometheus_targets.py+++ b/scripts/audit_prometheus_targets.py@@ -41,7 +41,15 @@ import argparseimport pathlibimport sys-REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent+# `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(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()PROMETHEUS = REPO_ROOT / "infra" / "docker" / "prometheus.yml"SERVICES_DIR = REPO_ROOT / "services"diff --git a/scripts/audit_runbook_links.py b/scripts/audit_runbook_links.pyindex 168fd380f..295568c78 100755--- a/scripts/audit_runbook_links.py+++ b/scripts/audit_runbook_links.py@@ -27,7 +27,15 @@ import pathlibimport reimport sys-REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent+# `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(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()ALERTS = REPO_ROOT / "infra" / "docker" / "alerts" / "aisoc.rules.yml"RUNBOOK_PATH_PREFIX = "docs/runbooks/"diff --git a/scripts/build_marketplace.py b/scripts/build_marketplace.pyindex 2377a7b89..76a433bd7 100644--- a/scripts/build_marketplace.py+++ b/scripts/build_marketplace.py@@ -41,7 +41,15 @@ from typing import Anyimport yaml-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()DETECTIONS_DIR = REPO_ROOT / "detections"PLAYBOOKS_PACKS_DIR = REPO_ROOT / "playbooks" / "packs"PLUGINS_DIR = REPO_ROOT / "plugins"diff --git a/scripts/build_quarantine_index.py b/scripts/build_quarantine_index.pyindex 9c2d1e698..821308be8 100644--- a/scripts/build_quarantine_index.py+++ b/scripts/build_quarantine_index.py@@ -54,7 +54,15 @@ from pathlib import Pathimport yaml-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()QUARANTINE_DIR = REPO_ROOT / "detections" / "splunk-imports" / "_quarantine"README_PATH = QUARANTINE_DIR / "README.md"diff --git a/scripts/check_action_contract.py b/scripts/check_action_contract.pyindex 161039512..abce202cb 100644--- a/scripts/check_action_contract.py+++ b/scripts/check_action_contract.py@@ -32,7 +32,15 @@ from typing import TypeVarimport structlog-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()ACTIONS = REPO_ROOT / "services" / "actions"sys.path.insert(0, str(ACTIONS))diff --git a/scripts/check_attribution.py b/scripts/check_attribution.pyindex d54dae8d1..1e30684ed 100644--- a/scripts/check_attribution.py+++ b/scripts/check_attribution.py@@ -36,7 +36,13 @@ import subprocessimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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++ROOT = repo_root()PATTERN_FILE = ROOT / ".githooks" / "attribution-patterns.txt"ALLOWLIST_FILE = ROOT / ".githooks" / "attribution-allowlist.txt"FIXTURES = ROOT / "scripts" / "attribution_fixtures.json"diff --git a/scripts/check_claim_gate_matrix.py b/scripts/check_claim_gate_matrix.pyindex 5934e32ee..0c9d6a31c 100644--- a/scripts/check_claim_gate_matrix.py+++ b/scripts/check_claim_gate_matrix.py@@ -21,7 +21,15 @@ import reimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()MATRIX = ROOT / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md"# Ratchet baseline: the number of NO GATE rows allowed. Lower this as phasesdiff --git a/scripts/check_codeql_alerts.py b/scripts/check_codeql_alerts.pyindex a66a6df49..c53d31271 100644--- a/scripts/check_codeql_alerts.py+++ b/scripts/check_codeql_alerts.py@@ -69,6 +69,12 @@ from datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom typing import Any+# `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+API_ROOT = "https://api.github.com"DEFAULT_REPO = "beenuar/AiSOC"DEFAULT_REF = "refs/heads/main"@@ -407,7 +413,7 @@ def main(argv: list[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY") or DEFAULT_REPO)parser.add_argument("--ref", default=DEFAULT_REF)- parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parent.parent)+ parser.add_argument("--repo-root", type=Path, default=repo_root())parser.add_argument("--max-analysis-age-days", type=int, default=DEFAULT_MAX_ANALYSIS_AGE_DAYS)parser.add_argument("--commit",diff --git a/scripts/check_connector_profiles.py b/scripts/check_connector_profiles.pyindex 110c22558..ad8e0db3e 100644--- a/scripts/check_connector_profiles.py+++ b/scripts/check_connector_profiles.py@@ -59,6 +59,12 @@ import reimport sysfrom 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+NORMALIZER_REL = Path("services/ingest/internal/normalizer/normalizer.go")NORMALIZER_TEST_REL = Path("services/ingest/internal/normalizer/normalizer_test.go")CONNECTORS_REL = Path("services/connectors/app/connectors")@@ -459,7 +465,7 @@ def load(root: Path) -> dict: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("--repo-root", type=Path, default=repo_root())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)diff --git a/scripts/check_dependency_pins.py b/scripts/check_dependency_pins.pyindex 4396803f4..9605b4678 100644--- a/scripts/check_dependency_pins.py+++ b/scripts/check_dependency_pins.py@@ -61,6 +61,12 @@ import tomllibfrom dataclasses import dataclass, fieldfrom 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+# ── Which packages must agree repo-wide ──────────────────────────────────────## Not every dependency belongs here. Two services may legitimately ship@@ -883,7 +889,7 @@ def main() -> int:if args.self_test:return self_test()- root = (args.repo_root or Path(__file__).resolve().parent.parent).resolve()+ root = (args.repo_root or repo_root()).resolve()return run(root, verbose=args.verbose)[0]diff --git a/scripts/check_detection_fields.py b/scripts/check_detection_fields.pyindex a30ab14b8..0a45a8753 100644--- a/scripts/check_detection_fields.py+++ b/scripts/check_detection_fields.py@@ -44,7 +44,15 @@ import reimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()RULESET = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"CONNECTORS = ROOT / "services" / "connectors" / "app" / "connectors"#: The AI SDK is a first-party emitter too — it posts spans straight to andiff --git a/scripts/check_fidelity_datasets.py b/scripts/check_fidelity_datasets.pyindex 0551a868d..15f5c35f5 100644--- a/scripts/check_fidelity_datasets.py+++ b/scripts/check_fidelity_datasets.py@@ -33,13 +33,21 @@ import reimport sysfrom 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_if_requested++self_test_if_requested(__file__)+try:import yamlexcept ImportError: # pragma: no coverprint("PyYAML is required: pip install pyyaml", file=sys.stderr)raise SystemExit(2) from None-REPO_ROOT = Path(__file__).resolve().parent.parent+REPO_ROOT = repo_root()FIDELITY = REPO_ROOT / "services" / "agents" / "tests" / "fidelity"DOWNLOADS = REPO_ROOT / "scripts" / "datasets"THRESHOLDS = FIDELITY / "expected_results.yaml"diff --git a/scripts/check_funnel_contract.py b/scripts/check_funnel_contract.pyindex ac23b85cb..2ae8cfb2f 100644--- a/scripts/check_funnel_contract.py+++ b/scripts/check_funnel_contract.py@@ -25,7 +25,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()METRICS = REPO_ROOT / "services" / "api" / "app" / "api" / "v1" / "endpoints" / "metrics.py"DOC = REPO_ROOT / "apps" / "docs" / "docs" / "console" / "funnel-kpis.md"diff --git a/scripts/check_gate_contract.py b/scripts/check_gate_contract.pynew file mode 100644index 000000000..21b6fcec4--- /dev/null+++ b/scripts/check_gate_contract.py@@ -0,0 +1,862 @@+#!/usr/bin/env python3+"""No gate in this tree may report OK over a repository containing nothing.++Why this exists+---------------+The cheapest diagnostic anyone has run on this repository was to copy+``scripts/`` into an empty git repository and run every wired check there.+Five reported OK over a tree with no content:++* ``validate_detections.py`` — the validator behind the rule count the front+ page quotes — printed a warning and exited 0, certifying zero rules valid.+* ``check_grafana_dashboards.py`` had both branches and had them backwards:+ it failed on an *empty* dashboards directory and passed on a *missing* one,+ forgiving the larger loss.+* ``check_go_module_paths.py`` reported ``OK: 0 published Go module path(s)``.+* ``check_repo_self_links.py`` called every self-link healthy over zero files+ — and it exists to replace a lychee run that accepted HTTP 403 as healthy,+ so it had inherited the same inability in a different costume.+* ``audit_health_probes.py --check`` printed a table header and exited 0.++All five are fixed. The probe that found them was a one-off, so the next gate+written could reintroduce the defect freely. This makes it permanent.++The question it asks+--------------------+Not "does the gate flag the right things" but **"what does it credit as+clean, and could it credit something it never opened?"** A gate that walks+zero files finds zero violations; unless it refuses an empty read, a clean+result is indistinguishable from a broken glob, a wrong root, or a tree that+is not there. *Found nothing* and *scanned nothing* print the same word.++What it checks+--------------+Three properties of every check in the tree, each with a shrink-only list of+recorded exceptions, each list verified in both directions so an entry that+stops being needed fails the build rather than sitting there:++``empty-tree``+ Run the gate the way CI runs it, inside a git repository holding only+ ``scripts/``. It must not exit 0.++``root-from-git``+ A gate that derives a repository root from ``__file__`` must also consult+ ``git rev-parse``. ``Path(__file__).parent.parent`` is whatever sits two+ levels above the script; a copy run from elsewhere scans that other tree+ and prints a confident OK about a checkout nobody asked about. One gate+ was in exactly that state and only a deliberate probe from another+ directory caught it.++``self-test``+ The gate declares ``--self-test``, so a contributor can prove it still+ detects what it claims to before CI does.++The inventory is not written here+---------------------------------+It comes from ``check_gate_coverage.py``, which already resolves the+workflow-to-check graph mechanically and classifies a script by what it does+rather than what it is called. Two scanners drift the first time either one+learns something the other has not — that gate went from 42 to 59 inventoried+checks the day its filename test was deleted, and a second inventory here+would have kept the old answer.++How an invocation is chosen+---------------------------+From the workflow surface, not from a list kept here. Every way a workflow+runs the script is a candidate, in CI's own spelling; ``--self-test`` is+excluded because it renders a verdict on the gate rather than on the tree,+and so are invocations naming an unexpanded shell variable or a path outside+the repository, because replaying those tests the argument list rather than+the tree. If nothing is replayable, the script's own declared verdict flag is+used.++A run that fails for a reason other than the empty tree — an argparse usage+error, or an import of a third-party module the environment lacks — proves+nothing, so it is reported as INCONCLUSIVE and fails this gate. Crediting a+refusal the probe never actually caused would be the same defect one level+up.++Usage+-----+ python3 scripts/check_gate_contract.py # gate+ python3 scripts/check_gate_contract.py --list # per-check detail+ python3 scripts/check_gate_contract.py --json+ python3 scripts/check_gate_contract.py --self-test # prove it detects drift++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 shlex+import subprocess+import sys+from collections.abc import Sequence+from dataclasses import asdict, 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. Its siblings sit beside it either way.+sys.path.insert(0, str(Path(__file__).resolve().parent))++import check_gate_coverage as coverage # noqa: E402+from gate_toolkit import ( # noqa: E402+ SELF_TEST_FLAG,+ VERDICT_FLAG_PREFERENCE,+ repo_root,+ run_in_scratch_tree,+ scratch_tree,+)++# --------------------------------------------------------------------------+# Recorded exceptions. Every one of these is shrink-only and checked in both+# directions: an entry naming a check that does not exist fails the build, and+# so does an entry whose reason has stopped being true.+# --------------------------------------------------------------------------++#: Checks the empty-tree question cannot be put to, each recorded with the+#: disposition it is expected to produce. Recording the disposition and not+#: just the name is what makes the entry falsifiable: an exception written+#: because argparse refused the arguments does not quietly go on covering the+#: gate on the day it starts exiting 0 instead.+EMPTY_TREE_EXCEPTIONS: dict[str, tuple[str, str]] = {+ "wet_eval_check.py": (+ "passed",+ "Reads two environment variables and no repository content at all. Its exit status is 0 by "+ "design so a fork with no secrets does not look like a broken build; the verdict is the JSON "+ "status file that wet-eval.yml branches on, which is why check_gate_coverage classifies it "+ "from the job graph rather than from anything intrinsic. There is no tree for it to credit, "+ "so its --self-test checks the verdict it does render: should_run across present, absent, "+ "partial and dry-run secrets.",+ ),+ "security_audit.py": (+ "passed",+ "Three of its four arms — pnpm, python, go — now refuse a tree with no manifests in it. The "+ "fourth, validate-ignores, has scripts/security_audit_ignores.txt as its entire subject, and "+ "scripts/ is the one directory the scratch tree has to keep for the gate to be runnable at "+ "all. So the probe cannot pose the question for that arm; the missing-policy-file case is "+ "covered instead by test_validate_ignores_refuses_a_missing_policy_file.",+ ),+ "openapi_diff.py": (+ "inconclusive",+ "Both specifications are named on the command line and one of them is a checkout of main that "+ "openapi-breaking.yml writes outside the repository, so it discovers nothing from the tree and "+ "there is no empty-tree verdict to render. Run with no arguments it refuses at argparse, before "+ "any file is opened.",+ ),+ "wet_eval_update_benchmark.py": (+ "inconclusive",+ "Same shape: --wet-block names a report the weekly workflow produces outside the checkout, so "+ "the only replayable invocation would be testing the argument list rather than the tree. "+ "Required arguments mean argparse refuses a bare run before it reads anything.",+ ),+}++#: Checks that derive a root from ``__file__`` and do not consult git. Empty:+#: every check in the tree resolves through git today. The list stays so that+#: a future exception has to be written down and justified rather than+#: appearing as a quietly relaxed rule.+NO_GIT_ROOT: dict[str, str] = {}++#: Checks that do not declare ``--self-test``. Also empty, same reason.+NO_SELF_TEST: dict[str, str] = {}+++class ProbeError(RuntimeError):+ """The probe could not be set up. Never downgraded to a passing result."""+++# --------------------------------------------------------------------------+# Choosing how to run each gate+# --------------------------------------------------------------------------+#: Command words that mean "the next path is a Python program". Requiring one+#: is what keeps a quoted path inside an `echo` out of the answer: shlex hands+#: back `['echo', 'scripts/foo.py']`, whose command word is `echo`. A matcher+#: that looked for the substring counted eleven services as CI-covered on the+#: strength of a quoted path in a shell array.+_INTERPRETERS = frozenset({"python", "python3", *(f"python3.{minor}" for minor in range(8, 20))})++#: `uv run python x.py` and `poetry run python x.py` reach the same place.+_RUNNERS = frozenset({"uv", "poetry"})+++def _segments(text: str) -> list[str]:+ """Individual commands inside a workflow `run:` block."""+ joined = text.replace("\\\n", " ")+ parts: list[str] = []+ for line in joined.splitlines():+ for piece in re.split(r"&&|\|\||[;|]", line):+ stripped = piece.strip()+ if stripped:+ parts.append(stripped)+ return parts+++def _argv_after(tokens: list[str], script: str) -> list[str] | None:+ """The arguments a command passes to ``scripts/<script>``, or None."""+ index = 0+ while index < len(tokens) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", tokens[index]):+ index += 1+ if index < len(tokens) and tokens[index] == "env":+ index += 1+ while index < len(tokens) and re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*=.*", tokens[index]):+ index += 1+ if index >= len(tokens):+ return None+ if tokens[index] in _RUNNERS:+ if index + 1 >= len(tokens) or tokens[index + 1] != "run":+ return None+ index += 2+ if index < len(tokens) and tokens[index] in _INTERPRETERS:+ index += 1+ elif tokens[index] in _INTERPRETERS:+ index += 1+ else:+ return None+ # `python -m pytest ...` runs a module, not this script.+ if index < len(tokens) and tokens[index].startswith("-"):+ return None+ if index >= len(tokens) or Path(tokens[index]).name != script:+ return None+ return tokens[index + 1 :]+++def _replayable(args: Sequence[str]) -> bool:+ """Whether replaying these arguments would test the tree rather than the argument list.++ An unexpanded `$VAR` becomes a literal path that cannot exist, and an+ absolute path is an artefact CI builds outside the checkout. Either way+ the gate would fail for a reason the empty tree did not cause, which is+ not evidence of anything.+ """+ return not any("$" in arg or arg.startswith("/") for arg in args)+++def ci_invocations(surface: coverage.Surface, script: str, signals: dict[str, str] | None = None) -> list[list[str]]:+ """Every replayable way a workflow asks ``script`` for a verdict.++ Asks for a verdict, not merely runs: several scripts here are a generator+ and a gate in one file, and CI runs both halves. ``build_marketplace.py``+ with no arguments *writes* ``marketplace/index.json``; only+ ``--check`` compares it. Probing the generator would report that writing+ an empty index over an empty tree is a gate crediting nothing, which is+ true of every generator and says nothing about the gate. So when a script+ declares verdict flags, only the invocations carrying one are probed —+ the same structural signal ``check_gate_coverage`` classifies it by.+ """+ verdict_flags = {f for f in (signals or {}).get("verdict-flag", "").split() if f != SELF_TEST_FLAG}+ found: list[list[str]] = []+ for _workflow, _wd, text in surface.texts():+ if f"/{script}" not in text and not text.strip().startswith(script):+ continue+ for segment in _segments(text):+ try:+ tokens = shlex.split(segment)+ except ValueError:+ continue+ args = _argv_after(tokens, script)+ if args is None or args == [SELF_TEST_FLAG] or not _replayable(args):+ continue+ if verdict_flags and not verdict_flags & set(args):+ continue+ if args not in found:+ found.append(args)+ # Longest first: a step that passes flags is asking a sharper question+ # than a bare run, and is the one whose behaviour matters most.+ found.sort(key=len, reverse=True)+ return found+++def declared_invocations(signals: dict[str, str]) -> list[list[str]]:+ """Fallbacks from the gate's own declared verdict flags."""+ flags = [f for f in signals.get("verdict-flag", "").split() if f != SELF_TEST_FLAG]+ ordered = [f for f in VERDICT_FLAG_PREFERENCE if f in flags]+ ordered += [f for f in flags if f not in ordered]+ return [[flag] for flag in ordered] + [[]]+++# --------------------------------------------------------------------------+# Reading the result+# --------------------------------------------------------------------------+_ARGPARSE_USAGE = re.compile(r"^usage: ", re.MULTILINE)+_ARGPARSE_ERROR = re.compile(r"^\S+: error: ", re.MULTILINE)+_MISSING_MODULE = re.compile(r"ModuleNotFoundError: No module named '([\w.]+)'")++REFUSED = "refused"+PASSED = "passed"+INCONCLUSIVE = "inconclusive"+++def importable_names(root: Path) -> frozenset[str]:+ """Top-level module names the repository itself supplies.++ A gate that dies on ``No module named 'app'`` inside the scratch tree died+ *because* the tree is empty — ``app`` is the package under ``services/``.+ One that dies on ``No module named 'structlog'`` died because the probe+ environment is short a dependency, which is evidence about the probe and+ not about the gate.+ """+ out = subprocess.run( # noqa: S603 - fixed argv, no shell+ ["git", "ls-files"],+ capture_output=True,+ text=True,+ check=False,+ cwd=root,+ )+ if out.returncode != 0:+ raise ProbeError(f"cannot list tracked files under {root}: {out.stderr.strip()}")+ names: set[str] = set()+ for line in out.stdout.splitlines():+ path = Path(line)+ if path.name == "__init__.py":+ names.add(path.parent.name)+ elif path.suffix == ".py":+ names.add(path.stem)+ if not names:+ raise ProbeError(f"git ls-files returned no Python under {root}")+ return frozenset(names)+++def classify(status: int | None, output: str, supplied: frozenset[str]) -> tuple[str, str]:+ """(disposition, why) for one run of a gate in the scratch tree."""+ if status is None:+ return INCONCLUSIVE, "timed out"+ if status == 0:+ return PASSED, "exited 0"+ if _ARGPARSE_USAGE.search(output) and _ARGPARSE_ERROR.search(output):+ return INCONCLUSIVE, "argparse rejected the arguments, so the tree was never read"+ missing = _MISSING_MODULE.search(output)+ if missing and missing.group(1).split(".")[0] not in supplied:+ return INCONCLUSIVE, f"the probe environment has no {missing.group(1)!r}, which this repository does not supply"+ return REFUSED, f"exited {status}"+++@dataclass+class Run:+ """One invocation of one gate inside the scratch tree."""++ args: list[str]+ source: str+ disposition: str+ why: str+ evidence: str = ""+++@dataclass+class Probe:+ """Everything the probe learned about one gate."""++ script: str+ runs: list[Run] = field(default_factory=list)++ @property+ def disposition(self) -> str:+ """The worst thing any invocation did.++ Worst, not first: a script CI runs four ways is four gates wearing one+ name, and excusing the set because the first one refused is how a+ subcommand that credits an empty tree stays hidden behind a sibling+ that does not.+ """+ seen = {run.disposition for run in self.runs}+ if PASSED in seen:+ return PASSED+ if REFUSED in seen:+ return REFUSED+ return INCONCLUSIVE++ @property+ def why(self) -> str:+ worst = self.disposition+ return next((run.why for run in self.runs if run.disposition == worst), "no invocation was attempted")+++def probe(surface: coverage.Surface, checks: dict[str, dict[str, str]], root: Path, *, only: str | None = None) -> list[Probe]:+ """Run every check inside a repository with no content and read the result.++ Every way CI runs a script is probed, because each is a verdict somebody+ relies on. Its own declared flags are the fallback, used only when nothing+ CI does can be replayed — a step whose arguments name an artefact built+ outside the checkout tests the argument list rather than the tree.+ """+ supplied = importable_names(root)+ results: list[Probe] = []+ with scratch_tree(root / "scripts") as tree:+ for script in sorted(checks):+ if only and script != only:+ continue+ result = Probe(script=script)+ for args in ci_invocations(surface, script, checks[script]):+ result.runs.append(_run_one(script, args, tree, supplied, "the workflow that runs it"))+ if result.disposition == INCONCLUSIVE:+ for args in declared_invocations(checks[script]):+ run = _run_one(script, args, tree, supplied, "its own declared verdict flag")+ result.runs.append(run)+ if run.disposition != INCONCLUSIVE:+ break+ results.append(result)+ return results+++def _run_one(script: str, args: Sequence[str], tree: Path, supplied: frozenset[str], source: str) -> Run:+ status, output = run_in_scratch_tree(script, args, tree=tree)+ _reset(tree)+ disposition, why = classify(status, output, supplied)+ return Run(args=list(args), source=source, disposition=disposition, why=why, evidence=_tail(output))+++def _reset(tree: Path) -> None:+ """Undo anything the gate just wrote, so the next one sees the same tree."""+ for argv in (["reset", "--hard", "-q"], ["clean", "-qxfd"]):+ subprocess.run(["git", *argv], cwd=tree, check=False, capture_output=True) # noqa: S603+++def _tail(output: str, limit: int = 220) -> str:+ lines = [line for line in output.strip().splitlines() if line.strip()]+ return lines[-1][-limit:] if lines else ""+++# --------------------------------------------------------------------------+# The two static properties+# --------------------------------------------------------------------------+#: Read from the syntax tree, never from the text. The first spelling of this+#: matched `\brepo_root\b` anywhere in the file, and `check_gate_coverage.py`+#: emits `"repo_root"` as a JSON key — so a gate that resolved its root from+#: `__file__` and never asked git read as compliant on the strength of a+#: dictionary key in its own output. A gate crediting something it never+#: opened, one level up from the gates it inspects.+_GIT_TOPLEVEL = "--show-toplevel"+_ROOT_HELPER = "repo_root"+++def static_properties(source: str) -> dict[str, bool]:+ """What the syntax tree says about root resolution and self-testing."""+ try:+ tree = ast.parse(source)+ except SyntaxError:+ return {"derives_root_from_file": False, "consults_git_for_root": False, "declares_self_test": False}+ return {+ "derives_root_from_file": any(_is_file_relative_root(n) for n in ast.walk(tree)),+ "consults_git_for_root": _consults_git(tree),+ "declares_self_test": _declares_self_test(tree),+ }+++def _is_file_relative_root(node: ast.AST) -> bool:+ """``Path(__file__)…parent.parent`` or ``…parents[n]`` — a root from a file path."""+ if isinstance(node, ast.Attribute) and node.attr == "parent":+ inner = node.value+ return isinstance(inner, ast.Attribute) and inner.attr == "parent" and _reaches_dunder_file(inner)+ if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Attribute) and node.value.attr == "parents":+ index = node.slice+ return isinstance(index, ast.Constant) and index.value != 0 and _reaches_dunder_file(node.value)+ return False+++def _reaches_dunder_file(node: ast.AST) -> bool:+ return any(isinstance(sub, ast.Name) and sub.id == "__file__" for sub in ast.walk(node))+++def _consults_git(tree: ast.Module) -> bool:+ """Either it shells out to git itself, or it calls the shared resolver."""+ for node in ast.walk(tree):+ if isinstance(node, ast.Constant) and node.value == _GIT_TOPLEVEL:+ return True+ if isinstance(node, ast.Call):+ called = node.func+ name = called.id if isinstance(called, ast.Name) else (called.attr if isinstance(called, ast.Attribute) else None)+ if name == _ROOT_HELPER:+ return True+ return False+++def _declares_self_test(tree: ast.Module) -> bool:+ """The flag reaches code, or the shared hook is installed.++ A docstring promising ``--self-test`` while nothing parses it is the+ documentation equivalent of a gate with no caller, and this repository has+ shipped that shape more than once — so the flag has to appear as a value+ the program uses, not as prose about the program.+ """+ for node in ast.walk(tree):+ if isinstance(node, ast.Constant) and node.value == SELF_TEST_FLAG:+ return True+ if isinstance(node, ast.Name) and node.id == "SELF_TEST_FLAG":+ return True+ if isinstance(node, ast.Call):+ called = node.func+ name = called.id if isinstance(called, ast.Name) else (called.attr if isinstance(called, ast.Attribute) else None)+ if name == "self_test_if_requested":+ return True+ return False+++# --------------------------------------------------------------------------+# Verdict+# --------------------------------------------------------------------------+def evaluate(+ checks: dict[str, dict[str, str]],+ probes: dict[str, Probe],+ properties: dict[str, dict[str, bool]],+ *,+ accepted: dict[str, tuple[str, str]],+ no_git_root: dict[str, str],+ no_self_test: dict[str, str],+) -> list[tuple[str, str]]:+ """Every finding, as (code, detail). Pure, so the self-test can drive it."""+ failures: list[tuple[str, str]] = []++ for script in sorted(checks):+ result = probes.get(script)+ excused, expected = script in accepted, (accepted.get(script) or ("", ""))[0]+ if result is None:+ failures.append(("not-probed", f"{script} is a check and the probe produced no result for it"))+ continue+ if excused and result.disposition != expected:+ failures.append(+ (+ "exception-stale",+ f"{script} is excused on the strength of a {expected!r} disposition and now reports "+ f"{result.disposition!r} ({result.why}). Either the reason has stopped being true and "+ "the entry should go, or it is covering something it was never written for.",+ )+ )+ elif result.disposition == INCONCLUSIVE and not excused:+ failures.append(+ (+ "inconclusive",+ f"{script}: {result.why}. The probe did not exercise the gate, so a non-zero exit is "+ "not evidence it refuses an empty tree — install the dependency in the job, or record "+ "an exception saying why the question cannot be asked.",+ )+ )+ elif result.disposition == PASSED and not excused:+ offending = [" ".join(r.args) or "(no arguments)" for r in result.runs if r.disposition == PASSED]+ failures.append(+ (+ "passes-over-empty-tree",+ f"{script} {', '.join(offending)} exited 0 inside a repository holding no content. "+ "Found nothing and scanned nothing print the same word: this gate credits a tree it "+ "never opened. Make it fail closed on an empty read, or record why the exit status is "+ "not its verdict.",+ )+ )++ static = properties.get(script, {})+ needs_git = static.get("derives_root_from_file") and not static.get("consults_git_for_root")+ if needs_git and script not in no_git_root:+ failures.append(+ (+ "root-from-file",+ f"{script} resolves a repository root from __file__ and never asks git. Two levels above "+ "the script is whatever happens to be there; use gate_toolkit.repo_root().",+ )+ )+ if not needs_git and script in no_git_root:+ failures.append(("ratchet-stale", f"{script} is on NO_GIT_ROOT but now resolves its root from git; remove the entry"))++ if not static.get("declares_self_test") and script not in no_self_test:+ failures.append(+ (+ "no-self-test",+ f"{script} declares no {SELF_TEST_FLAG}, so nothing proves it still detects what it "+ f"claims to. gate_toolkit.self_test_main() is the shared body.",+ )+ )+ if static.get("declares_self_test") and script in no_self_test:+ failures.append(("ratchet-stale", f"{script} is on NO_SELF_TEST but now declares {SELF_TEST_FLAG}; remove the entry"))++ reasons: dict[str, dict[str, str]] = {+ "EMPTY_TREE_EXCEPTIONS": {name: reason for name, (_disposition, reason) in accepted.items()},+ "NO_GIT_ROOT": no_git_root,+ "NO_SELF_TEST": no_self_test,+ }+ for name, label in reasons.items():+ for script in sorted(set(label) - set(checks)):+ failures.append(("ratchet-names-nothing", f"{name} lists {script!r}, which is not a check in the tree"))+ for script, reason in sorted(label.items()):+ if script in checks and not reason.strip():+ failures.append(("ratchet-unexplained", f"{name}[{script!r}] carries no reason"))++ return failures+++def _exception_summary() -> str:+ counts: dict[str, int] = {}+ for disposition, _reason in EMPTY_TREE_EXCEPTIONS.values():+ counts[disposition] = counts.get(disposition, 0) + 1+ return ", ".join(f"{count} {name}" for name, count in sorted(counts.items())) or "none"+++def load(root: Path, *, only: str | None = None) -> dict:+ surface = coverage.Surface(root)+ checks = coverage.collect_checks(root, surface.gating)+ results = probe(surface, checks, root, only=only)+ properties = {script: static_properties((root / "scripts" / script).read_text(encoding="utf-8", errors="replace")) for script in checks}+ return {"checks": checks, "probes": {p.script: p for p in results}, "properties": properties}+++# --------------------------------------------------------------------------+# 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="the tree to inspect (default: git rev-parse)")+ parser.add_argument("--list", action="store_true", help="print every check with its disposition")+ parser.add_argument("--json", action="store_true")+ parser.add_argument("--only", help="probe a single check, by file name")+ parser.add_argument(SELF_TEST_FLAG, action="store_true", help="prove this gate detects the drift it claims to")+ args = parser.parse_args(argv)++ if args.self_test:+ return self_test()++ root = (args.repo_root or repo_root()).resolve()+ try:+ data = load(root, only=args.only)+ except (ProbeError, coverage.GateError, FileNotFoundError) as exc:+ print(f"check_gate_contract: FAILED to run the probe: {exc}", file=sys.stderr)+ return 2++ checks, probes, properties = data["checks"], data["probes"], data["properties"]+ failures = evaluate(+ checks,+ probes,+ properties,+ accepted=EMPTY_TREE_EXCEPTIONS,+ no_git_root=NO_GIT_ROOT,+ no_self_test=NO_SELF_TEST,+ )++ if args.json:+ print(+ json.dumps(+ {+ "repo_root": str(root),+ "checks": sorted(checks),+ "probes": {name: asdict(p) for name, p in probes.items()},+ "properties": properties,+ "empty_tree_exceptions": EMPTY_TREE_EXCEPTIONS,+ "no_git_root": NO_GIT_ROOT,+ "no_self_test": NO_SELF_TEST,+ "failures": [{"code": c, "detail": d} for c, d in failures],+ },+ indent=2,+ sort_keys=True,+ )+ )+ return 1 if failures else 0++ counts = {name: sum(1 for p in probes.values() if p.disposition == name) for name in (REFUSED, PASSED, INCONCLUSIVE)}+ runs = sum(len(p.runs) for p in probes.values())+ print(f"repo root {root}")+ print(f"inventory check_gate_coverage.py ({len(checks)} checks, {len(probes)} probed over {runs} invocations)")+ print("scratch tree a git repository holding only scripts/ — no services, detections, apps, docs or workflows")+ print(f"dispositions {counts[REFUSED]} refused, {counts[PASSED]} exited 0, {counts[INCONCLUSIVE]} inconclusive")+ print(+ f"exceptions {len(EMPTY_TREE_EXCEPTIONS)} recorded ({_exception_summary()}), "+ f"{len(NO_GIT_ROOT)} without a git root, {len(NO_SELF_TEST)} without a self-test"+ )+ print()++ if args.list:+ width = max((len(s) for s in probes), default=10)+ for name in sorted(probes):+ for run in probes[name].runs:+ mark = {REFUSED: "refused ", PASSED: "EXITED 0", INCONCLUSIVE: "UNKNOWN "}[run.disposition]+ print(f" {mark} {name:{width}} {' '.join(run.args) or '(no arguments)'} [{run.source}]")+ if run.evidence:+ print(f" {'':{width}} {run.evidence}")+ print()++ if failures:+ print(f"FAIL — {len(failures)} finding(s):")+ for code, detail in failures:+ print(f" [{code}] {detail}")+ return 1+ print(f"OK — {len(checks) - len(EMPTY_TREE_EXCEPTIONS)} of {len(checks)} checks refuse a repository with no content;")+ print(f" the other {len(EMPTY_TREE_EXCEPTIONS)} are recorded exceptions, each with the disposition it is excused for.")+ return 0+++# --------------------------------------------------------------------------+# Self-test+# --------------------------------------------------------------------------+def self_test() -> int:+ """Inject each defect this gate exists to catch and require it to be caught."""+ checks = {"check_real.py": {"verdict-flag": "--check"}}++ def result(*dispositions: str) -> dict[str, Probe]:+ runs = [Run(args=["--check"], source="test", disposition=d, why=f"exited on {d}") for d in dispositions]+ return {"check_real.py": Probe(script="check_real.py", runs=runs)}++ good = result(REFUSED)+ clean_props = {"check_real.py": {"derives_root_from_file": False, "consults_git_for_root": True, "declares_self_test": True}}++ def run(probes, props=None, *, accepted=None, no_git=None, no_self=None):+ return {+ code+ for code, _ in evaluate(+ checks,+ probes,+ props or clean_props,+ accepted=accepted or {},+ no_git_root=no_git or {},+ no_self_test=no_self or {},+ )+ }++ cases: list[tuple[str, str, set[str]]] = [+ (+ "a gate that exits 0 over a repository with no content",+ "passes-over-empty-tree",+ run(result(PASSED)),+ ),+ (+ "one invocation of a gate exits 0 while a sibling invocation refuses",+ "passes-over-empty-tree",+ run(result(REFUSED, PASSED)),+ ),+ (+ "a run that failed for a reason the empty tree did not cause",+ "inconclusive",+ run(result(INCONCLUSIVE)),+ ),+ (+ "a check the probe never reached at all",+ "not-probed",+ run({}),+ ),+ (+ "an accepted empty-tree pass that has started refusing — a stale exception",+ "exception-stale",+ run(good, accepted={"check_real.py": (PASSED, "recorded reason")}),+ ),+ (+ "an exception written for an inconclusive probe now covering an outright pass",+ "exception-stale",+ run(result(PASSED), accepted={"check_real.py": (INCONCLUSIVE, "recorded reason")}),+ ),+ (+ "an exception naming a check that is not in the tree",+ "ratchet-names-nothing",+ run(good, accepted={"check_ghost.py": (PASSED, "recorded reason")}),+ ),+ (+ "an exception with no reason given",+ "ratchet-unexplained",+ run(good, accepted={"check_real.py": (REFUSED, " ")}),+ ),+ (+ "a gate rooting itself at __file__ with no git resolution",+ "root-from-file",+ run(+ good,+ {"check_real.py": {"derives_root_from_file": True, "consults_git_for_root": False, "declares_self_test": True}},+ ),+ ),+ (+ "a gate that has moved onto git but is still listed as if it had not",+ "ratchet-stale",+ run(good, no_git={"check_real.py": "recorded reason"}),+ ),+ (+ "a gate with no self-test",+ "no-self-test",+ run(+ good,+ {"check_real.py": {"derives_root_from_file": False, "consults_git_for_root": True, "declares_self_test": False}},+ ),+ ),+ ]++ print("check_gate_contract self-test")+ print("baseline: one clean check, 0 findings (every case below perturbs exactly that)\n")+ ok = not run(good)+ print(f" {'PASS' if ok else 'FAIL'} the unperturbed baseline reports nothing")++ for description, expected, codes in cases:+ caught = expected in codes+ ok &= caught+ print(f" {'PASS' if caught else 'FAIL'} {description}")+ print(f" expected [{expected}] got {sorted(codes) or 'nothing'}")++ # The reader of the result, not just the rules on top of it. A classifier+ # that called everything a refusal would pass every case above.+ supplied = frozenset({"app"})+ reader: list[tuple[str, tuple[str, str], str]] = [+ ("exit 0 is a pass", classify(0, "OK: 0 things checked", supplied), PASSED),+ ("exit 1 with a refusal is a refusal", classify(1, "no detections/ directory", supplied), REFUSED),+ ("an argparse usage error proves nothing", classify(2, "usage: x [-h]\nx: error: unrecognized arguments", supplied), INCONCLUSIVE),+ (+ "a missing third-party module proves nothing",+ classify(1, "ModuleNotFoundError: No module named 'structlog'", supplied),+ INCONCLUSIVE,+ ),+ (+ "a missing repo package is the empty tree doing its job",+ classify(1, "ModuleNotFoundError: No module named 'app'", supplied),+ REFUSED,+ ),+ ("a timeout is neither", classify(None, "", supplied), INCONCLUSIVE),+ ]+ for read_label, (read, _why), read_want in reader:+ correct = read == read_want+ ok &= correct+ print(f" {'PASS' if correct else 'FAIL'} READER: {read_label}")+ print(f" expected {read_want} got {read}")++ # The invocation chooser. A quoted path inside an `echo` is the shape that+ # manufactured CI coverage for eleven services in another gate.+ chooser: list[tuple[str, list[str] | None, list[str] | None]] = [+ ("a plain invocation yields its arguments", _argv_after(shlex.split("python3 scripts/x.py --check"), "x.py"), ["--check"]),+ ("a quoted path in an echo is not an invocation", _argv_after(shlex.split('echo "scripts/x.py --check"'), "x.py"), None),+ ("an env prefix is stepped over", _argv_after(shlex.split("FOO=1 python scripts/x.py --check"), "x.py"), ["--check"]),+ ("uv run reaches the same place", _argv_after(shlex.split("uv run python scripts/x.py"), "x.py"), []),+ ("python -m runs a module, not this script", _argv_after(shlex.split("python3 -m pytest scripts/x.py"), "x.py"), None),+ ]+ for chosen_label, chosen, chosen_want in chooser:+ correct = chosen == chosen_want+ ok &= correct+ print(f" {'PASS' if correct else 'FAIL'} CHOOSER: {chosen_label}")+ print(f" expected {chosen_want} got {chosen}")++ replay: list[tuple[str, bool, bool]] = [+ ("an unexpanded shell variable is not replayable", _replayable(["--root", "$GITHUB_WORKSPACE"]), False),+ ("a path CI builds outside the checkout is not replayable", _replayable(["--old", "/tmp/base.yaml"]), False),+ ("a repository-relative path is", _replayable(["--new", "docs/openapi.yaml"]), True),+ ]+ for replay_label, replayed, replay_want in replay:+ correct = replayed == replay_want+ ok &= correct+ print(f" {'PASS' if correct else 'FAIL'} REPLAY: {replay_label}")+ print(f" expected {replay_want} got {replayed}")++ # And the scratch tree itself, because every result above is only as good+ # as the claim that the tree really has nothing in it.+ with scratch_tree() as tree:+ present = sorted(p.name for p in tree.iterdir() if p.name != ".git")+ toplevel = subprocess.run( # noqa: S603+ ["git", "rev-parse", "--show-toplevel"], cwd=tree, capture_output=True, text=True, check=False+ )+ isolated = Path(toplevel.stdout.strip() or "/nowhere").resolve() == tree.resolve()+ bare = present == ["scripts"]+ ok &= bare and isolated+ print(f" {'PASS' if bare else 'FAIL'} TREE: the scratch repository holds scripts/ and nothing else")+ print(f" contents {present}")+ print(f" {'PASS' if isolated else 'FAIL'} TREE: git inside it resolves to itself, not to the real checkout")++ print()+ if not ok:+ print("self-test FAILED: this gate did not catch drift it claims to catch")+ return 1+ print(f"self-test OK: {len(cases)} injected defects and {len(reader) + len(chooser) + len(replay) + 2} component assertions")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_gate_coverage.py b/scripts/check_gate_coverage.pyindex 5e9adefd3..1caa325bc 100644--- a/scripts/check_gate_coverage.py+++ b/scripts/check_gate_coverage.py@@ -60,6 +60,12 @@ from pathlib import Pathimport yaml+# `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+WORKFLOWS_REL = Path(".github/workflows")SCRIPTS_REL = Path("scripts")MAKEFILE_REL = Path("Makefile")@@ -107,7 +113,15 @@ _VERDICT_PREFIXES = ("--fail-", "--max-", "--require-", "--assert-")#: service (`inject_scenario.py` posts alerts, `generate_runbook.py` queries a#: tracing backend) exit non-zero when the network call fails, which is an#: operational error and not a finding about the tree.-_INSPECTS_TREE = re.compile(r"Path\(__file__\)|\.glob\(|\.rglob\(|\.iterdir\(|\.read_text\(|\.read_bytes\(|os\.walk\(")+#+# `repo_root(` is in the list because it replaced `Path(__file__)` as the way+# a gate names the tree it is about, and six gates had no other signal: the+# migration onto `gate_toolkit.repo_root()` silently dropped+# `check_prompt_lock.py`, `export_openapi.py` and four `sync_vendored_*`+# mirrors out of this inventory, which would have left deleting their+# workflow steps unnoticed. A classifier keyed on an idiom has to move when+# the idiom does.+_INSPECTS_TREE = re.compile(r"Path\(__file__\)|\brepo_root\(|\.glob\(|\.rglob\(|\.iterdir\(|\.read_text\(|\.read_bytes\(|os\.walk\(")#: Calls that grow a collection._MUTATORS = {"append", "add", "extend", "update"}@@ -691,7 +705,7 @@ def load(root: Path) -> dict: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("--repo-root", type=Path, default=repo_root())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")diff --git a/scripts/check_go_module_paths.py b/scripts/check_go_module_paths.pyindex adafcaa79..2db4a9361 100755--- a/scripts/check_go_module_paths.py+++ b/scripts/check_go_module_paths.py@@ -24,6 +24,14 @@ import subprocessimport sysfrom 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 self_test_if_requested++self_test_if_requested(__file__)+def _repo_root() -> Path:"""The repository, per git — not per this file's location.diff --git a/scripts/check_governance.py b/scripts/check_governance.pyindex d67c09799..5deeae996 100644--- a/scripts/check_governance.py+++ b/scripts/check_governance.py@@ -16,8 +16,15 @@ from __future__ import annotationsimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()# file → (min non-whitespace chars, [required substrings])_REQUIRED = {"GOVERNANCE.md": (600, ["maintainer", "Neutral home", "Decision-making"]),diff --git a/scripts/check_grafana_dashboards.py b/scripts/check_grafana_dashboards.pyindex a29731f32..8265cce2d 100644--- a/scripts/check_grafana_dashboards.py+++ b/scripts/check_grafana_dashboards.py@@ -23,7 +23,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()GRAFANA = REPO_ROOT / "infra" / "docker" / "grafana"DASHBOARDS = GRAFANA / "dashboards"DATASOURCES = GRAFANA / "datasources"diff --git a/scripts/check_investigation_depth.py b/scripts/check_investigation_depth.pyindex 7e9f598f1..d9616e003 100644--- a/scripts/check_investigation_depth.py+++ b/scripts/check_investigation_depth.py@@ -31,7 +31,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()AGENTS = REPO_ROOT / "services" / "agents"sys.path.insert(0, str(AGENTS))diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.pyindex 7809eab74..2d0ebcd52 100644--- a/scripts/check_mock_data_gated.py+++ b/scripts/check_mock_data_gated.py@@ -58,6 +58,14 @@ import pathlibimport reimport sys+# `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(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import self_test_if_requested++self_test_if_requested(__file__)+MOCK_NAME = r"(?:MOCK|DEMO|SAMPLE|FALLBACK)_[A-Z0-9_]+"#: A `fallbackData:` whose value mentions sample data. Whether it is gated isdiff --git a/scripts/check_playbook_schema_parity.py b/scripts/check_playbook_schema_parity.pyindex 2944c9b85..8954cc227 100644--- a/scripts/check_playbook_schema_parity.py+++ b/scripts/check_playbook_schema_parity.py@@ -40,6 +40,12 @@ import sysfrom dataclasses import dataclass, field, replacefrom 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+#: Playbook-level keys the schema declares that the runtime model does not#: bind. Both are authored documentation rather than engine inputs, and the#: schema says so in their ``description``. This list is a named exemption,@@ -125,7 +131,7 @@ def _find_repo_root(explicit: str | None) -> Path:run it from an installed package, and it grades whatever happens to sittwo directories up. Every marker below must exist or we refuse to run."""- root = Path(explicit).resolve() if explicit else Path(__file__).resolve().parent.parent+ root = Path(explicit).resolve() if explicit else repo_root()markers = (Path("schemas/playbook.schema.json"),Path("services/agents/app/playbook/engine.py"),diff --git a/scripts/check_prompt_lock.py b/scripts/check_prompt_lock.pyindex 46c36a8d6..4797f21b8 100644--- a/scripts/check_prompt_lock.py+++ b/scripts/check_prompt_lock.py@@ -16,9 +16,15 @@ import importlib.utilimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested+self_test_if_requested(__file__)++ROOT = repo_root()def _load_prompt_registry_module():"""Load prompt_registry.py by path so we don't trigger app/llm/__init__.py(which imports contract → structlog). This gate runs in the dep-light lintdiff --git a/scripts/check_published_packages.py b/scripts/check_published_packages.pyindex 9ab47703b..7079df105 100755--- a/scripts/check_published_packages.py+++ b/scripts/check_published_packages.py@@ -32,7 +32,15 @@ import urllib.parseimport urllib.requestfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()README = ROOT / "README.md"#: The phrase the README uses while nothing is published.diff --git a/scripts/check_repo_self_links.py b/scripts/check_repo_self_links.pyindex 45af2b073..9240e6f43 100644--- a/scripts/check_repo_self_links.py+++ b/scripts/check_repo_self_links.py@@ -31,8 +31,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()CANONICAL_OWNER = "beenuar"CANONICAL_REPO = "AiSOC"diff --git a/scripts/check_route_tenant_scope.py b/scripts/check_route_tenant_scope.pyindex b7748cc3a..9968a98fa 100644--- a/scripts/check_route_tenant_scope.py+++ b/scripts/check_route_tenant_scope.py@@ -609,13 +609,48 @@ async def queue(user: AuthUser, tenant_id: UUID):# like a decision somebody made rather than one that lapsed.failures += _self_test_stale_exemption()+ # Fourth: a scan that found no routes must not report on them. This gate+ # printed "scanned 0 routes across 0 files" and then "OK: every route+ # taking a tenant identifier authenticates" against a services/ directory+ # with nothing in it — the clean verdict CI shows on a real pass.+ failures += _self_test_empty_corpus()+if failures:print(f"\nself-test FAILED: {failures} case(s) did not behave as specified", file=sys.stderr)return 1- print("\nself-test passed: the gate detects drift in both directions, clears both clean controls, and drops a stale exemption.")+ print(+ "\nself-test passed: the gate detects drift in both directions, clears both clean controls, "+ "drops a stale exemption, and refuses a corpus it never found."+ )return 0+def _self_test_empty_corpus() -> int:+ """Point the scan at a services/ directory with no routes and require a refusal.++ The directory-missing guard is not this case. A corpus is lost by a+ renamed package, a changed decorator spelling or a walk that stops+ descending — none of which removes ``services/``, and all of which leave+ the gate with nothing to look at and a clean verdict to print.+ """+ global REPO_ROOT, SERVICES_DIR # noqa: PLW0603 - the scanned root is module state+ original_root, original_services = REPO_ROOT, SERVICES_DIR+ with tempfile.TemporaryDirectory(prefix="route_scope_empty_") as tmp:+ root = Path(tmp)+ (root / "services" / "api" / "app").mkdir(parents=True)+ (root / "services" / "api" / "app" / "nothing.py").write_text("VALUE = 1\n", encoding="utf-8")+ REPO_ROOT, SERVICES_DIR = root, root / "services"+ try:+ status = main([])+ finally:+ REPO_ROOT, SERVICES_DIR = original_root, original_services+ if status != 0:+ print(f" [PASS] empty corpus: a services/ tree with no routes exits {status} rather than reporting it clean")+ return 0+ print(" [FAIL] empty corpus: reported OK having scanned zero routes")+ return 1++def _self_test_stale_exemption() -> int:"""Assert IN_BAND_CREDENTIAL_ROUTES stops exempting once its verifier is gone.@@ -683,6 +718,23 @@ def main(argv: list[str] | None = None) -> int:files = len({r.path for r in routes})print(f"check_route_tenant_scope: scanned {len(routes)} routes across {files} files under {SERVICES_DIR}")+ # And refuse when it opened nothing. Naming the count was half the fix:+ # against a tree with a services/ directory and no routes in it, this+ # printed "scanned 0 routes across 0 files" and then "OK: every route+ # taking a tenant identifier authenticates" — a clean verdict on an empty+ # set, in the same sentence CI shows when the real scan passes. The+ # directory check above only catches services/ being absent altogether,+ # which is not how a scan loses its corpus: a renamed package, a changed+ # decorator spelling or a broken walk all leave the directory in place.+ if not routes:+ print(+ f"\nFAIL: no routes found under {SERVICES_DIR}. Zero routes scanned is not zero routes "+ "unscoped — either the walk, SERVICES_DIR or the decorator patterns have stopped "+ "describing where the routes are.",+ file=sys.stderr,+ )+ return 2+if unauthenticated:print(f"\nFAIL: {len(unauthenticated)} route(s) take a tenant identifier with no auth dependency.", file=sys.stderr)print(" The tenant is whatever the caller typed. Derive it from the authenticated principal.", file=sys.stderr)diff --git a/scripts/check_scoreboard.py b/scripts/check_scoreboard.pyindex 58543843b..5c46f22d4 100644--- a/scripts/check_scoreboard.py+++ b/scripts/check_scoreboard.py@@ -37,7 +37,15 @@ import sysfrom datetime import datefrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()SCOREBOARD = ROOT / "apps" / "docs" / "static" / "data" / "scoreboard.json"SCHEMA = ROOT / "apps" / "docs" / "static" / "data" / "scoreboard.schema.json"_AGENTS = ROOT / "services" / "agents"diff --git a/scripts/check_slos.py b/scripts/check_slos.pyindex ca3007934..25e0726ba 100644--- a/scripts/check_slos.py+++ b/scripts/check_slos.py@@ -21,7 +21,15 @@ from pathlib import Pathimport yaml-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()SLOS = ROOT / "docs" / "operations" / "slos.yaml"SERVICES_DIR = ROOT / "services"diff --git a/scripts/check_sqlglot_pin.py b/scripts/check_sqlglot_pin.pyindex 4a6da8783..572afbd6e 100644--- a/scripts/check_sqlglot_pin.py+++ b/scripts/check_sqlglot_pin.py@@ -27,8 +27,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()# Every file that installs sqlglot for a build or a test run. A new one must# be added here; `test_every_declaration_is_registered` below is the backstop# that notices when a declaration exists in a file this list does not name.diff --git a/scripts/check_store_migrations.py b/scripts/check_store_migrations.pyindex 6376ceed2..b816b8c23 100644--- a/scripts/check_store_migrations.py+++ b/scripts/check_store_migrations.py@@ -30,8 +30,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()#: store -> (runner module, the file that must call it, the symbol it calls)#:#: The call site is named explicitly rather than searched for, because "somediff --git a/scripts/check_toolchain_versions.py b/scripts/check_toolchain_versions.pyindex ee26afba6..11adb7cac 100644--- a/scripts/check_toolchain_versions.py+++ b/scripts/check_toolchain_versions.py@@ -19,7 +19,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()WORKFLOWS = REPO_ROOT / ".github" / "workflows"diff --git a/scripts/connector_conformance.py b/scripts/connector_conformance.pyindex ea2b0b7fa..275b4b7a3 100644--- a/scripts/connector_conformance.py+++ b/scripts/connector_conformance.py@@ -31,7 +31,15 @@ import jsonimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()sys.path.insert(0, str(ROOT / "services" / "connectors"))DOC = ROOT / "docs" / "connectors" / "conformance-matrix.md"diff --git a/scripts/curate_detections.py b/scripts/curate_detections.pyindex 79ee25460..1f6ca3e70 100644--- a/scripts/curate_detections.py+++ b/scripts/curate_detections.py@@ -76,7 +76,15 @@ from typing import Anyimport yaml-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()DETECTIONS_DIR = REPO_ROOT / "detections"OUT_MANIFEST = REPO_ROOT / "marketplace" / "curated.json"OUT_REPORT = REPO_ROOT / "apps" / "docs" / "docs" / "detections" / "coverage.md"diff --git a/scripts/detection_truth_table.py b/scripts/detection_truth_table.pyindex ea623aafc..663eb788b 100644--- a/scripts/detection_truth_table.py+++ b/scripts/detection_truth_table.py@@ -59,7 +59,15 @@ from pathlib import Pathimport yaml-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()DETECTIONS = ROOT / "detections"DOC = ROOT / "docs" / "detections" / "truth-table.md"diff --git a/scripts/export_detection_ruleset.py b/scripts/export_detection_ruleset.pyindex 33da37308..266dfae62 100644--- a/scripts/export_detection_ruleset.py+++ b/scripts/export_detection_ruleset.py@@ -24,7 +24,15 @@ import jsonimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()sys.path.insert(0, str(ROOT / "scripts"))OUT = ROOT / "services" / "fusion" / "app" / "data" / "detection_ruleset.json"diff --git a/scripts/export_graph_schema.py b/scripts/export_graph_schema.pyindex 33afb1a34..56432714e 100755--- a/scripts/export_graph_schema.py+++ b/scripts/export_graph_schema.py@@ -50,7 +50,15 @@ from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()DEFAULT_YAML = REPO_ROOT / "schemas" / "graph-schema.yaml"DEFAULT_CURRENT_YAML = REPO_ROOT / "schemas" / "graph-schema-current.yaml"DEFAULT_GO_SOURCE = REPO_ROOT / "services" / "ingest" / "internal" / "graph" / "schema.go"diff --git a/scripts/export_openapi.py b/scripts/export_openapi.pyindex d96891816..588a0bfe7 100755--- a/scripts/export_openapi.py+++ b/scripts/export_openapi.py@@ -22,8 +22,16 @@ import osimport sysfrom 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_if_requested++self_test_if_requested(__file__)+# ── Ensure the api service is importable ─────────────────────────────────────-REPO_ROOT = Path(__file__).resolve().parents[1]+REPO_ROOT = repo_root()API_SRC = REPO_ROOT / "services" / "api"if str(API_SRC) not in sys.path:sys.path.insert(0, str(API_SRC))diff --git a/scripts/export_windowed_ruleset.py b/scripts/export_windowed_ruleset.pyindex d5b346104..cf9d2cc5e 100644--- a/scripts/export_windowed_ruleset.py+++ b/scripts/export_windowed_ruleset.py@@ -39,7 +39,15 @@ import jsonimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()OUT = ROOT / "services" / "fusion" / "app" / "data" / "windowed_ruleset.json"#: Windowed rules, authored here rather than in the engine module.diff --git a/scripts/gate_toolkit.py b/scripts/gate_toolkit.pynew file mode 100644index 000000000..6716954bc--- /dev/null+++ b/scripts/gate_toolkit.py@@ -0,0 +1,248 @@+#!/usr/bin/env python3+"""The two things every gate in this tree has to get right, implemented once.++Why this exists+---------------+A gate is only worth the tree it opened. Copying ``scripts/`` into an empty+git repository and running every wired check there found five that reported+OK over a repository containing nothing: the detection validator certified+zero rules as valid, the dashboard check forgave a *missing* directory while+failing an empty one, the Go module check reported ``OK: 0 published module+path(s)``, the self-link check called every link healthy over zero files, and+the health-probe audit printed a table header and exited 0.++Two root causes ran through all five, and neither is specific to those five:++``__file__`` as the repository root+ ``Path(__file__).resolve().parent.parent`` is whatever happens to sit two+ levels above the script. A copy of the script run from somewhere else+ scans that other tree and prints a confident OK about a checkout the+ caller never meant. Asking git instead makes the answer describe a real+ repository or fail loudly.++"found nothing" and "scanned nothing" print the same word+ A gate that walks zero files finds zero violations. Unless it counts what+ it opened and refuses an empty read, the clean result is indistinguishable+ from a broken glob, a wrong root, or a tree that is not there at all.++So both live here rather than in each gate. Five near-identical copies of the+git resolution had already accumulated across ``scripts/``, which is how the+sixth gets written subtly differently.++Nothing here imports anything outside the standard library: several gates run+on a bare interpreter before any ``pip install``, and a toolkit that drags in+a dependency would take that away from them.+"""++from __future__ import annotations++import ast+import os+import shutil+import subprocess+import sys+import tempfile+from collections.abc import Iterator, Sequence+from contextlib import contextmanager+from pathlib import Path++__all__ = [+ "SELF_TEST_FLAG",+ "VERDICT_FLAG_PREFERENCE",+ "verdict_args",+ "repo_root",+ "scratch_tree",+ "run_in_scratch_tree",+ "refuses_an_empty_tree",+ "self_test_main",+ "self_test_if_requested",+]++#: The flag every gate answers to. Named once so the meta-gate that looks for+#: it and the gates that declare it cannot disagree about the spelling.+SELF_TEST_FLAG = "--self-test"++#: The flags that turn a run into a verdict, most specific first. Several+#: scripts here are a generator and a gate in one file — ``build_marketplace``+#: with no arguments *writes* the index and only ``--check`` compares it — so+#: "run it with no arguments" is not the same question as "ask it for a+#: verdict", and probing the wrong half reports that writing an empty index+#: over an empty tree credits nothing. True of every generator, and nothing to+#: do with the gate. Defined here and imported by ``check_gate_contract`` so+#: the self-test and the meta-gate cannot pick different halves.+VERDICT_FLAG_PREFERENCE = ("--check", "--check-only", "--strict", "--verify")++#: Environment that would redirect a gate away from the tree under test.+#: ``security_audit.py`` prefers ``GITHUB_WORKSPACE`` over anything it can+#: work out for itself, so a scratch run under Actions would otherwise read+#: the real checkout and report on the wrong tree entirely.+_ROOT_OVERRIDES = ("AISOC_REPO_ROOT", "GITHUB_WORKSPACE")+++def repo_root(start: Path | None = None) -> Path:+ """The repository, per git — not per this file's location.++ ``start`` is the directory the question is asked from, and defaults to+ ``scripts/``: every gate lives there, so the answer is "the tree these+ gates belong to" rather than "wherever the caller happened to be".++ ``AISOC_REPO_ROOT`` overrides, which is how a caller points a gate at a+ tree deliberately. Falling back to the ``__file__`` walk is fine when+ there is no git — a release tarball, a container build context — but+ falling back *silently* is not, because the caller would never learn+ which tree was read.+ """+ override = os.environ.get("AISOC_REPO_ROOT")+ if override:+ return Path(override).resolve()++ here = Path(__file__).resolve().parent+ out = subprocess.run( # noqa: S603 - fixed argv, no shell+ ["git", "rev-parse", "--show-toplevel"],+ capture_output=True,+ text=True,+ check=False,+ cwd=start or here,+ )+ if out.returncode == 0 and out.stdout.strip():+ return Path(out.stdout.strip()).resolve()++ fallback = here.parent+ print(+ f"{Path(sys.argv[0]).name}: not a git checkout — falling back to {fallback}",+ file=sys.stderr,+ )+ return fallback+++@contextmanager+def scratch_tree(source: Path | None = None) -> Iterator[Path]:+ """A git repository holding this repository's ``scripts/`` and nothing else.++ Not an empty directory: the gate under test has to be *runnable*, which+ means its own file and the siblings it imports have to be present. What+ is absent is everything a gate renders a verdict about — ``services/``,+ ``detections/``, ``apps/``, ``packages/``, ``docs/``, ``.github/``. A gate+ pointed here has nothing to inspect, so anything other than a refusal is+ a result it invented.++ It is a real git repository with a commit, because a gate that resolves+ its root through ``git rev-parse`` must land *here* and not walk out into+ the checkout the scratch directory happens to sit inside.+ """+ scripts = (source or Path(__file__).resolve().parent).resolve()+ if not scripts.is_dir():+ raise FileNotFoundError(f"no scripts directory to copy from: {scripts}")++ tmp = Path(tempfile.mkdtemp(prefix="aisoc-empty-tree-"))+ try:+ shutil.copytree(scripts, tmp / "scripts")+ git = ["git", "-c", "user.name=gate", "-c", "user.email=gate@invalid", "-c", "commit.gpgsign=false"]+ for argv in (["init", "-q", "-b", "main"], ["add", "-A"], ["commit", "-qm", "scratch"]):+ subprocess.run(git + argv, cwd=tmp, check=True, capture_output=True) # noqa: S603+ yield tmp+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+++def run_in_scratch_tree(+ script: str,+ args: Sequence[str] = (),+ *,+ tree: Path,+ timeout: int = 180,+) -> tuple[int | None, str]:+ """Run ``scripts/<script>`` inside ``tree``. Returns (exit status, output).++ ``None`` for the status means the run timed out, which is neither a pass+ nor a refusal and is reported as such rather than rounded to either.+ """+ env = {k: v for k, v in os.environ.items() if k not in _ROOT_OVERRIDES}+ env["PYTHONDONTWRITEBYTECODE"] = "1"+ try:+ done = subprocess.run( # noqa: S603+ [sys.executable, str(Path("scripts") / script), *args],+ cwd=tree,+ capture_output=True,+ text=True,+ timeout=timeout,+ env=env,+ )+ except subprocess.TimeoutExpired:+ return None, f"timed out after {timeout}s"+ return done.returncode, (done.stdout or "") + (done.stderr or "")+++def refuses_an_empty_tree(script: str, args: Sequence[str] = ()) -> tuple[bool, str]:+ """Whether ``script`` declines to render a verdict about a tree with no content."""+ with scratch_tree() as tree:+ status, output = run_in_scratch_tree(script, args, tree=tree)+ if status is None:+ return False, output+ tail = "\n".join(line for line in output.strip().splitlines() if line.strip())[-400:]+ return status != 0, f"exit {status}\n{tail}" if tail else f"exit {status}"+++def self_test_main(script: str, args: Sequence[str] = (), extra: Sequence[tuple[str, bool]] = ()) -> int:+ """The shared ``--self-test`` body: prove the gate fails closed on nothing.++ ``extra`` carries results a gate has already computed for cases only it+ can express — an injected violation of the specific rule it enforces.+ Those are printed alongside so one command answers "does this gate still+ work", which is the point of running a self-test before the gate itself.+ """+ ok = True+ for description, passed in extra:+ ok &= passed+ print(f" {'PASS' if passed else 'FAIL'} {description}")++ refused, detail = refuses_an_empty_tree(script, args)+ ok &= refused+ print(f" {'PASS' if refused else 'FAIL'} refuses a tree with no content rather than reporting it clean")+ for line in detail.splitlines():+ print(f" {line}")++ print()+ if not ok:+ print(f"{script}: self-test FAILED")+ return 1+ print(f"{script}: self-test OK")+ return 0+++def verdict_args(script: Path) -> list[str]:+ """The arguments that ask ``script`` for a verdict, read from its own source.++ Read rather than passed, so a gate that grows a ``--check`` mode does not+ have to remember to tell its self-test about it.+ """+ try:+ source = script.read_text(encoding="utf-8", errors="replace")+ except OSError:+ return []+ declared = {+ node.value for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Constant) and node.value in VERDICT_FLAG_PREFERENCE+ }+ return next(([flag] for flag in VERDICT_FLAG_PREFERENCE if flag in declared), [])+++def self_test_if_requested(script_path: str, args: Sequence[str] | None = None) -> None:+ """Answer ``--self-test`` and exit, for gates with nothing bespoke to add.++ Installed as one statement just below a gate's imports, so it runs before+ the gate touches anything — which is the point of a self-test. Two things+ keep it from firing when it should not:++ * it only acts when the flag is on the command line, so an ordinary run is+ untouched;+ * it only acts when the process was launched as *this* script. Gates in+ this tree import one another (``check_route_auth`` imports+ ``check_route_tenant_scope``), and without that guard the imported+ module would answer a flag meant for its importer.+ """+ if SELF_TEST_FLAG not in sys.argv[1:]:+ return+ if Path(sys.argv[0]).name != Path(script_path).name:+ return+ script = Path(script_path)+ sys.exit(self_test_main(script.name, verdict_args(script) if args is None else args))diff --git a/scripts/generate_connector_count.py b/scripts/generate_connector_count.pyindex 7e570b7ad..04a348a32 100755--- a/scripts/generate_connector_count.py+++ b/scripts/generate_connector_count.py@@ -43,7 +43,15 @@ from collections import Counterfrom pathlib import Pathfrom typing import Any-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()REGISTRY_FILE = REPO_ROOT / "services" / "connectors" / "app" / "connectors" / "__init__.py"CONNECTORS_DIR = REPO_ROOT / "services" / "connectors" / "app" / "connectors"JSON_OUT = REPO_ROOT / "apps" / "web" / "src" / "data" / "connector-count.json"diff --git a/scripts/generate_connector_docs.py b/scripts/generate_connector_docs.pyindex d447c727e..c53292b22 100644--- a/scripts/generate_connector_docs.py+++ b/scripts/generate_connector_docs.py@@ -37,7 +37,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()CONNECTORS_SRC = REPO_ROOT / "services" / "connectors"DOCS_DIR = REPO_ROOT / "apps" / "docs" / "docs" / "connectors"SIDEBAR = REPO_ROOT / "apps" / "docs" / "sidebars.ts"diff --git a/scripts/generate_connector_types.py b/scripts/generate_connector_types.pyindex 370cc42da..00bae7e99 100644--- a/scripts/generate_connector_types.py+++ b/scripts/generate_connector_types.py@@ -83,6 +83,12 @@ import reimport sysfrom 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+REGISTRY_REL = Path("services/connectors/app/connectors/__init__.py")CONNECTORS_REL = Path("services/connectors/app/connectors")NORMALIZER_REL = Path("services/ingest/internal/normalizer/normalizer.go")@@ -374,7 +380,7 @@ def _read(path: Path) -> str | None: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("--repo-root", type=Path, default=repo_root())parser.add_argument("--check", action="store_true", help="fail (exit 1) on drift instead of rewriting the outputs")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")diff --git a/scripts/generate_detections.py b/scripts/generate_detections.pyindex 0b9ea2ce0..6b245a7e1 100644--- a/scripts/generate_detections.py+++ b/scripts/generate_detections.py@@ -44,6 +44,14 @@ import sysfrom pathlib import Pathfrom typing import Any+# `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_if_requested++self_test_if_requested(__file__)+try:import yamlexcept ImportError:@@ -52,7 +60,7 @@ except ImportError:sys.exit(1)raise-ROOT = Path(__file__).parent.parent+ROOT = repo_root()DETECTIONS_DIR = ROOT / "detections"SCRIPTS_DIR = ROOT / "scripts"diff --git a/scripts/generate_slo_alerts.py b/scripts/generate_slo_alerts.pyindex 800f1a818..b1ed8e618 100644--- a/scripts/generate_slo_alerts.py+++ b/scripts/generate_slo_alerts.py@@ -34,13 +34,21 @@ import reimport sysfrom 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_if_requested++self_test_if_requested(__file__)+try:import yamlexcept ImportError: # pragma: no coverprint("PyYAML is required: pip install pyyaml", file=sys.stderr)raise SystemExit(2) from None-REPO_ROOT = Path(__file__).resolve().parent.parent+REPO_ROOT = repo_root()SLOS = REPO_ROOT / "docs" / "operations" / "slos.yaml"PROMETHEUS = REPO_ROOT / "infra" / "docker" / "prometheus.yml"OUTPUT = REPO_ROOT / "infra" / "docker" / "alerts" / "slo.rules.yml"diff --git a/scripts/lint_playbooks.py b/scripts/lint_playbooks.pyindex d2df40876..4a4fd1f1e 100755--- a/scripts/lint_playbooks.py+++ b/scripts/lint_playbooks.py@@ -20,13 +20,21 @@ import jsonimport sysfrom 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_if_requested++self_test_if_requested(__file__)+try:import jsonschemaexcept ImportError:print("ERROR: jsonschema not installed. Run: pip install jsonschema", file=sys.stderr)sys.exit(1)-REPO_ROOT = Path(__file__).resolve().parent.parent+REPO_ROOT = repo_root()SCHEMA_PATH = REPO_ROOT / "schemas" / "playbook.schema.json"# Directories scanned for loose ``*.json`` playbooks.diff --git a/scripts/list_python_services_with_tests.py b/scripts/list_python_services_with_tests.pyindex f28dcb145..5bbe7942b 100755--- a/scripts/list_python_services_with_tests.py+++ b/scripts/list_python_services_with_tests.py@@ -35,7 +35,15 @@ import argparseimport pathlibimport sys-REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent+# `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(pathlib.Path(__file__).resolve().parent))++from gate_toolkit import repo_root, self_test_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SERVICES_DIR = REPO_ROOT / "services"WORKFLOW = REPO_ROOT / ".github" / "workflows" / "ci.yml"diff --git a/scripts/openapi_diff.py b/scripts/openapi_diff.pyindex db5f87d12..b564894da 100644--- a/scripts/openapi_diff.py+++ b/scripts/openapi_diff.py@@ -44,6 +44,14 @@ from typing import Anyimport yaml+# `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 self_test_if_requested++self_test_if_requested(__file__)+# Schema-name suffixes that indicate a request body (tightening these breaks# callers). Response-shaped schemas don't break a caller when a new optional# field appears, so a *new* required field only counts as breaking here.diff --git a/scripts/project_stats.py b/scripts/project_stats.pyindex 95c17abc6..36055c9b2 100755--- a/scripts/project_stats.py+++ b/scripts/project_stats.py@@ -33,9 +33,15 @@ import reimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested+self_test_if_requested(__file__)++ROOT = repo_root()def _connectors() -> int | None:"""Registered connector classes, read from the registry literal."""init = ROOT / "services" / "connectors" / "app" / "connectors" / "__init__.py"diff --git a/scripts/readme_gates.py b/scripts/readme_gates.pyindex db5b4e2dc..bde8e5f45 100644--- a/scripts/readme_gates.py+++ b/scripts/readme_gates.py@@ -38,7 +38,15 @@ from pathlib import Pathfrom urllib.error import HTTPError, URLErrorfrom urllib.request import Request, urlopen-REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()README = REPO_ROOT / "README.md"# Anything in this list is permitted to appear in README without resolvingdiff --git a/scripts/run_evals.py b/scripts/run_evals.pyindex 10926fbaf..ba7b922ab 100644--- a/scripts/run_evals.py+++ b/scripts/run_evals.py@@ -59,7 +59,15 @@ import timefrom datetime import UTC, datetimefrom pathlib import Path-_REPO_ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++_REPO_ROOT = repo_root()_AGENTS_ROOT = _REPO_ROOT / "services" / "agents"# Order matters: scripts/ also contains a tests/ package (scripts/tests/) for# the CLI smoke test, and would shadow services/agents/tests/ if it landed atdiff --git a/scripts/security_audit.py b/scripts/security_audit.pyindex 7e475a3e1..34765a3c0 100644--- a/scripts/security_audit.py+++ b/scripts/security_audit.py@@ -33,6 +33,14 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any+# `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_if_requested++self_test_if_requested(__file__, ["python"])+# ─── Data types ───────────────────────────────────────────────────────────────SEVERITY_ORDER = {"info": 0, "low": 1, "moderate": 2, "high": 3, "critical": 4}@@ -187,6 +195,15 @@ def classify_pnpm_audit(audit_json: dict[str, Any], ignores: list[Ignore]) -> Redef run_pnpm_audit(repo_root: Path, ignores: list[Ignore]) -> Report:"""Run pnpm audit with fallback registry on 403."""+ lockfile = repo_root / "pnpm-lock.yaml"+ if not lockfile.is_file():+ # `pnpm audit` in a directory with no lockfile has nothing to resolve+ # and can still answer with an empty advisory set. Refuse instead:+ # the workspace the audit is supposed to cover is not there.+ report = Report()+ report.unscanned.append(f"no pnpm-lock.yaml at {lockfile} — the workspace was NOT scanned")+ return report+fallback = os.environ.get("PNPM_AUDIT_REGISTRY", "https://registry.npmjs.org/")for attempt, registry in enumerate([None, fallback]):@@ -318,6 +335,17 @@ def _export_requirements(service_dir: Path, work_dir: Path) -> Path | None:return req_path+def _python_manifests(repo_root: Path) -> list[Path]:+ """Every service or package directory holding a ``pyproject.toml``."""+ found: list[Path] = []+ for search_dir in ("services", "packages"):+ parent = repo_root / search_dir+ if not parent.is_dir():+ continue+ found.extend(child for child in sorted(parent.iterdir()) if child.is_dir() and (child / "pyproject.toml").exists())+ return found++def run_pip_audit(repo_root: Path, ignores: list[Ignore]) -> Report:"""Run pip-audit on all Python services with pyproject.toml.@@ -326,63 +354,61 @@ def run_pip_audit(repo_root: Path, ignores: list[Ignore]) -> Report:2. pip-audit -r requirements.txt --format json"""combined = Report()+ manifests = _python_manifests(repo_root)+ if not manifests:+ # Zero manifests discovered is not zero manifests vulnerable. The arm+ # would otherwise print "python: 0 findings" over a tree with nothing+ # in it, which is the same sentence a clean audit of twenty services+ # prints. Recorded as unscanned so `exit_code_for` fails.+ combined.unscanned.append(f"no pyproject.toml under services/ or packages/ in {repo_root} — NOTHING was scanned")+ return combinedwith tempfile.TemporaryDirectory(prefix="security_audit_py_") as tmp:tmp_root = Path(tmp)- for search_dir in ["services", "packages"]:- parent = repo_root / search_dir- if not parent.exists():+ for child in manifests:+ target = str(child.relative_to(repo_root))+ safe_name = target.replace("/", "__")+ work_dir = tmp_root / safe_name+ work_dir.mkdir(parents=True, exist_ok=True)++ req_path = _export_requirements(child, work_dir)+ if req_path is None:+ # Not a warning: this service is now unscanned, and the+ # usual cause is a poetry.lock whose content hash no longer+ # matches pyproject.toml. Recorded so `exit_code_for` can+ # fail rather than letting coverage silently shrink.+ combined.unscanned.append(f"{target}: poetry export failed (stale poetry.lock?) — NOT scanned")continue- for child in sorted(parent.iterdir()):- if not child.is_dir():- continue- pyproject = child / "pyproject.toml"- if not pyproject.exists():- continue-- target = str(child.relative_to(repo_root))- safe_name = target.replace("/", "__")- work_dir = tmp_root / safe_name- work_dir.mkdir(parents=True, exist_ok=True)-- req_path = _export_requirements(child, work_dir)- if req_path is None:- # Not a warning: this service is now unscanned, and the- # usual cause is a poetry.lock whose content hash no longer- # matches pyproject.toml. Recorded so `exit_code_for` can- # fail rather than letting coverage silently shrink.- combined.unscanned.append(f"{target}: poetry export failed (stale poetry.lock?) — NOT scanned")- continue-- try:- cmd = [- "pip-audit",- "-r",- str(req_path),- "--format",- "json",- "--progress-spinner",- "off",- ]-- proc = subprocess.run(cmd, capture_output=True, text=True, cwd=repo_root)- except FileNotFoundError:- combined.unscanned.append("pip-audit not found on PATH — NO Python service was scanned")- break-- if proc.returncode not in (0, 1):- # pip-audit returns 1 when vulns found; anything else means- # it did not complete, so this service is unscanned too.- combined.unscanned.append(- f"{target}: pip-audit exited {proc.returncode} — NOT scanned " f"({proc.stderr[:160].strip()})"- )- continue-- deps = parse_pip_audit_json(proc.stdout)- sub = classify_pip_audit(target, deps, ignores)- combined.findings.extend(sub.findings)- combined.ignored.extend(sub.ignored)++ try:+ cmd = [+ "pip-audit",+ "-r",+ str(req_path),+ "--format",+ "json",+ "--progress-spinner",+ "off",+ ]++ proc = subprocess.run(cmd, capture_output=True, text=True, cwd=repo_root)+ except FileNotFoundError:+ combined.unscanned.append("pip-audit not found on PATH — NO Python service was scanned")+ break++ if proc.returncode not in (0, 1):+ # pip-audit returns 1 when vulns found; anything else means+ # it did not complete, so this service is unscanned too.+ combined.unscanned.append(+ f"{target}: pip-audit exited {proc.returncode} — NOT scanned " f"({proc.stderr[:160].strip()})"+ )+ continue++ deps = parse_pip_audit_json(proc.stdout)+ sub = classify_pip_audit(target, deps, ignores)+ combined.findings.extend(sub.findings)+ combined.ignored.extend(sub.ignored)return combined@@ -460,6 +486,12 @@ def run_govulncheck(repo_root: Path, ignores: list[Ignore]) -> Report:if parent.exists():go_mods.extend(sorted(parent.rglob("go.mod")))+ if not go_mods:+ # Same reason as the Python arm: "go: 0 findings" over a tree with no+ # go.mod in it reads exactly like a clean scan of every Go module.+ combined.unscanned.append(f"no go.mod under services/ or packages/ in {repo_root} — NOTHING was scanned")+ return combined+for go_mod in go_mods:module_dir = go_mod.parentmodule = str(module_dir.relative_to(repo_root))@@ -578,14 +610,16 @@ def exit_code_for(report: Report) -> int:def get_repo_root() -> Path:- workspace = os.environ.get("GITHUB_WORKSPACE")- if workspace:- return Path(workspace)- # Walk up from this script to find the repo root (contains .git/)- p = Path(__file__).resolve().parent.parent- if (p / ".git").exists():- return p- return Path.cwd()+ """The repository, per git.++ This used to prefer ``GITHUB_WORKSPACE``, then a ``.git`` probe two levels+ above this file, then ``Path.cwd()``. The last of those is the dangerous+ one: run from anywhere else it returns that directory, and the audit then+ scans whatever manifests happen to be under it and reports success. Under+ Actions the environment variable and ``git rev-parse`` name the same+ directory anyway, so nothing is lost by asking git.+ """+ return repo_root()def get_ignores_path() -> Path:@@ -593,13 +627,27 @@ def get_ignores_path() -> Path:def cmd_validate_ignores(args: argparse.Namespace) -> int:+ """Validate the suppression file, and refuse to validate one that is not there.++ ``load_ignores`` returns an empty list for a file that does not exist, so+ this printed "Validated 0 ignore entries." and exited 0 against a+ repository containing nothing at all — the same sentence, and the same+ exit status, as a real run over a file with every suppression retired.+ Found nothing and scanned nothing are not the same result, and the one+ that matters here is the one where the policy file has gone missing.+ """+ path = get_ignores_path()+ if not path.is_file():+ print(f"Ignore policy error: {path} does not exist — refusing to report a validated policy with no policy file.", file=sys.stderr)+ return 1+ lines = path.read_text(encoding="utf-8").splitlines()try:- ignores = load_ignores(get_ignores_path())- print(f"Validated {len(ignores)} ignore entries.")- return 0+ ignores = load_ignores(path)except ValueError as e:print(f"Ignore policy error: {e}", file=sys.stderr)return 1+ print(f"Validated {len(ignores)} ignore entries from {path} ({len(lines)} lines read).")+ return 0def cmd_pnpm(args: argparse.Namespace) -> int:diff --git a/scripts/storage_cost_model.py b/scripts/storage_cost_model.pyindex 11dc95fa2..5f33cb96a 100644--- a/scripts/storage_cost_model.py+++ b/scripts/storage_cost_model.py@@ -27,7 +27,15 @@ import jsonimport sysfrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()COMMITTED = ROOT / "docs" / "decisions" / "storage-cost-model.json"# Reference list prices, USD per GB-month. VERIFY against your provider/region.diff --git a/scripts/sync_vendored_llm_contract.py b/scripts/sync_vendored_llm_contract.pyindex cfb2b8341..de48a5b29 100755--- a/scripts/sync_vendored_llm_contract.py+++ b/scripts/sync_vendored_llm_contract.py@@ -29,7 +29,15 @@ import shutilimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SOURCE_FILE = REPO_ROOT / "services" / "agents" / "app" / "llm" / "contract_rules.py"VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "llm_contract_rules.py"diff --git a/scripts/sync_vendored_narrative.py b/scripts/sync_vendored_narrative.pyindex 24563f612..924c5c000 100755--- a/scripts/sync_vendored_narrative.py+++ b/scripts/sync_vendored_narrative.py@@ -31,7 +31,15 @@ import shutilimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SOURCE_FILE = REPO_ROOT / "services" / "fusion" / "app" / "services" / "narrative.py"VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "narrative.py"diff --git a/scripts/sync_vendored_nl_query.py b/scripts/sync_vendored_nl_query.pyindex f04d42dc0..3a37d8121 100755--- a/scripts/sync_vendored_nl_query.py+++ b/scripts/sync_vendored_nl_query.py@@ -26,7 +26,15 @@ import shutilimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SOURCE_DIR = REPO_ROOT / "services" / "agents" / "app" / "nl_query"VENDORED_DIR = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "nl_query"diff --git a/scripts/sync_vendored_redactor.py b/scripts/sync_vendored_redactor.pyindex cfc54c0dc..94b6a1b36 100644--- a/scripts/sync_vendored_redactor.py+++ b/scripts/sync_vendored_redactor.py@@ -29,7 +29,15 @@ import shutilimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SOURCE_FILE = REPO_ROOT / "services" / "agents" / "app" / "privacy" / "redactor.py"VENDORED_FILE = REPO_ROOT / "services" / "api" / "app" / "_vendor" / "redactor.py"diff --git a/scripts/sync_vendored_tenant_scope.py b/scripts/sync_vendored_tenant_scope.pyindex 120008065..62d953e7d 100644--- a/scripts/sync_vendored_tenant_scope.py+++ b/scripts/sync_vendored_tenant_scope.py@@ -30,7 +30,15 @@ import reimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SOURCE_FILE = REPO_ROOT / "services" / "fusion" / "app" / "security" / "tenant_scope.py"#: The test travels with the module. Each service runs the copy it shipsdiff --git a/scripts/sync_vendored_verdict.py b/scripts/sync_vendored_verdict.pyindex 8ce0553f3..de25e3a08 100644--- a/scripts/sync_vendored_verdict.py+++ b/scripts/sync_vendored_verdict.py@@ -26,7 +26,15 @@ import shutilimport sysfrom pathlib import Path-REPO_ROOT = Path(__file__).resolve().parents[1]+# `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_if_requested++self_test_if_requested(__file__)++REPO_ROOT = repo_root()SRC_DIR = REPO_ROOT / "packages" / "aisoc-lite" / "src" / "verdict"DST_DIR = REPO_ROOT / "packages" / "aisoc-action" / "src" / "_vendor" / "verdict"FILES = ("types.ts", "stages.ts", "engine.ts")diff --git a/scripts/tests/test_security_audit.py b/scripts/tests/test_security_audit.pyindex a1e57a9e8..c43f48a9f 100644--- a/scripts/tests/test_security_audit.py+++ b/scripts/tests/test_security_audit.py@@ -2,6 +2,7 @@from __future__ import annotations+import argparseimport datetime as dtimport textwrapfrom pathlib import Path@@ -26,6 +27,7 @@ from security_audit import (parse_govulncheck_json,parse_pip_audit_json,run_govulncheck,+ run_pip_audit,run_pnpm_audit,)@@ -490,6 +492,11 @@ class _Proc:class TestPnpmCoverageGaps:+ @staticmethod+ def _workspace(tmp_path: Path) -> Path:+ (tmp_path / "pnpm-lock.yaml").write_text("lockfileVersion: '9.0'\n")+ return tmp_path+def test_unparseable_output_is_a_coverage_gap_not_a_warning(self, monkeypatch, tmp_path: Path):"""pnpm audit that returns garbage has audited nothing.@@ -503,7 +510,7 @@ class TestPnpmCoverageGaps:lambda *a, **k: _Proc(returncode=1, stdout="<html>not json</html>"),)- report = run_pnpm_audit(tmp_path, [])+ report = run_pnpm_audit(self._workspace(tmp_path), [])assert report.unscanned, "unparseable pnpm output must be recorded as a coverage gap"assert not report.findings@@ -516,12 +523,52 @@ class TestPnpmCoverageGaps:lambda *a, **k: _Proc(returncode=0, stdout='{"advisories": {}}'),)- report = run_pnpm_audit(tmp_path, [])+ report = run_pnpm_audit(self._workspace(tmp_path), [])assert report.unscanned == []assert exit_code_for(report) == 0+class TestNothingToScanIsNotACleanScan:+ """Zero targets discovered is a coverage gap, not a clean result.++ Every arm of this audit printed "N findings" and exited 0 against a+ directory with no manifests in it — the same sentence, and the same exit+ status, as a clean audit of the real workspace. Found nothing and scanned+ nothing are different results and only one of them is good news.+ """++ def test_pnpm_refuses_a_workspace_with_no_lockfile(self, tmp_path: Path):+ report = run_pnpm_audit(tmp_path, [])++ assert report.unscanned, "no pnpm-lock.yaml must be a coverage gap"+ assert exit_code_for(report) == 1++ def test_python_refuses_a_tree_with_no_manifests(self, tmp_path: Path):+ report = run_pip_audit(tmp_path, [])++ assert report.unscanned, "no pyproject.toml anywhere must be a coverage gap"+ assert exit_code_for(report) == 1++ def test_go_refuses_a_tree_with_no_modules(self, tmp_path: Path):+ report = run_govulncheck(tmp_path, [])++ assert report.unscanned, "no go.mod anywhere must be a coverage gap"+ assert exit_code_for(report) == 1++ def test_validate_ignores_refuses_a_missing_policy_file(self, monkeypatch, tmp_path: Path):+ monkeypatch.setattr(security_audit, "get_repo_root", lambda: tmp_path)++ assert security_audit.cmd_validate_ignores(argparse.Namespace()) == 1++ def test_validate_ignores_accepts_a_policy_file_with_no_entries(self, monkeypatch, tmp_path: Path):+ (tmp_path / "scripts").mkdir()+ (tmp_path / "scripts" / "security_audit_ignores.txt").write_text("# every suppression has been retired\n")+ monkeypatch.setattr(security_audit, "get_repo_root", lambda: tmp_path)++ assert security_audit.cmd_validate_ignores(argparse.Namespace()) == 0++class TestGoCoverageGaps:@staticmethoddef _module(tmp_path: Path) -> Path:diff --git a/scripts/validate_detections.py b/scripts/validate_detections.pyindex 30cd2fc34..08bd92241 100755--- a/scripts/validate_detections.py+++ b/scripts/validate_detections.py@@ -44,13 +44,21 @@ import sysfrom pathlib import Pathfrom typing import Any+# `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_if_requested++self_test_if_requested(__file__)+try:import yamlexcept ImportError:print("ERROR: PyYAML not installed. Run: pip install pyyaml")sys.exit(1)-ROOT = Path(__file__).parent.parent+ROOT = repo_root()DETECTIONS_DIR = ROOT / "detections"FIXTURES_DIR = DETECTIONS_DIR / "fixtures"SCRIPTS_DIR = ROOT / "scripts"diff --git a/scripts/validate_playbooks.py b/scripts/validate_playbooks.pyindex 8e577f1ec..c8f1b917b 100755--- a/scripts/validate_playbooks.py+++ b/scripts/validate_playbooks.py@@ -32,7 +32,15 @@ import sysfrom collections.abc import Iterablefrom pathlib import Path-ROOT = Path(__file__).resolve().parent.parent+# `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_if_requested++self_test_if_requested(__file__)++ROOT = repo_root()DEFAULT_PACK = ROOT / "playbooks" / "packs" / "v1"# Make the services/agents Pydantic models importable.diff --git a/scripts/wet_eval_check.py b/scripts/wet_eval_check.pyindex de0b320cb..d6c6a91ad 100755--- a/scripts/wet_eval_check.py+++ b/scripts/wet_eval_check.py@@ -53,9 +53,16 @@ import argparseimport jsonimport osimport sys+import tempfilefrom datetime import UTC, datetimefrom 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 SELF_TEST_FLAG+# Secrets the workflow needs. Names match what's documented in# ``apps/docs/docs/operations/secrets.md`` so docs and code stay in step._REQUIRED_SECRETS_FOR_LIVE_RUN = (@@ -150,5 +157,53 @@ def main(argv: list[str] | None = None) -> int:return 0+def _self_test() -> int:+ """Prove the verdict this preflight actually renders.++ The shared empty-tree self-test does not apply here: this script reads two+ environment variables and no repository content, and exits 0 by design so+ a fork with no secrets does not look like a broken build. Its verdict is+ ``should_run`` in the status file, and that is what has to be checked —+ otherwise a preflight that answered "yes, dispatch" unconditionally would+ look identical from the outside, and the weekly workflow would proceed to+ call a provider with no key.+ """+ cases = [+ ("no secrets configured: the workflow must not dispatch", {}, False, False),+ ("both secrets present: the workflow dispatches", {n: "x" for n in _REQUIRED_SECRETS_FOR_LIVE_RUN}, False, True),+ ("one secret missing: still no dispatch", {_REQUIRED_SECRETS_FOR_LIVE_RUN[0]: "x"}, False, False),+ ("dry-run overrides present secrets", {n: "x" for n in _REQUIRED_SECRETS_FOR_LIVE_RUN}, True, False),+ ]+ ok = True+ saved = {name: os.environ.get(name) for name in _REQUIRED_SECRETS_FOR_LIVE_RUN}+ with tempfile.TemporaryDirectory(prefix="wet_eval_check_") as tmp:+ out = Path(tmp) / "status.json"+ for description, environment, dry_run, expected in cases:+ for name in _REQUIRED_SECRETS_FOR_LIVE_RUN:+ os.environ.pop(name, None)+ os.environ.update(environment)+ argv = ["--status-out", str(out)] + (["--dry-run"] if dry_run else [])+ status = main(argv)+ should_run = json.loads(out.read_text())["should_run"]+ passed = status == 0 and should_run is expected+ ok &= passed+ print(f" {'PASS' if passed else 'FAIL'} {description}")+ print(f" exit {status}, should_run={should_run} (want {expected})")+ for name, value in saved.items():+ if value is None:+ os.environ.pop(name, None)+ else:+ os.environ[name] = value++ print()+ if not ok:+ print("wet_eval_check.py: self-test FAILED")+ return 1+ print("wet_eval_check.py: self-test OK")+ return 0++if __name__ == "__main__":+ if SELF_TEST_FLAG in sys.argv[1:]:+ sys.exit(_self_test())sys.exit(main())diff --git a/scripts/wet_eval_update_benchmark.py b/scripts/wet_eval_update_benchmark.pyindex b7d735158..893b2c46b 100644--- a/scripts/wet_eval_update_benchmark.py+++ b/scripts/wet_eval_update_benchmark.py@@ -32,6 +32,14 @@ import sysfrom pathlib import Pathfrom typing import Any+# `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 self_test_if_requested++self_test_if_requested(__file__)+# Family ordering must match what's in ``apps/docs/docs/benchmark.md``:# Aggregate row first, then the five family rows in this exact order._FAMILY_ORDER: tuple[tuple[str, str], ...] = (diff --git a/tests/test_gate_contract.py b/tests/test_gate_contract.pynew file mode 100644index 000000000..e64843a81--- /dev/null+++ b/tests/test_gate_contract.py@@ -0,0 +1,301 @@+"""A gate is only worth the tree it opened.++``scripts/check_gate_contract.py`` runs every wired check inside a git+repository holding nothing but ``scripts/`` and requires each one to refuse.+The one-off version of that probe found five gates reporting OK over a+repository containing no content — among them the detection validator behind+the rule count on the front page, and a self-link checker written to replace+a link run that accepted HTTP 403 as healthy, which had inherited the same+inability in a different costume.++These tests pin the parts of that gate a reviewer cannot see by reading its+output: how it decides what to run, and how it reads the result. Both are+places where a gate quietly hands out credit.+"""++from __future__ import annotations++import shlex+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO_ROOT / "scripts"))++import check_gate_contract as cgc # noqa: E402+import gate_toolkit # noqa: E402++SUPPLIED = frozenset({"app", "detection_specs"})+++# ── Reading the result ───────────────────────────────────────────────────────+ ("status", "output", "expected"),+ [+ (0, "OK: 0 published Go module path(s)", cgc.PASSED),+ (1, "ERROR: detections/ directory not found", cgc.REFUSED),+ (2, "refusing to report a result for a tree I did not open", cgc.REFUSED),+ (None, "", cgc.INCONCLUSIVE),+ ],+)+def test_exit_status_is_read_for_what_it_means(status, output, expected):+ assert cgc.classify(status, output, SUPPLIED)[0] == expected+++def test_an_argparse_error_is_not_evidence_of_anything():+ """Exit 2 with a usage block means the tree was never opened.++ Counting it as a refusal would let the probe credit a failure it did not+ cause — the same shape as the gates it exists to find, one level up.+ """+ output = "usage: x [-h] --old OLD\nx: error: the following arguments are required: --old"++ assert cgc.classify(2, output, SUPPLIED)[0] == cgc.INCONCLUSIVE+++def test_a_missing_third_party_module_is_the_environment_not_the_tree():+ output = "ModuleNotFoundError: No module named 'structlog'"++ assert cgc.classify(1, output, SUPPLIED)[0] == cgc.INCONCLUSIVE+++def test_a_missing_repository_package_is_the_empty_tree_working():+ """``app`` is the package under ``services/``; its absence *is* the point."""+ output = "ModuleNotFoundError: No module named 'app'"++ assert cgc.classify(1, output, SUPPLIED)[0] == cgc.REFUSED+++def test_the_supplied_set_is_read_from_the_repository():+ supplied = cgc.importable_names(REPO_ROOT)++ assert "app" in supplied, "services/*/app is a package this repository supplies"+ assert "structlog" not in supplied, "a third-party dependency must not read as repository-supplied"+++# ── Choosing what to run ─────────────────────────────────────────────────────+ ("command", "expected"),+ [+ ("python3 scripts/x.py --check", ["--check"]),+ ("python scripts/x.py", []),+ ("FOO=1 BAR=2 python3 scripts/x.py --strict", ["--strict"]),+ ("env FOO=1 python3 scripts/x.py --strict", ["--strict"]),+ ("uv run python scripts/x.py --check", ["--check"]),+ ("poetry run python3 scripts/x.py", []),+ ("python3 ../../scripts/x.py --check", ["--check"]),+ ],+)+def test_an_invocation_is_recognised_however_it_is_spelled(command, expected):+ assert cgc._argv_after(shlex.split(command), "x.py") == expected+++ "command",+ [+ 'echo "scripts/x.py --check"',+ "echo scripts/x.py",+ "python3 -m pytest scripts/x.py",+ "cat scripts/x.py",+ "ruff check scripts/x.py",+ ],+)+def test_a_path_that_is_not_being_executed_is_not_an_invocation(command):+ """A quoted path inside an ``echo`` is the shape that manufactures coverage.++ Another gate in this tree matched a path inside a quoted shell string and+ reported eleven services as CI-covered on the strength of it.+ """+ assert cgc._argv_after(shlex.split(command), "x.py") is None+++ ("args", "replayable"),+ [+ (["--check"], True),+ (["--new", "docs/openapi.yaml"], True),+ (["--root", "$GITHUB_WORKSPACE"], False),+ (["--old", "/tmp/base-openapi.yaml"], False),+ ],+)+def test_only_arguments_that_test_the_tree_are_replayed(args, replayable):+ assert cgc._replayable(args) is replayable+++def test_a_generator_run_is_not_probed_when_the_script_also_declares_a_gate():+ """``build_marketplace.py`` writes the index; only ``--check`` compares it.++ Probing the writing half would report that producing an empty index over+ an empty tree is a gate crediting nothing — true of every generator, and+ nothing to do with the gate.+ """++ class _Surface:+ def texts(self):+ return [+ ("sync.yml", "", "python3 scripts/build_marketplace.py"),+ ("sync.yml", "", "python3 scripts/build_marketplace.py --check"),+ ]++ signals = {"verdict-flag": "--check"}++ assert cgc.ci_invocations(_Surface(), "build_marketplace.py", signals) == [["--check"]]+ assert [] in cgc.ci_invocations(_Surface(), "build_marketplace.py", {})+++# ── The two static properties ────────────────────────────────────────────────+def test_a_root_taken_from_this_file_is_visible_in_the_syntax_tree():+ properties = cgc.static_properties("from pathlib import Path\nROOT = Path(__file__).resolve().parent.parent\n")++ assert properties["derives_root_from_file"]+ assert not properties["consults_git_for_root"]+++def test_a_json_key_spelled_like_the_helper_is_not_a_call_to_it():+ """The first spelling of this matched ``repo_root`` anywhere in the text.++ ``check_gate_coverage.py`` emits ``"repo_root"`` as a JSON key, so a gate+ that rooted itself at ``__file__`` and never asked git read as compliant+ on the strength of a dictionary key in its own output.+ """+ source = 'from pathlib import Path\nROOT = Path(__file__).resolve().parent.parent\nprint({"repo_root": str(ROOT)})\n'++ assert not cgc.static_properties(source)["consults_git_for_root"]+++def test_the_shared_resolver_counts_as_consulting_git():+ source = "from gate_toolkit import repo_root\nROOT = repo_root()\n"++ assert cgc.static_properties(source)["consults_git_for_root"]+++def test_a_docstring_promising_a_self_test_is_not_a_self_test():+ """A promise nothing parses is the documentation form of a gate with no caller."""+ source = '"""Run with --self-test to prove it works."""\nimport sys\nsys.exit(0)\n'++ assert not cgc.static_properties(source)["declares_self_test"]+++ "source",+ [+ 'parser.add_argument("--self-test", action="store_true")',+ "parser.add_argument(SELF_TEST_FLAG, action='store_true')",+ "self_test_if_requested(__file__)",+ ],+)+def test_a_self_test_that_reaches_code_counts(source):+ assert cgc.static_properties(source)["declares_self_test"]+++# ── The scratch tree ─────────────────────────────────────────────────────────+def test_the_scratch_tree_is_a_repository_with_nothing_but_scripts():+ with gate_toolkit.scratch_tree() as tree:+ assert sorted(p.name for p in tree.iterdir() if p.name != ".git") == ["scripts"]+ assert (tree / "scripts" / "check_gate_contract.py").is_file()+ for absent in ("services", "detections", "apps", "packages", "docs", ".github"):+ assert not (tree / absent).exists(), f"{absent} must not be reachable from the scratch tree"+++def test_a_shared_self_test_asks_the_gate_for_a_verdict_not_a_bare_run(tmp_path):+ """The generator half of a generator-and-gate script is not the gate.++ ``build_marketplace.py`` with no arguments writes the index; only+ ``--check`` compares it. A self-test that ran the writing half would+ report every such script as crediting an empty tree, and the fix would+ have been to weaken the assertion rather than to ask the right question.+ """+ script = tmp_path / "check_thing.py"+ script.write_text('import argparse\np = argparse.ArgumentParser()\np.add_argument("--check", action="store_true")\n')++ assert gate_toolkit.verdict_args(script) == ["--check"]+ assert gate_toolkit.verdict_args(tmp_path / "nothing_here.py") == []+++def test_the_self_test_and_the_meta_gate_agree_on_what_a_verdict_looks_like():+ """One list, imported in both places. Two would drift on the first addition."""+ assert cgc.VERDICT_FLAG_PREFERENCE is gate_toolkit.VERDICT_FLAG_PREFERENCE+ assert cgc.declared_invocations({"verdict-flag": "--verify --check"})[0] == ["--check"]+++def test_a_gate_in_the_scratch_tree_resolves_the_scratch_tree():+ """Otherwise the probe would be asking every gate about the real checkout."""+ with gate_toolkit.scratch_tree() as tree:+ status, output = gate_toolkit.run_in_scratch_tree("check_grafana_dashboards.py", tree=tree, timeout=60)++ assert status != 0+ assert str(tree) in output, "the gate must name the tree it actually read"+ assert str(REPO_ROOT) not in output+++# ── The verdict ──────────────────────────────────────────────────────────────+def _probe(*dispositions: str) -> dict[str, cgc.Probe]:+ runs = [cgc.Run(args=["--check"], source="test", disposition=d, why=d) for d in dispositions]+ return {"check_x.py": cgc.Probe(script="check_x.py", runs=runs)}+++_CLEAN_PROPERTIES = {"check_x.py": {"derives_root_from_file": False, "consults_git_for_root": True, "declares_self_test": True}}+++def _codes(probes, *, accepted=None, properties=None):+ return {+ code+ for code, _detail in cgc.evaluate(+ {"check_x.py": {"verdict-flag": "--check"}},+ probes,+ properties or _CLEAN_PROPERTIES,+ accepted=accepted or {},+ no_git_root={},+ no_self_test={},+ )+ }+++def test_the_worst_invocation_decides_not_the_first():+ """Four subcommands under one name are four gates.++ ``security_audit.py`` runs as ``validate-ignores``, ``pnpm``, ``python``+ and ``go``. Three of them refused an empty tree while the others did not;+ excusing the set because one refused is how the rest stay hidden.+ """+ assert "passes-over-empty-tree" in _codes(_probe(cgc.REFUSED, cgc.PASSED))+++def test_an_exception_is_checked_against_the_disposition_it_was_written_for():+ excused = {"check_x.py": (cgc.INCONCLUSIVE, "its inputs are named on the command line")}++ assert not _codes(_probe(cgc.INCONCLUSIVE), accepted=excused)+ assert "exception-stale" in _codes(_probe(cgc.PASSED), accepted=excused)+ assert "exception-stale" in _codes(_probe(cgc.REFUSED), accepted=excused)+++def test_an_exception_naming_nothing_fails():+ assert "ratchet-names-nothing" in _codes(_probe(cgc.REFUSED), accepted={"check_gone.py": (cgc.PASSED, "reason")})+++def test_an_exception_with_no_reason_fails():+ assert "ratchet-unexplained" in _codes(_probe(cgc.REFUSED), accepted={"check_x.py": (cgc.REFUSED, " ")})+++# ── The real tree ────────────────────────────────────────────────────────────+def test_every_recorded_exception_names_a_check_that_exists():+ """The cheap half of the both-directions check, without running the probe."""+ import check_gate_coverage as coverage # noqa: PLC0415++ surface = coverage.Surface(REPO_ROOT)+ checks = set(coverage.collect_checks(REPO_ROOT, surface.gating))++ for name in (*cgc.EMPTY_TREE_EXCEPTIONS, *cgc.NO_GIT_ROOT, *cgc.NO_SELF_TEST):+ assert name in checks, f"{name} is excused but is not a check in the tree"+++def test_every_recorded_exception_carries_a_disposition_the_gate_understands():+ for name, (disposition, reason) in cgc.EMPTY_TREE_EXCEPTIONS.items():+ assert disposition in {cgc.PASSED, cgc.REFUSED, cgc.INCONCLUSIVE}, name+ assert len(reason.split()) >= 10, f"{name}: a one-line reason is not a justification"+++def test_the_self_test_catches_every_defect_it_claims_to():+ assert cgc.self_test() == 0