"""Deploy/docs contract: every documented unit path must resolve inside this repo. The tests are static: they parse the files shipped under ``deploy/`` and the two operator-facing docs. Nothing here starts a service, imports runtime code or touches the network. Mapping source of truth is the table in ``deploy/README.md``; the four core units under ``deploy/systemd/`` are checked against it. Services this repository does not implement (healthcheck, alert-watch, media adapter, firewall) ship nothing at all: no units, no templates, no stubs. """ from __future__ import annotations import re import shlex import unittest from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] DEPLOY = REPO_ROOT / "deploy" SYSTEMD = DEPLOY / "systemd" CADDY = DEPLOY / "caddy" / "Caddyfile.example" DEPLOY_README = DEPLOY / "README.md" RUNTIME_ENV = DEPLOY / "runtime.env.example" CONTRIBUTING = REPO_ROOT / "CONTRIBUTING.md" SECURITY = REPO_ROOT / "SECURITY.md" # Units that must exist: the first-party services this repo can actually run. CORE_UNITS = { "grok-bot.service": "bot", "iishko-webapp.service": "miniapp", "grok-web-skin.service": "gateway", "iishko-moderation.service": None, # native binary, not run through run.py } # Scripts that do not exist in this repository; they belong to the operator. ABSENT_EXTERNAL_SCRIPTS = ( "grok-healthcheck.py", "grok-alert-watch.py", "media_tts.py", "iishko-fw.sh", "/usr/local/sbin/iishko-fw", "zai_shim.caddy", ) # ``scripts/run.py`` is the shared bootstrap; it is part of the repo contract and # is referenced by every core target unit. If it is missing from a checkout the # units still point at a documented location, so the path check allows it only # when deploy/README.md documents it as the launcher. BOOTSTRAP_REL = "scripts/run.py" # Host paths are absolute, so anchoring on "/" keeps the target table (also # backticked) from being parsed as mapping rows across line breaks. MAPPING_ROW = re.compile(r"^\|\s*`(?P/[^`]+)`\s*\|\s*(?P[^|]*)\|\s*(?P[^|]*)\|", re.M) TARGET_ROW = re.compile(r"^\|\s*`(?P[a-z]+)`\s*\|\s*`(?P[^`]+)`", re.M) def read(path: Path) -> str: return path.read_text(encoding="utf-8", errors="replace") def mapping() -> dict[str, tuple[str, str]]: """host path -> (repo source description, kind).""" rows = {} for match in MAPPING_ROW.finditer(read(DEPLOY_README)): rows[match.group("host").strip()] = (match.group("source").strip(), match.group("kind").strip()) return rows def targets() -> dict[str, str]: """run.py target -> repo module.""" return {m.group("target"): m.group("module").strip() for m in TARGET_ROW.finditer(read(DEPLOY_README))} def unit_directives(path: Path) -> list[tuple[str, str]]: out = [] for line in read(path).splitlines(): line = line.strip() if not line or line.startswith(("#", ";", "[")): continue if "=" not in line: continue key, value = line.split("=", 1) out.append((key.strip(), value.strip())) return out def exec_paths(value: str) -> list[str]: """Absolute filesystem paths from an ExecStart line (argv[0] + path args).""" try: argv = shlex.split(value) except ValueError: argv = value.split() paths = [] for arg in argv: if arg.startswith(("-", "@", "+", "!", ":")): arg = arg.lstrip('-@+!:') if arg.startswith("/") and "$" not in arg: paths.append(arg) return paths def map_to_repo(host_path: str, table: dict[str, tuple[str, str]]) -> str | None: """Translate a host path into a repo-relative path using the mapping table.""" for host, (_source, _kind) in sorted(table.items(), key=lambda kv: -len(kv[0])): host = host.rstrip("/") if host_path == host: return "." if host_path.startswith(host + "/"): return host_path[len(host) + 1 :] return None class DeployMappingTest(unittest.TestCase): def test_mapping_table_is_documented(self): table = mapping() self.assertIn("/opt/iishko", table, "deploy/README.md must document the repo root mapping") self.assertIn("/etc/iishko/runtime.env", table, "runtime env file must be documented") kind = table["/opt/iishko"][1].lower() self.assertTrue("дерево" in kind or "tree" in kind, "repo root mapping must be documented as a tree") def test_core_unit_execstart_paths_resolve(self): table = mapping() self.assertTrue(table, "mapping table is unreadable") deploy_doc = read(DEPLOY_README) for unit in sorted(SYSTEMD.glob("*.service")): for key, value in unit_directives(unit): if key != "ExecStart": continue paths = exec_paths(value) self.assertTrue(paths, f"{unit.name}: ExecStart has no absolute path: {value}") for host_path in paths: if host_path == "/etc/iishko/runtime.env": # Server-side config: seeded from deploy/runtime.env.example. self.assertIn("/etc/iishko/runtime.env", table) continue rel = map_to_repo(host_path, table) self.assertIsNotNone(rel, f"{unit.name}: {host_path} is outside the documented mapping") if rel.startswith(".venv/"): # Generated on the host, documented as such. self.assertIn(".venv", deploy_doc) self.assertIn("venv", deploy_doc.lower()) continue if rel == BOOTSTRAP_REL: # Shared bootstrap: documented, may be provided separately. self.assertIn(BOOTSTRAP_REL, deploy_doc) self.assertTrue( (REPO_ROOT / BOOTSTRAP_REL).is_file(), "scripts/run.py is documented as the launcher but missing from this checkout", ) continue if rel == "bin/iishko-moderation": self.assertTrue( (REPO_ROOT / "moderation").is_dir(), "moderation/ must exist to build bin/iishko-moderation", ) continue self.assertTrue( (REPO_ROOT / rel).exists(), f"{unit.name}: {host_path} maps to missing {rel}", ) def test_core_units_use_bootstrap_and_required_env_file(self): for name, target in CORE_UNITS.items(): path = SYSTEMD / name self.assertTrue(path.is_file(), f"missing core unit {name}") directives = dict(unit_directives(path)) self.assertEqual(directives.get("WorkingDirectory"), "/opt/iishko", f"{name}: wrong WorkingDirectory") if target: execstart = directives.get("ExecStart", "") self.assertIn(f"/{BOOTSTRAP_REL} {target}", execstart, f"{name}: must start via scripts/run.py {target}") self.assertIn("--env-file /etc/iishko/runtime.env", execstart, f"{name}: runtime env file not passed") else: self.assertIn("/opt/iishko/bin/iishko-moderation", directives.get("ExecStart", ""), f"{name}: binary path") self.assertEqual( directives.get("EnvironmentFile"), "/etc/iishko/runtime.env", f"{name}: EnvironmentFile must be present and not optional ('-' prefix)", ) def test_run_targets_exist_in_repo(self): table_targets = targets() for target in ("bot", "miniapp", "gateway"): self.assertIn(target, table_targets, f"deploy/README.md must document run.py target {target}") module = table_targets[target] self.assertTrue((REPO_ROOT / module).is_file(), f"target {target} points at missing {module}") def test_docs_state_the_launcher_semantics(self): text = read(DEPLOY_README) self.assertIn(BOOTSTRAP_REL, text) self.assertIn("bot/iishko_bot.py", text) self.assertIn("bot/grok_bot.py", text) self.assertIn("--check", text) def test_canonical_resolver_matches_documented_order(self): module = REPO_ROOT / "bot" / "runtime_config.py" self.assertTrue(module.is_file(), "deploy/README.md points at bot/runtime_config.py, which is missing") body = read(module) for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG", "IISHKO_SKIN_DB", "GATE_TG_DB"): self.assertIn(name, body, f"bot/runtime_config.py must resolve {name}") # Documented precedence: canonical name wins over the legacy alias. order = [body.index(name) for name in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG")] self.assertEqual( order, sorted(order), "bot config precedence in runtime_config.py differs from deploy/README.md" ) self.assertLess(body.index("IISHKO_SKIN_DB"), body.index("GATE_TG_DB")) class DeployScopeTest(unittest.TestCase): def test_no_external_script_in_core_units(self): for unit in SYSTEMD.glob("*"): body = read(unit) for absent in ABSENT_EXTERNAL_SCRIPTS: self.assertNotIn(absent, body, f"{unit.name} references absent {absent}") def test_core_dir_has_no_templates(self): for item in SYSTEMD.iterdir(): self.assertFalse(item.name.endswith(".example"), f"{item.name} is a template, not a unit") self.assertEqual(set(CORE_UNITS), {p.name for p in SYSTEMD.glob("*.service")}) def test_no_external_template_graveyard(self): """Dead templates were removed: no directory may hold units the repo cannot run.""" self.assertFalse((DEPLOY / "external").exists(), "deploy/external must stay removed") self.assertEqual( {"systemd", "caddy"}, {p.name for p in DEPLOY.iterdir() if p.is_dir()}, "deploy/ grew an undocumented subdirectory", ) for path in DEPLOY.rglob("*.service*"): self.assertIn(path.parent, (SYSTEMD,), f"{path} ships a unit outside systemd/") self.assertIn(path.name, CORE_UNITS, f"{path.name} has no implementation in this repo") def test_readme_states_services_are_out_of_scope(self): text = read(DEPLOY_README).lower() for absent in ("healthcheck", "alert", "media", "firewall"): self.assertIn(absent, text, f"deploy/README.md must say {absent} is not included") self.assertNotIn("external/", text, "deploy/README.md still points at the removed template dir") self.assertNotIn("template only", text, "deploy/README.md still announces template files") class CaddyTest(unittest.TestCase): def test_imports_resolve_inside_repo(self): body = read(CADDY) defined = set(re.findall(r"\((\w+)\)\s*\{", body)) for name in re.findall(r"^\s*import\s+(\S+)", body, re.M): if name.startswith(("http://", "https://")): continue if name in defined: continue candidates = [DEPLOY / "caddy" / name, DEPLOY / "caddy" / f"{name}.caddy"] self.assertTrue( any(candidate.is_file() for candidate in candidates), f"Caddyfile imports {name}, which is neither an inline snippet nor a file in deploy/caddy/", ) def test_no_absent_media_service_route(self): body = read(CADDY) active = "\n".join(line for line in body.splitlines() if not line.strip().startswith("#")) self.assertNotIn("127.0.0.1:8000", active, "Caddyfile must not route to the absent media adapter") self.assertNotIn("zai_shim", body) self.assertIn("reverse_proxy 127.0.0.1:48001", active) self.assertIn("reverse_proxy 127.0.0.1:8850", active) class DocsTest(unittest.TestCase): def test_contributing_has_no_symlink_lie(self): text = read(CONTRIBUTING).lower() for forbidden in ("symlink", "симлинк", "120000"): self.assertNotIn(forbidden, text, f"CONTRIBUTING.md still claims a symlink ({forbidden})") def test_contributing_does_not_instruct_copying_modules(self): text = read(CONTRIBUTING) for pattern in (r"cp\s+bot/iishko_bot\.py", r"cp\s+bot/grok_bot\.py", r"copying the real module"): self.assertIsNone(re.search(pattern, text, re.I), f"CONTRIBUTING.md still recommends {pattern}") def test_contributing_points_at_real_launcher_and_tests(self): text = read(CONTRIBUTING) self.assertIn(f"python {BOOTSTRAP_REL} bot", text) self.assertIn("bot/grok_bot.py", text) self.assertIn("bot/iishko_bot.py", text) self.assertIn("pytest", text) self.assertNotIn("их почти нет", text) def test_no_placeholder_maintainer_handle(self): for doc in (CONTRIBUTING, SECURITY): text = read(doc) self.assertNotIn("@your-handle", text, f"{doc.name} still has a placeholder handle") self.assertIsNone( re.search(r"(? FILE", text, "shell redirection can create a 0644 session secret") def test_documented_env_names_match_example(self): text = read(RUNTIME_ENV) for name in ("GROK_BOT_CFG", "IISHKO_SKIN_DB", "IISHKO_UPSTREAM", "IISHKO_MODERATION_TOKEN"): self.assertIn(name, text, f"runtime.env.example must define {name}") deploy_doc = read(DEPLOY_README) for alias in ("GROK_BOT_CFG", "GROK_BOT_CONFIG", "GATE_BOT_CONFIG"): self.assertIn(alias, deploy_doc, f"deploy/README.md must document config alias {alias}") if __name__ == "__main__": unittest.main()