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
Type-check the fourteen trees nothing checked, and gate the coverage both ways
Beenu Arora1ad91875fb03
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 26c33b92b..84590a140 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -235,25 +235,50 @@ jobs:- name: Ruff format check (all services)run: ruff format --check services/# This job has been called "Lint & Type-check" since it was written, and- # until now it installed mypy and never ran it. Six manifests declare a- # `[tool.mypy]` table and three set `strict = true`, so the config asked- # for a check that had never once executed.+ # for most of that time it installed mypy and never ran it. #818 ran it+ # over the six manifests that declared a `[tool.mypy]` table — which+ # left fourteen Python trees checked by nothing while the job reported+ # green, and a tool that appears to cover the repository while covering+ # a third of it is indistinguishable from no tool at all, only more+ # reassuring. All twenty trees now declare one, matching the two+ # strictness shapes that already existed rather than inventing a third.#- # The findings are real and there are 690 of them. They are recorded in- # `scripts/mypy_baseline.json` exactly as mypy reports them and the gate- # fails when any grows — no `ignore_errors`, no widened config, no tree- # excluded. Nothing installs the services' dependencies here on purpose:- # mypy's answer depends on what is importable, so the baseline is only- # reproducible against a fixed environment, and "mypy alone on 3.11" is- # that environment — 3.11 because that is the interpreter every service- # image ships, and a baseline recorded on an interpreter production does- # not run is a baseline for software nobody ships. Re-record with+ # The findings are recorded in `scripts/mypy_baseline.json` exactly as+ # mypy reports them and the gate fails when any grows — no+ # `ignore_errors`, no widened config, no tree excluded. Nothing installs+ # the services' dependencies here on purpose: mypy's answer depends on+ # what is importable, so the baseline is only reproducible against a+ # fixed environment, and "mypy alone on 3.11" is that environment — 3.11+ # because that is the interpreter every service image ships, and a+ # baseline recorded on an interpreter production does not run is a+ # baseline for software nobody ships. Re-record with# `python scripts/check_mypy_baseline.py --update` under the same# conditions.+ #+ # The same gate now also fails when a Python tree declares no+ # `[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.- name: The type-check this job is named afterrun: |python scripts/check_mypy_baseline.py --self-testpython scripts/check_mypy_baseline.py+ # `logging.Logger.warning` accepts four keywords; structlog's bound+ # logger accepts any. Both are used in this tree, so+ # `logger.warning("x", reason=...)` is correct in one module and a+ # TypeError in the next, and the call sites are identical to read. #818+ # found five, all inside `except` blocks — where the raised TypeError+ # 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.+ - name: No stdlib logger is called with a structlog keyword+ run: |+ python scripts/check_logger_kwargs.py --self-test+ python scripts/check_logger_kwargs.py# The aisoc-api Docker image is built with `services/api` as its build# context, so anything under `services/agents` is *not* shipped in the# container. The natural-language query translator is consumed by bothdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex cffecb315..8630af5bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,76 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **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+ "Lint & Type-check" reported green over 787 Python files it never opened — a+ tool that appears to cover the repository while covering a third of it is+ indistinguishable from no tool at all, only more reassuring.++ Every tree now declares one, matching the two strictness shapes that already+ existed rather than inventing a third: the ten services take+ `python_version = "3.11"` / `strict = false` / `ignore_missing_imports = true`+ like `services/api` and `services/osquery-tls`; the four packages take+ `strict = true` / `python_version = "3.11"` like `packages/sdk-py`,+ `plugin-sdk-py` and `aisoc-cli`. No `ignore_errors`, no widened config, no+ `# type: ignore` added to reach a number.++ `scripts/check_mypy_baseline.py` gains the coverage check itself, rather than+ a second gate with its own idea of what a tree is. A Python tree on disk that+ declares no `[tool.mypy]` fails (`tree -> config`), and a configured or+ recorded tree that is no longer on disk fails (`config -> tree`) — the+ direction that rots quietly, because nothing ever fails when a stale entry is+ simply never consulted. Discovery is now structural, every directory holding a+ `pyproject.toml`, instead of `services/*` plus `packages/*`: the glob was a+ naming convention, and a Python tree added anywhere else would have satisfied+ a coverage gate written against that same glob while being checked by nothing.+ The gate resolves its root from `git rev-parse` rather than from its own file+ location, prints how many trees and files were in scope, and its `--self-test`+ injects coverage drift each way against a throwaway repository.++- **`scripts/check_logger_kwargs.py` — no stdlib logger may be called with a+ structlog keyword.** `logging.Logger.warning` accepts exactly `exc_info`,+ `stack_info`, `stacklevel` and `extra`; structlog's bound logger accepts any+ keyword and turns it into the event dict. Both libraries are used in this+ tree, so `logger.warning("x", reason=exc.reason)` is correct in one module and+ a `TypeError` in the next, and the two call sites are identical to read — only+ the binding decides.++ This needs a checker rather than a grep because of *where* it hides. All five+ instances `#818` fixed were inside `except` blocks, where the raised+ `TypeError` replaces the exception being handled and no sibling handler can+ catch it. A misused keyword on the happy path is found by the first person to+ run the code; the same keyword in a fallback runs only when something has+ already gone wrong. The report sorts by context and names how many findings+ sit on such a path.++ The scanner resolves each module's logger flavour rather than assuming one:+ every binding, not just `logger`; `self._log` and class-body loggers reached+ through the instance; `from app.core.logging import get_logger` followed to+ the defining module, because both in-repo `get_logger` helpers return+ structlog while their name says nothing; `.bind()` / `.getChild()` chains;+ annotations, including parameters, for a logger that is handed in; and+ `logging.warning(...)` on the root logger. A `**kwargs` splat onto a stdlib+ logger cannot be decided statically and is reported separately rather than+ counted as clean, and a receiver it cannot classify is counted as+ `unresolved`, never as clean.++ It covers all 1,408 Python files including the ~150 under `scripts/`,+ `tests/`, `tools/` and `plugins/` that belong to no tree and so are checked by+ no `[tool.mypy]` at all. It classifies 514 stdlib and 970 structlog call sites+ with 18 unresolved receivers, and reports zero defects — and fails outright if+ it classifies no stdlib logger, because "found nothing" and "resolved nothing"+ otherwise print the same word. Pointed at the pre-`#818` files it reports all+ five, each labelled `[inside except]`.++ Three shapes were added after the first version reported a clean tree and the+ shapes were then found *in* that tree: an inline+ `logging.getLogger(__name__).warning(...)` with no binding to look up+ (`detection_proposals.py`), a class-body logger reached as `self.logger`+ (`core/config.py`), and an annotation with no factory call in sight. All three+ were invisible to a scanner that only read assignments of a name.+- **CI now runs the interpreter production runs, and `gofmt`, `services/realtime`and the published image list are gated.** Three loose ends `#817` named anddid not close.@@ -914,6 +984,69 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Every live Okta password reset raised `TypeError` and came back FAILED.**+ `ResetPasswordExecutor` documents `parameters.send_email` as "used only for+ the Okta path", reads it, and passed `send_email=` to+ `OktaClient.reset_password(self, login_or_id)` — which did not accept it. The+ executor's `except Exception` turned the `TypeError` into a FAILED+ `ActionResult`, so the verb did not crash; it simply could never succeed+ against Okta, and the failure read as an Okta problem. Simulation mode never+ constructs a vendor client, which is why no test saw it: the one that covers+ this executor stubs the client as `async def reset_password(self, *_args,+ **_kw)`, and a fake that accepts anything proves the dispatch order and+ nothing about the call. The client now takes `send_email` and maps it to+ Okta's `sendEmail` parameter, and `test_identity_client_signatures.py`+ autospecs all three IdP clients across every executor arm — the companion to+ `test_siem_client_signatures.py`, for the third instance of the same defect.++- **The natural-language playbook drafter could never reach an LLM.**+ `nl_drafter._llm_factory` called `make_chat_model()`, and `role` is a required+ positional parameter; every other caller in the tree passes one. The+ `TypeError` was caught by the `except Exception` two lines down, which logged+ "no chat model available" and returned `None`, so the drafter fell back to its+ deterministic substrate path on every call, permanently, while reporting the+ condition as a missing provider. Every test monkeypatches `_llm_factory`, so+ the one line that mattered was the one line nothing exercised. Now passes+ `"nl"`, the declared role in `app.llm.model_pins`.++- **A cancelled context-graph walk crashed the context bundle.**+ `_fetch_neighborhoods` and `_fetch_ueba_baselines` filter+ `asyncio.gather(..., return_exceptions=True)` results with+ `isinstance(r, Exception)`, then unpack the survivors as a tuple.+ `asyncio.CancelledError` is a `BaseException` and not an `Exception` on 3.8+,+ so a cancelled child task passed the filter and reached the unpack as+ `TypeError: cannot unpack non-sequence CancelledError`. `services/slack-bot`+ carries a comment spelling out this exact trap; these two sites got it wrong.+ Both now filter on `BaseException`.++- **`_SECRET_PATTERNS` was declared with a type its value cannot have, which+ switched off checking of the secret-masking loop.** The annotation in the AI+ SDK's redaction module read+ `tuple[tuple[str, re.Pattern[str]], None | str] | tuple`, whose first member+ is a two-element tuple — structurally impossible for the eight-pair value, so+ it only ever matched through the bare `| tuple`. That erases the element type+ to `Any`, which is why nothing objected to calling `.subn` on something typed+ as possibly a `str`. In a path whose job is to stop secrets leaving the+ process, a checker that has been silently switched off is worse than none.+ Declared `tuple[tuple[str, re.Pattern[str]], ...]`, which is what it is.++- **`diff_fingerprints` was declared to return `dict[str, list[str]]` and never+ has.** It returns `unchanged_count` as an `int`, which the connector+ scheduler stores and a test asserts on. Because the scheduler assigns the+ result straight into a `dict[str, Any]` variable, the wrong declaration+ narrowed that variable and made the three correct lines underneath it look+ like type errors instead — one wrong annotation producing four findings across+ two modules. Declared `dict[str, Any]`, which is what both consumers and the+ JSONB column already expect.++- **A Google Workspace key that was valid JSON but not an object failed inside+ the JWT signing path.** `json.loads` returns a `str`, `list` or `int` for a+ document that is valid JSON and not an object, and the constructor accepted+ it; the failure surfaced later as `TypeError: string indices must be integers`+ at `self._key["client_email"]`, at the moment an operator triggered a live+ action. The configuration is wrong either way — it now says so when the+ credential is saved rather than when it is used.+- **Five LLM input-contract handlers raised `TypeError` instead of degrading.**`/translation`, `/phishing`, `/knowledge-base`, `/hunts` and `/detection-loop`each catch `LLMContractViolation` — the untrusted-input boundary refusing adiff --git a/packages/aisoc-ai-sdk/aisoc_ai/redaction.py b/packages/aisoc-ai-sdk/aisoc_ai/redaction.pyindex 98b4cc076..3d66fb075 100644--- a/packages/aisoc-ai-sdk/aisoc_ai/redaction.py+++ b/packages/aisoc-ai-sdk/aisoc_ai/redaction.py@@ -42,7 +42,14 @@ class CaptureMode(str, Enum):#: Deliberately narrow and high-confidence. A greedy redactor that mangles#: ordinary prose trains people to turn redaction off, which is a worse#: outcome than a narrow one that they leave on.-_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], None | str] | tuple = (+#: The declared type used to be+#: ``tuple[tuple[str, re.Pattern[str]], None | str] | tuple``, whose first+#: member is a two-element tuple — structurally impossible for the eight-pair+#: value below, so it only ever matched through the bare ``| tuple``. That+#: erases the element type to ``Any``, which is why nothing objected to+#: ``pattern.subn`` on something typed as possibly a ``str``. In a masking+#: path, a checker that has been silently switched off is worse than none.+_SECRET_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (("aws_access_key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),("github_token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b")),("openai_key", re.compile(r"\bsk-[A-Za-z0-9_-]{20,}\b")),diff --git a/packages/aisoc-ai-sdk/pyproject.toml b/packages/aisoc-ai-sdk/pyproject.tomlindex b2479a33c..a708cfbb0 100644--- a/packages/aisoc-ai-sdk/pyproject.toml+++ b/packages/aisoc-ai-sdk/pyproject.toml@@ -32,3 +32,9 @@ Source = "https://github.com/beenuar/AiSOC/tree/main/packages/aisoc-ai-sdk"[tool.hatch.build.targets.wheel]packages = ["aisoc_ai"]++# Same shape as packages/sdk-py, plugin-sdk-py and aisoc-cli — the three+# package trees that already declare one.+[tool.mypy]+strict = true+python_version = "3.11"diff --git a/packages/aisoc-benchmark/pyproject.toml b/packages/aisoc-benchmark/pyproject.tomlindex f2dd53869..9e2a81b18 100644--- a/packages/aisoc-benchmark/pyproject.toml+++ b/packages/aisoc-benchmark/pyproject.toml@@ -19,3 +19,9 @@ packages = ["aisoc_benchmark"][tool.hatch.build.targets.sdist]include = ["aisoc_benchmark", "corpus", "README.md"]++# Same shape as packages/sdk-py, plugin-sdk-py and aisoc-cli — the three+# package trees that already declare one.+[tool.mypy]+strict = true+python_version = "3.11"diff --git a/packages/aisoc-detections/pyproject.toml b/packages/aisoc-detections/pyproject.tomlindex 3705920a7..98fef2edc 100644--- a/packages/aisoc-detections/pyproject.toml+++ b/packages/aisoc-detections/pyproject.toml@@ -55,3 +55,9 @@ target-version = "py311"[tool.pytest.ini_options]testpaths = ["tests"]++# Same shape as packages/sdk-py, plugin-sdk-py and aisoc-cli — the three+# package trees that already declare one.+[tool.mypy]+strict = true+python_version = "3.11"diff --git a/packages/aisoc-sandbox/pyproject.toml b/packages/aisoc-sandbox/pyproject.tomlindex 5b151a838..ecaf978fc 100644--- a/packages/aisoc-sandbox/pyproject.toml+++ b/packages/aisoc-sandbox/pyproject.toml@@ -56,3 +56,11 @@ aisoc_sandbox = ["scenarios/*.json", "py.typed"][tool.pytest.ini_options]addopts = "-ra --strict-markers"testpaths = ["tests"]++# Same shape as packages/sdk-py, plugin-sdk-py and aisoc-cli — the three+# package trees that already declare one. `python_version` is pinned to 3.11+# even though the wheel supports 3.10+: the baseline has to be reproducible,+# and 3.11 is the interpreter CI runs.+[tool.mypy]+strict = true+python_version = "3.11"diff --git a/scripts/check_logger_kwargs.py b/scripts/check_logger_kwargs.pynew file mode 100644index 000000000..7f5d8f77f--- /dev/null+++ b/scripts/check_logger_kwargs.py@@ -0,0 +1,776 @@+#!/usr/bin/env python3+"""Refuse a stdlib logger called with a structlog keyword.++`logging.Logger.warning(msg, *args, **kwargs)` accepts exactly four keywords —+`exc_info`, `stack_info`, `stacklevel`, `extra`. Anything else is a+`TypeError`. structlog's bound logger accepts arbitrary keywords and turns+them into the event dict, and both libraries are used in this tree, so+`logger.warning("thing.failed", reason=exc.reason)` is correct in one module+and raises in the next. The two are indistinguishable by eye: the call site+looks identical, and only the binding three hundred lines up decides.++The reason this needs a gate rather than a grep is *where* it hides. #818+found five of these, all in the handler for a refused LLM prompt. An+exception raised inside an `except` block is not caught by a sibling handler,+so the `except Exception` underneath never saw it: the one path whose entire+job was to degrade gracefully was the only path that raised. One of the five+even carried a comment explaining the log line existed because the handler+used to fail silently — the fix for the silent failure was itself throwing.++That is the general shape. A misused keyword on the happy path is found by+the first person to run the code. The same keyword in an exception handler, a+`finally`, or a fallback branch runs only when something has already gone+wrong, converts a handled error into an unhandled one, and is invisible until+the day it matters. So the report sorts by context, and names how many of the+findings sit on a path that only executes when something else already broke.++Deciding stdlib vs structlog is the whole problem, and the parser is written+assuming it has a blind spot:++ * every binding is tracked, not the name `logger` — `LOG`, `log`, `_log`+ and `self._logger` are all in the tree;+ * `from app.core.logging import get_logger` is resolved to the defining+ module and re-asked, because both in-repo `get_logger` helpers return+ structlog while their *name* says nothing;+ * a name rebound later in the module takes the later flavour;+ * a `**kwargs` splat onto a stdlib logger cannot be decided statically, so+ it is reported separately rather than counted as clean;+ * `logging.warning(...)` module-level calls are checked too, since the+ root logger has the same signature.++Three shapes were added after the first version reported a clean tree and the+shapes were then found *in* that tree, which is the only reason to believe+any of the rest works. `logging.getLogger(__name__).warning(...)` with no+intermediate binding is used in `detection_proposals.py`; a class-body+`logger = logging.getLogger(...)` reached later as `self.logger` is used in+`core/config.py`; and an annotation (`x: logging.Logger`, including a+parameter) settles the flavour with no factory call in sight. All three were+invisible to a scanner that only looked at assignments of a name.++Unresolved bindings are reported as `unknown`, never as clean. A scanner that+silently drops what it could not classify is the failure mode this repository+keeps rediscovering — a gate that matched a tool name inside quoted strings+and printed OK about the exact gap it existed to find.++Usage:+ python scripts/check_logger_kwargs.py+ python scripts/check_logger_kwargs.py --self-test+ python scripts/check_logger_kwargs.py --show-unknown+"""++from __future__ import annotations++import argparse+import ast+import subprocess+import sys+from collections import defaultdict+from dataclasses import dataclass+from pathlib import Path++# `logging.Logger._log` forwards exactly these. Everything else is a TypeError.+STDLIB_KWARGS = frozenset({"exc_info", "stack_info", "stacklevel", "extra"})++# Methods a stdlib Logger actually has. structlog adds `msg`, `failure` and+# friends; calling those on a stdlib logger is an AttributeError, which is a+# different defect and not one this gate claims to find.+LOG_METHODS = frozenset({"debug", "info", "warning", "warn", "error", "exception", "critical", "fatal", "log"})++STDLIB = "stdlib"+STRUCTLOG = "structlog"++# Factories, as (module, attribute). The module part is matched against the+# alias actually imported, so `import logging as pylog` still resolves.+_STDLIB_FACTORIES = {("logging", "getLogger"), ("logging", "Logger"), ("logging", "LoggerAdapter"), ("logging", "getLoggerClass")}+_STRUCTLOG_FACTORIES = {+ ("structlog", "get_logger"),+ ("structlog", "getLogger"),+ ("structlog", "wrap_logger"),+ ("structlog.stdlib", "get_logger"),+ ("structlog.stdlib", "BoundLogger"),+}++# An annotation settles the flavour with no factory call in sight, which is+# the only evidence available when a logger arrives as a parameter.+_STDLIB_ANNOTATIONS = {"logging.Logger", "logging.LoggerAdapter", "Logger", "LoggerAdapter"}+_STRUCTLOG_ANNOTATIONS = {+ "structlog.BoundLogger",+ "structlog.stdlib.BoundLogger",+ "structlog.types.FilteringBoundLogger",+ "BoundLogger",+ "FilteringBoundLogger",+}++# Methods that return another logger of the same flavour. `bind` is how every+# structlog call site in this tree narrows a logger, and `getChild` is its+# stdlib counterpart — without them a chained receiver is unresolved, and an+# unresolved receiver is one this gate cannot speak for.+_REBINDING_METHODS = frozenset({"bind", "new", "unbind", "try_unbind", "getChild"})++# Modules whose members collide with a log method name. `math.log` and+# `warnings.warn` are not loggers, and counting them as unresolved makes the+# unresolved bucket look worse than it is.+_NOT_LOGGING_MODULES = frozenset({"math", "cmath", "numpy", "np", "warnings", "statistics"})++_SKIP_DIRS = frozenset({"node_modules", ".venv", "venv", "site-packages", "__pycache__", ".git", "dist", "build"})+# The archived prototype. CodeQL already carries the same exclusion, and the+# project rules forbid editing anything under it, so a finding there is not+# actionable.+_SKIP_PREFIXES = ("plans/",)+++@dataclass(frozen=True)+class Finding:+ path: str+ line: int+ binding: str+ method: str+ keywords: tuple[str, ...]+ context: str # "except", "finally", "handler-adjacent" or "normal"+ kind: str # "stdlib-kwarg" or "unknown-splat"++ def describe(self) -> str:+ where = "" if self.context == "normal" else f" [inside {self.context}]"+ kw = ", ".join(f"{k}=" for k in self.keywords)+ return f"{self.path}:{self.line}: {self.binding}.{self.method}({kw}…){where}"+++def repo_root() -> Path:+ """The repository, per git — not per this file's location.++ A sibling gate resolved its root from ``Path(__file__).parent.parent`` and+ would have printed a confident OK about a tree it never opened, because a+ copy of the script run from anywhere else scans whatever happens to sit+ two levels above it.+ """+ 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+++def python_files(root: Path) -> list[Path]:+ files: list[Path] = []+ for path in root.rglob("*.py"):+ rel = path.relative_to(root).as_posix()+ if any(part in _SKIP_DIRS for part in path.parts):+ continue+ if rel.startswith(_SKIP_PREFIXES):+ continue+ files.append(path)+ return sorted(files)+++def _dotted(node: ast.expr) -> str | None:+ """`a.b.c` -> "a.b.c", for Name/Attribute chains only."""+ parts: list[str] = []+ while isinstance(node, ast.Attribute):+ parts.append(node.attr)+ node = node.value+ if not isinstance(node, ast.Name):+ return None+ parts.append(node.id)+ return ".".join(reversed(parts))+++def _class_bodies(tree: ast.Module) -> set[int]:+ """`id()` of every statement sitting directly in a class body."""+ ids: set[int] = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef):+ ids.update(id(stmt) for stmt in node.body)+ return ids+++def _tree_root(path: Path, root: Path) -> Path:+ """Nearest ancestor holding a pyproject.toml — the import root for `app.*`."""+ for parent in [path.parent, *path.parent.parents]:+ if (parent / "pyproject.toml").is_file():+ return parent+ if parent == root:+ break+ return root+++class _ModuleScan:+ """Logger flavours bound in one module, plus every logging call site."""++ def __init__(self, path: Path, root: Path, resolver: _Resolver) -> None:+ self.path = path+ self.root = root+ self.resolver = resolver+ self.rel = path.relative_to(root).as_posix()+ # alias -> canonical module, e.g. {"logging": "logging", "sl": "structlog"}+ self.module_aliases: dict[str, str] = {}+ # bare name -> (module, attr), e.g. {"getLogger": ("logging", "getLogger")}+ self.name_imports: dict[str, tuple[str, str]] = {}+ # binding -> STDLIB | STRUCTLOG | None+ self.flavours: dict[str, str | None] = {}+ self.exports: dict[str, str | None] = {}++ # -- imports ---------------------------------------------------------+ def collect_imports(self, tree: ast.Module) -> None:+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ self.module_aliases[alias.asname or alias.name.split(".")[0]] = alias.name+ elif isinstance(node, ast.ImportFrom):+ module = self._absolute_module(node)+ for alias in node.names:+ if alias.name == "*":+ continue+ self.name_imports[alias.asname or alias.name] = (module, alias.name)++ def _absolute_module(self, node: ast.ImportFrom) -> str:+ if not node.level:+ return node.module or ""+ # Relative import: walk up from this file's package.+ pkg = self.path.parent+ for _ in range(node.level - 1):+ pkg = pkg.parent+ tree_root = _tree_root(self.path, self.root)+ try:+ base = pkg.relative_to(tree_root).as_posix().replace("/", ".")+ except ValueError:+ base = ""+ return f"{base}.{node.module}" if node.module else base++ # -- flavour of an expression ---------------------------------------+ def flavour_of_call(self, call: ast.Call) -> str | None:+ target = call.func+ # `logger.bind(...)` / `logger.getChild(...)` — same logger, narrowed.+ if isinstance(target, ast.Attribute) and target.attr in _REBINDING_METHODS:+ inner = self.flavour_of_expr(target.value)+ if inner is not None:+ return inner+ dotted = _dotted(target)+ if dotted is None:+ return None+ head, _, tail = dotted.rpartition(".")+ if head:+ # `logging.getLogger(...)` / `structlog.stdlib.get_logger(...)`+ root_alias, _, rest = head.partition(".")+ canonical = self.module_aliases.get(root_alias, root_alias)+ module = f"{canonical}.{rest}" if rest else canonical+ if (module, tail) in _STDLIB_FACTORIES:+ return STDLIB+ if (module, tail) in _STRUCTLOG_FACTORIES:+ return STRUCTLOG+ return None+ # A bare call: `get_logger(...)` / `getLogger(...)`.+ imported = self.name_imports.get(tail)+ if imported is None:+ return None+ module, original = imported+ if (module, original) in _STDLIB_FACTORIES:+ return STDLIB+ if (module, original) in _STRUCTLOG_FACTORIES:+ return STRUCTLOG+ # Defined somewhere in this repository — go and read it.+ return self.resolver.flavour_of_export(module, original, self.path)++ def flavour_of_expr(self, node: ast.expr) -> str | None:+ """Flavour of any receiver expression: a name, an attribute, or a call."""+ if isinstance(node, ast.Call):+ return self.flavour_of_call(node)+ dotted = _dotted(node)+ if dotted is None:+ return None+ if dotted.partition(".")[0] in _NOT_LOGGING_MODULES:+ return None+ return self.flavours.get(dotted)++ def flavour_of_annotation(self, annotation: ast.expr | None) -> str | None:+ dotted = _dotted(annotation) if annotation is not None else None+ if dotted is None and isinstance(annotation, ast.Constant) and isinstance(annotation.value, str):+ dotted = annotation.value.strip().strip("\"'") # `from __future__ import annotations` string form+ if dotted is None:+ return None+ if dotted in _STDLIB_ANNOTATIONS:+ return STDLIB+ if dotted in _STRUCTLOG_ANNOTATIONS:+ return STRUCTLOG+ return None++ def collect_bindings(self, tree: ast.Module) -> None:+ """Every binding that resolves to a logger, anywhere in the module.++ Deliberately not restricted to module scope or to the name `logger`:+ this tree binds `LOG`, `log`, `_log` and `self._logger`, and a+ function-local logger is exactly as capable of raising.+ """+ in_class = _class_bodies(tree)+ for node in ast.walk(tree):+ # A parameter annotated as a logger is the only evidence there is+ # when the logger is handed in rather than created.+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ args = node.args+ for arg in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:+ if arg is None:+ continue+ flavour = self.flavour_of_annotation(arg.annotation)+ if flavour is not None:+ self.flavours.setdefault(arg.arg, flavour)+ continue++ if not isinstance(node, (ast.Assign, ast.AnnAssign)):+ continue+ value = node.value+ flavour = self.flavour_of_call(value) if isinstance(value, ast.Call) else None+ if flavour is None and isinstance(node, ast.AnnAssign):+ flavour = self.flavour_of_annotation(node.annotation)+ if flavour is None:+ continue+ targets = node.targets if isinstance(node, ast.Assign) else [node.target]+ for target in targets:+ name = self._binding_name(target)+ if not name:+ continue+ # A later rebinding wins, which is what the interpreter does.+ self.flavours[name] = flavour+ if "." not in name:+ self.exports[name] = flavour+ # A class-body logger is reached through the instance, and+ # `self.logger` is a different string from `logger`.+ if id(node) in in_class:+ self.flavours[f"self.{name}"] = flavour+ self.flavours[f"cls.{name}"] = flavour++ @staticmethod+ def _binding_name(target: ast.expr) -> str | None:+ if isinstance(target, ast.Name):+ return target.id+ if isinstance(target, ast.Attribute) and isinstance(target.value, ast.Name):+ return f"{target.value.id}.{target.attr}"+ return None++ def resolve_imported_bindings(self) -> None:+ """`from app.core.logging import logger` inherits that module's flavour."""+ for local, (module, original) in self.name_imports.items():+ if local in self.flavours or not module:+ continue+ flavour = self.resolver.flavour_of_export(module, original, self.path)+ if flavour is not None:+ self.flavours[local] = flavour+++class _Resolver:+ """Answers "what flavour is `module.name`?" by reading the defining file."""++ def __init__(self, root: Path) -> None:+ self.root = root+ self._cache: dict[tuple[str, str], str | None] = {}+ self._inflight: set[tuple[str, str]] = set()++ def module_path(self, module: str, importer: Path) -> Path | None:+ if not module:+ return None+ rel = module.replace(".", "/")+ bases = [_tree_root(importer, self.root), self.root]+ for base in bases:+ for candidate in (base / f"{rel}.py", base / rel / "__init__.py"):+ if candidate.is_file():+ return candidate+ return None++ def flavour_of_export(self, module: str, name: str, importer: Path) -> str | None:+ key = (module, name)+ if key in self._cache:+ return self._cache[key]+ if key in self._inflight: # import cycle — give up rather than recurse+ return None+ path = self.module_path(module, importer)+ if path is None:+ return None+ self._inflight.add(key)+ try:+ scan = scan_module(path, self.root, self)+ flavour = None+ if scan is not None:+ flavour = scan.exports.get(name)+ if flavour is None:+ flavour = self._flavour_of_function_return(path, name, scan)+ self._cache[key] = flavour+ return flavour+ finally:+ self._inflight.discard(key)++ def _flavour_of_function_return(self, path: Path, name: str, scan: _ModuleScan) -> str | None:+ """`def get_logger(...): return structlog.get_logger(name)`.++ Both in-repo `get_logger` helpers are this shape, and their names say+ nothing about which library they wrap — which is the point.+ """+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (OSError, SyntaxError):+ return None+ for node in ast.walk(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or node.name != name:+ continue+ for inner in ast.walk(node):+ if isinstance(inner, ast.Return) and isinstance(inner.value, ast.Call):+ flavour = scan.flavour_of_call(inner.value)+ if flavour is not None:+ return flavour+ return None+++_SCAN_CACHE: dict[Path, _ModuleScan | None] = {}+++def scan_module(path: Path, root: Path, resolver: _Resolver) -> _ModuleScan | None:+ if path in _SCAN_CACHE:+ return _SCAN_CACHE[path]+ _SCAN_CACHE[path] = None # cycle guard while we parse+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (OSError, SyntaxError, ValueError):+ return None+ scan = _ModuleScan(path, root, resolver)+ scan.collect_imports(tree)+ scan.collect_bindings(tree)+ _SCAN_CACHE[path] = scan+ return scan+++def _context_map(tree: ast.Module) -> dict[int, str]:+ """Line -> the most-defensive enclosing construct.++ `except` beats `finally` beats a `try` body, because a keyword error+ inside an `except` clause replaces the exception being handled and cannot+ be caught by a sibling handler — that is the case worth naming first.+ """+ marks: dict[int, str] = {}++ def mark(body: list[ast.stmt], label: str) -> None:+ for stmt in body:+ for node in ast.walk(stmt):+ line = getattr(node, "lineno", None)+ if line is not None and marks.get(line) not in ("except",):+ marks[line] = label++ for node in ast.walk(tree):+ if isinstance(node, ast.Try):+ mark(node.finalbody, "finally")+ mark(node.orelse, "try/else")+ for handler in node.handlers:+ mark(handler.body, "except")+ return marks+++def scan_file(path: Path, root: Path, resolver: _Resolver, tally: dict[str, int] | None = None) -> list[Finding]:+ scan = scan_module(path, root, resolver)+ if scan is None:+ if tally is not None:+ tally["unparseable"] += 1+ return []+ try:+ tree = ast.parse(path.read_text(encoding="utf-8"))+ except (OSError, SyntaxError, ValueError):+ if tally is not None:+ tally["unparseable"] += 1+ return []+ scan.resolve_imported_bindings()+ contexts = _context_map(tree)++ # Module-level `logging.warning(...)` hits the root logger, same signature.+ root_logger_aliases = {alias for alias, module in scan.module_aliases.items() if module == "logging"}++ findings: list[Finding] = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):+ continue+ method = node.func.attr+ if method not in LOG_METHODS:+ continue+ receiver = node.func.value+ if isinstance(receiver, ast.Call):+ # `logging.getLogger(__name__).warning(...)` — no binding to look+ # up, and the shape is in this tree. A scanner that only reads+ # assignments never sees it.+ binding = f"{_dotted(receiver.func) or '<expr>'}(…)"+ flavour: str | None = scan.flavour_of_call(receiver)+ else:+ binding = _dotted(receiver) or ""+ if not binding:+ continue+ if binding.partition(".")[0] in _NOT_LOGGING_MODULES:+ continue # `math.log`, `warnings.warn` — not loggers+ flavour = STDLIB if binding in root_logger_aliases else scan.flavours.get(binding)+ if tally is not None:+ tally[flavour or "unresolved"] += 1+ if flavour != STDLIB:+ continue+ bad = tuple(sorted(kw.arg for kw in node.keywords if kw.arg and kw.arg not in STDLIB_KWARGS))+ splat = any(kw.arg is None for kw in node.keywords)+ context = contexts.get(node.lineno, "normal")+ if bad:+ findings.append(Finding(scan.rel, node.lineno, binding, method, bad, context, "stdlib-kwarg"))+ elif splat:+ findings.append(Finding(scan.rel, node.lineno, binding, method, ("**kwargs",), context, "unknown-splat"))+ return findings+++def run(root: Path, show_unknown: bool = False) -> int:+ files = python_files(root)+ resolver = _Resolver(root)+ _SCAN_CACHE.clear()++ errors: list[Finding] = []+ unknown: list[Finding] = []+ tally: dict[str, int] = defaultdict(int)+ for path in files:+ for finding in scan_file(path, root, resolver, tally):+ (errors if finding.kind == "stdlib-kwarg" else unknown).append(finding)++ print(f"check_logger_kwargs: root {root}")+ print(f" scanned {len(files)} Python file(s) (plans/ excluded)")+ # "No findings" and "resolved nothing" print the same word otherwise, and+ # the second is how a gate certifies a gap it never looked at.+ print(+ f" classified {tally[STDLIB] + tally[STRUCTLOG] + tally['unresolved']} logging call(s): "+ f"{tally[STDLIB]} stdlib, {tally[STRUCTLOG]} structlog, {tally['unresolved']} unresolved receiver(s)"+ )+ if tally[STDLIB] == 0:+ print("check_logger_kwargs: FAIL — classified no stdlib logger at all, so a clean result would be vacuous")+ return 1++ if unknown:+ print(f" {len(unknown)} call(s) splat **kwargs onto a stdlib logger and cannot be decided statically")+ if show_unknown:+ for finding in unknown:+ print(f" - {finding.describe()}")++ if not errors:+ print("check_logger_kwargs: OK — no stdlib logger is called with a structlog keyword")+ return 0++ defensive = [f for f in errors if f.context != "normal"]+ print("check_logger_kwargs: FAIL")+ print(f" {len(errors)} stdlib logger call(s) pass a keyword the stdlib Logger will reject with TypeError")+ print(f" {len(defensive)} of them sit on a path that only runs when something has already gone wrong")+ for finding in sorted(errors, key=lambda f: (f.context == "normal", f.path, f.line)):+ print(f" - {finding.describe()}")+ print(" Fix by folding the value into the message (%-style), or bind a structlog logger if that is what was meant.")+ return 1+++# ---------------------------------------------------------------------------+# Self-test+# ---------------------------------------------------------------------------++_FIXTURES: dict[str, str] = {+ # A structlog-flavoured helper, imported by two of the cases below. Its+ # name says nothing about which library it wraps, which is the point.+ "pkg/shared_logging.py": (+ "import structlog\n\n\ndef get_logger(name):\n return structlog.get_logger(name)\n\n\nlogger = structlog.get_logger()\n"+ ),+ "pkg/stdlib_logging.py": ("import logging\n\nlogger = logging.getLogger(__name__)\n"),+}++_CASES: list[tuple[str, str, bool]] = [+ (+ "stdlib logger with a structlog keyword",+ "import logging\nlogger = logging.getLogger(__name__)\nlogger.warning('x.failed', reason='r')\n",+ True,+ ),+ (+ "the same keyword inside an except block",+ "import logging\nlogger = logging.getLogger(__name__)\n"+ "try:\n pass\nexcept ValueError as exc:\n logger.warning('x.refused', reason=str(exc))\n",+ True,+ ),+ (+ "structlog logger with the same keyword",+ "import structlog\nlogger = structlog.get_logger()\nlogger.warning('x.failed', reason='r')\n",+ False,+ ),+ (+ "stdlib logger with keywords the stdlib accepts",+ "import logging\nlogger = logging.getLogger(__name__)\nlogger.error('boom', exc_info=True, extra={'a': 1}, stacklevel=2)\n",+ False,+ ),+ (+ "stdlib logger, %-style positional",+ "import logging\nlogger = logging.getLogger(__name__)\nlogger.warning('x.failed reason=%s', 'r')\n",+ False,+ ),+ (+ "binding is not called `logger`",+ "import logging\nLOG = logging.getLogger(__name__)\nLOG.info('x', count=1)\n",+ True,+ ),+ (+ "logger on self, bound in __init__",+ "import logging\n\n\nclass C:\n def __init__(self):\n self._log = logging.getLogger(__name__)\n\n"+ " def go(self):\n self._log.error('x', code=1)\n",+ True,+ ),+ (+ "aliased logging module",+ "import logging as pylog\nlogger = pylog.getLogger(__name__)\nlogger.warning('x', reason='r')\n",+ True,+ ),+ (+ "from-imported getLogger",+ "from logging import getLogger\nlogger = getLogger(__name__)\nlogger.warning('x', reason='r')\n",+ True,+ ),+ (+ "root logger via the module",+ "import logging\nlogging.warning('x', reason='r')\n",+ True,+ ),+ (+ "logger imported from a structlog-flavoured module",+ "from pkg.shared_logging import logger\nlogger.warning('x', reason='r')\n",+ False,+ ),+ (+ "logger imported from a stdlib-flavoured module",+ "from pkg.stdlib_logging import logger\nlogger.warning('x', reason='r')\n",+ True,+ ),+ (+ "in-repo get_logger that returns structlog",+ "from pkg.shared_logging import get_logger\nlogger = get_logger(__name__)\nlogger.warning('x', reason='r')\n",+ False,+ ),+ (+ "rebound to stdlib after a structlog binding",+ "import logging\nimport structlog\nlogger = structlog.get_logger()\n"+ "logger = logging.getLogger(__name__)\nlogger.warning('x', reason='r')\n",+ True,+ ),+ (+ "an unrelated object with a .error method",+ "class R:\n def error(self, msg, **kw):\n pass\n\n\nresponse = R()\nresponse.error('x', reason='r')\n",+ False,+ ),+ # The three shapes the first version of this scanner could not see. Each+ # exists in the repository, which is why they are here.+ (+ "inline factory call as the receiver",+ "import logging as _logging\n_logging.getLogger(__name__).warning('x', reason='r')\n",+ True,+ ),+ (+ "inline structlog factory as the receiver",+ "import structlog\nstructlog.get_logger(__name__).warning('x', reason='r')\n",+ False,+ ),+ (+ "class-body logger reached through self",+ "import logging\n\n\nclass C:\n logger = logging.getLogger('c')\n\n"+ " def go(self):\n self.logger.warning('x', reason='r')\n",+ True,+ ),+ (+ "logger handed in as an annotated parameter",+ "import logging\n\n\ndef go(logger: logging.Logger) -> None:\n logger.warning('x', reason='r')\n",+ True,+ ),+ (+ "structlog logger handed in as an annotated parameter",+ "import structlog\n\n\ndef go(logger: structlog.BoundLogger) -> None:\n logger.warning('x', reason='r')\n",+ False,+ ),+ (+ "annotated attribute with no factory call",+ "import logging\n\n\nclass C:\n log: logging.Logger\n\n def go(self):\n self.log.error('x', code=1)\n",+ True,+ ),+ (+ "structlog logger narrowed with .bind()",+ "import structlog\nlogger = structlog.get_logger()\nlog = logger.bind(a=1)\nlog.warning('x', reason='r')\n",+ False,+ ),+ (+ "stdlib logger narrowed with .getChild()",+ "import logging\nlogger = logging.getLogger(__name__)\nchild = logger.getChild('sub')\nchild.warning('x', reason='r')\n",+ True,+ ),+ (+ "math.log is not a logger",+ "import math\nmath.log(2.0)\n",+ False,+ ),+]+++def self_test() -> int:+ import tempfile++ failures: list[str] = []+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ (root / "pkg").mkdir()+ (root / "pyproject.toml").write_text("[tool.stub]\n", encoding="utf-8")+ for rel, body in _FIXTURES.items():+ (root / rel).write_text(body, encoding="utf-8")++ for index, (name, source, should_flag) in enumerate(_CASES):+ case = root / f"case_{index}.py"+ case.write_text(source, encoding="utf-8")+ _SCAN_CACHE.clear()+ found = [f for f in scan_file(case, root, _Resolver(root)) if f.kind == "stdlib-kwarg"]+ case.unlink()+ ok = bool(found) == should_flag+ if not ok:+ failures.append(f"{name}: expected {'a finding' if should_flag else 'no finding'}, got {[f.describe() for f in found]}")+ print(f" self-test [{'ok' if ok else 'FAIL'}] {name}")++ # The context labeller must actually label, or the "how many are on a+ # path that only runs when something already broke" line is decoration.+ case = root / "ctx.py"+ case.write_text(_CASES[1][1], encoding="utf-8")+ _SCAN_CACHE.clear()+ contexts = {f.context for f in scan_file(case, root, _Resolver(root))}+ case.unlink()+ ctx_ok = contexts == {"except"}+ if not ctx_ok:+ failures.append(f"context labelling: expected {{'except'}}, got {contexts}")+ print(f" self-test [{'ok' if ctx_ok else 'FAIL'}] an except-block finding is labelled as one")++ # A scanner that reports zero because it read nothing is the failure+ # this file is about. Prove the walker sees the fixtures it was given.+ seen = len(python_files(root))+ walk_ok = seen >= len(_FIXTURES)+ if not walk_ok:+ failures.append(f"file walk found {seen} file(s), expected at least {len(_FIXTURES)}")+ print(f" self-test [{'ok' if walk_ok else 'FAIL'}] the walker reports the files it scanned")++ if failures:+ print("\ncheck_logger_kwargs --self-test: FAIL")+ for failure in failures:+ print(f" - {failure}")+ return 1+ print(f"\ncheck_logger_kwargs --self-test: OK — {len(_CASES) + 2} cases")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--repo-root", type=Path, default=None)+ parser.add_argument("--self-test", action="store_true", help="prove the scanner separates the two libraries")+ parser.add_argument("--show-unknown", action="store_true", help="list **kwargs splats that cannot be decided")+ args = parser.parse_args()++ if args.self_test:+ return self_test()+ root = (args.repo_root or repo_root()).resolve()+ if not (root / "services").is_dir():+ print(f"{root} does not look like the AiSOC repository (no services/)")+ return 1+ return run(root, show_unknown=args.show_unknown)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/check_mypy_baseline.py b/scripts/check_mypy_baseline.pyindex 085503547..9785e6094 100644--- a/scripts/check_mypy_baseline.py+++ b/scripts/check_mypy_baseline.py@@ -47,6 +47,27 @@ Directions, because a one-directional gate is how drift escapes here:baseline fails, so adding a config does not quietlyadd an unchecked treebaseline -> config a baseline entry for a tree with no config fails+ tree -> config a Python tree on disk that declares no [tool.mypy]+ fails, so a new service is type-checked from its+ first commit rather than from whenever somebody+ notices+ config -> tree a config, or a baseline entry, naming a tree that is+ no longer on disk fails++The last two 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+indistinguishable from no tool at all, only more reassuring. `tree -> config`+is the direction that catches a new service; `config -> tree` is the one that+rots quietly, because nothing ever fails when a stale entry is simply never+consulted.++Discovery is structural — every directory holding a `pyproject.toml` — not+`services/*` plus `packages/*`. The glob was a naming convention, and a+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.Usage:python scripts/check_mypy_baseline.py@@ -61,29 +82,89 @@ import jsonimport reimport subprocessimport sys+import tempfileimport tomllibfrom collections import defaultdictfrom pathlib import PathBASELINE = Path("scripts/mypy_baseline.json")+# 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.+_EXCLUDED_PREFIXES = ("plans/",)+_SKIP_DIRS = frozenset({"node_modules", ".venv", "venv", "site-packages", "__pycache__", ".git", "dist", "build"})+# `file:line: error: message [code]`_FINDING = re.compile(r"^(?P<file>[^:]+):\d+:(?:\d+:)?\s*error:\s*(?P<message>.*?)\s*(?:\[(?P<code>[\w-]+)\])?$")-def discover(root: Path) -> list[str]:- """Every tree whose manifest declares a [tool.mypy] table.+def repo_root() -> Path:+ """The repository, per git — not per this file's location.++ A sibling gate resolved its root from ``Path(__file__).parent.parent``,+ so a copy run from anywhere else would scan whatever happened to sit two+ levels above it and print 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+- Structural: it asks the manifests what they configured, rather than- matching a directory naming convention that a new service would not- follow.+def python_trees(root: Path) -> list[str]:+ """Every directory in the repository that holds a `pyproject.toml`.++ Structural rather than `services/*` + `packages/*`: a glob is a naming+ convention, and a Python tree added anywhere else is exactly the one a+ convention-shaped gate would miss."""trees: list[str] = []- for manifest in sorted(root.glob("services/*/pyproject.toml")) + sorted(root.glob("packages/*/pyproject.toml")):- data = tomllib.loads(manifest.read_text(encoding="utf-8"))- if "mypy" in data.get("tool", {}):- trees.append(manifest.parent.relative_to(root).as_posix())- return trees+ for manifest in root.rglob("pyproject.toml"):+ if any(part in _SKIP_DIRS for part in manifest.parts):+ continue+ rel = manifest.parent.relative_to(root).as_posix()+ if rel == "." or rel.startswith(_EXCLUDED_PREFIXES):+ continue+ trees.append(rel)+ return sorted(trees)+++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", {})+++def discover(root: Path) -> list[str]:+ """Every Python tree whose manifest declares a [tool.mypy] table."""+ return [tree for tree in python_trees(root) if declares_mypy(root, tree)]+++def coverage_problems(root: Path, trees: list[str], recorded: dict) -> list[str]:+ """Both directions of "is every Python tree actually type-checked?"."""+ problems: list[str] = []+ for tree in python_trees(root):+ if tree not in trees:+ problems.append(+ f"{tree}/pyproject.toml declares no [tool.mypy] — a Python tree nothing "+ f"type-checks (tree -> config). Copy the table from a sibling: the services "+ 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)):+ 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)"+ )+ return problemsdef run_mypy(root: Path, tree: str) -> tuple[dict[str, dict[str, int]], str]:@@ -135,7 +216,12 @@ def load(root: Path) -> dict:return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}+def _python_file_count(root: Path, tree: str) -> int:+ return sum(1 for path in (root / tree).rglob("*.py") if not any(part in _SKIP_DIRS for part in path.parts))++def run(root: Path, update: bool = False) -> int:+ all_trees = python_trees(root)trees = discover(root)if not trees:print(f"check_mypy_baseline: no tree under {root} declares [tool.mypy]")@@ -143,9 +229,14 @@ def run(root: Path, update: bool = False) -> int:recorded = load(root)results: dict[str, dict[str, dict[str, int]]] = {}- problems: list[str] = []+ problems: list[str] = coverage_problems(root, trees, recorded)+ 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")for tree in trees:found, error = run_mypy(root, tree)if error:@@ -188,6 +279,72 @@ def run(root: Path, update: bool = False) -> int:return 0+def _coverage_self_test() -> tuple[list[str], int]:+ """Inject coverage drift each way against a throwaway repository.++ A fixture is worth building here, unlike for `compare`, because the+ property under test is discovery — whether the walk *finds* a tree — and+ that cannot be exercised by handing a function two dictionaries.+ """+ failures: list[str] = []+ service = '[tool.poetry]\nname = "x"\n\n[tool.mypy]\npython_version = "3.11"\n'+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ (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.+ (root / "tools" / "gamma").mkdir(parents=True)+ (root / "tools" / "gamma" / "pyproject.toml").write_text(service, encoding="utf-8")+ # The prototype subtree, which is excluded on purpose.+ (root / "plans" / "cyble-aisoc" / "platform").mkdir(parents=True)+ (root / "plans" / "cyble-aisoc" / "platform" / "pyproject.toml").write_text("[tool.poetry]\nname = 'old'\n", encoding="utf-8")++ cases: list[tuple[str, str]] = []++ found = python_trees(root)+ cases.append(+ (+ "discovery is structural, not services/* + packages/*",+ "" if set(found) == {"services/alpha", "tools/gamma"} else f"walk found {found}",+ )+ )++ # tree -> config: a Python tree with no [tool.mypy].+ (root / "services" / "beta").mkdir()+ (root / "services" / "beta" / "pyproject.toml").write_text("[tool.poetry]\nname = 'beta'\n", encoding="utf-8")+ problems = coverage_problems(root, discover(root), {})+ cases.append(+ (+ "an unconfigured Python tree is reported",+ "" if any("tree -> config" in p and "services/beta" in p for p in problems) else f"got {problems}",+ )+ )++ # config -> tree: a baseline entry whose directory is gone.+ problems = coverage_problems(root, ["services/alpha"], {"services/alpha": {}, "services/deleted": {}})+ cases.append(+ (+ "a recorded tree that no longer exists is reported",+ "" if any("config -> tree" in p and "services/deleted" in p for p in problems) else f"got {problems}",+ )+ )++ # And the excluded prototype must not be demanded.+ problems = coverage_problems(root, discover(root), {})+ cases.append(+ (+ "the archived plans/ subtree is not demanded",+ "" if not any("plans/" in p for p in problems) else f"got {problems}",+ )+ )++ for name, failure in cases:+ if failure:+ failures.append(f"{name}: {failure}")+ print(f" self-test [{'FAIL' if failure else 'ok'}] {name}")+ return failures, len(cases)++def self_test(root: Path) -> int:"""Prove the comparison reports drift in each direction.@@ -229,12 +386,15 @@ def self_test(root: Path) -> int:failures.append(f"baseline covers {sorted(recorded)} but the tree declares {sorted(trees)}")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()+ failures += coverage_failures+if failures:print("\ncheck_mypy_baseline --self-test: FAIL")for failure in failures:print(f" - {failure}")return 1- print(f"\ncheck_mypy_baseline --self-test: OK — {len(cases) + 1} cases")+ print(f"\ncheck_mypy_baseline --self-test: OK — {len(cases) + 1 + coverage_cases} cases")return 0@@ -245,7 +405,7 @@ def main() -> int:parser.add_argument("--self-test", action="store_true", help="prove the comparison detects drift")args = parser.parse_args()- root = (args.repo_root or Path(__file__).resolve().parent.parent).resolve()+ root = (args.repo_root or repo_root()).resolve()if not (root / "services").is_dir():print(f"{root} does not look like the AiSOC repository (no services/)")return 1diff --git a/scripts/mypy_baseline.json b/scripts/mypy_baseline.jsonindex 72ea9f351..e078509c6 100644--- a/scripts/mypy_baseline.json+++ b/scripts/mypy_baseline.json@@ -1,4 +1,30 @@{+ "packages/aisoc-ai-sdk": {+ "aisoc_ai/client.py": {+ "type-arg": 1+ },+ "tests/test_ai_sdk.py": {+ "import-not-found": 1,+ "no-untyped-def": 21,+ "type-arg": 3,+ "untyped-decorator": 1+ }+ },+ "packages/aisoc-benchmark": {+ "aisoc_benchmark/adapter.py": {+ "import-not-found": 1+ },+ "aisoc_benchmark/runner.py": {+ "no-untyped-def": 1+ },+ "build_corpus.py": {+ "type-arg": 2+ },+ "tests/test_benchmark.py": {+ "import-not-found": 1,+ "untyped-decorator": 2+ }+ },"packages/aisoc-cli": {"src/aisoc_cli/main.py": {"import-not-found": 7,@@ -32,6 +58,34 @@"untyped-decorator": 1}},+ "packages/aisoc-detections": {+ "detections/aws_root_console_login.py": {+ "no-any-return": 1,+ "type-arg": 2+ },+ "detections/okta_mfa_fatigue.py": {+ "type-arg": 3+ },+ "tests/test_framework.py": {+ "import-not-found": 1,+ "no-untyped-def": 7+ }+ },+ "packages/aisoc-sandbox": {+ "src/aisoc_sandbox/cli.py": {+ "attr-defined": 7+ },+ "tests/test_determinism.py": {+ "import-not-found": 1,+ "no-any-return": 1,+ "untyped-decorator": 2+ },+ "tests/test_smoke.py": {+ "attr-defined": 2,+ "import-not-found": 1,+ "untyped-decorator": 1+ }+ },"packages/plugin-sdk-py": {"src/aisoc_plugin_sdk/action.py": {"import-not-found": 1,@@ -101,6 +155,129 @@"untyped-decorator": 8}},+ "services/actions": {+ "app/executors/network.py": {+ "arg-type": 1+ },+ "app/executors/notification.py": {+ "arg-type": 2,+ "assignment": 2+ },+ "app/live_actions/capability_contracts.py": {+ "attr-defined": 7+ },+ "app/services/approval_gate.py": {+ "arg-type": 1+ },+ "tests/test_approval_gate_wiring.py": {+ "attr-defined": 1+ },+ "tests/test_capability_reachability.py": {+ "attr-defined": 4+ },+ "tests/test_capture_forensics.py": {+ "attr-defined": 3+ },+ "tests/test_disposition_writeback.py": {+ "assignment": 1+ },+ "tests/test_tenant_policy.py": {+ "var-annotated": 1+ },+ "tests/test_vendor_breadth.py": {+ "attr-defined": 1+ }+ },+ "services/agents": {+ "app/hunt/loader.py": {+ "import-untyped": 1+ },+ "app/investigator/report_writer_agent.py": {+ "import-untyped": 1+ },+ "app/nl_query/translator.py": {+ "no-redef": 3+ },+ "app/orchestrator/report.py": {+ "import-untyped": 1+ },+ "app/orchestrator/router.py": {+ "arg-type": 5+ },+ "app/playbook/engine.py": {+ "misc": 1+ },+ "app/playbook/ssrf_guard.py": {+ "attr-defined": 6,+ "union-attr": 1+ },+ "app/playbook/store.py": {+ "valid-type": 1+ },+ "app/policy/guardrails.py": {+ "arg-type": 1+ },+ "app/security/llm_resolver.py": {+ "arg-type": 2+ },+ "app/tools/mitre_full.py": {+ "attr-defined": 19,+ "call-overload": 2,+ "var-annotated": 2+ },+ "app/workers/business_context.py": {+ "import-untyped": 1+ },+ "app/workers/fused_alert_consumer.py": {+ "union-attr": 1+ },+ "tests/test_alert_reduction.py": {+ "valid-type": 1+ },+ "tests/test_audit_helpers.py": {+ "attr-defined": 24,+ "valid-type": 1+ },+ "tests/test_autonomy_guardrails.py": {+ "import-untyped": 1+ },+ "tests/test_business_context_not_clause.py": {+ "attr-defined": 1,+ "misc": 1+ },+ "tests/test_cost_governor.py": {+ "arg-type": 1+ },+ "tests/test_detection_fp_rate.py": {+ "attr-defined": 8+ },+ "tests/test_eval_telemetry.py": {+ "attr-defined": 4+ },+ "tests/test_fidelity_harness.py": {+ "index": 2+ },+ "tests/test_four_agent_facade.py": {+ "attr-defined": 2+ },+ "tests/test_hunt_corpus.py": {+ "attr-defined": 12+ },+ "tests/test_litellm_config.py": {+ "import-untyped": 1+ },+ "tests/test_llm_resolver.py": {+ "misc": 1,+ "var-annotated": 1+ },+ "tests/test_osquery_live_query_step.py": {+ "func-returns-value": 2,+ "misc": 2+ },+ "tests/test_playbook_completion_rate.py": {+ "attr-defined": 15+ }+ },"services/api": {"app/api/v1/endpoints/business_context.py": {"import-untyped": 1@@ -267,6 +444,42 @@"misc": 3}},+ "services/connectors": {+ "app/api/router.py": {+ "attr-defined": 1+ },+ "app/connectors/ai_gateway.py": {+ "attr-defined": 1+ },+ "app/connectors/aws_security_hub.py": {+ "override": 1+ },+ "app/connectors/email_inbox.py": {+ "union-attr": 4+ },+ "app/connectors/github.py": {+ "override": 1+ },+ "app/connectors/oci.py": {+ "operator": 1,+ "union-attr": 7+ },+ "app/connectors/okta.py": {+ "override": 1+ },+ "app/connectors/tenable.py": {+ "arg-type": 1+ },+ "tests/test_pipeline_filter_rules.py": {+ "arg-type": 1+ },+ "tests/test_pipeline_fingerprint.py": {+ "arg-type": 1+ },+ "tests/test_push_capabilities.py": {+ "union-attr": 16+ }+ },"services/fusion": {"tests/test_consumer_dlq.py": {"arg-type": 1@@ -275,9 +488,58 @@"arg-type": 1}},+ "services/honeytokens": {+ "alembic/env.py": {+ "attr-defined": 1+ },+ "alembic/versions/0001_initial_honeytoken_tables.py": {+ "attr-defined": 1+ }+ },+ "services/mesh": {},"services/osquery-tls": {"app/services/pack_loader.py": {"import-untyped": 1}+ },+ "services/purple-team": {+ "alembic/env.py": {+ "attr-defined": 1+ },+ "alembic/versions/0001_initial_purple_team_tables.py": {+ "attr-defined": 1+ },+ "alembic/versions/0002_detection_drift_snapshots.py": {+ "attr-defined": 1+ },+ "app/services/atomic_loader.py": {+ "import-untyped": 1+ }+ },+ "services/slack-bot": {+ "app/notify.py": {+ "union-attr": 1+ },+ "app/services/approval_timeout.py": {+ "func-returns-value": 1+ }+ },+ "services/teams-bot": {+ "tests/test_callbacks_approver.py": {+ "index": 1+ }+ },+ "services/threatintel": {+ "app/feeds/pipeline.py": {+ "union-attr": 1+ }+ },+ "services/ueba": {+ "alembic/env.py": {+ "attr-defined": 1+ },+ "alembic/versions/0001_initial_ueba_tables.py": {+ "attr-defined": 1+ }}}diff --git a/services/actions/app/clients/google_workspace_client.py b/services/actions/app/clients/google_workspace_client.pyindex fbcbf90d3..036cd0a4c 100644--- a/services/actions/app/clients/google_workspace_client.py+++ b/services/actions/app/clients/google_workspace_client.py@@ -88,7 +88,16 @@ class GoogleWorkspaceClient:service_account_key = json.loads(service_account_key)except json.JSONDecodeError as exc:raise ValueError(f"gws_service_account_key is not valid JSON: {exc}") from exc- self._key = service_account_key+ # `json.loads` happily returns a str, list or int for a document that+ # is valid JSON but not an object. Without this the credential passed+ # construction and failed at `self._key["client_email"]` — inside the+ # JWT signing path, with `TypeError: string indices must be integers`,+ # at the moment an operator triggered a live containment action. The+ # configuration is wrong either way; it should say so when it is+ # saved, not when it is used.+ if not isinstance(service_account_key, dict):+ raise ValueError(f"gws_service_account_key must be a JSON object, got {type(service_account_key).__name__}")+ self._key: dict[str, Any] = service_account_keyself._subject = subject_emailself._token: str | None = Noneself._token_expiry: float = 0.0diff --git a/services/actions/app/clients/okta_client.py b/services/actions/app/clients/okta_client.pyindex 1ae411015..7761eccaa 100644--- a/services/actions/app/clients/okta_client.py+++ b/services/actions/app/clients/okta_client.py@@ -143,15 +143,23 @@ class OktaClient:logger.info("okta.clear_sessions.success", user_id=user_id)return {"success": True, "action": "clear_sessions", "user_id": user_id, "login": login_or_id}- async def reset_password(self, login_or_id: str) -> dict[str, Any]:- """Trigger a password reset email for the user."""+ async def reset_password(self, login_or_id: str, *, send_email: bool = True) -> dict[str, Any]:+ """Trigger a password reset for the user.++ ``send_email`` maps to Okta's ``sendEmail`` query parameter. It is a+ keyword because ``ResetPasswordExecutor`` has always read+ ``parameters.send_email`` and passed it here — against a signature+ that did not accept it, so every live Okta reset raised ``TypeError``+ and came back as a FAILED action. Simulation mode never constructs+ this client, which is why nothing caught it.+ """async with httpx.AsyncClient(timeout=20.0) as client:user = await self._find_user(client, login_or_id)user_id = user["id"]resp = await client.post(f"{self._domain}/api/v1/users/{user_id}/lifecycle/reset_password",headers=self._headers(),- params={"sendEmail": "true"},+ params={"sendEmail": "true" if send_email else "false"},)resp.raise_for_status()data = resp.json()diff --git a/services/actions/pyproject.toml b/services/actions/pyproject.tomlindex c12607815..fa7ce33cf 100644--- a/services/actions/pyproject.toml+++ b/services/actions/pyproject.toml@@ -30,6 +30,14 @@ cryptography = ">=46,<51"pytest = ">=9.0.3,<10.0"pytest-asyncio = ">=1.0,<2.0"+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/actions/tests/test_identity_client_signatures.py b/services/actions/tests/test_identity_client_signatures.pynew file mode 100644index 000000000..4a987338d--- /dev/null+++ b/services/actions/tests/test_identity_client_signatures.py@@ -0,0 +1,137 @@+"""Identity executors must call their IdP clients with the signatures they have.++The companion to ``test_siem_client_signatures.py``, for the same defect and+the same reason: simulation mode never constructs a vendor client, so a wrong+keyword argument is invisible in every test that supplies no credentials and+raises ``TypeError`` on the first live call.++This one shipped. ``ResetPasswordExecutor`` documents ``parameters.send_email``+as "used only for the Okta path" and passed ``send_email=`` to+``OktaClient.reset_password(self, login_or_id)``, which did not accept it. The+executor's ``except Exception`` turned the ``TypeError`` into a FAILED+``ActionResult``, so the verb did not crash — it simply could never succeed+against Okta, and the failure looked like an Okta problem.++``test_identity_executor_vendors.py`` covers the same executors and could not+catch it, because its stub client is ``async def reset_password(self, *_args,+**_kw)``. A fake that accepts anything proves the dispatch order and nothing+about the call. ``create_autospec(..., spec_set=True)`` enforces the real+signature and fails exactly where the live client would.+"""++from __future__ import annotations++from unittest.mock import create_autospec+from uuid import uuid4++import pytest+from app.clients.azure_entra_client import AzureEntraClient+from app.clients.google_workspace_client import GoogleWorkspaceClient+from app.clients.okta_client import OktaClient+from app.executors import identity+from app.executors.identity import (+ DisableUserExecutor,+ ForceMFAExecutor,+ ResetPasswordExecutor,+ SuspendSessionExecutor,+)+from app.models.action import ActionRequest, ActionStatus, ActionType++_FACTORIES = ("_okta_client", "_entra_client", "_gws_client")+++def _autospec(cls: type):+ """An autospec whose methods reject arguments the real client rejects."""+ return create_autospec(cls, spec_set=True, instance=True)+++def _request(action_type: ActionType, **parameters: object) -> ActionRequest:+ return ActionRequest(+ incident_id=uuid4(),+ tenant_id=uuid4(),+ action_type=action_type,+ target="[email protected]",+ parameters=dict(parameters),+ rationale="signature conformance test",+ )+++def _only(monkeypatch: pytest.MonkeyPatch, factory: str, client: object) -> None:+ """Wire one vendor in and the other two out, so dispatch is unambiguous."""+ for attr in _FACTORIES:+ monkeypatch.setattr(identity, attr, (lambda params: client) if attr == factory else (lambda params: None))+++async def test_okta_reset_password_matches_the_client_signature(monkeypatch: pytest.MonkeyPatch) -> None:+ """Fails on the pre-fix client: `send_email=` was not a parameter of it."""+ client = _autospec(OktaClient)+ client.reset_password.return_value = {"success": True}+ _only(monkeypatch, "_okta_client", client)++ result = await ResetPasswordExecutor().execute(_request(ActionType.RESET_PASSWORD, send_email=False))++ assert result.status is ActionStatus.COMPLETED, result.error+ assert client.reset_password.call_args.kwargs["send_email"] is False+++async def test_okta_reset_password_defaults_to_sending_the_email(monkeypatch: pytest.MonkeyPatch) -> None:+ """The documented default — a reset the user is never told about is not one."""+ client = _autospec(OktaClient)+ client.reset_password.return_value = {"success": True}+ _only(monkeypatch, "_okta_client", client)++ result = await ResetPasswordExecutor().execute(_request(ActionType.RESET_PASSWORD))++ assert result.status is ActionStatus.COMPLETED, result.error+ assert client.reset_password.call_args.kwargs["send_email"] is True+++ ("executor_cls", "action_type", "factory", "client_cls", "method"),+ [+ (DisableUserExecutor, ActionType.DISABLE_USER, "_okta_client", OktaClient, "disable_user"),+ (DisableUserExecutor, ActionType.DISABLE_USER, "_entra_client", AzureEntraClient, "disable_user"),+ (DisableUserExecutor, ActionType.DISABLE_USER, "_gws_client", GoogleWorkspaceClient, "suspend_user"),+ (ResetPasswordExecutor, ActionType.RESET_PASSWORD, "_entra_client", AzureEntraClient, "reset_password"),+ (ResetPasswordExecutor, ActionType.RESET_PASSWORD, "_gws_client", GoogleWorkspaceClient, "reset_password"),+ (SuspendSessionExecutor, ActionType.SUSPEND_SESSION, "_entra_client", AzureEntraClient, "revoke_sessions"),+ (SuspendSessionExecutor, ActionType.SUSPEND_SESSION, "_gws_client", GoogleWorkspaceClient, "revoke_sessions"),+ (ForceMFAExecutor, ActionType.FORCE_MFA, "_okta_client", OktaClient, "force_mfa_enrollment"),+ (ForceMFAExecutor, ActionType.FORCE_MFA, "_entra_client", AzureEntraClient, "require_mfa"),+ ],+)+async def test_every_identity_arm_matches_its_client_signature(+ monkeypatch: pytest.MonkeyPatch,+ executor_cls: type,+ action_type: ActionType,+ factory: str,+ client_cls: type,+ method: str,+) -> None:+ """Every remaining executor/vendor pair, under a spec that can reject."""+ client = _autospec(client_cls)+ getattr(client, method).return_value = {"success": True}+ _only(monkeypatch, factory, client)++ result = await executor_cls().execute(_request(action_type))++ assert result.status is ActionStatus.COMPLETED, result.error+ getattr(client, method).assert_called_once()+++async def test_okta_suspend_session_calls_both_halves_under_spec(monkeypatch: pytest.MonkeyPatch) -> None:+ """The Okta session arm is two calls, and both have to match."""+ client = _autospec(OktaClient)+ client.clear_sessions.return_value = {"success": True}+ client.suspend_user.return_value = {"success": True}+ _only(monkeypatch, "_okta_client", client)++ result = await SuspendSessionExecutor().execute(_request(ActionType.SUSPEND_SESSION))++ assert result.status is ActionStatus.COMPLETED, result.error+ client.clear_sessions.assert_called_once()+ client.suspend_user.assert_called_once()diff --git a/services/agents/app/context/bundle.py b/services/agents/app/context/bundle.pyindex 92bdfab1b..57b131dac 100644--- a/services/agents/app/context/bundle.py+++ b/services/agents/app/context/bundle.py@@ -633,7 +633,12 @@ class ContextBundleBuilder:out: dict[str, EntityNeighborhood] = {}results = await asyncio.gather(*[_walk(e) for e in principals], return_exceptions=True)for r in results:- if isinstance(r, Exception):+ # BaseException, not Exception: `gather(return_exceptions=True)`+ # hands back a cancelled child's `CancelledError`, which is a+ # BaseException on 3.8+. Filtering on `Exception` let it through+ # to the unpack below, turning a cancelled graph walk into+ # `TypeError: cannot unpack non-sequence CancelledError`.+ if isinstance(r, BaseException):logger.debug("context.neighborhood.failed", error=str(r))continuekey, nbr = r@@ -738,7 +743,9 @@ class ContextBundleBuilder:results = await asyncio.gather(*[_one(e) for e in principals], return_exceptions=True)for r in results:- if isinstance(r, Exception) or r is None:+ # See `_fetch_neighborhoods`: a cancelled child returns a+ # `CancelledError`, which is not an `Exception`.+ if isinstance(r, BaseException) or r is None:continuekey, baseline = rout[key] = baselinediff --git a/services/agents/app/playbook/nl_drafter.py b/services/agents/app/playbook/nl_drafter.pyindex 8cee751f9..372198534 100644--- a/services/agents/app/playbook/nl_drafter.py+++ b/services/agents/app/playbook/nl_drafter.py@@ -551,7 +551,13 @@ def _llm_factory() -> Any | None:except Exception:return Nonetry:- return make_chat_model()+ # "nl" is the declared role for natural-language translation+ # (``app.llm.model_pins``). This was a bare ``make_chat_model()``,+ # and ``role`` is required — so the TypeError was caught below and+ # the drafter reported "no chat model available" on every call,+ # permanently. Every test monkeypatches ``_llm_factory``, so the one+ # line that mattered was the one line nothing exercised.+ return make_chat_model("nl")except Exception as exc:logger.info("nl_drafter: no chat model available (%s)", exc)return Nonediff --git a/services/agents/pyproject.toml b/services/agents/pyproject.tomlindex e3b794a7f..d2955b13a 100644--- a/services/agents/pyproject.toml+++ b/services/agents/pyproject.toml@@ -83,6 +83,14 @@ markers = ["integration: mark a test as requiring external infrastructure (Kafka, Neo4j, Postgres). Run with `pytest -m integration`.",]+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/connectors/app/pipeline/fingerprint.py b/services/connectors/app/pipeline/fingerprint.pyindex 205210d6e..76ed7d90f 100644--- a/services/connectors/app/pipeline/fingerprint.py+++ b/services/connectors/app/pipeline/fingerprint.py@@ -77,7 +77,7 @@ def compute_fingerprint(events: Iterable[dict[str, Any]]) -> str | None:def diff_fingerprints(previous_keys: Iterable[str],current_keys: Iterable[str],-) -> dict[str, list[str]]:+) -> dict[str, Any]:"""Describe what changed between two field sets.Used by the scheduler to populate ``last_drift_details`` so the UI can@@ -85,6 +85,16 @@ def diff_fingerprints(Both arguments are the raw key sets — the caller is responsible forpulling them from the most recent batch and the prior baseline batch(we cache the prior batch's keys in-memory in the scheduler).++ The mapping is not homogeneous: ``added`` and ``removed`` are sorted key+ lists and ``unchanged_count`` is an int. It was declared+ ``dict[str, list[str]]``, which the body has never returned — and because+ the scheduler assigns the result straight into a ``dict[str, Any]``+ variable, the wrong declaration narrowed that variable and made the three+ correct lines underneath it look like type errors instead. Both+ consumers, ``connector_repo`` and the API's connector model, already+ declare ``dict[str, Any]``, which is what actually reaches the JSONB+ column."""prev = set(previous_keys)curr = set(current_keys)diff --git a/services/connectors/pyproject.toml b/services/connectors/pyproject.tomlindex 32a64e778..793531994 100644--- a/services/connectors/pyproject.toml+++ b/services/connectors/pyproject.toml@@ -71,6 +71,14 @@ exclude_lines = ["if __name__ == .__main__.:",]+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/honeytokens/pyproject.toml b/services/honeytokens/pyproject.tomlindex c72b9692a..654b6051c 100644--- a/services/honeytokens/pyproject.toml+++ b/services/honeytokens/pyproject.toml@@ -41,6 +41,14 @@ dev = ["pytest", "pytest-asyncio", "httpx"]# Why pyproject instead of pytest.ini: keeps the floor next to the# dep constraint that produced it, so a bump in either is reviewed# in the same diff.+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[tool.coverage.run]source = ["app"]branch = truediff --git a/services/mesh/pyproject.toml b/services/mesh/pyproject.tomlindex cf28f50c2..f56e93894 100644--- a/services/mesh/pyproject.toml+++ b/services/mesh/pyproject.toml@@ -23,6 +23,14 @@ httpx = ">=0.27,<0.29"# resolve together or not at all.pytest = ">=9.0.3,<10.0"+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/purple-team/pyproject.toml b/services/purple-team/pyproject.tomlindex d05a288c7..7a9646627 100644--- a/services/purple-team/pyproject.toml+++ b/services/purple-team/pyproject.toml@@ -42,6 +42,14 @@ dev = ["pytest", "pytest-asyncio", "httpx"]# Why pyproject instead of pytest.ini: keeps the floor next to the# dep constraint that produced it, so a bump in either is reviewed# in the same diff.+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[tool.coverage.run]source = ["app"]branch = truediff --git a/services/slack-bot/pyproject.toml b/services/slack-bot/pyproject.tomlindex eb62787a3..5ab412da9 100644--- a/services/slack-bot/pyproject.toml+++ b/services/slack-bot/pyproject.toml@@ -38,6 +38,14 @@ pytest = ">=9.0.3,<10.0"pytest-asyncio = ">=1.0,<2.0"respx = "^0.21.1"+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/teams-bot/pyproject.toml b/services/teams-bot/pyproject.tomlindex c75266052..a1ec7d7c0 100644--- a/services/teams-bot/pyproject.toml+++ b/services/teams-bot/pyproject.toml@@ -29,6 +29,14 @@ pytest = ">=9.0.3,<10.0"pytest-asyncio = ">=1.0,<2.0"respx = "^0.21.1"+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/threatintel/pyproject.toml b/services/threatintel/pyproject.tomlindex dc921330d..7a77df917 100644--- a/services/threatintel/pyproject.toml+++ b/services/threatintel/pyproject.toml@@ -35,6 +35,14 @@ mmh3 = "^4.1.0"pytest = ">=9.0.3,<10.0"pytest-asyncio = ">=1.0,<2.0"+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[build-system]requires = ["poetry-core"]build-backend = "poetry.core.masonry.api"diff --git a/services/ueba/pyproject.toml b/services/ueba/pyproject.tomlindex b2e2eb6c8..c307ba84d 100644--- a/services/ueba/pyproject.toml+++ b/services/ueba/pyproject.toml@@ -44,6 +44,14 @@ dev = ["pytest", "pytest-asyncio", "httpx"]# Why pyproject instead of pytest.ini: keeps the floor next to the# dep constraint that produced it, so a bump in either is reviewed# in the same diff.+# Same shape as services/api and services/osquery-tls rather than a third+# strictness level. `python_version` is pinned so the finding set does not+# move with whatever interpreter mypy happens to run on.+[tool.mypy]+python_version = "3.11"+strict = false+ignore_missing_imports = true+[tool.coverage.run]source = ["app"]branch = true