Files
AiSOC/scripts/check_comment_paths.py
Beenu Arora 58f42c724d depth2 Lane E: land Phase 7 provider coverage, hosted agents and the AI rule pack on main (#1599)
* depth2 Phase 0: kickoff, re-derived baseline and the SIEM-scope decision

Phase 0.1-0.4 of the wave-2 depth plan, which lands here locked beside the
other four plans.

0.2 re-derives every figure the plan captured. All twenty reproduce exactly
except the cloud/identity/SaaS/code condition count, which the plan itself
flagged as approximate: measured 344 against 'about 358'. D1 records why,
and the finding underneath it — no script in the tree implements that
sentence, so every published value of it was hand-counted with a slightly
different product set, and windowed rules contribute zero because they
carry no product field at all. Phase 2.1's gate has to decide that
explicitly.

0.3 captures the baselines, including 'make up-full' — the one the first
depth plan recorded as never captured (its D2). 22 containers on the full
profile; CORE passed 'make smoke' 10 of 10. The baseline host had nine
unrelated containers on it including a foreign Postgres on 5432, and
'make up-full' failed its first bind before the port resolver's overlay
landed. D2 records the sequence and, deliberately, does not claim a defect
from it: the preceding state is not replayable, so it carries a clean-host
reproduction as a follow-up instead.

0.4 is ADR-0015: AiSOC federates to the SIEM rather than replacing it. The
README's 'Not a drop-in SIEM replacement' is now a decided position with its
cost argument — compliance search needs raw-payload retention outside the
8 GB CORE budget and an availability promise this project has no measured
evidence it can keep. Proposed, and nothing in this plan builds from it.

* depth2 Lane E: AI provider coverage, chat-compliance minimisation, hosted agents, repository AI config and four replayed AI rules (#1585)

* depth2 Lane E: claim migrations 146-150 and ADR 0021

* test(connectors): reproduce the AI provider-coverage gap in llm_usage

Depth 6.3 / wave-2 7.1. `LlmUsageConnector` accepted `openai` and
`anthropic` and nothing else, so Gemini in Workspace, Copilot in M365,
Copilot in GitHub and Entra consent grants to AI applications had no
reader at all and the AI estate's provider-audit discovery source could
only ever see two vendors.

Six of the seven tests fail on this tree: four drive the real HTTP path
against a mock server returning vendor-shaped payloads and get a
ValueError from the constructor, one asserts the org-scoping refusal and
one asserts the schema's select options match the accepted providers
(`PROVIDERS` does not exist yet).

Endpoints, query parameters and event names come from the vendors'
current public references, each fetched and 200 before being written:
the Admin SDK Reports API `gemini_in_workspace_apps` application, the
GitHub organization audit log, the Office 365 Management Activity API
schema (RecordType 261 CopilotInteraction, 284 AIAppInteraction) and
Microsoft Graph directoryAudits.

* feat(connectors): four more AI provider audit feeds in llm_usage

Depth 6.3 / wave-2 7.1. Closes the gap the previous commit reproduced:
the connector now reads Gemini in Workspace, GitHub Copilot, Microsoft
365 Copilot and Entra consent grants alongside OpenAI and Anthropic.

Each client was written against the vendor's current public reference,
every one of which was fetched and returned 200 before being committed;
the module docstring names them per provider. The Workspace
`gemini_in_workspace_apps` applicationName and the `ai_usage_event` /
`feature_utilization` event names, the 23 published `copilot.*` audit
actions, RecordType 261 CopilotInteraction and 284 AIAppInteraction, and
the directoryAudits consent activities are all read values, not
inferred ones.

Three things the tests pin beyond "it parses":

- Filtering happens server-side where the vendor supports it. Asking
  GitHub for an organisation's whole audit stream and discarding
  client-side is a rate-budget problem on a busy org, not a style one.
- Where it cannot, the reader discards non-AI records by RecordType and
  by consent activity name. `Audit.General` is the entire Microsoft 365
  general audit and `directoryAudits` is every directory change; a
  reader that forwarded both would replace the AI feed with a second
  copy of the general audit.
- A consent grant's scopes are lifted out of the free-text
  `ConsentAction.Permissions` property into a sorted `scopes` list on
  the envelope. A grant whose scopes stay buried scores in the AI estate
  as a grant with no scope at all, which is the opposite of the truth
  for `Mail.Read`.

M365 needs a second request because the subscription endpoint returns
blob references rather than content; a reader that stopped at the first
response would poll successfully forever and emit nothing.

Workspace OAuth token grants are deliberately not read here —
`google_workspace` already polls the `token` application, and a second
reader would double-count every grant. What is missing there is
classification, which is the next commit.

Docs and the conformance matrix regenerated, not hand-edited.

* test(fusion): reproduce the recorder reading a path no connector emits

Wave-2 7.1 wiring. `test_ai_asset_recorder.py` writes
`finding.evidence.scopes` into a hand-built OCSF event and asserts the
recorder reads `finding.evidence.scopes`. Both halves are the test's own
invention: no connector in the tree produces that path and ingest does
not synthesise it, so the assertion holds whether or not the production
path works.

What ingest really hands fusion is the connector's normalized dict as a
JSON string under `ocsf["raw_data"]`, which is why `_connector_fields`
exists for the endpoint path and is not used by the provider-audit path.

Driven through that real shape, both new tests fail: an Entra consent
grant reaches the inventory with no scopes at all, so an AI notetaker
consented into every mailbox in the organisation scores identically to
one granted nothing, and the console's reason list is silent about the
single fact that decides whether the grant matters.

The fixtures are the real output of `LlmUsageConnector.normalize()`.
The two services cannot import each other — both package their
application as `app` — so they are held together by a committed
artefact plus a check in each direction, the way the vendored narrative
and the detection ruleset already are.

* fix(fusion): read provider-audit fields where the connector puts them

Wave-2 7.1 wiring. `_from_provider_audit` now reads through
`_connector_fields`, the same reconstruction the endpoint path already
performs, instead of off the canonical OCSF map. An Entra consent
grant's scope list reaches `score_risk`, so a grant holding `Mail.Read`
scores as broad and says so in its reason list.

Two further corrections the real shape forced:

- An OAuth grant is keyed on the **application**, not the audit record.
  Keying on the record id would make every re-consent a new asset and
  reset `first_seen_at` on each, so the inventory would grow a row per
  event and never show that this application has been there since May.
- The OCSF-native `finding.evidence.scopes` read is kept as a fallback
  rather than replaced, so a producer that does emit it is still read.
  Trading one blind spot for another is not a fix.

Negative control, recorded: with the `fields.get("scopes")` read
reverted to the pre-fix path and nothing else changed, both new tests
fail again (`KeyError: 'scopes'`). Restored, the fusion suite is 1063
passed / 28 skipped.

The `normalize` contract is unchanged across all 87 connectors: the
"is this record AI activity at all" decision is a separate
`is_ai_record` predicate rather than a `None` return, which keeps the
base signature intact and makes the filter — the thing that stops the
Microsoft 365 AI feed becoming a second copy of the general audit —
callable and testable on its own.

* feat(api): enterprise AI-chat compliance logs, minimised by the schema

Wave-2 7.1, second half. Reads an AI provider's compliance API for the
directory, projects and activity feed, and — behind a second, narrower
opt-in — classifies message content without keeping any of it.

Written against Anthropic's Compliance API, the one enterprise AI-chat
compliance surface with a complete public reference. Every path, scope,
key prefix and response field was read from pages that each returned 200
before being committed; the client's module docstring names them. The
Activity Feed record and the chat record in the tests are the vendor's
published examples field for field.

The minimisation is in the schema, which is the point of ADR-0021.
A plan sentence saying "never full conversations" that a TEXT column
permits is not a control; it holds until the first caller who binds
"\n".join(messages) and succeeds silently.

- No table has a column able to hold a message. Asserted against the
  ORM, since that is what application code binds through.
- The snippet is VARCHAR(280). The collector truncates; the column is
  the backstop for the caller that forgets.
- The snippet is masked BEFORE it is cut, so a row saying "this chat
  contained an AWS key" does not contain the key. A verbatim window
  would create a new copy of the secret in a table an operator believes
  is safe to keep, and label it so an attacker can find it. A
  per-pattern sweep asserts the value is absent for every shape in the
  shared list.
- The label vocabulary is a CHECK constraint, and a test asserts the
  three copies of it (constraint, ORM, classifier) agree.
- The client has no method returning message text, asserted on its
  public surface.
- Two opt-ins, stricter one default-off: collection does not imply
  reading message bodies.
- Off by default per tenant, through the console, vault-held key. No
  environment variable. A vault failure is a 503, never a plaintext row.

The secret-shape patterns are the AI SDK's own, vendored by
scripts/sync_vendored_ai_redaction.py and held byte-identical by its
--check. A prompt and a chat message containing the same AWS key must
produce the same shape name on both surfaces; a second hand-written
copy is how two surfaces come to disagree about the same rows. The SDK
groups e-mail and card shapes with credentials because it is answering
a transmission question; _SDK_LABEL maps each shape to one of the
plan's four classes rather than relabelling the shared list.

Luhn is applied to the shared card shape. Without it the digits-only
pattern labels order ids as payment data, and a classifier that labels
everything is one nobody believes.

Retention, legal hold and erasure come free and are tested: every table
carries a column named exactly `tenant_id`, which is how
`discover_tenant_tables` finds it. Discovery rather than a declared
list is deliberate — a list is the thing that goes stale.

Tests use httpx.MockTransport rather than respx, because respx is not
in this service's locked dependency set and a test needing a package CI
does not install is a test CI cannot run. MockTransport replaces only
the network leg.

Negative control, recorded: adding a `transcript: Mapped[str | None]
= mapped_column(Text)` to AiChatContentLabel and changing nothing else
fails two tests (the forbidden-column sweep and the unbounded-TEXT
sweep). Removed, the API suite is 5074 passed / 174 skipped.

Migration 146 and ADR-0021 were claimed in DEPTH2_PROGRESS.md before
either file was written.

* docs(depth2): record 7.1 in the progress tracker

* feat(ai-estate): hosted agents and repository AI config as asset kinds

Wave-2 7.2. Two new kinds on `aisoc_ai_assets` (migration 147), both
scored by the one existing `score_risk` and rendered with their reasons
on the AI estate page. No second scorer: the plan forbids it by name and
it is the drift this repository keeps finding.

**Hosted agents** come from `GET /v1/agents` with the
`managed-agents-2026-04-01` beta header, read against the vendor's
published reference (fetched, 200). An agent configured in a provider's
control plane is invisible to every other discovery path here: endpoint
telemetry never sees it, and gateway telemetry sees its traffic without
knowing what it was configured to do. The client is read-only — the
vendor offers create, update and archive and none of them is here,
because an inventory that can reconfigure a customer's agents is a
different risk conversation and 7.2 is read-only by the plan's rule.

**Repository AI config** is the scan of agent-instruction files, skill
directories and MCP configuration through the code-platform connectors,
recording the tools and servers each references. "Which repositories
point an agent at this MCP server" is a question the estate could not
answer.

Every byte of that scan is attacker-controlled and is treated as such.
These files are checked in, editable by anyone who can land a pull
request, and read by an agent verbatim as instructions — the same trust
class as a retrieved runbook, which this platform already scans. So:

- Nothing is stored raw. Excerpts are flattened and capped at 400
  characters, with zero-width and bidirectional characters stripped,
  because an instruction file is exactly where a payload invisible in a
  diff gets hidden.
- The content is scanned at capture and only the matched *pattern
  names* are kept — never the matching text, which would put the
  attacker's payload in a table the console renders, labelled so a
  security team looks at it.
- Those names reach `score_risk`, so a flagged file raises the asset's
  exposure and the reason names the channel.
- A hosted agent's `system` prompt goes through the identical path, for
  the identical reason.

The patterns are **generated** from the agents guard's own `_RULES`
table rather than hand-picked, by
scripts/sync_vendored_ai_instruction_rules.py with a --check wired into
ci.yml. A hand-copied subset drifts: a pattern added to the guard after
the next incident would never reach the scanner and nothing would say
so. One rule is excluded with its reason recorded — `fabricated_tool_result`
matches a model-output envelope rather than a repository file, and its
pattern is assembled from a set, so it renders in a different order in
every process and no generated file could match itself. The generator
fails if an excluded name leaves the guard, so the exclusion cannot
outlive the rule and become a silent gap.

Two things found while building it:

- `path.lstrip("./")` eats the leading dot of a dotfolder, so
  `.cursor/rules/x.mdc` became `cursor/rules/x.mdc` and stopped
  matching — silently, as a path that simply is not an AI artefact.
  Every convention here lives in a dotfolder, so that one call would
  have turned most of the scan off. Caught by the classification table,
  which is why it enumerates real paths rather than a couple of
  examples.
- `DEVICELESS_KINDS` is shared between the model and `score_risk`, so
  the four kinds that cannot have a device are not charged for lacking
  one. A hosted agent has no laptop to isolate; the reason string
  "containment has nowhere to act" would simply be false.

The tool reader matches grants, not prose: "do not use `write_file`" in
a paragraph is not a grant, and counting it would make a careful
instruction file score worse than a careless one.

Also: a committed JWT-shaped literal in the 7.1 classifier test is now
assembled from parts. The repository's secret scan was right to refuse
it, and a test fixture has no business looking like a credential.

* docs(depth2): record 7.2 in the progress tracker

* feat(detections): four AI rules on the provider feeds 7.1 added

Wave-2 7.4, partial — four of the rule pack's targets, each earned
rather than declared. Executable corpus 2,530 -> 2,534, regenerated
from `scripts/project_stats.py` and propagated to the README, ROADMAP,
truth table, corpus stats, marketplace index and the packaged API copy
by their own generators. Nothing was hand-typed.

- `llm-copilot-content-exclusion-changed` (critical) — content
  exclusion is the control that stops a coding assistant reading the
  paths an organisation declared off limits. It is changed in a
  settings page rather than in a pull request, so nothing else reviews
  it.
- `llm-copilot-agent-mcp-config-changed` (high) — adding an MCP server
  adds a party that can instruct a hosted agent. A scope change, not a
  settings change, and the agent runs on the provider's infrastructure
  so no endpoint control sees the result.
- `llm-ai-app-granted-write-scope` (high) — a consent grant letting an
  AI application change a mailbox, drive, site or the directory. The
  read equivalent is an exposure; this one can act.
- `llm-copilot-bulk-resource-access` (medium) — one assistant turn that
  read 25 or more distinct resources. An assistant with a user's grant
  is an exfiltration path that authenticates as that user and looks
  like ordinary application traffic.

Every rule is replayed through the REAL connector and the REAL engine
in `services/fusion/tests/test_ai_rule_pack_replay.py`. The fixtures
are the committed output of `LlmUsageConnector.normalize()` on
vendor-shaped records, regenerated and drift-checked from the
connectors side, because the two services cannot import each other.

Nothing here is synthesized from the rule it tests. That is the whole
point: 1 of 12 GitHub rules fired on real connector output while all
twelve passed their own fixture replay, because a fixture generated
from a rule carries the rule's own clause key and the replay is
tautological.

Each negative twin differs in exactly ONE decisive field — a different
Copilot action, `Mail.Read` where the twin is `Mail.ReadWrite`, 24
resources where the twin is 40 — and a test asserts that property on
the fixtures rather than trusting it, since a negative that also moved
the actor would pass for a reason unrelated to the clause.

Negative control, recorded: rewriting one rule's clause to the
unprefixed vendor action (`event_type: content_exclusion_changed`),
which is the exact shape of the measured GitHub failure, and
re-exporting, fails that rule's positive replay while the other three
stay green. Restored, all ten pass.

`test_builtin_rule_catalogue.py`'s hand-typed counts moved 760 -> 764
and 2609 -> 2613 with the reason recorded beside the existing history,
in the style that file already keeps.

* docs(depth2): record 7.4 partial and 7.3 not delivered, with evidence

* chore(detections): regenerate the curated index for the four new rules

`curate_detections.py --check` is a drift gate I had not run: adding four
rules moves the curated selection and the coverage page, and neither is
produced by any of the seven generators I did regenerate. Caught by CI,
reproduced locally with the same command, and regenerated rather than
hand-edited.

Worth recording because it is the shape this repository keeps finding: a
published artefact with its own generator and its own `--check`, sitting
outside the chain everything else in the family runs through. All eight
detection drift gates now pass together.

* fix(ci): correct the gitleaks fingerprints the four new rules shifted

`.gitleaksignore` pins a finding by `file:rule:line`, so inserting four
entries into `detections/rule-ids.lock.json` moved every line below them
and five fingerprints stopped matching the findings they were triaged
for. The file's own header describes this rot and says the fix is to
correct the line number, never to drop the entry or relax the job, so
that is what this does: the set is re-derived by running CI's exact
gitleaks 8.21.2 with the allow-list removed, and all fourteen are
written back.

Thirteen are the same pre-existing, benign findings — the heuristic
fires on rule *slugs* such as `llm-api-key-created` and
`slack-token-exposed`, never on a value. One is genuinely new:
`llm-copilot-bulk-resource-access` trips it on the word "access".

Verified under 8.21.2 rather than the 8.30.1 on this machine, because
the two disagree about this tree and only the pinned one decides.

Also regenerates `apps/web/public/marketplace/{index,curated}.json`
through `pnpm marketplace:sync`. `curate_detections.py --check` passing
is not the whole gate: the web mirror is copied by a separate step, and
a curated index that is current in one place and stale in the other is
the drift that check exists to catch.

* chore(depth2): move Lane E's phase-7 reproduction out of lane scratch

A '.laneE/' directory is session scratch, and session scratch does not
belong in the repository. The script itself is evidence the plan asks
for — the measured gap each Phase 7 item claimed — so it lands beside
the other depth2 baseline artefacts instead of being deleted.

* fix(ai-estate): wire the 7.1/7.2 collectors, which nothing was calling

Two CI failures on the landing branch, both correct findings.

**`check_module_reachability`: five modules with no production importer.**
The classifier, the compliance client, the repository scanner and the
hosted-agent client each had a suite and no caller — the "mechanism
exists, nothing calls it" family, where a passing test on an uncalled
function is indistinguishable from a working feature until somebody
traces the call graph. The gate said so in those words and was right.

`ai_estate_collectors.py` is the call graph: one pass over the chat
compliance API, one hosted-agent inventory, one repository scan, reached
from three routes behind `ai_estate:write`. Both asset collectors write
through the one `score_risk`, reading the existing row's `sanctioned`
rather than resetting it — a collection pass must not undo an operator's
judgement, and the sanction state is an input to the score.

Explicit rather than scheduled. Each collector reaches a third party with
the tenant's own credential, and the rule for anything that reaches out
is off by default and enabled per tenant; a loop that started the moment
a key was saved would be a different decision from the one ADR-0021
records. Results are reported per sink with a `skipped` reason, because a
single number presented as the operation's result reads as total failure
when one sink failed and the others worked.

**`check_enrichment_decisions`: a retired rule looked resolvable.** The
gate judges reachability against the **union of every connector's**
namespace, so promoting a bare `scopes` on Entra consent events made
`ident-github-pat-classic-created-with-broad-scopes` look reachable when
nothing had changed for GitHub — its audit log still does not carry a
created classic PAT's scopes, so un-retiring it would have shipped a rule
that cannot fire.

The field is now `granted_scopes`, which is both more precise (a consent
grant's scopes and a token's scopes are different things sharing a word)
and does not lie to the gate. The rule that reads it was updated in the
same commit and still replays green.

The gate's global-namespace weakness is real and is recorded in
DEPTH2_PROGRESS.md for whoever owns it: a rule's reachability should be
judged against the fields its own log source emits, not against every
connector's. Renaming avoided a false un-retire; it did not fix that.

`.gitleaksignore` fingerprints re-derived with the allow-list removed,
and all eight detection drift gates plus the web marketplace mirror
regenerated.

* fix(ci): run the vendored-rules check where the agents runtime exists

The step was in `Python — Lint & Type-check` under a comment saying it
ran "after that install step". There is no such step in that job — it
installs ruff and mypy and nothing else — so the check failed with
`No module named structlog`. The comment was a justification I wrote and
did not verify, which is worse than no comment.

Moved to `Python — Tests`, which installs the agents requirements a few
lines above, so reading `app.prompting.envelope` genuinely resolves.

An `ast` parser was tried first and rejected on the evidence: two of the
25 rules build their pattern from a module-level constant rather than an
inline literal, so parsing would have silently dropped them and generated
a 23-rule table that still looked plausible. Refusing them instead would
have shipped a copy missing two patterns the guard has. Importing reads
all 25, and the right fix was to run it somewhere it can import.

* chore(depth2): regenerate llms.txt for the Phase 7 surfaces

* chore(depth2): regenerate the bundled connector catalog

* test: re-pin the packaged-corpus total at 2613 after the AI rule pack

The positive control asserts the sync reports a plausible rule total, and
the figure is hand-typed. This branch adds four AI-runtime rules to
detection_ruleset.json (760 -> 764), so the total it prints moves 2609 ->
2613. The artefacts themselves are already in sync; only the pinned figure
was stale, the same way test_builtin_rule_catalogue.py's per-artefact
counts were moved in this branch.
2026-11-01 11:09:36 -08:00

682 lines
30 KiB
Python

#!/usr/bin/env python3
"""Every repository path named in a code comment must exist.
Why this exists as a separate gate
----------------------------------
``docker-compose.yml`` carried a reference to an ADR under
``docs/architecture/decisions/`` — a path with no directory behind it. Two
workstreams tripped over it within an hour, and it had survived every check
in the tree, because **a comment is the one place no gate reads**.
``check_repo_self_links.py`` opens markdown and matches
``github.com/...`` URLs; lychee resolves links; nothing had ever looked at
the prose inside source files, which is where most cross-file references in
this repository actually live.
That prose is load-bearing. "Keep this in sync with X", "the operator table
lives at Y", "CI check Z compares the two sets" — each is an instruction to
the next contributor, and each is worthless the moment the path is wrong. On
its first run this gate found nine dead references in comments and thirteen
more in Python docstrings, including a migration renumbered 055 → 063, a
connector doc that moved under ``apps/docs/docs/``, and three separate
pointers at CI checks that had never been written.
What it reads, and what it deliberately does not
------------------------------------------------
The corpus was measured before the gate was written, because a naive version
would have been mostly noise. Of **3,092** path-shaped strings in non-
markdown comments, most are not repository paths at all: MIME types, MCP
method names (``tools/call``), Splunk REST routes (``services/search/jobs``),
container images, URL routes, Go import paths. Flagging those would produce a
gate people learn to ignore, which is worse than none.
Three structural filters cut the corpus to the references that are actually
claims about this tree:
1. **A known file extension.** ``tools/call`` and ``services/ocsf`` are not
files. This is also what excludes ``cost_telemetry._PRICING`` and
``graph_ws.Broadcaster``, which are attribute references wearing a slash.
2. **A first segment that names something at the top of this repository.**
``application/json`` and ``github.com/x/y`` do not survive it; the
``docs/…`` reference that started this does.
3. **Not a URL, not templated, not a glob, not gitignored.** A build artefact
under ``dist/`` legitimately does not exist in a clean checkout.
A path is then resolved against the repository root *and* against each
ancestor of the file that mentions it, because a comment in
``services/agents/tests/`` naming a ``conftest.py`` under ``tests/`` means
the one beside it, not one at the root.
Measured blind spot, accepted on purpose
----------------------------------------
Extension-less directory references — ``infra/terraform/aws``,
``services/ocsf`` — are **not** checked. 286 of them resolve and 52 do not,
and hand-classifying the 52 put genuine rot at roughly one in five: the rest
are URL routes, API paths and tool names that happen to start with a
directory name. A gate at 20% precision is a gate that gets ignored, so this
one says what it skipped (see the summary it prints) rather than guessing.
Exceptions
----------
``ACCEPTED`` records the references that are deliberately unresolvable:
placeholders in usage text, and prose *about* a path that was removed or
moved. Each carries a reason and is checked in both directions — an entry
naming a reference that now resolves, or one that is no longer in the
corpus, fails the build rather than sitting there.
Usage
-----
python3 scripts/check_comment_paths.py
python3 scripts/check_comment_paths.py --list # every reference read
python3 scripts/check_comment_paths.py --self-test # prove it still detects
Exit codes: 0 clean, 1 findings, 2 the scan itself could not run.
"""
from __future__ import annotations
import argparse
import ast
import re
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
# `scripts/` is on sys.path when this file is run as a program, but not when a
# test loads it by path with importlib. gate_toolkit sits beside it either way.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gate_toolkit import SELF_TEST_FLAG, repo_root, self_test_main # noqa: E402
# --------------------------------------------------------------------------
# Corpus definition
# --------------------------------------------------------------------------
#: (line-comment token, block-comment delimiters) per extension. A language
#: absent from here is not read, and the summary says how many files that was.
COMMENT_SYNTAX: dict[str, tuple[str | None, tuple[str, str] | None]] = {
".py": ("#", None),
".sh": ("#", None),
".bash": ("#", None),
".yaml": ("#", None),
".yml": ("#", None),
".toml": ("#", None),
".tf": ("#", None),
".ini": ("#", None),
".cfg": ("#", None),
".go": ("//", ("/*", "*/")),
".ts": ("//", ("/*", "*/")),
".tsx": ("//", ("/*", "*/")),
".js": ("//", ("/*", "*/")),
".mjs": ("//", ("/*", "*/")),
".cjs": ("//", ("/*", "*/")),
".sql": ("--", ("/*", "*/")),
}
#: Files with no extension that are still comment-bearing.
COMMENT_FILENAMES = {"Dockerfile": ("#", None), "Makefile": ("#", None)}
#: An archived prototype subtree kept for history; its paths describe a repo
#: that no longer exists. CodeQL excludes it for the same reason.
EXCLUDED_PREFIXES = ("plans/cyble-aisoc/",)
#: Suffixes that make a token a plausible file reference. Anything else is
#: either not a file or a directory, and directories are the measured blind
#: spot documented above.
FILE_SUFFIXES = frozenset(
{
".py",
".go",
".ts",
".tsx",
".js",
".mjs",
".cjs",
".md",
".mdx",
".yaml",
".yml",
".json",
".sql",
".sh",
".tf",
".toml",
".ini",
".cfg",
".txt",
".lock",
".tmpl",
".tpl",
".mod",
".sum",
".css",
".html",
".svg",
".png",
}
)
#: A path-shaped run of characters. The first segment is deliberately
#: narrower than the rest: a leading `(` or `[` is punctuation around the
#: reference, while `apps/web/src/app/(app)/…` is a real Next.js route group.
TOKEN_RE = re.compile(r"[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.()\[\]-]+)+")
#: Trailing punctuation a sentence leaves attached to a path.
TRAILING = "`'\"),;:.]}>"
#: A scheme, or a dotted host followed by a slash, immediately before the
#: token — in which case the token is part of a URL and not our path.
URL_PREFIX_RE = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*://\S*|[A-Za-z0-9-]+\.[A-Za-z]{2,}/\S*)$")
# --------------------------------------------------------------------------
# Recorded exceptions. Shrink-only, checked in both directions.
# --------------------------------------------------------------------------
#: Keyed ``(file, token) -> reason``. An entry whose reference now resolves,
#: or which no longer appears in the corpus at all, is a finding: a stale
#: exception is how a list stops describing the tree it excuses.
ACCEPTED: dict[tuple[str, str], str] = {
("scripts/perf/load_harness.py", "scripts/load_harness.py"): (
"Prose asserting the file's absence. The comment explains why the self-test probe is "
"passed 'perf/load_harness.py' rather than a basename: a basename would have resolved to "
"scripts/load_harness.py, which does not exist, and a missing file exits non-zero so the "
"refusal would have passed while proving nothing. Making this path resolve would recreate "
"the trap the comment exists to warn about."
),
(".github/workflows/screencast.yml", "apps/web/pnpm-lock.yaml"): (
"Prose asserting the file's absence — the sentence is 'apps/web/pnpm-lock.yaml does not "
"exist', which is the fact the step depends on."
),
("apps/web/eslint.config.mjs", "apps/web/.eslintrc.json"): (
"Names the file this config replaced. The reference is historical and rewriting it to a "
"path that exists would lose the only record of the migration."
),
("infra/fly/managed/provision.sh", "infra/fly/managed/tenants/acme.yaml"): (
"A placeholder tenant file in the usage line. Real tenant descriptors are supplied by the operator and are not committed."
),
("infra/fly/managed/render.sh", "infra/fly/managed/tenants/acme.yaml"): ("Same usage line in the sibling script, same placeholder."),
("services/api/app/services/ai_repo_scan.py", ".github/copilot-instructions.md"): (
"A filename convention this scanner looks for in a *customer's* repositories, quoted in "
"the module docstring beside the other conventions it recognises. It is not a path in "
"this repository and creating one to satisfy the gate would add an agent-instruction "
"file nobody asked for."
),
("scripts/audit_runbook_links.py", "docs/runbooks/foo.md"): (
"An illustrative path in a docstring explaining which link shapes the gate accepts."
),
("scripts/check_competitor_names.py", "docs/connectors/x.md"): (
"An illustrative path in a docstring explaining glob semantics: 'docs/connectors/** matches docs/connectors/x.md'."
),
("scripts/check_gate_contract.py", "scripts/foo.py"): (
"An illustrative path in a docstring showing what shlex returns for a quoted path inside an "
"echo. Naming a real script would make the example read as a claim about that script."
),
("scripts/check_repo_self_links.py", "services/api/app/api/deps.py"): (
"Prose recording the dead link that motivated that gate — the path moved under v1/, and the sentence is about it having moved."
),
("tools/detection_import/splunk_importer.py", "detections/cloud/foo.yml"): (
"An illustrative path in a docstring showing how a category is derived from a rule path."
),
("scripts/aisoc-demo.ts", "apps/web/public/screenshots/01-alerts-queue.png"): (
"An output destination, not an existing file: `--screenshots` writes the four PNGs there "
"from a live stack. The directory ships SVG placeholders until someone runs it, which "
"apps/web/public/screenshots/README.md states."
),
}
# --------------------------------------------------------------------------
# Reading the corpus
# --------------------------------------------------------------------------
@dataclass(frozen=True)
class Reference:
"""One path-shaped token found in one comment."""
file: str
line: int
token: str
context: str
class ScanError(RuntimeError):
"""The scan could not be set up. Never downgraded to a clean result."""
def tracked_files(root: Path) -> list[str]:
out = subprocess.run( # noqa: S603 - fixed argv, no shell
["git", "ls-files"],
cwd=root,
capture_output=True,
text=True,
check=False,
)
if out.returncode != 0:
raise ScanError(f"cannot list tracked files under {root}: {out.stderr.strip()}")
return [f for f in out.stdout.splitlines() if f and not f.startswith(EXCLUDED_PREFIXES)]
def ignored_paths(root: Path, candidates: list[str]) -> set[str]:
"""Which candidates git would ignore. One subprocess, not one per path.
A reference to ``services/mcp/dist/index.js`` is correct and unresolvable
at the same time: the file is a build artefact that exists at runtime and
never in a checkout. Asking git keeps that judgement structural instead of
becoming a second list of directory names to maintain.
"""
if not candidates:
return set()
out = subprocess.run( # noqa: S603 - fixed argv, no shell
["git", "check-ignore", "--stdin"],
cwd=root,
input="\n".join(candidates),
capture_output=True,
text=True,
check=False,
)
return {line.strip() for line in out.stdout.splitlines() if line.strip()}
def comment_text(path: Path, ext: str) -> list[tuple[int, str]]:
"""Every comment in the file, as (line number, comment body).
Crude on purpose: a ``#`` inside a string literal is read as a comment.
That costs nothing, because the token still has to survive three
structural filters and then fail to resolve before it is reported.
"""
line_token, block = COMMENT_SYNTAX.get(ext, COMMENT_FILENAMES.get(path.name, (None, None)))
try:
text = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
return []
out: list[tuple[int, str]] = []
in_block = False
for lineno, line in enumerate(text.splitlines(), start=1):
rest = line
if block:
if in_block:
end = rest.find(block[1])
if end >= 0:
out.append((lineno, rest[:end]))
in_block = False
rest = rest[end + len(block[1]) :]
else:
out.append((lineno, rest))
continue
start = rest.find(block[0])
if start >= 0:
end = rest.find(block[1], start + len(block[0]))
if end >= 0:
out.append((lineno, rest[start + len(block[0]) : end]))
rest = rest[:start] + " " + rest[end + len(block[1]) :]
else:
out.append((lineno, rest[start + len(block[0]) :]))
in_block = True
continue
if line_token:
found = re.search(r"(?:^|\s)" + re.escape(line_token), rest)
if found:
out.append((lineno, rest[found.end() :]))
return out
def docstring_text(path: Path) -> list[tuple[int, str]]:
"""Every Python docstring, as (line number, line).
Docstrings are the same invisible prose as comments and carry more of it:
they held thirteen of the twenty-two dead references this gate found on
its first run, including every 'keep these copies in sync' pointer.
"""
try:
tree = ast.parse(path.read_text(encoding="utf-8"))
except (SyntaxError, UnicodeDecodeError, OSError, ValueError):
return []
out: list[tuple[int, str]] = []
for node in ast.walk(tree):
if not isinstance(node, ast.Module | ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
continue
doc = ast.get_docstring(node, clean=False)
if not doc:
continue
first = getattr(node.body[0], "lineno", 1) if node.body else 1
# The literal's lineno is its last line for a multi-line string in
# some versions; anchoring at the node keeps the number close enough
# to find the text, which is all a reader needs.
start = first - doc.count("\n")
for offset, line in enumerate(doc.splitlines()):
out.append((max(1, start + offset), line))
return out
def extract(root: Path, files: list[str]) -> tuple[list[Reference], dict[str, int]]:
"""Every path-shaped token in every comment and docstring we can read."""
refs: list[Reference] = []
counts = {"files_read": 0, "files_skipped_unknown_syntax": 0, "tokens_seen": 0}
for rel in files:
path = root / rel
ext = path.suffix
readable = ext in COMMENT_SYNTAX or path.name in COMMENT_FILENAMES
if not readable:
counts["files_skipped_unknown_syntax"] += 1
continue
counts["files_read"] += 1
lines = comment_text(path, ext)
if ext == ".py":
lines += docstring_text(path)
for lineno, body in lines:
for match in TOKEN_RE.finditer(body):
counts["tokens_seen"] += 1
token = match.group(0).rstrip(TRAILING)
if not token or URL_PREFIX_RE.search(body[: match.start()]):
continue
refs.append(Reference(file=rel, line=lineno, token=token, context=body.strip()[:120]))
return refs, counts
# --------------------------------------------------------------------------
# Deciding which references are claims about this tree
# --------------------------------------------------------------------------
def is_repo_path(token: str, toplevel: frozenset[str]) -> bool:
"""Whether this token is asserting that a file exists in this repository.
Three structural questions, in the order that discards the most: is it a
URL or a template, does it name a file, and does it start at the top of
this tree. See the module docstring for the measurement behind each.
"""
if "://" in token or "$" in token or "{" in token or "*" in token:
return False
if Path(token).suffix not in FILE_SUFFIXES:
return False
return token.split("/", 1)[0] in toplevel
def resolve(ref: Reference, known: frozenset[str]) -> str | None:
"""The path this reference names, or None.
Tried against the repository root first and then against each ancestor of
the referring file, because a ``tests/`` path named in a comment inside
``services/agents/tests/`` means the file beside it.
"""
if ref.token in known:
return ref.token
base = Path(ref.file).parent
for parent in [base, *base.parents]:
if str(parent) == ".":
continue
candidate = f"{parent}/{ref.token}"
if candidate in known:
return candidate
return None
def known_paths(files: list[str]) -> frozenset[str]:
"""Every tracked file and every directory containing one."""
known: set[str] = set(files)
for rel in files:
for parent in Path(rel).parents:
if str(parent) != ".":
known.add(str(parent))
return frozenset(known)
@dataclass
class Result:
refs_examined: int = 0
resolved: int = 0
excused: int = 0
ignored: int = 0
missing: list[Reference] = None # type: ignore[assignment]
stale_exceptions: list[tuple[tuple[str, str], str]] = None # type: ignore[assignment]
def __post_init__(self) -> None:
if self.missing is None:
self.missing = []
if self.stale_exceptions is None:
self.stale_exceptions = []
def judge(
refs: list[Reference],
known: frozenset[str],
toplevel: frozenset[str],
ignored: frozenset[str],
accepted: dict[tuple[str, str], str],
) -> Result:
"""Pure verdict over an already-read corpus, so the self-test can drive it."""
result = Result()
seen_keys: set[tuple[str, str]] = set()
resolved_keys: set[tuple[str, str]] = set()
for ref in refs:
if not is_repo_path(ref.token, toplevel):
continue
result.refs_examined += 1
key = (ref.file, ref.token)
seen_keys.add(key)
if resolve(ref, known) is not None:
result.resolved += 1
resolved_keys.add(key)
continue
if ref.token in ignored:
result.ignored += 1
continue
if key in accepted:
result.excused += 1
continue
result.missing.append(ref)
# The other direction. An exception that no longer excuses anything is a
# claim about the tree that has stopped being true, and leaving it makes
# the list a liability instead of a control.
for key, reason in sorted(accepted.items()):
if key not in seen_keys:
result.stale_exceptions.append((key, "no longer appears in any comment — remove the entry"))
elif key in resolved_keys:
result.stale_exceptions.append((key, "now resolves to a real path — remove the entry"))
elif not reason.strip():
result.stale_exceptions.append((key, "carries no reason"))
return result
# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--repo-root", type=Path, default=None, help="the tree to inspect (default: git rev-parse)")
parser.add_argument("--list", action="store_true", help="print every reference that was resolved")
parser.add_argument(SELF_TEST_FLAG, action="store_true", help="prove this gate detects the drift it claims to")
args = parser.parse_args(argv)
if args.self_test:
return self_test()
root = (args.repo_root or repo_root()).resolve()
try:
files = tracked_files(root)
except ScanError as exc:
print(f"check_comment_paths: FAILED to run the scan: {exc}", file=sys.stderr)
return 2
known = known_paths(files)
toplevel = frozenset(f.split("/", 1)[0] for f in files)
refs, counts = extract(root, files)
candidates = sorted({r.token for r in refs if is_repo_path(r.token, toplevel)})
ignored = frozenset(ignored_paths(root, candidates))
result = judge(refs, known, toplevel, ignored, ACCEPTED)
print(f"repo root {root}")
print(
f"corpus {counts['files_read']} comment-bearing file(s) read, "
f"{counts['files_skipped_unknown_syntax']} with no comment syntax this gate knows"
)
print(f" {counts['tokens_seen']} path-shaped token(s) seen, {result.refs_examined} of them repository-path claims")
print(
f"verdict {result.resolved} resolve, {result.ignored} name a gitignored build artefact, "
f"{result.excused} excused, {len(result.missing)} do not"
)
print("not checked extension-less directory references (286 resolve / 52 do not, and hand-")
print(" classifying the 52 put genuine rot near one in five — see the module docstring)")
print()
# Say what was opened before saying it was clean. An empty corpus and a
# clean corpus produce the same "OK" from the same branch otherwise, which
# is the failure this repository has shipped five times.
if not counts["files_read"] or not result.refs_examined:
print(
f"check_comment_paths: FAIL — read {counts['files_read']} file(s) and found "
f"{result.refs_examined} repository-path claim(s) under {root}. A clean result over "
"nothing is not a clean result; check COMMENT_SYNTAX and TOKEN_RE.",
file=sys.stderr,
)
return 1
if args.list:
for ref in sorted(refs, key=lambda r: (r.file, r.line)):
if is_repo_path(ref.token, toplevel) and resolve(ref, known):
print(f" ok {ref.file}:{ref.line} {ref.token}")
print()
if not result.missing and not result.stale_exceptions:
print(f"check_comment_paths: OK — every repository path named in a comment exists ({result.resolved} checked)")
return 0
if result.missing:
print(f"{len(result.missing)} comment(s) name a path that does not exist:")
for ref in result.missing:
print(f" {ref.file}:{ref.line} -> {ref.token}")
print(f" {ref.context}")
print("\nA comment is an instruction to the next contributor. Fix the path, or record it")
print("in ACCEPTED with the reason it cannot resolve.")
if result.stale_exceptions:
print(f"\n{len(result.stale_exceptions)} recorded exception(s) no longer describe the tree:")
for (file, token), why in result.stale_exceptions:
print(f" {file} -> {token}: {why}")
return 1
# --------------------------------------------------------------------------
# Self-test
# --------------------------------------------------------------------------
def self_test() -> int:
"""Inject each defect this gate exists to catch, and each it must not.
Every case builds its corpus from a fresh constructor. A shared reference
list mutated between cases would let one case poison the baseline and
every later case would 'catch' an inherited finding rather than its own.
"""
# Mirrors the real tree closely enough to be meaningful: `tests` is a
# top-level directory in this repository, which is what lets a
# package-relative conftest reference be examined at all.
toplevel = frozenset({"docs", "services", "apps", "scripts", "tests"})
known = frozenset(
{
"docs",
"docs/architecture",
"docs/architecture/overview.md",
"services",
"services/agents",
"services/agents/tests",
"services/agents/tests/conftest.py",
"scripts",
"scripts/check_comment_paths.py",
"tests",
}
)
def ref(file: str, token: str, line: int = 1) -> Reference:
return Reference(file=file, line=line, token=token, context=f"see {token}")
def run(refs: list[Reference], *, ignored: frozenset[str] = frozenset(), accepted: dict | None = None) -> Result:
return judge(refs, known, toplevel, ignored, dict(accepted or {}))
checks: list[tuple[str, bool]] = []
baseline = run([ref("services/agents/main.py", "docs/architecture/overview.md")])
checks.append(("the unperturbed baseline reports nothing", not baseline.missing and baseline.resolved == 1))
# --- what it must flag -------------------------------------------------
dead = run([ref("docker-compose.yml", "docs/architecture/decisions/0001-llm-gateway-in-core.md")])
checks.append(
(
"the compose comment that started this — a path with no directory behind it",
[r.token for r in dead.missing] == ["docs/architecture/decisions/0001-llm-gateway-in-core.md"],
)
)
renumbered = run([ref("services/agents/x.py", "services/api/migrations/055_cost_provenance.sql")])
checks.append(("a migration referenced by a number it no longer has", len(renumbered.missing) == 1))
# --- what it must NOT flag: enumerate what it credits -------------------
# This direction is the one that finds the blind spot. A gate that flagged
# everything would pass every case above.
credited = [
("a MIME type", ref("services/api/x.py", "application/json")),
("an MCP method name", ref("services/mcp/src/server.ts", "tools/call")),
("a Splunk REST route", ref("services/connectors/x.py", "services/search/jobs")),
("a Go import path", ref("services/ingest/main.go", "github.com/segmentio/kafka-go")),
("a container image", ref("infra/x.yaml", "ghcr.io/beenuar/aisoc-devcontainer")),
("a glob", ref("scripts/x.py", "services/**/*.py")),
("a templated path", ref("scripts/x.py", "services/${SERVICE}/app.py")),
("an attribute reference wearing a slash", ref("x.py", "services/api/app/core/config.is_dev_env")),
("an extension-less directory reference (the accepted blind spot)", ref("x.py", "infra/terraform/aws")),
("a URL route", ref("apps/web/x.tsx", "playbooks/new")),
# Conservative by construction: a package-relative reference whose
# first segment names nothing at the top of the tree is skipped
# rather than guessed at. A miss, not a false positive, and recorded
# here so the trade is visible rather than discovered.
("a relative path anchored at no top-level name", ref("services/agents/x.py", "internal/helper.py")),
]
for label, reference in credited:
outcome = run([reference])
checks.append((f"does not flag {label}", not outcome.missing and outcome.refs_examined == 0))
# A path relative to the referring package resolves, and is not a finding.
relative = run([ref("services/agents/tests/test_x.py", "tests/conftest.py")])
checks.append(("a package-relative path resolves against the referring file", not relative.missing and relative.resolved == 1))
# A gitignored build artefact is correct and unresolvable at once.
artefact = run([ref("services/mcp/src/config.ts", "services/mcp/dist/config.js")], ignored=frozenset({"services/mcp/dist/config.js"}))
checks.append(("a gitignored build artefact is not a finding", not artefact.missing and artefact.ignored == 1))
# --- the exceptions ratchet, both directions ---------------------------
excused = run([ref("a.sh", "docs/nope.md")], accepted={("a.sh", "docs/nope.md"): "recorded reason"})
checks.append(("a recorded exception suppresses its own finding", not excused.missing and excused.excused == 1))
now_real = run(
[ref("services/agents/main.py", "docs/architecture/overview.md")],
accepted={("services/agents/main.py", "docs/architecture/overview.md"): "recorded reason"},
)
checks.append(("an exception whose path now resolves is reported stale", len(now_real.stale_exceptions) == 1))
vanished = run([], accepted={("gone.py", "docs/gone.md"): "recorded reason"})
checks.append(("an exception for a comment that no longer exists is reported stale", len(vanished.stale_exceptions) == 1))
unexplained = run([ref("a.sh", "docs/nope.md")], accepted={("a.sh", "docs/nope.md"): " "})
checks.append(("an exception with no reason is reported", len(unexplained.stale_exceptions) == 1))
# An exception is keyed on (file, token): the same bad path in another
# file is still a finding, so one excused placeholder cannot licence it
# everywhere.
elsewhere = run(
[ref("a.sh", "docs/nope.md"), ref("b.sh", "docs/nope.md")],
accepted={("a.sh", "docs/nope.md"): "recorded reason"},
)
checks.append(("an exception covers only the file it names", [r.file for r in elsewhere.missing] == ["b.sh"]))
# --- the readers, not just the rules -----------------------------------
parsed = comment_text(Path(__file__), ".py")
checks.append(("the comment reader finds comments in this very file", len(parsed) > 20))
docs = docstring_text(Path(__file__))
checks.append(("the docstring reader finds this module's own docstring", any("docker-compose.yml" in line for _, line in docs)))
checks.append(
(
"a URL is recognised by its prefix, not by the token",
bool(URL_PREFIX_RE.search("see https://github.com/beenuar/AiSOC/blob/main/")) and not URL_PREFIX_RE.search("see "),
)
)
return self_test_main(Path(__file__).name, [], checks)
if __name__ == "__main__":
sys.exit(main())