#!/usr/bin/env python3 """AI maintainability audit: project shape, context surface, verification surface, decision artifacts, drift markers, generated mirrors, and markdown links. Run as: python3 check_maintainability.py [ROOT] [summary|deep] Owns repository-signal, verifier, doc-link, generated-mirror, and drift receipts. Counts, missing maps, and large files stay informational unless tied to risk or real failure evidence. """ from __future__ import annotations import argparse import hashlib import json import os import re import subprocess import sys import urllib.parse from collections import Counter from pathlib import Path # Mechanical definitions (excluded dirs, source extensions, marker regex, # minified filter) are kept identical with skills/check/scripts/audit_signals.py # by tests/python/test_auditor_alignment.py; thresholds stay per-product. EXCLUDED_DIRS = { ".git", ".hg", ".svn", "node_modules", "dist", "build", ".next", "__pycache__", ".turbo", "target", ".venv", "venv", "vendor", "coverage", ".cache", ".parcel-cache", ".pytest_cache", ".mypy_cache", ".ruff_cache", "Pods", "Carthage", ".swiftpm", ".gradle", } SOURCE_EXTS = { ".bash", ".c", ".cc", ".cpp", ".cs", ".css", ".go", ".h", ".hpp", ".html", ".java", ".js", ".jsx", ".kt", ".lua", ".m", ".mjs", ".mm", ".md", ".php", ".py", ".rb", ".rs", ".scss", ".sh", ".swift", ".ts", ".tsx", ".vue", ".yaml", ".yml", ".zsh", } MARKER_RE = re.compile(r"\b(TODO|FIXME|HACK|XXX)\b", re.IGNORECASE) MARKER_EXAMPLE_RE = re.compile(r"\b(example|placeholder|fixture|marker|taxonomy)\b", re.IGNORECASE) MINIFIED_RE = re.compile(r"\.min\.[a-z]+$", re.IGNORECASE) MAKE_RE = re.compile(r"^([A-Za-z0-9_.-]+)\s*:(?![=])") MAKE_CMD_RE = re.compile(r"\bmake\s+([A-Za-z0-9_.-]+)\b") NPM_CMD_RE = re.compile(r"\b(?:npm|pnpm|yarn|bun)\s+run\s+([A-Za-z0-9:_-]+)\b") COMMAND_LINE_RE = re.compile(r"^(?:make|npm|pnpm|yarn|bun)\s+") VERIFIER_NAME_RE = re.compile( r"(?:^|[-_:.])(test|check|lint|type|build|package|verify|smoke)(?:$|[-_:.])", re.IGNORECASE, ) HOLLOW_COMMAND_RE = re.compile( r"^(?:echo\b.*|printf\b.*|true|false|:|exit(?:\s+\d+)?|set\s+-[^\s]+|" r"cd\b.*|(?:export|readonly|local)\b.*|trap\b.*|umask\b.*|" r"(?:mkdir|touch|chmod|chown|cp|mv|rm)\b.*|" r"[A-Za-z_][A-Za-z0-9_]*=.*)$", re.IGNORECASE, ) SHELL_OPTION_RE = re.compile( r"^set(?:\s+[-+][A-Za-z0-9_-]+)*(?:\s+[A-Za-z0-9_-]+)*$", re.IGNORECASE, ) VERIFIER_COMMAND_RE = re.compile( r"(?:" r"^(?:test|\[)\s+|" r"\bgit\s+diff\s+--check\b|" r"^(?:sudo\s+)?(?:shellcheck|pytest|ruff|mypy|eslint|stylelint|biome|hadolint)\b|" r"\bpython(?:3)?\s+-m\s+(?:pytest|unittest|compileall|py_compile)\b|" r"\b(?:cargo|go|mvn|gradle|deno)\s+(?:test|check|build|verify|vet|clippy)\b|" r"\bswift\s+(?:build|test)\b|" r"\b(?:npm|pnpm|yarn|bun)\s+(?:test|check|lint|build|verify|pack)\b|" r"(?:^|[\s/])[A-Za-z0-9_.-]*(?:test|check|verify|lint|smoke|build)" r"[A-Za-z0-9_./-]*\.(?:sh|py)\b" r")", re.IGNORECASE, ) SETUP_ONLY_COMMAND_RE = re.compile( r"(?:" r"\b(?:apt-get|apt|brew)\s+(?:install|update|upgrade)\b|" r"\bpython(?:3)?\s+-m\s+pip\s+install\b|" r"\bpip(?:3)?\s+install\b|" r"\b(?:npm|pnpm|yarn|bun)\s+(?:install|add|publish|view)\b|" r"\b(?:curl|wget)\b|" r"--version\b" r")", re.IGNORECASE, ) MARKDOWN_LINK_RE = re.compile(r"!?\[[^\]]*\]\(([^)]+)\)") URL_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:") RUSTDOC_LINK_RE = re.compile( r"(?:^|/)(?:constant|enum|fn|macro|mod|static|struct|trait|type|union)\." r"[^/]+\.html$" ) ACTIONABLE_COMMAND_RE = re.compile( r"(?:" r"\b(?:run|execute|invoke)\s+$|" r"\b(?:build|check|package|test|verify)\s+(?:using|via|with)\s+$|" r"\b(?:command|verification|verifier)\s*:\s*$" r")", re.IGNORECASE, ) MAX_TEXT_BYTES = 2_000_000 MAX_MIRROR_DIGEST_BYTES = 16_000_000 SECRET_TOKEN_RE = re.compile( r"\b(?:sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9]{12,}|" r"github_pat_[A-Za-z0-9_]{12,}|xox[baprs]-[A-Za-z0-9-]{10,}|" r"AKIA[A-Z0-9]{16}|eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\." r"[A-Za-z0-9_-]{10,})\b" ) SECRET_ASSIGNMENT_RE = re.compile( r"(?-{0,2}(?P[\x22\x27]?)(?:[A-Za-z0-9]+[_-])*" r"(?:secret[_-]access[_-]key|private[_-]?key|api[_-]?key|" r"authorization|password|passwd|pwd|token|secret)(?P=quote))" r"(?![A-Za-z0-9_-])" r"(?P\s*[:=]\s*)" r"(?:Bearer\s+|Basic\s+)?(?:\"(?:\\[^\r\n]|[^\"\\\r\n])*(?:\"|\\?(?=\r?\n|\Z))|" r"\x27(?:\\[^\r\n]|[^\x27\\\r\n])*(?:\x27|\\?(?=\r?\n|\Z))|[^\s,;]+)", re.IGNORECASE, ) PRIVATE_PATH_RE = re.compile( r"(?]+" ) WINDOWS_PATH_RE = re.compile( r"(?]+" ) # The file-walk helpers below are deliberately duplicated in # skills/check/scripts/audit_signals.py. Both scripts ship standalone # (see packaging.allowlist) and run inside an arbitrary target project, so # they import only stdlib. Do not hoist them into a shared scripts/ # module: it is dev-only, not on the ship allowlist, and would couple a # standalone tool to the install layout. def rel(path: Path, root: Path) -> str: try: value = path.resolve().relative_to(root).as_posix() except ValueError: value = path.as_posix() return safe_label(value) def safe_label(value: str, limit: int = 500) -> str: if any(ord(char) < 32 or ord(char) == 127 for char in value): value = json.dumps(value, ensure_ascii=False) return value if len(value) <= limit else f"{value[: limit - 3]}..." def redact_command_label(value: str) -> str: """Keep verifier inventory useful without emitting secrets or host paths.""" value = SECRET_TOKEN_RE.sub("[REDACTED]", value) value = SECRET_ASSIGNMENT_RE.sub( lambda match: f"{match.group('name')}{match.group('separator')}[REDACTED]", value, ) value = PRIVATE_PATH_RE.sub("[PATH]", value) return WINDOWS_PATH_RE.sub("[PATH]", value) def is_excluded(path: Path, root: Path) -> bool: parts = path.relative_to(root).parts if path.is_absolute() else path.parts if any(part in EXCLUDED_DIRS for part in parts): return True return bool(MINIFIED_RE.search(path.name)) def is_repo_file(path: Path, root: Path) -> bool: """Return true only for a regular file reached without any symlink hop.""" try: relative = path.relative_to(root) except ValueError: return False if not relative.parts: return False current = root try: for part in relative.parts: current /= part if current.is_symlink(): return False return current.is_file() except OSError: return False def is_repo_dir(path: Path, root: Path) -> bool: """Return true only for a directory reached without any symlink hop.""" try: relative = path.relative_to(root) except ValueError: return False current = root try: for part in relative.parts: current /= part if current.is_symlink(): return False return current.is_dir() except OSError: return False def is_safe_repo_reference(path: Path, root: Path) -> bool: """Allow documentation symlinks only when their final target stays in-repo.""" try: path.relative_to(root) resolved = path.resolve(strict=True) resolved.relative_to(root.resolve()) return resolved.is_file() or resolved.is_dir() except (OSError, RuntimeError, ValueError): return False def read_text(path: Path, root: Path, limit: int | None = None) -> str: if not is_repo_file(path, root): return "" byte_limit = limit or MAX_TEXT_BYTES try: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) descriptor = os.open(path, flags) except OSError: return "" try: chunks: list[bytes] = [] remaining = byte_limit while remaining: chunk = os.read(descriptor, min(65_536, remaining)) if not chunk: break chunks.append(chunk) remaining -= len(chunk) except OSError: return "" finally: os.close(descriptor) return b"".join(chunks).decode("utf-8", errors="replace") def file_digest(path: Path, root: Path) -> tuple[int, bytes] | None: """Hash a stable regular file without trusting a shared prefix.""" if not is_repo_file(path, root): return None try: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) descriptor = os.open(path, flags) except OSError: return None try: before = os.fstat(descriptor) if before.st_size > MAX_MIRROR_DIGEST_BYTES: return None digest = hashlib.sha256() while True: chunk = os.read(descriptor, 65_536) if not chunk: break digest.update(chunk) after = os.fstat(descriptor) if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns): return None return before.st_size, digest.digest() except OSError: return None finally: os.close(descriptor) def iter_files(root: Path) -> list[Path]: try: proc = subprocess.run( [ "git", "-c", "core.fsmonitor=false", "-C", str(root), "ls-files", "--cached", "--others", "--exclude-standard", "-z", ], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, check=False, ) if proc.returncode == 0 and proc.stdout: files = [] for raw_path in proc.stdout.split(b"\0"): if not raw_path: continue path = root / os.fsdecode(raw_path) if is_repo_file(path, root) and not is_excluded(path, root): files.append(path) return files except OSError: pass files = [] for dirpath, dirnames, filenames in os.walk(root): current = Path(dirpath) dirnames[:] = [ name for name in dirnames if name not in EXCLUDED_DIRS and is_repo_dir(current / name, root) ] if is_excluded(current, root): continue for filename in filenames: path = current / filename if is_repo_file(path, root) and not is_excluded(path, root): files.append(path) return files def collapse_generated_mirrors( files: list[Path], root: Path ) -> tuple[list[Path], int, list[str], list[str]]: """Fold byte-identical Codex plugin mirrors into their source files.""" file_set = set(files) digests: dict[Path, tuple[int, bytes] | None] = {} def digest(path: Path) -> tuple[int, bytes] | None: if path not in digests: digests[path] = file_digest(path, root) return digests[path] logical: list[Path] = [] collapsed = 0 drifted: list[str] = [] coverage_gaps: list[str] = [] for path in files: try: parts = path.relative_to(root).parts except ValueError: logical.append(path) continue source: Path | None = None if len(parts) >= 4 and parts[0] == "plugins" and parts[2] in {"skills", "rules"}: source = root.joinpath(*parts[2:]) if source is not None and source in file_set: mirror_digest = digest(path) source_digest = digest(source) if mirror_digest is None or source_digest is None: coverage_gaps.append( f"{rel(path, root)} -> {rel(source, root)}" ) elif mirror_digest == source_digest: collapsed += 1 continue else: drifted.append(f"{rel(path, root)} -> {rel(source, root)}") logical.append(path) return logical, collapsed, drifted, coverage_gaps def line_count(path: Path, root: Path) -> int: if not is_repo_file(path, root): return 0 try: flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) with os.fdopen(os.open(path, flags), "rb") as handle: return sum(1 for _ in handle) except OSError: return 0 def print_list(items: list[str], empty: str = "(none)", limit: int | None = None) -> None: shown = items if limit is None else items[:limit] if not shown: print(f" {empty}") return for item in shown: print(f" {safe_label(item)}") if limit is not None and len(items) > limit: print(f" ... {len(items) - limit} more") def instruction_paths(root: Path) -> list[Path]: candidates = [ root / "AGENTS.md", root / "CLAUDE.md", root / ".github" / "copilot-instructions.md", root / "GEMINI.md", ] instructions_dir = root / ".github" / "instructions" if is_repo_dir(instructions_dir, root): candidates.extend(sorted(instructions_dir.glob("*.md"))) rules_dir = root / ".claude" / "rules" if is_repo_dir(rules_dir, root): candidates.extend(sorted(rules_dir.glob("*.md"))) return [ path for path in candidates if is_repo_file(path, root) and not is_excluded(path, root) ] def has_substantive_instruction_evidence(path: Path, root: Path) -> bool: """Reject empty/frontmatter/heading-only placeholders as context evidence.""" in_frontmatter = False frontmatter_seen = False for raw_line in read_text(path, root, 200_000).splitlines(): line = raw_line.strip() if not line: continue if line == "---" and not frontmatter_seen: in_frontmatter = True frontmatter_seen = True continue if line == "---" and in_frontmatter: in_frontmatter = False continue if in_frontmatter or line.startswith("#") or line.startswith("