Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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

Type-check the 153 files in no tree, and the five gates that said OK over nothing

Beenu Arora036f66e3b14d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 84590a140..3879791cf 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -259,6 +259,18 @@ jobs:
# `[tool.mypy]`, and when a configured or recorded tree is no longer on
# disk. Both directions, because the dominant failure shape here is a
# check that compares A against B and never B against A.
+ #
+ # "Every tree is configured" still could not ask whether every *file* is
+ # in a tree, and 153 were not — `scripts/`, `tests/`, `tools/` and
+ # `plugins/`, which is to say the CI gates themselves were the only
+ # Python here nothing type-checked. They are covered by a scoped
+ # invocation under `mypy-unmanaged.toml` rather than by a repo-root
+ # manifest, which would make `poetry check` invalid from every directory
+ # without one of its own; that file records the measurements. The scope
+ # is computed as `git ls-files` minus the manifest trees, so a script
+ # added anywhere is checked with no edit, and mypy's own
+ # `--linecount-report` has to account for every module before the run is
+ # allowed to report clean.
- name: The type-check this job is named after
run: |
python scripts/check_mypy_baseline.py --self-test
@@ -271,10 +283,10 @@ jobs:
# replaces the exception being handled and no sibling handler can catch
# it, so the one path whose job was to degrade gracefully was the only
# path that raised. A type checker only sees this in a tree it checks;
- # this scan covers every Python file in the repository, including the
- # ~150 under scripts/, tests/, tools/ and plugins/ that belong to no
- # tree, and reports how many receivers it could not classify rather than
- # counting them as clean.
+ # this scan covers every Python file in the repository and reports how
+ # many receivers it could not classify rather than counting them as
+ # clean. It reached the files in no manifest tree before a type checker
+ # did, which is how that gap was found.
- name: No stdlib logger is called with a structlog keyword
run: |
python scripts/check_logger_kwargs.py --self-test
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 24496ed8a..ce7a8f1d7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -77,6 +77,59 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **The 153 Python files that belong to no manifest tree are type-checked, and
+ five gates that reported OK over nothing now fail.** Giving all twenty trees
+ a `[tool.mypy]` table still left `scripts/`, `tests/`, `tools/` and
+ `plugins/` outside every config — which is to say the CI gates themselves
+ were the only Python in the repository nothing type-checked, while every
+ other claim here rests on them.
+
+ They are covered by a scoped invocation under a new root
+ `mypy-unmanaged.toml`, not by a root `pyproject.toml`. Three things were
+ measured rather than assumed: a root manifest carrying only `[tool.mypy]`
+ makes `poetry check` answer *"The Poetry configuration is invalid"* from
+ every directory without a manifest of its own, because poetry searches
+ upward; pytest gains a `configfile` where it had none; and
+ `check_dependency_pins.py`, `check_toolchain_pins.py` and
+ `security_audit.py` all pass with one present only because each is scoped to
+ `services/*` + `packages/*`, so they would miss it by accident of a glob and
+ fail closed on it the day any of them is made structural.
+
+ The scope is **computed, never listed** — `git ls-files '*.py'` minus every
+ manifest tree — so a script added anywhere is checked with no edit, and
+ deleting a tree's manifest moves its files into this scope rather than out
+ of coverage. Sixteen `plugins/*/plugin.py` files share one module name in
+ directories whose hyphens keep them from ever being packages, so the run is
+ split into the minimum number of invocations with no collision, derived
+ rather than configured. mypy's own `--linecount-report` must account for
+ every module asked of it before the run may report clean, and a finding
+ against a file outside the scope fails rather than being recorded.
+
+ Five gates were found reporting OK over a repository containing nothing, by
+ copying `scripts/` into an empty git repository and running all forty:
+ `validate_detections.py` printed a warning and exited 0 over an empty
+ detections corpus — the validator for the number the front page quotes,
+ certifying zero rules as valid; `check_grafana_dashboards.py` failed on an
+ empty dashboards directory and *passed* on a missing one, so the larger loss
+ was the one it forgave; `check_go_module_paths.py` reported "OK: 0 published
+ Go module path(s)"; `check_repo_self_links.py` reported every self-link
+ healthy over zero files, having replaced a lychee run that could not tell a
+ rate-limited 403 from a live link; and `audit_health_probes.py --check`
+ printed a table header and exited 0 over zero services. Each now fails and
+ says what it opened. `check_repo_self_links.py` also reported a file it
+ could not decode as checked, and now names it.
+
+ The ratchet in `scripts/check_mypy_baseline.py` gains a `file -> scope`
+ direction and goes **919 → 994**: +89 newly visible, −14 fixed. Of the 89,
+ 20 are `import-untyped` against the deliberate no-dependency environment the
+ baseline is recorded in and the rest are annotation and narrowing findings.
+ A separate `--warn-unreachable` pass over the same scope reported 8
+ statements, all one shape: a defensive `isinstance` guard against untrusted
+ YAML or JSON that the parameter's own annotation declares impossible. None
+ is dead at runtime, so the annotations are what is wrong and the flag is
+ deliberately not enabled — recording those 8 would invite someone to delete
+ the guards to clear them.
+
- **All twenty Python trees are type-checked, and the coverage is gated in both
directions.** `#818` ran mypy for the first time, over the six trees that
declared a `[tool.mypy]` table. Fourteen declared none, so the job named
diff --git a/apps/docs/docs/contributing/reproducible-builds.md b/apps/docs/docs/contributing/reproducible-builds.md
index 30d8e1b25..45fa4a60c 100644
--- a/apps/docs/docs/contributing/reproducible-builds.md
+++ b/apps/docs/docs/contributing/reproducible-builds.md
@@ -145,12 +145,27 @@ too.
recorded in `scripts/mypy_baseline.json` exactly as mypy reports them — no
widened config, no excluded tree, and `strict = true` stays strict.
+Every tree being configured is not the same as every file being checked. 153
+Python files belong to no `pyproject.toml` — `scripts/`, `tests/`, `tools/`
+and `plugins/` — so the gate also runs a scope recorded under the key
+`(unmanaged)`, configured by `mypy-unmanaged.toml` at the repository root.
+That scope is **computed, not listed**: `git ls-files '*.py'` minus every
+manifest tree. Adding a script anywhere brings it into scope with no edit,
+and deleting a tree's manifest moves that tree's files into this scope rather
+than out of coverage.
+
+It is a scoped invocation rather than a root `pyproject.toml` because a root
+manifest carrying only `[tool.mypy]` makes `poetry check` answer *"The Poetry
+configuration is invalid"* from every directory that does not hold a manifest
+of its own — poetry searches upward. The header of `mypy-unmanaged.toml`
+records that and the two other measurements behind the choice.
+
The baseline is only reproducible against a fixed environment: **mypy alone,
-no project dependencies installed, on Python 3.12**, which is what CI does.
-Re-record under the same conditions:
+no project dependencies installed, on Python 3.11** — the interpreter CI uses
+and the one every service image ships. Re-record under the same conditions:
```bash
-docker run --rm -v "$PWD":/w -w /w python:3.12-slim \
+docker run --rm -v "$PWD":/w -w /w python:3.11-slim \
bash -c "pip install 'mypy>=1.10,<2' && python scripts/check_mypy_baseline.py --update"
```
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 8196915a2..800d36397 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -10,7 +10,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
|---|---|---|---|---|
| Offline sandbox demo runs with no key/network in < 5 s | README L38 | `readme-gates.yml :: sandbox-offline` (ubuntu+macos matrix) | GATED | - |
| `pnpm aisoc:demo` boots the real stack | README L40, L45 | `compose-smoke.yml` (cold health) + `integration.yml :: spine` (Phase A3 — default `docker compose up` ships connectors + graph-at-ingest by default; asserts cold-boot → ingest → lake + detection engine → alert row with the spine test's measured raw-event→alert latency) | GATED | - |
-| 69 connectors | README L116, L168 | `ci.yml :: python-lint` (`generate_connector_count.py --check`) | GATED (count) | - |
+| 84 connectors | README L116, L168 | `ci.yml :: python-lint` (`generate_connector_count.py --check`) | GATED (count) | - |
| Connectors: schema-driven config + vault-encrypted secrets | README L168 | `ci.yml` connectors matrix (`test_schemas.py` + `test_conformance.py` — secret-shaped fields must be `type=secret`); vault tests + `test_live_vendor_smoke.py` (Phase D3 — mock-server drives each connector's real HTTP client + normalize) | GATED | - |
| Connectors: live Test connection | README L168 | `ci.yml` connectors matrix (`test_conformance.py` — every connector implements the async `test_connection` contract) + `connector_conformance.py --check` published matrix + `test_live_vendor_smoke.py` (Phase D3 — mock-server conformance: `test_connection()` + paginated `fetch_alerts()` HTTP path exercised against realistic vendor payloads) | GATED | - |
| Investigation Ledger stores every step | README L61, L169 | `ci.yml :: api tests` (`audit_hash`, audit immutability) | PARTIAL (write path gated; UI replay only in hermetic e2e) | Phase 3.2 |
diff --git a/mypy-unmanaged.toml b/mypy-unmanaged.toml
new file mode 100644
index 000000000..ba0d31640
--- /dev/null
+++ b/mypy-unmanaged.toml
@@ -0,0 +1,51 @@
+# The type-checker configuration for Python files that belong to no
+# `pyproject.toml` tree — `scripts/`, `tests/`, `tools/`, `plugins/` today,
+# and anything added anywhere else tomorrow.
+#
+# #820 gave all twenty manifest trees a `[tool.mypy]` table, which left this
+# set as the only Python in the repository nothing type-checks. That set is
+# mostly `scripts/`, which is where the CI gates live: the code every other
+# claim in this repository is verified by was the least-verified code in it.
+#
+# Why this file and not a repo-root `pyproject.toml`, which is the obvious
+# route. Three things were measured, not assumed:
+#
+# * `poetry check` run from the repository root against a root manifest
+# carrying only `[tool.mypy]` answers "The Poetry configuration is
+# invalid: Either [project.name] or [tool.poetry.name] is required in
+# package mode." Poetry searches *upward* for a manifest, so that is the
+# answer for every directory in the tree that does not hold one of its
+# own.
+# * pytest gains a `configfile` where it had none. `rootdir` is unchanged,
+# but the file that governs test configuration becomes one whose subject
+# is type checking.
+# * `check_dependency_pins.py`, `check_toolchain_pins.py` and
+# `security_audit.py` all pass with a root manifest present — and they
+# pass because each is scoped to `services/*` + `packages/*`, so they
+# miss it by accident of a glob rather than by design. #820 established
+# that glob-scoped discovery is this repository's recurring defect. A
+# root manifest would be a 21st Python tree that those gates cannot see
+# today and would fail closed on the day any of them is made structural,
+# which is the direction they should move.
+#
+# So the coverage is real and the manifest is not: `check_mypy_baseline.py`
+# computes the unmanaged set from `git ls-files` minus the manifest trees and
+# invokes mypy with this config over exactly that list. Adding a script
+# anywhere puts it in scope with no edit here; deleting a tree's manifest
+# moves its files into this scope rather than out of coverage.
+#
+# Strictness matches the ten services rather than inventing a third shape.
+# There is no `ignore_errors` and no per-module override: an exemption here
+# would be invisible, and the findings are on the ratchet in
+# `scripts/mypy_baseline.json` where they can be read.
+[tool.mypy]
+python_version = "3.11"
+strict = false
+ignore_missing_imports = true
+
+# The scope is a flat list of files that import each other rarely and the
+# service trees not at all. Following an import out of the scope would report
+# findings against a file that its own tree already checks under its own
+# config — two answers for one file, and a baseline that double-counts.
+# `silent` keeps the types and drops the findings.
+follow_imports = "silent"
diff --git a/scripts/audit_health_probes.py b/scripts/audit_health_probes.py
index dd40076ba..13b35f631 100644
--- a/scripts/audit_health_probes.py
+++ b/scripts/audit_health_probes.py
@@ -81,6 +81,18 @@ def main() -> int:
args = parser.parse_args()
services = discover_fastapi_services()
+ if not services:
+ # Discovery walks `services/*/app/main.py`. An empty result printed a
+ # table header, no rows, and exit 0 — the audit passing because it
+ # found no service to hold to the standard, which reads identically
+ # to every service meeting it.
+ print(
+ f"health-probes: found no FastAPI service under {SERVICES_DIR}. "
+ f"Zero services audited is not zero services missing the probes.",
+ file=sys.stderr,
+ )
+ return 1
+
print(f"{'service':<18} {'_health.py':<11} {'import':<7} {'wire':<5}")
print(f"{'-' * 18} {'-' * 11} {'-' * 7} {'-' * 5}")
drift: list[str] = []
diff --git a/scripts/check_action_contract.py b/scripts/check_action_contract.py
index 11e31a243..161039512 100644
--- a/scripts/check_action_contract.py
+++ b/scripts/check_action_contract.py
@@ -28,6 +28,7 @@ import argparse
import logging
import sys
from pathlib import Path
+from typing import TypeVar
import structlog
@@ -377,8 +378,10 @@ def check_capability_reachability() -> list[str]:
errors: list[str] = []
adapters = builtins._BUILTIN_ADAPTERS # noqa: SLF001
adapter_capabilities = {cls.capability for cls in adapters}
- adapter_action_types = {getattr(cls, "_legacy_action_type", None) for cls in adapters}
- adapter_action_types.discard(None)
+ # Built by filtering rather than by adding `None` and discarding it: the
+ # discard is invisible to a reader three hundred lines below, where the
+ # set is unpacked as `a.value`.
+ adapter_action_types = {t for t in (getattr(cls, "_legacy_action_type", None) for cls in adapters) if t is not None}
# ── Direction 1: adapter → vocabulary ──────────────────────────────────
# register_executor() only *warns* on an unknown capability, so this drift
@@ -693,8 +696,11 @@ def check_capability_mirror() -> list[str]:
return errors
-def _all_subclasses(cls: type) -> list[type]:
- found: list[type] = []
+_T = TypeVar("_T")
+
+
+def _all_subclasses(cls: type[_T]) -> list[type[_T]]:
+ found: list[type[_T]] = []
for sub in cls.__subclasses__():
found.append(sub)
found.extend(_all_subclasses(sub))
diff --git a/scripts/check_go_module_paths.py b/scripts/check_go_module_paths.py
index b61039e05..adafcaa79 100755
--- a/scripts/check_go_module_paths.py
+++ b/scripts/check_go_module_paths.py
@@ -20,10 +20,31 @@ and asserts the declared module path matches where the directory actually is.
from __future__ import annotations
import re
+import subprocess
import sys
from pathlib import Path
-ROOT = Path(__file__).resolve().parent.parent
+
+def _repo_root() -> Path:
+ """The repository, per git — not per this file's location.
+
+ Resolving two levels up from `__file__` means a copy of this script run
+ from anywhere else scans whatever happens to sit above it and prints a
+ confident OK about a tree it never opened.
+ """
+ out = subprocess.run( # noqa: S603 - fixed argv, no shell
+ ["git", "rev-parse", "--show-toplevel"],
+ capture_output=True,
+ text=True,
+ check=False,
+ cwd=Path(__file__).resolve().parent,
+ )
+ if out.returncode == 0 and out.stdout.strip():
+ return Path(out.stdout.strip()).resolve()
+ return Path(__file__).resolve().parent.parent
+
+
+ROOT = _repo_root()
#: The canonical repository path, matching the GitHub org and repo casing.
REPO_PATH = "github.com/beenuar/AiSOC"
@@ -67,6 +88,21 @@ def main() -> int:
"case-sensitive, so this module is not installable."
)
+ # "Found nothing" and "opened nothing" print the same word otherwise. The
+ # published roots are a hand-written tuple, so a module moving out of
+ # `packages/` takes its coverage with it silently — and the failure this
+ # gate exists to catch is precisely one nobody in-tree can observe,
+ # because every in-repo consumer uses a `replace` directive.
+ if not checked:
+ print(
+ f"GO MODULE PATH GATE FAILED: found no go.mod under {', '.join(PUBLISHED_ROOTS)}/ "
+ f"in {ROOT}. Zero modules checked is not zero modules broken — either "
+ f"PUBLISHED_ROOTS no longer describes where the published SDKs live, or the "
+ f"walk is looking at the wrong tree.",
+ file=sys.stderr,
+ )
+ return 1
+
if problems:
print("GO MODULE PATH GATE FAILED:", file=sys.stderr)
for problem in problems:
diff --git a/scripts/check_grafana_dashboards.py b/scripts/check_grafana_dashboards.py
index 825fc5e05..a29731f32 100644
--- a/scripts/check_grafana_dashboards.py
+++ b/scripts/check_grafana_dashboards.py
@@ -107,9 +107,20 @@ def referenced_datasource_uids() -> set[str]:
def main(argv: list[str] | None = None) -> int:
argparse.ArgumentParser(description=__doc__).parse_args(argv)
+ # These two branches used to disagree about the same thing. An empty
+ # dashboards directory failed; a *missing* one printed "nothing to check"
+ # and passed — so the larger loss was the one the gate forgave, and
+ # deleting the directory was enough to make it green. Both are now the
+ # same answer, because neither is distinguishable from "the walk broke".
if not DASHBOARDS.is_dir():
- print("grafana-dashboards: no dashboards directory; nothing to check")
- return 0
+ print(
+ f"grafana-dashboards: no dashboards directory at {DASHBOARDS}. "
+ f"Nothing to check and nothing checked are the same word here, so this fails: "
+ f"the dashboards are the artefact the SLO alerts and the observability claims "
+ f"point at.",
+ file=sys.stderr,
+ )
+ return 1
files = sorted(DASHBOARDS.glob("*.json"))
if not files:
diff --git a/scripts/check_mock_data_gated.py b/scripts/check_mock_data_gated.py
index a9e4e217d..7809eab74 100644
--- a/scripts/check_mock_data_gated.py
+++ b/scripts/check_mock_data_gated.py
@@ -233,11 +233,14 @@ def scan(root: pathlib.Path) -> list[str]:
f"canUseDemoData() check in this file. Show an error or empty state instead."
)
- for rel, number, name, gated in find_inline_records(root):
- if gated or _allowlist_key(rel, name) is not None:
+ # A distinct name from the `rel: Path` above. `_allowlist_key` matches on
+ # a string suffix, and handing it a Path would make every allow-list entry
+ # miss — noisily, but for a reason nobody would look for here.
+ for record_path, number, name, gated in find_inline_records(root):
+ if gated or _allowlist_key(record_path, name) is not None:
continue
problems.append(
- f"{rel}:{number}: `{name}` is a module-scope array of named entities with "
+ f"{record_path}:{number}: `{name}` is a module-scope array of named entities with "
f"measurements attached, in a component with no demo gate. If it is a tenant's "
f"state, read it from the API; if it is a sample, gate it with canUseDemoData()."
)
diff --git a/scripts/check_mypy_baseline.py b/scripts/check_mypy_baseline.py
index 9785e6094..a6417f780 100644
--- a/scripts/check_mypy_baseline.py
+++ b/scripts/check_mypy_baseline.py
@@ -53,8 +53,10 @@ Directions, because a one-directional gate is how drift escapes here:
notices
config -> tree a config, or a baseline entry, naming a tree that is
no longer on disk fails
+ file -> scope a Python file this repository tracks that no tree and
+ no scope covers fails
-The last two are the coverage gate, and they exist because of what this
+The last three are the coverage gate, and they exist because of what this
started as: six of twenty trees declared `[tool.mypy]`, and the job named
"Lint & Type-check" reported green over the fourteen it never opened. A tool
that appears to cover the repository while covering a third of it is
@@ -69,6 +71,36 @@ Python tree added anywhere else would have satisfied a coverage gate written
against the same glob while being checked by nothing, which is the shape this
file exists to refuse.
+The unmanaged scope
+-------------------
+`tree -> config` asks whether every tree is configured. It cannot ask whether
+every *file* is in a tree, and 153 were not: `scripts/`, `tests/`, `tools/`
+and `plugins/` hold Python that belongs to no manifest, so giving all twenty
+trees a `[tool.mypy]` table still left those unchecked. Most of them are
+under `scripts/`, which is where the CI gates live — the code the rest of
+this repository's claims are verified by was the only Python in it nothing
+type-checked.
+
+They are covered by a scoped invocation rather than by a repo-root manifest.
+`mypy-unmanaged.toml` records the three measurements behind that choice; the
+short version is that a root `pyproject.toml` makes `poetry check` invalid
+from every directory without a manifest of its own, hands pytest a configfile
+it did not have, and would be a 21st Python tree that the packaging gates
+miss only because their globs stop at `services/*` + `packages/*`.
+
+The scope is **computed, never listed**: `git ls-files '*.py'` minus every
+manifest tree minus the archived prototype. A list would be a path-glob
+convention wearing different clothes, and the file added outside it is
+exactly the one a convention cannot see. Adding a script anywhere puts it in
+scope with no edit; deleting a tree's manifest moves that tree's files into
+this scope rather than out of coverage, so the two directions cannot both be
+satisfied by removing something.
+
+Scanned, not assumed. mypy is invoked with an explicit file list and
+`--linecount-report`, and the run fails unless mypy's own report accounts for
+every module asked of it. "Found nothing" and "opened nothing" print the same
+word otherwise, which is the failure mode this file was written against.
+
Usage:
python scripts/check_mypy_baseline.py
python scripts/check_mypy_baseline.py --update # re-record, then read the diff
@@ -89,6 +121,12 @@ from pathlib import Path
BASELINE = Path("scripts/mypy_baseline.json")
+#: The config the unmanaged scope is checked under, and the name it is
+#: recorded against. The name is bracketed so it cannot be mistaken for the
+#: directory paths every other key in the baseline is.
+UNMANAGED_CONFIG = Path("mypy-unmanaged.toml")
+UNMANAGED_SCOPE = "(unmanaged)"
+
# The archived prototype. `.github/workflows/codeql.yml` carries the same
# exclusion and the project rules forbid editing anything under it, so a
# finding there is not actionable.
@@ -136,6 +174,87 @@ def python_trees(root: Path) -> list[str]:
return sorted(trees)
+def tracked_python_files(root: Path) -> list[str]:
+ """Every `.py` file this repository tracks, per git.
+
+ git rather than a filesystem walk because the question is "what does this
+ repository contain", and a walk answers "what is on this disk" — which
+ includes a contributor's virtualenv, a stale build directory and whatever
+ a previous run wrote. Those are the inputs that make a coverage number
+ depend on who ran it.
+
+ Fails closed: if git cannot enumerate, the caller gets an exception rather
+ than an empty list, because an empty list here reads as "no file is
+ unmanaged" and would turn the coverage claim into its own opposite.
+ """
+ out = subprocess.run( # noqa: S603 - fixed argv, no shell
+ ["git", "ls-files", "-z", "--", "*.py"],
+ capture_output=True,
+ text=True,
+ check=False,
+ cwd=root,
+ )
+ if out.returncode != 0:
+ raise RuntimeError(f"git ls-files failed in {root}: {out.stderr.strip()[:300]}")
+ return sorted(f for f in out.stdout.split("\0") if f)
+
+
+def unmanaged_files(root: Path, trees: list[str]) -> list[str]:
+ """Tracked Python belonging to no manifest tree.
+
+ Computed as a complement, so it is not a list anybody has to remember to
+ extend. The two memberships move together: a file leaves this set only by
+ a tree's manifest appearing above it, which `tree -> config` then requires
+ to declare `[tool.mypy]`.
+ """
+ prefixes = tuple(f"{tree}/" for tree in trees)
+ return [
+ rel
+ for rel in tracked_python_files(root)
+ if not rel.startswith(_EXCLUDED_PREFIXES) and not rel.startswith(prefixes) and rel not in trees
+ ]
+
+
+def module_name(root: Path, rel: str) -> str:
+ """The module name mypy will give a file, by mypy's own rule.
+
+ Walk up while the directory holds an `__init__.py`; everything above that
+ is the search path. Needed because two files that resolve to the same
+ module name cannot be checked in one invocation, and sixteen do:
+ `plugins/*/plugin.py`, in directories whose hyphens keep them from ever
+ being packages.
+ """
+ path = Path(rel)
+ parts = [] if path.stem == "__init__" else [path.stem]
+ parent = path.parent
+ while parent != Path(".") and (root / parent / "__init__.py").is_file():
+ parts.insert(0, parent.name)
+ parent = parent.parent
+ return ".".join(parts) or path.parent.name
+
+
+def batch(root: Path, files: list[str]) -> list[list[str]]:
+ """Split a file list so no invocation sees one module name twice.
+
+ Computed rather than configured. The collision today is
+ `plugins/*/plugin.py`; the point of deriving it is that the seventeenth
+ plugin, or any other future collision, costs nobody a code change.
+ """
+ batches: list[list[str]] = []
+ taken: list[set[str]] = []
+ for rel in files:
+ name = module_name(root, rel)
+ for index, names in enumerate(taken):
+ if name not in names:
+ batches[index].append(rel)
+ names.add(name)
+ break
+ else:
+ batches.append([rel])
+ taken.append({name})
+ return batches
+
+
def declares_mypy(root: Path, tree: str) -> bool:
data = tomllib.loads((root / tree / "pyproject.toml").read_text(encoding="utf-8"))
return "mypy" in data.get("tool", {})
@@ -147,7 +266,7 @@ def discover(root: Path) -> list[str]:
def coverage_problems(root: Path, trees: list[str], recorded: dict) -> list[str]:
- """Both directions of "is every Python tree actually type-checked?"."""
+ """Every direction of "is every Python file actually type-checked?"."""
problems: list[str] = []
for tree in python_trees(root):
if tree not in trees:
@@ -157,13 +276,26 @@ def coverage_problems(root: Path, trees: list[str], recorded: dict) -> list[str]
f"use python_version/strict=false/ignore_missing_imports, the packages use "
f"strict=true. Then run --update to record what it surfaces"
)
- for tree in sorted(set(recorded) | set(trees)):
+ for tree in sorted((set(recorded) | set(trees)) - {UNMANAGED_SCOPE}):
if not (root / tree / "pyproject.toml").is_file():
problems.append(
f"`{tree}` is configured or recorded but has no pyproject.toml on disk — "
f"a config for a tree that no longer exists never fails on its own, which is "
f"why it is checked here (config -> tree)"
)
+
+ # file -> scope. The manifest trees cover what is under them; this scope
+ # covers the rest, and it only covers the rest while its config exists.
+ # Deleting that file would return 153 files to being checked by nothing
+ # while every other direction above kept printing OK, so it is the one
+ # thing here that is checked by name.
+ if not (root / UNMANAGED_CONFIG).is_file():
+ orphans = unmanaged_files(root, trees)
+ problems.append(
+ f"{UNMANAGED_CONFIG} is missing, so {len(orphans)} tracked Python file(s) under "
+ f"{', '.join(sorted({f.split('/')[0] for f in orphans})) or '(none)'} belong to no "
+ f"tree and no scope — nothing type-checks them (file -> scope)"
+ )
return problems
@@ -190,6 +322,103 @@ def run_mypy(root: Path, tree: str) -> tuple[dict[str, dict[str, int]], str]:
return {f: dict(c) for f, c in findings.items()}, ""
+def _reported_modules(report_dir: Path) -> set[str]:
+ """The modules mypy says it opened, from `--linecount-report`."""
+ path = report_dir / "linecount.txt"
+ if not path.is_file():
+ return set()
+ seen: set[str] = set()
+ for line in path.read_text(encoding="utf-8").splitlines():
+ fields = line.split()
+ if len(fields) >= 5 and fields[-1] != "total":
+ seen.add(fields[-1])
+ return seen
+
+
+def run_mypy_unmanaged(root: Path, files: list[str]) -> tuple[dict[str, dict[str, int]], str]:
+ """Findings for the files that belong to no manifest tree.
+
+ Three properties the per-tree runner gets for free and this one has to
+ assert, because it passes a computed list rather than a directory:
+
+ * mypy is asked for `--linecount-report` and the run fails unless its own
+ report accounts for every module handed to it. Passing a path mypy
+ cannot read is a crash, not a silence — but "the list was empty" and
+ "the list was checked" are indistinguishable from the exit code alone,
+ and that is precisely the confusion this gate exists to refuse.
+ * a finding against a file outside the scope fails rather than being
+ recorded. `follow_imports = "silent"` should make that impossible; if
+ it ever stops being true, the baseline would start double-counting a
+ file its own tree already checks, under a different config.
+ * an empty scope fails. It is legitimate only if the repository has no
+ unmanaged Python at all, and reaching that state by breaking the walk
+ is far likelier than reaching it by tidying.
+ """
+ if not files:
+ return {}, (
+ f"{UNMANAGED_SCOPE}: the scope is empty — every tracked .py file resolved to a "
+ f"manifest tree, which is either a repository nobody expects or a broken walk"
+ )
+ config = root / UNMANAGED_CONFIG
+ if not config.is_file():
+ return {}, f"{UNMANAGED_SCOPE}: {UNMANAGED_CONFIG} is missing, so the scope has no config to be checked under"
+
+ findings: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
+ in_scope = set(files)
+ wanted = {module_name(root, rel) for rel in files}
+ opened: set[str] = set()
+ stray: set[str] = set()
+
+ with tempfile.TemporaryDirectory(prefix="mypy_unmanaged_") as tmp:
+ for index, group in enumerate(batch(root, files)):
+ report = Path(tmp) / str(index)
+ completed = subprocess.run( # noqa: S603 - fixed argv, no shell
+ [
+ sys.executable,
+ "-m",
+ "mypy",
+ "--no-color-output",
+ "--no-error-summary",
+ "--config-file",
+ str(config),
+ "--linecount-report",
+ str(report),
+ *group,
+ ],
+ cwd=root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if completed.returncode not in (0, 1):
+ return {}, f"{UNMANAGED_SCOPE}: mypy exited {completed.returncode} — {completed.stderr.strip()[:400]}"
+ opened |= _reported_modules(report)
+ for line in completed.stdout.splitlines():
+ match = _FINDING.match(line.strip())
+ if not match:
+ continue
+ file = match.group("file")
+ if file not in in_scope:
+ stray.add(file)
+ continue
+ findings[file][match.group("code") or "no-code"] += 1
+
+ if stray:
+ return {}, (
+ f"{UNMANAGED_SCOPE}: mypy reported findings for {len(stray)} file(s) outside the scope "
+ f"({', '.join(sorted(stray)[:3])}...) — follow_imports is leaking into trees that are "
+ f"checked under their own config, so these would be counted twice"
+ )
+ missed = wanted - opened
+ if missed:
+ return {}, (
+ f"{UNMANAGED_SCOPE}: mypy's linecount report accounts for {len(opened)} module(s) but "
+ f"{len(missed)} of the {len(wanted)} asked for are absent ({', '.join(sorted(missed)[:5])}) — "
+ f"the scope was not scanned, and an empty finding list here would have read as clean"
+ )
+ return {f: dict(c) for f, c in findings.items()}, ""
+
+
def compare(tree: str, found: dict[str, dict[str, int]], recorded: dict[str, dict[str, int]]) -> list[str]:
problems: list[str] = []
for file in sorted(set(found) | set(recorded)):
@@ -231,12 +460,17 @@ def run(root: Path, update: bool = False) -> int:
results: dict[str, dict[str, dict[str, int]]] = {}
problems: list[str] = coverage_problems(root, trees, recorded)
+ unmanaged = unmanaged_files(root, all_trees)
scanned = sum(_python_file_count(root, tree) for tree in trees)
print(f"check_mypy_baseline: root {root}")
# Name what was scanned. "OK" over a tree that was never opened is the
# failure this gate exists to make impossible, and a count is the cheapest
# way for a reader to notice it happened.
print(f" {len(trees)}/{len(all_trees)} Python tree(s) configured, {scanned} .py file(s) in scope")
+ print(
+ f" {UNMANAGED_SCOPE}: {len(unmanaged)} tracked .py file(s) in no tree, "
+ f"checked under {UNMANAGED_CONFIG} in {len(batch(root, unmanaged))} invocation(s)"
+ )
for tree in trees:
found, error = run_mypy(root, tree)
if error:
@@ -246,6 +480,14 @@ def run(root: Path, update: bool = False) -> int:
total = sum(sum(c.values()) for c in found.values())
print(f" {tree}: {total} finding(s) across {len(found)} file(s)")
+ found, error = run_mypy_unmanaged(root, unmanaged)
+ if error:
+ problems.append(error)
+ else:
+ results[UNMANAGED_SCOPE] = found
+ total = sum(sum(c.values()) for c in found.values())
+ print(f" {UNMANAGED_SCOPE}: {total} finding(s) across {len(found)} file(s)")
+
if update:
(root / BASELINE).write_text(json.dumps(results, indent=2, sort_keys=True) + "\n", encoding="utf-8")
total = sum(sum(sum(c.values()) for c in f.values()) for f in results.values())
@@ -254,13 +496,14 @@ def run(root: Path, update: bool = False) -> int:
for tree in sorted(results):
if tree not in recorded:
+ what = "is checked but" if tree == UNMANAGED_SCOPE else "declares [tool.mypy] but"
problems.append(
- f"{tree} declares [tool.mypy] but has no baseline entry — a tree added "
- f"without being recorded is a tree nothing checks (config -> baseline)"
+ f"{tree} {what} has no baseline entry — a scope added "
+ f"without being recorded is a scope nothing checks (config -> baseline)"
)
continue
problems += compare(tree, results[tree], recorded[tree])
- for tree in sorted(set(recorded) - set(trees)):
+ for tree in sorted(set(recorded) - set(trees) - {UNMANAGED_SCOPE}):
problems.append(
f"{BASELINE} records `{tree}`, which no longer declares [tool.mypy] — "
f"remove it rather than leaving a baseline for a tree nobody checks "
@@ -268,7 +511,7 @@ def run(root: Path, update: bool = False) -> int:
)
total = sum(sum(sum(c.values()) for c in f.values()) for f in results.values())
- print(f" {total} finding(s) total, {len(trees)} tree(s) checked: {', '.join(trees)}")
+ print(f" {total} finding(s) total, {len(trees)} tree(s) + {UNMANAGED_SCOPE} checked: {', '.join(trees)}")
if problems:
print("check_mypy_baseline: FAIL")
@@ -290,6 +533,9 @@ def _coverage_self_test() -> tuple[list[str], int]:
service = '[tool.poetry]\nname = "x"\n\n[tool.mypy]\npython_version = "3.11"\n'
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
+ # `unmanaged_files` reads the tree through git and fails closed when
+ # it cannot, so the fixture has to be a real repository.
+ subprocess.run(["git", "init", "-q"], cwd=root, check=False, capture_output=True) # noqa: S603 - fixed argv
(root / "services" / "alpha").mkdir(parents=True)
(root / "services" / "alpha" / "pyproject.toml").write_text(service, encoding="utf-8")
# A tree somewhere the old `services/*` + `packages/*` glob never looked.
@@ -338,6 +584,91 @@ def _coverage_self_test() -> tuple[list[str], int]:
)
)
+ # file -> scope, against a real git repository: the complement has to
+ # be computed from the tree, because a listed one is the convention
+ # this gate exists to refuse.
+ (root / "scripts").mkdir()
+ (root / "scripts" / "gate.py").write_text("x = 1\n", encoding="utf-8")
+ (root / "services" / "alpha" / "mod.py").write_text("y = 2\n", encoding="utf-8")
+ # A tree in a directory no convention would have thought to look in.
+ (root / "bench").mkdir()
+ (root / "bench" / "runner.py").write_text("z = 3\n", encoding="utf-8")
+ (root / "plans" / "cyble-aisoc" / "old.py").write_text("w = 4\n", encoding="utf-8")
+ subprocess.run(["git", "add", "-A"], cwd=root, check=False, capture_output=True) # noqa: S603 - fixed argv
+
+ orphans = set(unmanaged_files(root, python_trees(root)))
+ cases.append(
+ (
+ "a file in no tree is unmanaged, wherever it sits",
+ "" if {"scripts/gate.py", "bench/runner.py"} <= orphans else f"got {sorted(orphans)}",
+ )
+ )
+ cases.append(
+ (
+ "a file inside a tree is not unmanaged, and plans/ is excluded",
+ "" if not ({"services/alpha/mod.py", "plans/cyble-aisoc/old.py"} & orphans) else f"got {sorted(orphans)}",
+ )
+ )
+
+ # Deleting a manifest must move its files into the unmanaged scope
+ # rather than out of coverage — the two directions cannot both be
+ # satisfied by removing something.
+ (root / "services" / "alpha" / "pyproject.toml").unlink()
+ moved = set(unmanaged_files(root, python_trees(root)))
+ cases.append(
+ (
+ "deleting a manifest moves its files into the scope, not out of coverage",
+ "" if "services/alpha/mod.py" in moved else f"got {sorted(moved)}",
+ )
+ )
+
+ # And the scope loses its config: 153 files returning to nothing must
+ # fail, not pass quietly.
+ problems = coverage_problems(root, discover(root), {})
+ cases.append(
+ (
+ "a missing unmanaged config is reported",
+ "" if any("file -> scope" in p for p in problems) else f"got {problems}",
+ )
+ )
+
+ # Module-name batching, which is what makes plugins/*/plugin.py
+ # checkable at all. Derived from the tree, so a future collision costs
+ # nobody a code change.
+ for plugin in ("one", "two"):
+ (root / "plugins" / plugin).mkdir(parents=True)
+ (root / "plugins" / plugin / "plugin.py").write_text("v = 5\n", encoding="utf-8")
+ groups = batch(root, ["plugins/one/plugin.py", "plugins/two/plugin.py", "scripts/gate.py"])
+ cases.append(
+ (
+ "two files with one module name go to separate invocations",
+ "" if len(groups) == 2 and all(len({module_name(root, f) for f in g}) == len(g) for g in groups) else f"got {groups}",
+ )
+ )
+ # `tools/__init__.py` makes `tools.detection_import.common` rather
+ # than `common`, and getting that wrong invents collisions that split
+ # the run into hundreds of invocations.
+ (root / "pkg").mkdir()
+ (root / "pkg" / "__init__.py").write_text("", encoding="utf-8")
+ (root / "pkg" / "leaf.py").write_text("", encoding="utf-8")
+ cases.append(
+ (
+ "module names follow __init__.py up the tree",
+ ""
+ if (module_name(root, "pkg/leaf.py"), module_name(root, "scripts/gate.py")) == ("pkg.leaf", "gate")
+ else f"got {module_name(root, 'pkg/leaf.py')} / {module_name(root, 'scripts/gate.py')}",
+ )
+ )
+
+ # An empty scope is a broken walk far more often than a tidy tree.
+ empty, error = run_mypy_unmanaged(root, [])
+ cases.append(
+ (
+ "an empty scope fails rather than reporting clean",
+ "" if error and not empty else f"got {error!r}",
+ )
+ )
+
for name, failure in cases:
if failure:
failures.append(f"{name}: {failure}")
@@ -382,8 +713,8 @@ def self_test(root: Path) -> int:
# The baseline must describe this tree, not a remembered one.
trees, recorded = discover(root), load(root)
- if trees and recorded and set(trees) != set(recorded):
- failures.append(f"baseline covers {sorted(recorded)} but the tree declares {sorted(trees)}")
+ if trees and recorded and set(trees) | {UNMANAGED_SCOPE} != set(recorded):
+ failures.append(f"baseline covers {sorted(recorded)} but the tree declares {sorted(trees)} plus {UNMANAGED_SCOPE}")
print(f" self-test [{'FAIL' if failures and 'baseline covers' in failures[-1] else 'ok'}] baseline matches the tree")
coverage_failures, coverage_cases = _coverage_self_test()
diff --git a/scripts/check_repo_self_links.py b/scripts/check_repo_self_links.py
index aa4ecc6e0..45af2b073 100644
--- a/scripts/check_repo_self_links.py
+++ b/scripts/check_repo_self_links.py
@@ -86,14 +86,23 @@ def _is_ours(owner: str, repo: str) -> bool:
def main() -> int:
wrong_owner: list[tuple[Path, int, str]] = []
missing_path: list[tuple[Path, int, str]] = []
+ unreadable: list[str] = []
+ links_examined = 0
- for md in _markdown_files():
+ files = _markdown_files()
+ for md in files:
try:
lines = md.read_text(encoding="utf-8").splitlines()
except UnicodeDecodeError:
+ # Skipping it silently means a file nobody can read is a file
+ # nobody checks, reported as clean. This gate replaced a lychee
+ # run that accepted 403 and 429 as healthy; inheriting the same
+ # inability in a different costume is the thing to avoid.
+ unreadable.append(md.relative_to(REPO_ROOT).as_posix())
continue
for lineno, line in enumerate(lines, start=1):
for m in LINK_RE.finditer(line):
+ links_examined += 1
owner, repo = m.group("owner"), m.group("repo")
if not _is_ours(owner, repo):
continue
@@ -113,6 +122,28 @@ def main() -> int:
if not (REPO_ROOT / target).exists():
missing_path.append((rel, lineno, target))
+ # Say what was opened before saying it was clean. Zero markdown files and
+ # zero broken links produce the same "OK" from the same branch, and the
+ # eight wrong-org 404s that prompted this gate survived a link job that
+ # was reporting healthy for exactly that reason.
+ print(f"check_repo_self_links: {len(files)} markdown file(s), {links_examined} GitHub link(s) examined")
+ if not files or not links_examined:
+ print(
+ f"\ncheck_repo_self_links: FAIL — scanned {len(files)} file(s) and found "
+ f"{links_examined} link(s) to examine under {REPO_ROOT}. A clean result over "
+ f"nothing is not a clean result; check SEARCH_ROOTS and LINK_RE.",
+ file=sys.stderr,
+ )
+ return 1
+ if unreadable:
+ print(
+ f"\n{len(unreadable)} file(s) could not be decoded and were therefore not checked:",
+ file=sys.stderr,
+ )
+ for rel_path in unreadable:
+ print(f" {rel_path}", file=sys.stderr)
+ return 1
+
if not wrong_owner and not missing_path:
print("check_repo_self_links: OK — every self-link resolves to a real path")
return 0
diff --git a/scripts/generate_connector_count.py b/scripts/generate_connector_count.py
index f69033b39..7e570b7ad 100755
--- a/scripts/generate_connector_count.py
+++ b/scripts/generate_connector_count.py
@@ -41,6 +41,7 @@ import re
import sys
from collections import Counter
from pathlib import Path
+from typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parent
REGISTRY_FILE = REPO_ROOT / "services" / "connectors" / "app" / "connectors" / "__init__.py"
@@ -140,8 +141,15 @@ def parse_category_counts() -> dict[str, int]:
return dict(sorted(counts.items()))
-def build_payload() -> dict[str, object]:
- """Produce the on-disk payload."""
+def build_payload() -> dict[str, Any]:
+ """Produce the on-disk payload.
+
+ `Any` rather than `object`: this is a JSON document with heterogeneous
+ values, and declaring `object` forced the two read sites below to carry
+ `# type: ignore[arg-type]` comments for an error code mypy does not emit
+ here — a suppression that suppresses nothing while telling the next
+ reader a checker was consulted and agreed.
+ """
count = parse_registry_count()
categories = parse_category_counts()
return {
@@ -218,7 +226,7 @@ def main(argv: list[str]) -> int:
args = parser.parse_args(argv)
payload = build_payload()
- count = int(payload["count"]) # type: ignore[arg-type]
+ count = int(payload["count"])
drift: list[str] = []
@@ -240,10 +248,7 @@ def main(argv: list[str]) -> int:
print(f" - {line}", file=sys.stderr)
return 1
- print(
- f"connector-count OK — {count} registered, {len(payload['categories'])}" # type: ignore[arg-type]
- " categories"
- )
+ print(f"connector-count OK — {count} registered, {len(payload['categories'])}" " categories")
return 0
diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.json
index e078509c6..634ece853 100644
--- a/scripts/mypy_baseline.json
+++ b/scripts/mypy_baseline.json
@@ -1,4 +1,114 @@
{
+ "(unmanaged)": {
+ "plugins/mttr-widget/plugin.py": {
+ "arg-type": 3,
+ "return-value": 1
+ },
+ "scripts/audit_managed_tenants.py": {
+ "import-untyped": 1
+ },
+ "scripts/build_marketplace.py": {
+ "import-untyped": 1
+ },
+ "scripts/build_quarantine_index.py": {
+ "import-untyped": 1
+ },
+ "scripts/check_codeql_alerts.py": {
+ "assignment": 1,
+ "index": 3
+ },
+ "scripts/check_fidelity_datasets.py": {
+ "import-untyped": 1
+ },
+ "scripts/check_gate_coverage.py": {
+ "import-untyped": 1
+ },
+ "scripts/check_slos.py": {
+ "import-untyped": 1
+ },
+ "scripts/curate_detections.py": {
+ "import-untyped": 1
+ },
+ "scripts/datasets/download_ait_lds.py": {
+ "arg-type": 1,
+ "misc": 1
+ },
+ "scripts/detection_specs_part3_helpers.py": {
+ "arg-type": 1
+ },
+ "scripts/detection_truth_table.py": {
+ "import-untyped": 1
+ },
+ "scripts/eval_telemetry.py": {
+ "arg-type": 3
+ },
+ "scripts/export_openapi.py": {
+ "import-untyped": 1
+ },
+ "scripts/generate_connector_types.py": {
+ "attr-defined": 2
+ },
+ "scripts/generate_detections.py": {
+ "import-untyped": 1
+ },
+ "scripts/generate_slo_alerts.py": {
+ "import-untyped": 1
+ },
+ "scripts/lint_playbooks.py": {
+ "assignment": 1
+ },
+ "scripts/openapi_diff.py": {
+ "import-untyped": 1
+ },
+ "scripts/project_stats.py": {
+ "assignment": 1,
+ "import-untyped": 1
+ },
+ "scripts/run_evals.py": {
+ "attr-defined": 9,
+ "index": 13,
+ "no-redef": 1
+ },
+ "scripts/upgrade_playbooks.py": {
+ "arg-type": 1
+ },
+ "scripts/validate_detections.py": {
+ "import-untyped": 1
+ },
+ "scripts/wet_eval.py": {
+ "arg-type": 4
+ },
+ "scripts/wet_eval_check.py": {
+ "arg-type": 1
+ },
+ "tests/test_detection_id_stability.py": {
+ "attr-defined": 2
+ },
+ "tests/test_first_run_gate.py": {
+ "import-untyped": 1
+ },
+ "tests/test_openapi_diff.py": {
+ "import-untyped": 1
+ },
+ "tests/test_readme_figures_gate.py": {
+ "attr-defined": 5
+ },
+ "tests/test_toolchain_pin_gate.py": {
+ "name-defined": 1
+ },
+ "tools/detection_import/car_importer.py": {
+ "import-untyped": 1
+ },
+ "tools/detection_import/common.py": {
+ "import-untyped": 1
+ },
+ "tools/detection_import/sigma_importer.py": {
+ "import-untyped": 1
+ },
+ "tools/detection_import/splunk_importer.py": {
+ "import-untyped": 1
+ }
+ },
"packages/aisoc-ai-sdk": {
"aisoc_ai/client.py": {
"type-arg": 1
diff --git a/scripts/validate_detections.py b/scripts/validate_detections.py
index 0908773c0..30cd2fc34 100755
--- a/scripts/validate_detections.py
+++ b/scripts/validate_detections.py
@@ -365,8 +365,17 @@ def main() -> int:
yaml_files = sorted(DETECTIONS_DIR.rglob("*.yaml"))
if not yaml_files:
- print("WARNING: No .yaml files found under detections/")
- return 0
+ # This was a WARNING and an exit 0 — the validator for the corpus the
+ # product's headline number describes, certifying an empty corpus as
+ # valid. "No rules are broken" and "no rules were opened" are the same
+ # sentence here, and only one of them is good news.
+ print(
+ f"ERROR: no .yaml files found under {DETECTIONS_DIR}. Zero rules validated is "
+ f"not zero rules broken — either the corpus is gone or this is not the tree "
+ f"it was meant to read.",
+ file=sys.stderr,
+ )
+ return 1
seen_ids: dict[str, Path] = {}
total = 0