#!/usr/bin/env python3 """Offline sanity check for an iishko checkout. What this script actually does (be precise about it): * ``--source-only`` (the credential-free mode used by CI): parses every runtime module with ``ast`` — this checks **syntax and file presence only**, it does NOT import anything, so it proves neither that third-party dependencies are installed nor that module-level code runs. It also verifies that the local import closure of the runtime modules resolves inside the tree, that config templates are valid JSON, and that no secret-looking literal is committed. It never prints environment values. * default mode: additionally tries real ``import`` of the runtime modules when their third-party dependencies are importable. If a dependency is missing the module is reported as "not imported (dependency missing)" — an honest limitation, not a pass. Nothing here touches the network, writes files, installs packages or performs any money/balance mutation. Exit code: 0 = no blocking problem, 1 = blocking problem found. """ from __future__ import annotations import argparse import ast import importlib.util import json import os import re import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MODULE_DIRS = [os.path.join(ROOT, "bot"), os.path.join(ROOT, "gateway")] # Runtime modules that must exist and parse. Third-party names are checked # separately so a missing dependency is reported, not mistaken for a pass. REQUIRED = [ # bot / economy / mini app "grok_bot", "bot_schema", "model_catalogue", "account_admin", "account_limits", "assistant_runtime", "bounty_store", "bounty_ui", "community_economy", "econ_cap", "econ_guard", "entry_admin", "entry_autoban", "entry_geo", "entry_telemetry", "file_intake", "forum_panels", "key_issue_guard", "key_notifications", "kie_media", "miniapp_guard", "model_uptime", "neurolab", "piapi_music", "quest_economy", "reminders", "session_context", "support_store", # gateway (native gateway + commerce/board surface) "gateway_errors", "gateway_features", "gateway_policy", "gateway_usage", "gateway_providers", "gateway_provider_relay", "gateway_commerce", "commerce_access", "community_board", "model_identity", "public_site", "transparent_api", ] THIRD_PARTY = ["aiogram", "aiohttp", "multidict", "yarl", "psutil", "bcrypt"] OPTIONAL_THIRD_PARTY = ["ddgs", "duckduckgo_search", "pypdf"] SECRET_PATTERNS = [ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{36,}"), re.compile(r"\b\d{8,10}:AA[A-Za-z0-9_-]{30,}"), re.compile(r"\bAKIA[0-9A-Z]{16}\b"), re.compile(r"\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b"), ] SKIP_DIRS = {".git", "__pycache__", "node_modules", ".pytest_cache"} def _importable(name: str) -> bool: """True when a module can be located. Never raises: a dotted or missing parent package must not crash the source-only check on any platform.""" try: return importlib.util.find_spec(name) is not None except (ImportError, AttributeError, ValueError, ModuleNotFoundError): return False def module_path(name: str): for directory in MODULE_DIRS: candidate = os.path.join(directory, name + ".py") if os.path.isfile(candidate): return candidate return None def local_modules(): names = set() for directory in MODULE_DIRS: if not os.path.isdir(directory): continue for entry in os.listdir(directory): if entry.endswith(".py"): names.add(entry[:-3]) names.add("vendor_entry_geo") return names def check_syntax_and_closure(problems, notes): known = local_modules() for name in REQUIRED: path = module_path(name) if path is None: problems.append("missing runtime module: %s" % name) continue try: tree = ast.parse(open(path, encoding="utf-8").read(), filename=path) except SyntaxError as exc: problems.append("syntax error in %s: %s" % (name, exc)) continue unresolved = set() for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: head = alias.name.split(".")[0] if head not in known and head in THIRD_PARTY + OPTIONAL_THIRD_PARTY: continue if head not in known and head not in sys.stdlib_module_names \ and not _importable(head): unresolved.add(head) elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: head = node.module.split(".")[0] if head in known or head in sys.stdlib_module_names: continue unresolved.add(head) for head in sorted(unresolved): notes.append("%s imports %s (not in tree, not stdlib)" % (name, head)) def check_imports(problems, notes): missing_deps = [name for name in THIRD_PARTY if not _importable(name)] if missing_deps: notes.append("real imports skipped: missing %s " "(pip install -r requirements.txt)" % ", ".join(missing_deps)) return for directory in MODULE_DIRS: if directory not in sys.path: sys.path.insert(0, directory) for name in REQUIRED: if module_path(name) is None: continue try: importlib.import_module(name) except Exception as exc: # noqa: BLE001 - report honestly, keep going problems.append("import %s failed: %s: %s" % (name, type(exc).__name__, exc)) notes.append("real imports attempted for %d modules" % len(REQUIRED)) def check_config_templates(problems, notes): for rel in ("bot/config.example.json", "gateway/providers.example.json", "iishko-ts/config.example.json"): path = os.path.join(ROOT, rel) if not os.path.isfile(path): notes.append("config template absent (optional): %s" % rel) continue try: json.load(open(path, encoding="utf-8")) except ValueError as exc: problems.append("invalid JSON template %s: %s" % (rel, exc)) cfg = os.environ.get("GROK_BOT_CFG") or os.path.join(ROOT, "bot", "config.json") if os.path.isfile(cfg): try: data = json.load(open(cfg, encoding="utf-8")) placeholders = sorted(k for k, v in data.items() if isinstance(v, str) and ("REPLACE_ME" in v or "your_" in v)) if placeholders: notes.append("bot config placeholders still set: %s" % ", ".join(placeholders)) except ValueError as exc: problems.append("bot config is not valid JSON: %s" % exc) else: notes.append("bot config not found (%s) — copy bot/config.example.json" % cfg) geo = os.path.join(ROOT, "bot", "geo", "dbip-city-lite-2026-10.mmdb") notes.append("geo dataset: %s" % ("present" if os.path.isfile(geo) else "absent (IP geolocation stays disabled)")) def check_no_committed_secrets(problems, notes): hits = [] for dp, dns, fns in os.walk(ROOT): dns[:] = [d for d in dns if d not in SKIP_DIRS] for fn in fns: if os.path.splitext(fn)[1].lower() in {".png", ".jpg", ".mmdb", ".gz", ".whl"}: continue path = os.path.join(dp, fn) try: text = open(path, encoding="utf-8").read() except (UnicodeDecodeError, OSError): continue for rx in SECRET_PATTERNS: if rx.search(text): hits.append(os.path.relpath(path, ROOT).replace("\\", "/")) break if hits: problems.append("secret-looking literal in: %s" % ", ".join(sorted(set(hits)))) else: notes.append("no secret-looking literals found") def check_env_presence(notes): # Presence only. Values (even prefixes) are never printed. for key in ("GROK_BOT_TOKEN", "GROK_BOT_CFG", "IISHKO_BOT_DB", "IISHKO_UPSTREAM", "IISHKO_ADMIN_IDS", "IISHKO_PROVIDERS_FILE"): notes.append("%s: %s" % (key, "set" if os.environ.get(key) else "unset")) def main() -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--source-only", action="store_true", help="syntax/closure/config checks only: no imports, no " "credentials, safe for CI") args = parser.parse_args() problems, notes = [], [] check_syntax_and_closure(problems, notes) check_config_templates(problems, notes) check_no_committed_secrets(problems, notes) if args.source_only: notes.append("mode: source-only (ast syntax + closure, real imports NOT performed)") else: notes.append("mode: full (real imports attempted where dependencies exist)") check_imports(problems, notes) check_env_presence(notes) for note in notes: print("note:", note) for problem in problems: print("FAIL:", problem) print("selfcheck:", "ok" if not problems else "%d problem(s)" % len(problems)) return 0 if not problems else 1 if __name__ == "__main__": raise SystemExit(main())