| #!/usr/bin/env python3 | |
| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Timeless whole-tree isolation checker for the `experimental/` incubator. | |
| Enforces the structural invariants of `experimental/<slug>/` without relying on | |
| wall-clock time or Git history (dated `expires_on` windows are enforced by | |
| `ci/check_pr_hygiene.py`): | |
| 1. No inbound edges (including symlinks, capitalized Lean imports, or direct | |
| shell/Python references) from outside `experimental/`, and no sideways or | |
| escaping relative references from inside a slug. | |
| 2. Schema-valid `EXPERIMENT.toml` (`owners`, `tracking_issue`, `expires_on`, | |
| `ci_command`) and `README.md` with the experimental incubator banner. | |
| 3. Cargo dependencies restricted to intra-slug path dependencies and external | |
| `crates.io` crate versions whose `(name, version, source, checksum)` are | |
| pinned in a slug `Cargo.lock` and already locked in root or registered | |
| `tools/`/`crates/` lockfiles (no `[patch]`/`[replace]`, `build.rs`, | |
| `package.build`, `proc-macro`, git/custom registries, or escaping target | |
| paths). | |
| 4. Forbidden content (matched case-insensitively): symlinks, submodules, | |
| binaries/media, `.olean` files, `target/`, `.build/`, `.lake/`, `.cargo`, | |
| `AGENTS.md`, `AGENTS.override.md`, `build.rs`, `lakefile.*`, | |
| `lean-toolchain`, `rust-toolchain*`, bidi control characters, missing | |
| license headers, and deterministic internal-only identifier patterns. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import datetime | |
| import fnmatch | |
| import json | |
| import os | |
| from pathlib import Path | |
| import re | |
| import sys | |
| import tomllib | |
| from typing import Iterable | |
| SLUG_RE = re.compile(r"^[a-z][a-z0-9-]{0,63}$") | |
| HANDLE_RE = re.compile(r"^@[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") | |
| GITHUB_ISSUE_RE = re.compile( | |
| r"^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/(?:issues|pull)/[1-9][0-9]*$" | |
| ) | |
| ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") | |
| SHA256_RE = re.compile(r"^[0-9a-f]{64}$") | |
| CRATES_IO_REGISTRY_SOURCE = ( | |
| "registry+https://github.com/rust-lang/crates.io-index" | |
| ) | |
| REQUIRED_EXPERIMENT_KEYS = frozenset( | |
| {"owners", "tracking_issue", "expires_on", "ci_command"} | |
| ) | |
| DEP_SECTION_NAMES = ( | |
| "dependencies", | |
| "dev-dependencies", | |
| "dev_dependencies", | |
| "build-dependencies", | |
| "build_dependencies", | |
| ) | |
| FORBIDDEN_FILENAMES_LOWER = frozenset({ | |
| "agents.md", | |
| "agents.override.md", | |
| "claude.md", | |
| "gemini.md", | |
| "build.rs", | |
| "makefile", | |
| "gnumakefile", | |
| "justfile", | |
| "flake.nix", | |
| "flake.lock", | |
| "lakefile.lean", | |
| "lakefile.toml", | |
| "lake-manifest.json", | |
| "lean-toolchain", | |
| "rust-toolchain", | |
| "rust-toolchain.toml", | |
| ".gitattributes", | |
| ".gitmodules", | |
| ".envrc", | |
| ".mcp.json", | |
| ".cursorrules", | |
| ".windsurfrules", | |
| ".clinerules", | |
| ".pre-commit-config.yaml", | |
| ".pre-commit-config.yml", | |
| }) | |
| FORBIDDEN_DIRNAMES_LOWER = frozenset({ | |
| "target", | |
| "__pycache__", | |
| ".cargo", | |
| ".git", | |
| ".github", | |
| ".lake", | |
| ".build", | |
| ".agents", | |
| ".claude", | |
| ".gemini", | |
| ".codex", | |
| ".vscode", | |
| ".cursor", | |
| ".devcontainer", | |
| ".idea", | |
| ".zed", | |
| }) | |
| FORBIDDEN_CONFIG_EXTENSIONS = frozenset({ | |
| ".nix", | |
| ".yml", | |
| ".yaml", | |
| }) | |
| FORBIDDEN_EXTENSIONS = frozenset({ | |
| ".olean", | |
| ".ilean", | |
| ".ir", | |
| ".png", | |
| ".jpg", | |
| ".jpeg", | |
| ".gif", | |
| ".webp", | |
| ".bmp", | |
| ".ico", | |
| ".pdf", | |
| ".mp4", | |
| ".webm", | |
| ".wav", | |
| ".mp3", | |
| ".wasm", | |
| ".so", | |
| ".a", | |
| ".dylib", | |
| ".dll", | |
| ".exe", | |
| ".tar", | |
| ".gz", | |
| ".xz", | |
| ".bz2", | |
| ".zst", | |
| ".zip", | |
| ".7z", | |
| }) | |
| FORBIDDEN_SUFFIXES = ( | |
| ".olean.server", | |
| ".olean.private", | |
| ".ir.sig", | |
| ) | |
| HEADER_EXTS = frozenset({ | |
| ".rs", | |
| ".py", | |
| ".sh", | |
| ".lean", | |
| ".toml", | |
| ".md", | |
| ".yml", | |
| ".yaml", | |
| }) | |
| HEADER_RE = re.compile( | |
| r"Copyright \d{4} The Fuchsia Authors.*" | |
| r"Licensed under a BSD-style license <LICENSE-BSD>, Apache License, " | |
| r"Version 2\.0", | |
| re.DOTALL, | |
| ) | |
| # Unicode bidirectional override / isolate and invisible format characters. | |
| BIDI_CODEPOINTS = frozenset({ | |
| "\u200b", | |
| "\u200c", | |
| "\u200d", | |
| "\u200e", | |
| "\u200f", | |
| "\u061c", | |
| "\u202a", | |
| "\u202b", | |
| "\u202c", | |
| "\u202d", | |
| "\u202e", | |
| "\u2060", | |
| "\u2061", | |
| "\u2062", | |
| "\u2063", | |
| "\u2064", | |
| "\u2066", | |
| "\u2067", | |
| "\u2068", | |
| "\u2069", | |
| "\ufeff", | |
| }) | |
| # Deterministic non-public patterns banned from public experimental files. | |
| INTERNAL_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( | |
| ( | |
| "private corporate hostname", | |
| re.compile( | |
| r"(?:https?://|ssh://|git@)[A-Za-z0-9._-]+\.(?:corp|internal|local)\b" | |
| r"|\b[A-Za-z0-9._-]+\.corp\b" | |
| ), | |
| ), | |
| ("workstation path", re.compile(r"(?:^|[\s'\"(`])(?:/Users/|/home/)")), | |
| ("file URI", re.compile(r"\bfile:///[A-Za-z0-9._/-]+")), | |
| ) | |
| # Top-level directories outside `experimental/` that contain only non-code | |
| # documentation or vendored/build trees; note symlinks are still checked under | |
| # `docs/`, `site/`, and `skills/`. | |
| INBOUND_TEXT_SKIP_DIRS = frozenset({ | |
| ".git", | |
| "target", | |
| "vendor", | |
| "experimental", | |
| "docs", | |
| "site", | |
| "skills", | |
| ".lake", | |
| }) | |
| INBOUND_SYMLINK_SKIP_DIRS = frozenset({ | |
| ".git", | |
| "target", | |
| "vendor", | |
| "experimental", | |
| ".lake", | |
| }) | |
| # Only policy prose and this checker (+ its unit test) are exempt from all | |
| # inbound text patterns; the 6 sibling test files that construct synthetic | |
| # `"experimental/<slug>"` strings are exempt only from the generic script/path | |
| # literal regex (`INBOUND_EDGE_PATTERNS[3]`) and are still scanned for Cargo | |
| # `path` dependencies, Rust `#[path]`/`include*!`, and Lean `import` edges. | |
| INBOUND_SCAN_EXEMPT_FILES = frozenset({ | |
| "AGENTS.md", | |
| ".gemini/styleguide.md", | |
| "ci/check_experimental_isolation.py", | |
| "ci/test_check_experimental_isolation.py", | |
| }) | |
| INBOUND_SCRIPT_LITERAL_EXEMPT_FILES = frozenset({ | |
| "ci/test_check_todo.py", | |
| "ci/check_pr_hygiene_tests/hardening.py", | |
| "ci/ci_workflow_tests/ci_core_workflows.py", | |
| "ci/release_workflow_tests/history_guards.py", | |
| "ci/test_run_experimental_ci.py", | |
| "tests/audit/tests/boundary_audit/cargo_boundary.rs", | |
| }) | |
| INBOUND_SCAN_EXEMPT_PREFIXES: tuple[str, ...] = () | |
| # Patterns matching inbound edges targeting `experimental/<slug>`. | |
| INBOUND_EDGE_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = ( | |
| ( | |
| "Cargo path dependency into experimental/", | |
| re.compile( | |
| r"""path\s*=\s*r?#*["'][^"']*\bexperimental(?:/|["'])""", | |
| re.IGNORECASE, | |
| ), | |
| ), | |
| ( | |
| "Rust #[path] or include*! into experimental/", | |
| re.compile( | |
| r"""(?:#\[path\s*=|include(?:_str|_bytes)?!\s*\()\s*r?#*["'][^"']*\bexperimental/""", | |
| re.IGNORECASE, | |
| ), | |
| ), | |
| ( | |
| "Lean import targeting experimental", | |
| re.compile( | |
| r"""(?<![A-Za-z0-9_.-])(?:(?:public|private|meta)\s+)*import\s+(?:all\s+)?(?:[A-Za-z0-9_-]+\.)*experimental(?:\.|\b)""", | |
| re.IGNORECASE, | |
| ), | |
| ), | |
| ( | |
| "Python/shell reference to experimental/<slug>", | |
| re.compile( | |
| r"""(?:from\s+experimental(?:\.[A-Za-z0-9_.]*)?\s+import\b""" | |
| r"""|import\s+experimental(?:\.|\b)""" | |
| r"""|import_module\s*\(\s*["']experimental(?:\.|\b)""" | |
| r"""|python3?\s+(?:-[A-Za-z0-9]+\s+)*-m\s+experimental(?:\.|\b)""" | |
| r"""|\bcd\s+[^\n;|&]*\bexperimental(?:/|\b)""" | |
| r"""|(?:join|Path)\s*\(\s*[^)\r\n]*["']experimental["']""" | |
| r"""|["']experimental["']\s*(?:\\\s*)?/""" | |
| r"""|(?:^|[\s'"`(=/{}$])(?:[A-Za-z0-9_.$+-]+/|\./|\.\./)*experimental/(?!README\.md\b|\*)[a-z0-9][a-z0-9_-]*(?:/|\b))""", | |
| re.IGNORECASE | re.DOTALL, | |
| ), | |
| ), | |
| ) | |
| SIDEWAYS_SLUG_RE = re.compile( | |
| r"\bexperimental/(?!README\.md\b)([a-z][a-z0-9-]{0,63})(?:/|\b)", | |
| re.IGNORECASE, | |
| ) | |
| LEAN_IMPORT_MOD_RE = re.compile( | |
| r"(?<![A-Za-z0-9_.-])(?:(?:public|private|meta)\s+)*import\s+(?:all\s+)?([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)*)", | |
| ) | |
| REL_PARENT_TOKEN_RE = re.compile(r"[A-Za-z0-9_./-]*\.\./[A-Za-z0-9_./-]*") | |
| def _lean_segment_matches_slug(raw_seg: str, slug: str) -> bool: | |
| if not raw_seg: | |
| return False | |
| if "-" in raw_seg or "_" in raw_seg: | |
| return raw_seg.lower().replace("_", "-") == slug.lower() | |
| if "-" in slug: | |
| camel = "".join(p.capitalize() for p in slug.split("-")) | |
| return raw_seg == camel | |
| return raw_seg.lower() == slug.lower() | |
| def _strip_lean_comments_and_guillemets(text: str) -> str: | |
| """Strips nested `/- ... -/` comments, `--` comments, strings, and `«»`.""" | |
| out: list[str] = [] | |
| i = 0 | |
| n = len(text) | |
| depth = 0 | |
| in_str = False | |
| while i < n: | |
| ch = text[i] | |
| if depth > 0: | |
| if ch == "/" and i + 1 < n and text[i + 1] == "-": | |
| depth += 1 | |
| out.append(" ") | |
| i += 2 | |
| elif ch == "-" and i + 1 < n and text[i + 1] == "/": | |
| depth -= 1 | |
| out.append(" ") | |
| i += 2 | |
| else: | |
| out.append("\n" if ch == "\n" else " ") | |
| i += 1 | |
| elif in_str: | |
| if ch == "\\" and i + 1 < n: | |
| out.append(" ") | |
| i += 2 | |
| elif ch == '"': | |
| in_str = False | |
| out.append(" ") | |
| i += 1 | |
| else: | |
| out.append("\n" if ch == "\n" else " ") | |
| i += 1 | |
| else: | |
| if ch == '"': | |
| in_str = True | |
| out.append(" ") | |
| i += 1 | |
| elif ch == "/" and i + 1 < n and text[i + 1] == "-": | |
| depth = 1 | |
| out.append(" ") | |
| i += 2 | |
| elif ch == "-" and i + 1 < n and text[i + 1] == "-": | |
| while i < n and text[i] != "\n": | |
| out.append(" ") | |
| i += 1 | |
| elif ch in ("«", "»"): | |
| i += 1 | |
| else: | |
| out.append(ch) | |
| i += 1 | |
| return "".join(out) | |
| def _is_binary_bytes(data: bytes) -> bool: | |
| return b"\x00" in data | |
| def _has_symlink_below(base: Path, target: Path) -> bool: | |
| """True when `target` or any component below `base` is a symlink.""" | |
| try: | |
| rel = target.relative_to(base) | |
| except ValueError: | |
| return target.is_symlink() | |
| cur = base | |
| for part in rel.parts: | |
| cur = cur / part | |
| if cur.is_symlink(): | |
| return True | |
| return False | |
| def _collect_allowed_lock_packages( | |
| repo_root: Path, | |
| ) -> set[tuple[str, str, str, str]]: | |
| """Collect pinned `(name, version, source, checksum)` crates.io packages.""" | |
| lockfiles: list[Path] = [] | |
| root_lock = repo_root / "Cargo.lock" | |
| if root_lock.is_file() and not root_lock.is_symlink(): | |
| lockfiles.append(root_lock) | |
| root_toml = repo_root / "Cargo.toml" | |
| if root_toml.is_file() and not root_toml.is_symlink(): | |
| try: | |
| parsed = tomllib.loads(root_toml.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): | |
| parsed = {} | |
| excludes = parsed.get("workspace", {}).get("exclude", []) | |
| if isinstance(excludes, list): | |
| for entry in excludes: | |
| if not isinstance(entry, str) or entry.lower() == "experimental": | |
| continue | |
| cand = repo_root / entry / "Cargo.lock" | |
| if cand.is_file() and not cand.is_symlink(): | |
| lockfiles.append(cand) | |
| pkgs: set[tuple[str, str, str, str]] = set() | |
| for lf in lockfiles: | |
| try: | |
| data = tomllib.loads(lf.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError): | |
| continue | |
| packages = data.get("package") | |
| if not isinstance(packages, list): | |
| continue | |
| for pkg in packages: | |
| if not isinstance(pkg, dict): | |
| continue | |
| name = pkg.get("name") | |
| version = pkg.get("version") | |
| source = pkg.get("source") | |
| checksum = pkg.get("checksum") | |
| if ( | |
| isinstance(name, str) | |
| and name | |
| and isinstance(version, str) | |
| and version | |
| and source == CRATES_IO_REGISTRY_SOURCE | |
| and isinstance(checksum, str) | |
| and SHA256_RE.fullmatch(checksum) | |
| ): | |
| pkgs.add((name, version, source, checksum)) | |
| return pkgs | |
| def _check_text_hygiene( | |
| rel_path: str, text: str, errors: list[str], *, require_header: bool | |
| ) -> None: | |
| for cp in BIDI_CODEPOINTS: | |
| if cp in text: | |
| errors.append( | |
| f"{rel_path}: forbidden Unicode bidi control U+{ord(cp):04X}" | |
| ) | |
| break | |
| if require_header: | |
| head = "\n".join(text.splitlines()[:20]) | |
| if not HEADER_RE.search(head): | |
| errors.append(f"{rel_path}: missing Fuchsia copyright/license header") | |
| for label, pat in INTERNAL_PATTERNS: | |
| m = pat.search(text) | |
| if m: | |
| errors.append( | |
| f"{rel_path}: forbidden public-sink pattern ({label}: {m.group(0)!r})" | |
| ) | |
| def _validate_experiment_toml( | |
| slug: str, toml_path: Path, slug_dir: Path, errors: list[str] | |
| ) -> None: | |
| rel = f"experimental/{slug}/EXPERIMENT.toml" | |
| if toml_path.is_symlink() or not toml_path.is_file(): | |
| errors.append(f"{rel}: missing required regular file") | |
| return | |
| try: | |
| raw = toml_path.read_text(encoding="utf-8") | |
| except (OSError, UnicodeDecodeError) as exc: | |
| errors.append(f"{rel}: cannot read UTF-8: {exc}") | |
| return | |
| try: | |
| data = tomllib.loads(raw) | |
| except tomllib.TOMLDecodeError as exc: | |
| errors.append(f"{rel}: invalid TOML: {exc}") | |
| return | |
| keys = set(data.keys()) | |
| missing = sorted(REQUIRED_EXPERIMENT_KEYS - keys) | |
| extra = sorted(keys - REQUIRED_EXPERIMENT_KEYS) | |
| if missing: | |
| errors.append(f"{rel}: missing required keys: {', '.join(missing)}") | |
| if extra: | |
| errors.append(f"{rel}: unexpected keys: {', '.join(extra)}") | |
| owners = data.get("owners") | |
| if ( | |
| not isinstance(owners, list) | |
| or not owners | |
| or not all(isinstance(o, str) and HANDLE_RE.fullmatch(o) for o in owners) | |
| ): | |
| errors.append( | |
| f"{rel}: `owners` must be a non-empty list of `@github-handle` strings" | |
| ) | |
| tracking = data.get("tracking_issue") | |
| if not isinstance(tracking, str) or not GITHUB_ISSUE_RE.fullmatch(tracking): | |
| errors.append( | |
| f"{rel}: `tracking_issue` must be a public " | |
| "https://github.com/.../issues/<N> URL" | |
| ) | |
| expires_on = data.get("expires_on") | |
| if isinstance(expires_on, datetime.date) and not isinstance( | |
| expires_on, datetime.datetime | |
| ): | |
| # TOML native local date is acceptable as well as ISO string. | |
| pass | |
| elif isinstance(expires_on, str) and ISO_DATE_RE.fullmatch(expires_on): | |
| try: | |
| datetime.date.fromisoformat(expires_on) | |
| except ValueError: | |
| errors.append( | |
| f"{rel}: `expires_on` is not a valid calendar date: {expires_on!r}" | |
| ) | |
| else: | |
| errors.append(f"{rel}: `expires_on` must be an ISO date YYYY-MM-DD") | |
| ci_cmd = data.get("ci_command") | |
| if ( | |
| not isinstance(ci_cmd, list) | |
| or not ci_cmd | |
| or not all(isinstance(a, str) and a.strip() for a in ci_cmd) | |
| ): | |
| errors.append(f"{rel}: `ci_command` must be a non-empty list of strings") | |
| return | |
| slug_resolved = slug_dir.resolve() | |
| for idx, arg in enumerate(ci_cmd): | |
| if "\\" in arg: | |
| errors.append( | |
| f"{rel}: `ci_command[{idx}]` must not contain backslashes: {arg!r}" | |
| ) | |
| continue | |
| sub_tokens = [t for t in re.split(r"[\s='\"`<>;|&:]+", arg) if t] | |
| if ( | |
| arg.startswith("/") | |
| or any(t.startswith("/") for t in sub_tokens) | |
| or any(".." in Path(t).parts for t in [arg, *sub_tokens]) | |
| ): | |
| errors.append( | |
| f"{rel}: `ci_command[{idx}]` must not be absolute or traverse " | |
| f"outside the slug: {arg!r}" | |
| ) | |
| exe = ci_cmd[0] | |
| if ( | |
| "\\" not in exe | |
| and exe.startswith("./") | |
| and ".." not in Path(exe).parts | |
| ): | |
| raw_script = slug_dir / exe[2:] | |
| if _has_symlink_below(slug_dir, raw_script): | |
| errors.append( | |
| f"{rel}: `ci_command[0]` must not traverse symlinks: {exe!r}" | |
| ) | |
| elif not raw_script.resolve().is_relative_to(slug_resolved): | |
| errors.append( | |
| f"{rel}: `ci_command[0]` escapes slug directory: {exe!r}" | |
| ) | |
| elif not raw_script.is_file(): | |
| errors.append( | |
| f"{rel}: `ci_command[0]` script does not exist as a regular " | |
| f"file inside the slug: {exe!r}" | |
| ) | |
| def _validate_experiment_readme( | |
| slug: str, readme_path: Path, errors: list[str] | |
| ) -> None: | |
| rel = f"experimental/{slug}/README.md" | |
| if readme_path.is_symlink() or not readme_path.is_file(): | |
| errors.append(f"{rel}: missing required regular file") | |
| return | |
| try: | |
| text = readme_path.read_text(encoding="utf-8") | |
| except (OSError, UnicodeDecodeError) as exc: | |
| errors.append(f"{rel}: cannot read UTF-8: {exc}") | |
| return | |
| top = "\n".join(text.splitlines()[:40]) | |
| if "[!NOTE]" not in top or "experimental incubator" not in top.lower(): | |
| errors.append( | |
| f"{rel}: must open with a `[!NOTE]` banner containing " | |
| "`Experimental incubator`" | |
| ) | |
| def _posix_glob_match(path_str: str, pat_str: str) -> bool: | |
| p_parts = [s for s in path_str.split("/") if s and s != "."] | |
| g_parts = [s for s in pat_str.split("/") if s and s != "."] | |
| def _rec(pi: int, gi: int) -> bool: | |
| if gi == len(g_parts): | |
| return pi == len(p_parts) | |
| if g_parts[gi] == "**": | |
| return _rec(pi, gi + 1) or ( | |
| pi < len(p_parts) and _rec(pi + 1, gi) | |
| ) | |
| if pi == len(p_parts): | |
| return False | |
| return fnmatch.fnmatchcase(p_parts[pi], g_parts[gi]) and _rec( | |
| pi + 1, gi + 1 | |
| ) | |
| return _rec(0, 0) | |
| def _find_nearest_in_slug( | |
| start_dir: Path, | |
| slug_dir: Path, | |
| mapping: dict[Path, object], | |
| workspaces_by_dir: dict[Path, tuple[list[str], list[str]]], | |
| ) -> object | None: | |
| if start_dir in workspaces_by_dir: | |
| return mapping.get(start_dir) | |
| cur = start_dir | |
| while cur != slug_dir and cur.parent != cur: | |
| cur = cur.parent | |
| if cur not in workspaces_by_dir: | |
| continue | |
| members, excludes = workspaces_by_dir[cur] | |
| rel_sub = start_dir.relative_to(cur).as_posix() | |
| if any( | |
| _posix_glob_match(rel_sub, pat) | |
| or rel_sub.startswith(pat.rstrip("/") + "/") | |
| for pat in excludes | |
| ): | |
| break | |
| if any(_posix_glob_match(rel_sub, pat) for pat in members): | |
| return mapping.get(cur) | |
| return None | |
| return mapping.get(start_dir) | |
| def _parse_semver_triple(ver: str) -> tuple[int, int, int, str] | None: | |
| m = re.fullmatch( | |
| r"(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?", | |
| ver.strip(), | |
| ) | |
| if not m: | |
| return None | |
| return int(m.group(1)), int(m.group(2)), int(m.group(3)), m.group(4) or "" | |
| def _version_req_matches(req_str: str, locked_ver: str) -> bool: | |
| parsed_locked = _parse_semver_triple(locked_ver) | |
| if parsed_locked is None: | |
| return False | |
| l_maj, l_min, l_pat, l_pre = parsed_locked | |
| l_tuple = (l_maj, l_min, l_pat) | |
| clauses = [c.strip() for c in req_str.split(",")] | |
| if not clauses or any(not c for c in clauses): | |
| return False | |
| for clause in clauses: | |
| if clause == "*": | |
| if l_pre: | |
| return False | |
| continue | |
| m = re.fullmatch( | |
| r"(>=|<=|!=|=|>|<|\^|~)?\s*(\d+)(?:\.(\d+|\*)(?:\.(\d+|\*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?)?)?", | |
| clause, | |
| ) | |
| if not m: | |
| return False | |
| op = m.group(1) or "^" | |
| r_maj = int(m.group(2)) | |
| raw_min, raw_pat, r_pre = m.group(3), m.group(4), m.group(5) or "" | |
| if l_pre and not r_pre: | |
| return False | |
| if r_pre and l_pre != r_pre: | |
| return False | |
| if raw_min == "*": | |
| if m.group(1) is not None or ( | |
| raw_pat is not None and raw_pat != "*" | |
| ): | |
| return False | |
| if l_maj != r_maj: | |
| return False | |
| continue | |
| if raw_pat == "*": | |
| if m.group(1) is not None or raw_min is None: | |
| return False | |
| r_min_val = int(raw_min) | |
| if (l_maj, l_min) != (r_maj, r_min_val): | |
| return False | |
| continue | |
| r_min = int(raw_min) if raw_min is not None else None | |
| r_pat = int(raw_pat) if raw_pat is not None else None | |
| low = (r_maj, r_min or 0, r_pat or 0) | |
| partial_upper = ( | |
| (r_maj + 1, 0, 0) if r_min is None else (r_maj, r_min + 1, 0) | |
| ) | |
| if op == "=": | |
| ok = ( | |
| (low <= l_tuple < partial_upper) | |
| if r_pat is None | |
| else (l_tuple == low) | |
| ) | |
| elif op == "!=": | |
| ok = ( | |
| not (low <= l_tuple < partial_upper) | |
| if r_pat is None | |
| else (l_tuple != low) | |
| ) | |
| elif op == ">=": | |
| ok = l_tuple >= low | |
| elif op == ">": | |
| ok = ( | |
| (l_tuple >= partial_upper) | |
| if r_pat is None | |
| else (l_tuple > low) | |
| ) | |
| elif op == "<=": | |
| ok = ( | |
| (l_tuple < partial_upper) | |
| if r_pat is None | |
| else (l_tuple <= low) | |
| ) | |
| elif op == "<": | |
| ok = l_tuple < low | |
| elif op == "~": | |
| ok = low <= l_tuple < partial_upper | |
| else: # "^" | |
| if r_maj > 0: | |
| upper = (r_maj + 1, 0, 0) | |
| elif r_min is None: | |
| upper = (1, 0, 0) | |
| elif r_min > 0 or r_pat is None: | |
| upper = (0, r_min + 1, 0) | |
| else: | |
| upper = (0, 0, r_pat + 1) | |
| ok = low <= l_tuple < upper | |
| if not ok: | |
| return False | |
| return True | |
| def _validate_path_within_slug( | |
| rel: str, | |
| context: str, | |
| manifest_dir: Path, | |
| raw_path: object, | |
| slug_dir: Path, | |
| slug_resolved: Path, | |
| errors: list[str], | |
| ) -> None: | |
| if not isinstance(raw_path, str) or not raw_path.strip(): | |
| errors.append(f"{rel}: {context} has invalid path {raw_path!r}") | |
| return | |
| if "\\" in raw_path: | |
| errors.append( | |
| f"{rel}: {context} path `{raw_path}` must not contain backslashes" | |
| ) | |
| return | |
| if raw_path.startswith("/") or Path(raw_path).is_absolute(): | |
| errors.append( | |
| f"{rel}: {context} path `{raw_path}` must not be absolute" | |
| ) | |
| return | |
| candidate = manifest_dir / raw_path | |
| norm_abs = Path(os.path.normpath(str(candidate))) | |
| if not norm_abs.is_relative_to(slug_dir): | |
| errors.append( | |
| f"{rel}: {context} path `{raw_path}` escapes experimental/{slug_dir.name}/" | |
| ) | |
| return | |
| if _has_symlink_below(slug_dir, norm_abs): | |
| errors.append( | |
| f"{rel}: {context} path `{raw_path}` traverses a symlink" | |
| ) | |
| return | |
| if not candidate.resolve().is_relative_to(slug_resolved): | |
| errors.append( | |
| f"{rel}: {context} path `{raw_path}` escapes experimental/{slug_dir.name}/" | |
| ) | |
| def _validate_cargo_lock_in_slug( | |
| slug_dir: Path, | |
| lock_path: Path, | |
| allowed_pkgs: set[tuple[str, str, str, str]], | |
| local_pkg_names: set[str], | |
| errors: list[str], | |
| ) -> dict[str, set[str]]: | |
| rel = lock_path.relative_to(slug_dir.parent.parent).as_posix() | |
| locked_external_versions: dict[str, set[str]] = {} | |
| try: | |
| data = tomllib.loads(lock_path.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: | |
| errors.append(f"{rel}: invalid Cargo.lock: {exc}") | |
| return locked_external_versions | |
| packages = data.get("package") | |
| if not isinstance(packages, list): | |
| errors.append(f"{rel}: expected `[[package]]` list in Cargo.lock") | |
| return locked_external_versions | |
| for idx, pkg in enumerate(packages): | |
| if not isinstance(pkg, dict): | |
| errors.append(f"{rel}: package[{idx}] must be a TOML table") | |
| continue | |
| name = pkg.get("name") | |
| version = pkg.get("version") | |
| if not isinstance(name, str) or not name or not isinstance(version, str) or not version: | |
| errors.append( | |
| f"{rel}: package[{idx}] must declare string `name` and `version`" | |
| ) | |
| continue | |
| source = pkg.get("source") | |
| checksum = pkg.get("checksum") | |
| if source is None: | |
| if checksum is not None: | |
| errors.append( | |
| f"{rel}: local package `{name} {version}` must not set `checksum`" | |
| ) | |
| if name not in local_pkg_names: | |
| errors.append( | |
| f"{rel}: source-less package `{name} {version}` does not " | |
| f"match any local Cargo.toml in experimental/{slug_dir.name}/" | |
| ) | |
| continue | |
| if source != CRATES_IO_REGISTRY_SOURCE: | |
| errors.append( | |
| f"{rel}: locked external crate `{name} {version}` uses " | |
| f"forbidden source {source!r}" | |
| ) | |
| continue | |
| if not isinstance(checksum, str) or not SHA256_RE.fullmatch(checksum): | |
| errors.append( | |
| f"{rel}: locked external crate `{name} {version}` is missing a " | |
| "valid SHA-256 `checksum`" | |
| ) | |
| continue | |
| if (name, version, source, checksum) not in allowed_pkgs: | |
| errors.append( | |
| f"{rel}: locked external crate `{name} {version}` " | |
| "(source/checksum) is not present in root or registered " | |
| "tools/crates Cargo.lock" | |
| ) | |
| continue | |
| locked_external_versions.setdefault(name, set()).add(version) | |
| return locked_external_versions | |
| def _check_external_dep_version( | |
| rel: str, | |
| section: str, | |
| pkg_name: str, | |
| ver_req: object, | |
| allowed_names: set[str], | |
| locked_ext_versions: dict[str, set[str]] | None, | |
| errors: list[str], | |
| ) -> None: | |
| if pkg_name not in allowed_names: | |
| errors.append( | |
| f"{rel}: [{section}] dependency `{pkg_name}` is not present in " | |
| "root or registered tools/crates Cargo.lock" | |
| ) | |
| return | |
| if locked_ext_versions is None: | |
| errors.append( | |
| f"{rel}: [{section}] external dependency `{pkg_name}` requires " | |
| "a checked-in Cargo.lock inside the experiment" | |
| ) | |
| return | |
| locked_vers = locked_ext_versions.get(pkg_name) | |
| if not locked_vers: | |
| errors.append( | |
| f"{rel}: [{section}] external dependency `{pkg_name}` is not " | |
| "pinned in the experiment's Cargo.lock" | |
| ) | |
| return | |
| if not isinstance(ver_req, str) or not ver_req.strip(): | |
| errors.append( | |
| f"{rel}: [{section}] external dependency `{pkg_name}` must " | |
| "declare a version requirement string" | |
| ) | |
| return | |
| if not any(_version_req_matches(ver_req, lv) for lv in locked_vers): | |
| errors.append( | |
| f"{rel}: [{section}] dependency `{pkg_name}` version requirement " | |
| f"{ver_req!r} does not match locked version(s) {sorted(locked_vers)}" | |
| ) | |
| def _validate_dep_spec( | |
| rel: str, | |
| section: str, | |
| dep_name: str, | |
| spec: object, | |
| manifest_dir: Path, | |
| slug_dir: Path, | |
| slug_resolved: Path, | |
| allowed_names: set[str], | |
| locked_ext_versions: dict[str, set[str]] | None, | |
| workspace_deps: dict[str, object] | None, | |
| *, | |
| allow_workspace_inherit: bool, | |
| errors: list[str], | |
| ) -> None: | |
| pkg_name = dep_name | |
| if isinstance(spec, str): | |
| _check_external_dep_version( | |
| rel, | |
| section, | |
| pkg_name, | |
| spec, | |
| allowed_names, | |
| locked_ext_versions, | |
| errors, | |
| ) | |
| return | |
| if not isinstance(spec, dict): | |
| errors.append(f"{rel}: [{section}] `{dep_name}` has invalid spec") | |
| return | |
| if isinstance(spec.get("package"), str) and spec["package"]: | |
| pkg_name = spec["package"] | |
| if "git" in spec or "registry" in spec or "registry-index" in spec: | |
| errors.append( | |
| f"{rel}: [{section}] `{dep_name}` uses forbidden git or custom registry" | |
| ) | |
| return | |
| if spec.get("workspace") is True: | |
| if not allow_workspace_inherit: | |
| errors.append( | |
| f"{rel}: [{section}] `{dep_name}` cannot use `workspace = true` here" | |
| ) | |
| return | |
| if workspace_deps is None or dep_name not in workspace_deps: | |
| errors.append( | |
| f"{rel}: [{section}] `{dep_name}` uses `workspace = true` " | |
| f"without a matching [workspace.dependencies] inside " | |
| f"experimental/{slug_dir.name}/" | |
| ) | |
| return | |
| if "path" in spec: | |
| _validate_path_within_slug( | |
| rel, | |
| f"[{section}] `{dep_name}`", | |
| manifest_dir, | |
| spec["path"], | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| return | |
| if "path" in spec: | |
| _validate_path_within_slug( | |
| rel, | |
| f"[{section}] `{dep_name}`", | |
| manifest_dir, | |
| spec["path"], | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| return | |
| _check_external_dep_version( | |
| rel, | |
| section, | |
| pkg_name, | |
| spec.get("version"), | |
| allowed_names, | |
| locked_ext_versions, | |
| errors, | |
| ) | |
| def _check_target_table( | |
| rel: str, | |
| label: str, | |
| tbl: dict, | |
| manifest_dir: Path, | |
| slug_dir: Path, | |
| slug_resolved: Path, | |
| errors: list[str], | |
| ) -> None: | |
| crate_types = tbl.get("crate-type") or tbl.get("crate_type") | |
| has_proc_macro_type = isinstance(crate_types, list) and any( | |
| isinstance(ct, str) and ct.lower() in ("proc-macro", "proc_macro") | |
| for ct in crate_types | |
| ) | |
| if ( | |
| tbl.get("proc-macro") | |
| or tbl.get("proc_macro") | |
| or has_proc_macro_type | |
| ): | |
| errors.append( | |
| f"{rel}: {label} proc-macro targets are forbidden inside experiments" | |
| ) | |
| if "path" in tbl: | |
| _validate_path_within_slug( | |
| rel, | |
| label, | |
| manifest_dir, | |
| tbl["path"], | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| def _validate_cargo_manifest_in_slug( | |
| slug: str, | |
| slug_dir: Path, | |
| manifest_path: Path, | |
| data: dict, | |
| allowed_pkgs: set[tuple[str, str, str, str]], | |
| locked_ext_by_dir: dict[Path, dict[str, set[str]]], | |
| workspace_deps_by_dir: dict[Path, dict[str, object]], | |
| workspaces_by_dir: dict[Path, tuple[list[str], list[str]]], | |
| errors: list[str], | |
| ) -> None: | |
| rel = manifest_path.relative_to(slug_dir.parent.parent).as_posix() | |
| slug_resolved = slug_dir.resolve() | |
| allowed_names = {name for name, _, _, _ in allowed_pkgs} | |
| if "patch" in data or "replace" in data: | |
| errors.append( | |
| f"{rel}: `[patch]` and `[replace]` are forbidden inside experiments" | |
| ) | |
| if "project" in data: | |
| errors.append( | |
| f"{rel}: `[project]` alias is forbidden inside experiments; " | |
| "use `[package]`" | |
| ) | |
| pkg = ( | |
| data.get("package") | |
| if isinstance(data.get("package"), dict) | |
| else data.get("project") | |
| ) | |
| if isinstance(pkg, dict): | |
| if pkg.get("publish") is not False: | |
| errors.append( | |
| f"{rel}: `[package]` must set `publish = false` inside experiments" | |
| ) | |
| if "build" in pkg and pkg["build"] is not False: | |
| errors.append( | |
| f"{rel}: `[package].build` ({pkg['build']!r}) is forbidden " | |
| "inside experiments" | |
| ) | |
| if "workspace" in pkg: | |
| _validate_path_within_slug( | |
| rel, | |
| "[package].workspace", | |
| manifest_path.parent, | |
| pkg["workspace"], | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| lib_tbl = data.get("lib") | |
| if isinstance(lib_tbl, dict): | |
| _check_target_table( | |
| rel, | |
| "[lib]", | |
| lib_tbl, | |
| manifest_path.parent, | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| for target_kind in ("bin", "example", "test", "bench"): | |
| entries = data.get(target_kind) | |
| if isinstance(entries, list): | |
| for idx, entry in enumerate(entries): | |
| if isinstance(entry, dict): | |
| _check_target_table( | |
| rel, | |
| f"[[{target_kind}]][{idx}]", | |
| entry, | |
| manifest_path.parent, | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| ws_tbl = data.get("workspace") | |
| if isinstance(ws_tbl, dict): | |
| for ws_key in ("members", "exclude"): | |
| items = ws_tbl.get(ws_key) | |
| if isinstance(items, list): | |
| for item in items: | |
| if isinstance(item, str): | |
| if ( | |
| "\\" in item | |
| or item.startswith("/") | |
| or ".." in Path(item).parts | |
| ): | |
| errors.append( | |
| f"{rel}: [workspace].{ws_key} path `{item}` " | |
| "must not be absolute, contain `..`, or use backslashes" | |
| ) | |
| continue | |
| # Strip trailing glob characters to validate prefix. | |
| prefix = re.split(r"[*?\[\]]", item, maxsplit=1)[0] | |
| if prefix: | |
| _validate_path_within_slug( | |
| rel, | |
| f"[workspace].{ws_key}", | |
| manifest_path.parent, | |
| prefix, | |
| slug_dir, | |
| slug_resolved, | |
| errors, | |
| ) | |
| locked_ext = _find_nearest_in_slug( | |
| manifest_path.parent, slug_dir, locked_ext_by_dir, workspaces_by_dir | |
| ) | |
| locked_ext_map = locked_ext if isinstance(locked_ext, dict) else None | |
| ws_deps_obj = _find_nearest_in_slug( | |
| manifest_path.parent, | |
| slug_dir, | |
| workspace_deps_by_dir, | |
| workspaces_by_dir, | |
| ) | |
| ws_deps = ws_deps_obj if isinstance(ws_deps_obj, dict) else None | |
| if isinstance(ws_tbl, dict): | |
| ws_dep_tbl = ws_tbl.get("dependencies") | |
| if isinstance(ws_dep_tbl, dict): | |
| for dep_name, spec in ws_dep_tbl.items(): | |
| _validate_dep_spec( | |
| rel, | |
| "workspace.dependencies", | |
| dep_name, | |
| spec, | |
| manifest_path.parent, | |
| slug_dir, | |
| slug_resolved, | |
| allowed_names, | |
| locked_ext_map, | |
| None, | |
| allow_workspace_inherit=False, | |
| errors=errors, | |
| ) | |
| dep_tables: list[tuple[str, dict]] = [] | |
| for section in DEP_SECTION_NAMES: | |
| tbl = data.get(section) | |
| if isinstance(tbl, dict): | |
| dep_tables.append((section, tbl)) | |
| target_tbl = data.get("target") | |
| if isinstance(target_tbl, dict): | |
| for cfg, cfg_val in target_tbl.items(): | |
| if isinstance(cfg_val, dict): | |
| for section in DEP_SECTION_NAMES: | |
| tbl = cfg_val.get(section) | |
| if isinstance(tbl, dict): | |
| dep_tables.append((f"target.{cfg}.{section}", tbl)) | |
| for section, tbl in dep_tables: | |
| for dep_name, spec in tbl.items(): | |
| _validate_dep_spec( | |
| rel, | |
| section, | |
| dep_name, | |
| spec, | |
| manifest_path.parent, | |
| slug_dir, | |
| slug_resolved, | |
| allowed_names, | |
| locked_ext_map, | |
| ws_deps, | |
| allow_workspace_inherit=True, | |
| errors=errors, | |
| ) | |
| def _check_inbound_symlink( | |
| full: Path, | |
| rel: str, | |
| exp_resolved: Path, | |
| errors: list[str], | |
| ) -> None: | |
| try: | |
| raw_target = os.readlink(full) | |
| except OSError: | |
| return | |
| lower_target = raw_target.replace("\\", "/").lower() | |
| targets_exp = ( | |
| lower_target == "experimental" | |
| or lower_target.startswith("experimental/") | |
| or "/experimental/" in lower_target | |
| or lower_target.endswith("/experimental") | |
| ) | |
| if not targets_exp: | |
| try: | |
| resolved = full.resolve() | |
| if resolved == exp_resolved or resolved.is_relative_to(exp_resolved): | |
| targets_exp = True | |
| except OSError: | |
| pass | |
| if targets_exp: | |
| errors.append( | |
| f"{rel}: forbidden inbound symlink targeting experimental/ " | |
| f"({raw_target!r})" | |
| ) | |
| def _check_inbound_cargo_toml( | |
| full: Path, | |
| rel: str, | |
| repo_root: Path, | |
| exp_resolved: Path, | |
| errors: list[str], | |
| ) -> None: | |
| try: | |
| data = tomllib.loads(full.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: | |
| errors.append(f"{rel}: invalid Cargo.toml: {exc}") | |
| return | |
| def _walk(node: object, key_ctx: str = "") -> None: | |
| if isinstance(node, dict): | |
| for k, v in node.items(): | |
| if k == "path" and isinstance(v, str): | |
| clean_v = v.replace("\\", "/") | |
| parts_lower = [ | |
| p.lower() for p in clean_v.split("/") if p and p != "." | |
| ] | |
| targets_exp = "experimental" in parts_lower | |
| if not targets_exp: | |
| try: | |
| res = (full.parent / clean_v).resolve() | |
| if res == exp_resolved or res.is_relative_to( | |
| exp_resolved | |
| ): | |
| targets_exp = True | |
| except OSError: | |
| pass | |
| if targets_exp: | |
| errors.append( | |
| f"{rel}: forbidden inbound edge " | |
| f"(Cargo path dependency into experimental/): {v!r}" | |
| ) | |
| else: | |
| _walk(v, k) | |
| elif isinstance(node, list): | |
| for item in node: | |
| if key_ctx == "members" and isinstance(item, str): | |
| clean_i = item.replace("\\", "/") | |
| if "experimental" in [ | |
| p.lower() for p in clean_i.split("/") if p | |
| ]: | |
| errors.append( | |
| f"{rel}: forbidden inbound edge " | |
| f"(Cargo workspace member in experimental/): {item!r}" | |
| ) | |
| else: | |
| _walk(item, key_ctx) | |
| _walk(data) | |
| def _scan_inbound_edges(repo_root: Path, errors: list[str]) -> None: | |
| exp_resolved = (repo_root / "experimental").resolve() | |
| for dirpath, dirnames, filenames in os.walk(repo_root, followlinks=False): | |
| rel_dir = Path(dirpath).relative_to(repo_root).as_posix() | |
| top_dir = rel_dir.split("/", 1)[0] | |
| skip_text_here = rel_dir != "." and top_dir in INBOUND_TEXT_SKIP_DIRS | |
| kept: list[str] = [] | |
| for d in sorted(dirnames): | |
| full = Path(dirpath) / d | |
| rel_child = d if rel_dir == "." else f"{rel_dir}/{d}" | |
| if full.is_symlink(): | |
| _check_inbound_symlink(full, rel_child, exp_resolved, errors) | |
| continue | |
| if rel_dir == "." and d.lower() in INBOUND_SYMLINK_SKIP_DIRS: | |
| continue | |
| if d == "__pycache__" and top_dir == "ci": | |
| continue | |
| if d == "target" and ( | |
| rel_dir == "." | |
| or (rel_dir.count("/") == 1 and top_dir in ("tools", "crates")) | |
| ): | |
| continue | |
| kept.append(d) | |
| dirnames[:] = kept | |
| for fname in sorted(filenames): | |
| full = Path(dirpath) / fname | |
| rel = full.relative_to(repo_root).as_posix() | |
| if full.is_symlink(): | |
| _check_inbound_symlink(full, rel, exp_resolved, errors) | |
| continue | |
| if skip_text_here: | |
| continue | |
| if rel in INBOUND_SCAN_EXEMPT_FILES or rel.startswith( | |
| INBOUND_SCAN_EXEMPT_PREFIXES | |
| ): | |
| continue | |
| if full.suffix.lower() in FORBIDDEN_EXTENSIONS: | |
| continue | |
| if fname.lower() == "cargo.toml" and rel != "Cargo.toml": | |
| _check_inbound_cargo_toml( | |
| full, rel, repo_root, exp_resolved, errors | |
| ) | |
| try: | |
| raw = full.read_bytes() | |
| except OSError: | |
| continue | |
| if _is_binary_bytes(raw): | |
| continue | |
| text = raw.decode("utf-8", errors="replace") | |
| if full.suffix.lower() == ".lean": | |
| lean_clean = _strip_lean_comments_and_guillemets(text) | |
| if "experimental" in lean_clean.lower(): | |
| label, pat = INBOUND_EDGE_PATTERNS[2] | |
| m = pat.search(lean_clean) | |
| if m: | |
| errors.append( | |
| f"{rel}: forbidden inbound edge ({label}): " | |
| f"{m.group(0).strip()!r}" | |
| ) | |
| continue | |
| if b"experimental" not in raw.lower(): | |
| continue | |
| patterns = ( | |
| INBOUND_EDGE_PATTERNS[:3] | |
| if rel in INBOUND_SCRIPT_LITERAL_EXEMPT_FILES | |
| else INBOUND_EDGE_PATTERNS | |
| ) | |
| for label, pat in patterns: | |
| m = pat.search(text) | |
| if m: | |
| errors.append( | |
| f"{rel}: forbidden inbound edge ({label}): " | |
| f"{m.group(0).strip()!r}" | |
| ) | |
| def _check_slug_relative_escapes( | |
| f_path: Path, | |
| f_rel: str, | |
| slug_dir: Path, | |
| text: str, | |
| errors: list[str], | |
| ) -> None: | |
| slug_norm = os.path.normpath(str(slug_dir)) | |
| exp_norm = os.path.normpath(str(slug_dir.parent)) | |
| exp_readme_norm = os.path.normpath(str(slug_dir.parent / "README.md")) | |
| is_md = f_path.suffix.lower() == ".md" | |
| norm_text = text.replace("\\", "/") | |
| for m in REL_PARENT_TOKEN_RE.finditer(norm_text): | |
| rel_ref = m.group(0) | |
| if not rel_ref: | |
| continue | |
| target_norm = os.path.normpath(str(f_path.parent / rel_ref)) | |
| if target_norm == slug_norm or target_norm.startswith( | |
| slug_norm + os.sep | |
| ): | |
| continue | |
| if is_md: | |
| # In Markdown prose, allow links to `experimental/README.md` or | |
| # repo docs outside `experimental/`, while rejecting links to | |
| # sibling experiment slugs. | |
| if target_norm == exp_readme_norm: | |
| continue | |
| if target_norm.startswith(exp_norm + os.sep): | |
| errors.append( | |
| f"{f_rel}: forbidden sideways relative link {rel_ref!r} " | |
| f"leaves experimental/{slug_dir.name}/" | |
| ) | |
| break | |
| continue | |
| errors.append( | |
| f"{f_rel}: forbidden escaping/sideways relative path " | |
| f"{rel_ref!r} leaves experimental/{slug_dir.name}/" | |
| ) | |
| break | |
| def check_repo(repo_root: Path) -> list[str]: | |
| """Validate `experimental/` isolation across `repo_root` and return errors.""" | |
| errors: list[str] = [] | |
| exp_root = repo_root / "experimental" | |
| for child in sorted(repo_root.iterdir(), key=lambda p: p.name): | |
| if child.name.lower() == "experimental" and child.name != "experimental": | |
| errors.append( | |
| f"{child.name}: case-variant experimental directory is forbidden" | |
| ) | |
| if exp_root.is_symlink(): | |
| return errors + [ | |
| "experimental: must be a regular directory, not a symlink" | |
| ] | |
| if exp_root.exists() and not exp_root.is_dir(): | |
| return errors + ["experimental: must be a regular directory"] | |
| _scan_inbound_edges(repo_root, errors) | |
| if not exp_root.exists(): | |
| return errors | |
| allowed_pkgs = _collect_allowed_lock_packages(repo_root) | |
| slugs: list[str] = [] | |
| for child in sorted(exp_root.iterdir(), key=lambda p: p.name): | |
| name = child.name | |
| rel = f"experimental/{name}" | |
| if child.is_symlink(): | |
| errors.append(f"{rel}: symlinks are forbidden under experimental/") | |
| continue | |
| if name == "README.md": | |
| if not child.is_file(): | |
| errors.append(f"{rel}: expected a regular file") | |
| else: | |
| text = child.read_text(encoding="utf-8", errors="replace") | |
| _check_text_hygiene(rel, text, errors, require_header=True) | |
| continue | |
| if not child.is_dir(): | |
| errors.append( | |
| f"{rel}: unexpected top-level file (only README.md and " | |
| "<slug>/ dirs allowed)" | |
| ) | |
| continue | |
| if not SLUG_RE.fullmatch(name): | |
| errors.append( | |
| f"{rel}: invalid experiment slug (must match {SLUG_RE.pattern})" | |
| ) | |
| continue | |
| slugs.append(name) | |
| for slug in slugs: | |
| slug_dir = exp_root / slug | |
| _validate_experiment_toml( | |
| slug, slug_dir / "EXPERIMENT.toml", slug_dir, errors | |
| ) | |
| _validate_experiment_readme(slug, slug_dir / "README.md", errors) | |
| manifest_paths: list[Path] = [] | |
| lock_paths: list[Path] = [] | |
| for dirpath, dirnames, filenames in os.walk(slug_dir, followlinks=False): | |
| cur = Path(dirpath) | |
| rel_cur = cur.relative_to(repo_root).as_posix() | |
| kept_dirs: list[str] = [] | |
| for d in sorted(dirnames): | |
| d_path = cur / d | |
| d_rel = f"{rel_cur}/{d}" | |
| if d_path.is_symlink(): | |
| errors.append( | |
| f"{d_rel}: symlinks are forbidden inside experiments" | |
| ) | |
| continue | |
| d_lower = d.lower() | |
| if d_lower in FORBIDDEN_DIRNAMES_LOWER or d_lower.startswith( | |
| ".cargo" | |
| ): | |
| errors.append( | |
| f"{d_rel}: forbidden directory inside experimental/" | |
| ) | |
| continue | |
| kept_dirs.append(d) | |
| dirnames[:] = kept_dirs | |
| for fname in sorted(filenames): | |
| f_path = cur / fname | |
| f_rel = f"{rel_cur}/{fname}" | |
| if f_path.is_symlink(): | |
| errors.append( | |
| f"{f_rel}: symlinks are forbidden inside experiments" | |
| ) | |
| continue | |
| lower = fname.lower() | |
| if ( | |
| lower in FORBIDDEN_FILENAMES_LOWER | |
| or lower.startswith("rust-toolchain") | |
| or lower.startswith("lakefile.") | |
| or lower == ".cargo" | |
| or lower.startswith(".cargo.") | |
| ): | |
| errors.append( | |
| f"{f_rel}: forbidden file inside experimental/" | |
| ) | |
| continue | |
| if cur == slug_dir and lower == "experiment.toml" and fname != "EXPERIMENT.toml": | |
| errors.append( | |
| f"{f_rel}: non-canonical casing for EXPERIMENT.toml" | |
| ) | |
| if cur == slug_dir and lower == "readme.md" and fname != "README.md": | |
| errors.append( | |
| f"{f_rel}: non-canonical casing for README.md" | |
| ) | |
| if f_path.suffix.lower() in FORBIDDEN_CONFIG_EXTENSIONS: | |
| errors.append( | |
| f"{f_rel}: forbidden file inside experimental/" | |
| ) | |
| if f_path.suffix.lower() in FORBIDDEN_EXTENSIONS or any( | |
| lower.endswith(sfx) for sfx in FORBIDDEN_SUFFIXES | |
| ): | |
| errors.append( | |
| f"{f_rel}: forbidden binary/artifact file inside experimental/" | |
| ) | |
| continue | |
| try: | |
| raw = f_path.read_bytes() | |
| except OSError as exc: | |
| errors.append(f"{f_rel}: cannot read file: {exc}") | |
| continue | |
| if _is_binary_bytes(raw): | |
| errors.append( | |
| f"{f_rel}: binary content is forbidden inside experimental/" | |
| ) | |
| continue | |
| try: | |
| text = raw.decode("utf-8") | |
| except UnicodeDecodeError: | |
| errors.append( | |
| f"{f_rel}: non-UTF-8 file is forbidden inside experimental/" | |
| ) | |
| continue | |
| require_header = ( | |
| f_path.suffix.lower() in HEADER_EXTS and lower != "cargo.lock" | |
| ) | |
| _check_text_hygiene( | |
| f_rel, text, errors, require_header=require_header | |
| ) | |
| for m in SIDEWAYS_SLUG_RE.finditer(text): | |
| other = m.group(1) | |
| if other.lower() != slug.lower(): | |
| errors.append( | |
| f"{f_rel}: forbidden sideways reference to sibling " | |
| f"experiment `experimental/{other}`" | |
| ) | |
| if f_path.suffix.lower() == ".lean": | |
| lean_clean = _strip_lean_comments_and_guillemets(text) | |
| for lm in LEAN_IMPORT_MOD_RE.finditer(lean_clean): | |
| mod_path = lm.group(1) | |
| parts = mod_path.split(".") | |
| for idx, seg in enumerate(parts): | |
| if seg.lower() == "experimental": | |
| next_seg = ( | |
| parts[idx + 1] | |
| if idx + 1 < len(parts) | |
| else "" | |
| ) | |
| if not _lean_segment_matches_slug( | |
| next_seg, slug | |
| ): | |
| errors.append( | |
| f"{f_rel}: forbidden sideways Lean " | |
| f"import `{mod_path}` from " | |
| f"experimental/{slug}/" | |
| ) | |
| break | |
| _check_slug_relative_escapes( | |
| f_path, f_rel, slug_dir, text, errors | |
| ) | |
| if lower == "cargo.toml": | |
| if fname != "Cargo.toml": | |
| errors.append( | |
| f"{f_rel}: non-canonical casing for Cargo.toml" | |
| ) | |
| manifest_paths.append(f_path) | |
| elif lower == "cargo.lock": | |
| if fname != "Cargo.lock": | |
| errors.append( | |
| f"{f_rel}: non-canonical casing for Cargo.lock" | |
| ) | |
| lock_paths.append(f_path) | |
| parsed_manifests: list[tuple[Path, dict]] = [] | |
| local_pkg_names: set[str] = set() | |
| workspace_deps_by_dir: dict[Path, dict[str, object]] = {} | |
| workspaces_by_dir: dict[Path, tuple[list[str], list[str]]] = {} | |
| for m_path in manifest_paths: | |
| rel = m_path.relative_to(repo_root).as_posix() | |
| try: | |
| data = tomllib.loads(m_path.read_text(encoding="utf-8")) | |
| except (OSError, UnicodeDecodeError, tomllib.TOMLDecodeError) as exc: | |
| errors.append(f"{rel}: invalid Cargo.toml: {exc}") | |
| continue | |
| parsed_manifests.append((m_path, data)) | |
| pkg_tbl = ( | |
| data.get("package") | |
| if isinstance(data.get("package"), dict) | |
| else data.get("project") | |
| ) | |
| if isinstance(pkg_tbl, dict) and isinstance( | |
| pkg_tbl.get("name"), str | |
| ): | |
| local_pkg_names.add(pkg_tbl["name"]) | |
| ws_tbl = data.get("workspace") | |
| if isinstance(ws_tbl, dict): | |
| raw_members = ws_tbl.get("members") | |
| members = ( | |
| [x for x in raw_members if isinstance(x, str)] | |
| if isinstance(raw_members, list) | |
| else [] | |
| ) | |
| raw_excludes = ws_tbl.get("exclude") | |
| excludes = ( | |
| [x for x in raw_excludes if isinstance(x, str)] | |
| if isinstance(raw_excludes, list) | |
| else [] | |
| ) | |
| workspaces_by_dir[m_path.parent] = (members, excludes) | |
| if isinstance(ws_tbl.get("dependencies"), dict): | |
| workspace_deps_by_dir[m_path.parent] = ws_tbl[ | |
| "dependencies" | |
| ] | |
| locked_ext_by_dir: dict[Path, dict[str, set[str]]] = {} | |
| for l_path in lock_paths: | |
| locked_ext_by_dir[l_path.parent] = _validate_cargo_lock_in_slug( | |
| slug_dir, l_path, allowed_pkgs, local_pkg_names, errors | |
| ) | |
| for m_path, data in parsed_manifests: | |
| _validate_cargo_manifest_in_slug( | |
| slug, | |
| slug_dir, | |
| m_path, | |
| data, | |
| allowed_pkgs, | |
| locked_ext_by_dir, | |
| workspace_deps_by_dir, | |
| workspaces_by_dir, | |
| errors, | |
| ) | |
| return errors | |
| def main(argv: Iterable[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) | |
| parser.add_argument( | |
| "--root", | |
| type=Path, | |
| default=Path(__file__).resolve().parent.parent, | |
| help="repository root (default: parent of ci/)", | |
| ) | |
| parser.add_argument("--json", action="store_true", help="emit JSON report") | |
| args = parser.parse_args(list(argv) if argv is not None else None) | |
| errors = check_repo(args.root.resolve()) | |
| if args.json: | |
| print(json.dumps({"ok": not errors, "errors": errors}, indent=2)) | |
| elif errors: | |
| for err in errors: | |
| print(f"experimental-isolation: {err}", file=sys.stderr) | |
| else: | |
| print("experimental-isolation: OK") | |
| return 0 if not errors else 1 | |
| if __name__ == "__main__": | |
| sys.exit(main()) |