Files
AiSOC/scripts/check_go_module_paths.py
Beenu AroraandBeenu Arora f3348223a8 Five gates said OK over nothing; the probe that found them is now a gate (#823)
* Five gates said OK over nothing; the probe that found them is now a gate

Copying scripts/ into an empty git repository and running every wired check
found five reporting OK over a tree containing nothing: the detection
validator behind the rule count on the front page certifying zero rules as
valid, a dashboard check that failed on an empty directory and passed on a
missing one, "OK: 0 published Go module path(s)", every self-link healthy
over zero files, and a health-probe audit printing a table header and
exiting 0. Those five were fixed. The probe was a one-off, so the next gate
written could reintroduce the defect freely.

scripts/check_gate_contract.py is that probe made permanent. It runs all 69
inventoried checks the way a workflow runs each one, inside a git repository
holding only scripts/, and requires each to exit non-zero. The inventory
comes from check_gate_coverage.py rather than a second scanner here, because
two scanners drift the first time either learns something the other has not.
A run that failed for a reason the empty tree did not cause is INCONCLUSIVE
and fails rather than counting as a refusal. Every way CI runs a script is
probed and the worst result decides, because four subcommands under one name
are four gates.

Two properties come with it, both enforced with empty exception lists: a
root resolved through git rather than from __file__, and a declared
--self-test. Sixty of sixty-nine did the former; fifty-four lacked the
latter. scripts/gate_toolkit.py holds the single implementation of both.

Found while building it:

- check_gate_coverage.py decided "inspects the repository" partly by looking
  for Path(__file__) -- the idiom being migrated away from -- so moving six
  gates onto the shared resolver dropped them out of the inventory.
- The first spelling of the root property matched repo_root anywhere in the
  text, and check_gate_coverage.py emits it as a JSON key, so a gate rooted
  at __file__ read as compliant on a key in its own output.
- check_route_tenant_scope.py printed "scanned 0 routes across 0 files" and
  then "OK: every route taking a tenant identifier authenticates" against a
  services/ tree with no routes in it.
- security_audit.py's pnpm, python and go arms each printed "0 findings"
  over a tree with no manifests, and get_repo_root() fell back to cwd.

* Make every gate find gate_toolkit however it is loaded

Five CI jobs failed with ModuleNotFoundError: No module named 'gate_toolkit'.
Sixteen test modules load a gate with importlib.util.spec_from_file_location,
which executes the file without putting its directory on sys.path — so the
scripts were importable as programs and not as modules, and the scripts that
already import a sibling carry the same tweak for the same reason.

Each gate now inserts its own directory before the import. Also corrects the
claim-to-gate tally in the compliance evidence pack, which quotes it in prose
and was the second place the figure lives.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-24 08:08:57 -07:00

126 lines
4.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Every published Go module must declare a path `go get` can resolve.
Both published SDKs declared `github.com/beenuar/aisoc/<name>`:
* wrong case — the repository is `AiSOC`, and Go module paths are
case-sensitive against the VCS path;
* missing the `packages/` prefix — the directory the module lives in.
So `go get github.com/beenuar/aisoc/sdk-go` resolved to nothing, and neither
SDK was installable by anyone outside this repository. Nothing caught it
because every in-repo consumer used a `replace` directive or a relative
import, which is exactly the shape that hides a broken published path: the
tree builds perfectly and the artifact does not exist.
This is a path check, not a network check. It runs offline and deterministically
and asserts the declared module path matches where the directory actually is.
"""
from __future__ import annotations
import re
import subprocess
import sys
from pathlib import Path
# `scripts/` is on sys.path when this file is run as a program, but not when a
# test loads it by path with importlib. gate_toolkit sits beside it either way.
sys.path.insert(0, str(Path(__file__).resolve().parent))
from gate_toolkit import self_test_if_requested
self_test_if_requested(__file__)
def _repo_root() -> Path:
"""The repository, per git — not per this file's location.
Resolving two levels up from `__file__` means a copy of this script run
from anywhere else scans whatever happens to sit above it and prints a
confident OK about a tree it never opened.
"""
out = subprocess.run( # noqa: S603 - fixed argv, no shell
["git", "rev-parse", "--show-toplevel"],
capture_output=True,
text=True,
check=False,
cwd=Path(__file__).resolve().parent,
)
if out.returncode == 0 and out.stdout.strip():
return Path(out.stdout.strip()).resolve()
return Path(__file__).resolve().parent.parent
ROOT = _repo_root()
#: The canonical repository path, matching the GitHub org and repo casing.
REPO_PATH = "github.com/beenuar/AiSOC"
#: Directories whose modules are published for external consumption. A module
#: under services/ is internal to a deployable image and is not `go get`-able
#: by design, so only these are checked.
PUBLISHED_ROOTS = ("packages",)
_MODULE_RE = re.compile(r"^module\s+(\S+)", re.MULTILINE)
def declared_path(go_mod: Path) -> str | None:
match = _MODULE_RE.search(go_mod.read_text(encoding="utf-8"))
return match.group(1) if match else None
def expected_path(go_mod: Path) -> str:
return f"{REPO_PATH}/{go_mod.parent.relative_to(ROOT).as_posix()}"
def main() -> int:
problems: list[str] = []
checked = 0
for root in PUBLISHED_ROOTS:
for go_mod in sorted((ROOT / root).rglob("go.mod")):
if "node_modules" in go_mod.parts:
continue
checked += 1
declared = declared_path(go_mod)
expected = expected_path(go_mod)
rel = go_mod.relative_to(ROOT)
if declared is None:
problems.append(f"{rel}: no `module` directive")
elif declared != expected:
problems.append(
f"{rel}: declares `{declared}` but lives at `{expected}`. "
"`go get` resolves the module path against the VCS path, and it is "
"case-sensitive, so this module is not installable."
)
# "Found nothing" and "opened nothing" print the same word otherwise. The
# published roots are a hand-written tuple, so a module moving out of
# `packages/` takes its coverage with it silently — and the failure this
# gate exists to catch is precisely one nobody in-tree can observe,
# because every in-repo consumer uses a `replace` directive.
if not checked:
print(
f"GO MODULE PATH GATE FAILED: found no go.mod under {', '.join(PUBLISHED_ROOTS)}/ "
f"in {ROOT}. Zero modules checked is not zero modules broken — either "
f"PUBLISHED_ROOTS no longer describes where the published SDKs live, or the "
f"walk is looking at the wrong tree.",
file=sys.stderr,
)
return 1
if problems:
print("GO MODULE PATH GATE FAILED:", file=sys.stderr)
for problem in problems:
print(f" - {problem}", file=sys.stderr)
return 1
print(f"OK: {checked} published Go module path(s) resolve against {REPO_PATH}.")
return 0
if __name__ == "__main__":
raise SystemExit(main())