import importlib.util import plistlib import sys from pathlib import Path import pytest SCRIPT = Path(__file__).parents[1] / "scripts/manage_runtime_log_policy.py" # Script imports its canonical sibling management helpers. sys.path.insert(0, str(SCRIPT.parent)) spec = importlib.util.spec_from_file_location("runtime_log_policy", SCRIPT) manager = importlib.util.module_from_spec(spec) spec.loader.exec_module(manager) def fixture(tmp_path): root = tmp_path / "repo" root.mkdir() home = tmp_path / "home" path = home / "Library/LaunchAgents/com.nodedc.mission-core.local.plist" path.parent.mkdir(parents=True) value = { "Label": "com.nodedc.mission-core.local", "ProgramArguments": ["/opt/homebrew/bin/uv", "run", "--no-sync", "k1link", "serve"], "WorkingDirectory": str(root), "EnvironmentVariables": {"keep": "private"}, "KeepAlive": True, "StandardErrorPath": str(home / "Library/Logs/core.log"), "StandardOutPath": str(home / "Library/Logs/core.log"), } path.write_bytes(plistlib.dumps(value)) return root, home, path def test_plan_preserves_foreign_fields_and_apply_refuses_stale(tmp_path, monkeypatch): root, home, path = fixture(tmp_path) original = path.read_bytes() plan, before, desired = manager.plan(root, "core", home=home) assert before == original and path.read_bytes() == original assert plistlib.loads(desired)["EnvironmentVariables"] == {"keep": "private"} monkeypatch.setattr(Path, "home", lambda: home) value = plistlib.loads(original) value["KeepAlive"] = False path.write_bytes(plistlib.dumps(value)) with pytest.raises(ValueError, match="Stale"): manager.apply(plan) assert plistlib.loads(path.read_bytes())["KeepAlive"] is False def test_failed_acceptance_restores_exact_declaration(tmp_path, monkeypatch): root, home, path = fixture(tmp_path) plan, before, _ = manager.plan(root, "core", home=home) monkeypatch.setattr(Path, "home", lambda: home) calls = [] monkeypatch.setattr(manager, "_reload_launch_agent", lambda p: calls.append(p)) def acceptance(*args): if len(calls) == 1: raise RuntimeError("failed canary") return {"restored": True} monkeypatch.setattr(manager, "accept", acceptance) with pytest.raises(RuntimeError, match="failed canary"): manager.apply(plan) assert path.read_bytes() == before and len(calls) == 2 assert list((root / ".runtime/storage-maintenance/log-policy").rglob("*.plist")) def test_scanner_records_and_rotated_permissions_are_bounded(tmp_path): import logging import stat from k1link.web.runtime_diagnostics import ( _EXTRA_FIELDS, PrivateRotatingFileHandler, ScannerDiagnosticJsonFormatter, ) record = logging.LogRecord("test", logging.INFO, "x", 1, "x" * 100000, (), None) for field in _EXTRA_FIELDS: setattr(record, field, "я" * 100000) formatter = ScannerDiagnosticJsonFormatter() payload = formatter.format(record) assert len(payload.encode()) <= 16384 path = tmp_path / "diagnostic.log" handler = PrivateRotatingFileHandler(path, maxBytes=200, backupCount=2, encoding="utf-8") handler.setFormatter(formatter) for _ in range(4): handler.emit(logging.LogRecord("test", logging.INFO, "x", 1, "test message", (), None)) handler.close() assert len(list(tmp_path.iterdir())) == 3 assert all(stat.S_IMODE(p.stat().st_mode) == 0o600 for p in tmp_path.iterdir()) @pytest.mark.parametrize("exit_code", [0, 9]) def test_check_wrapper_cleans_only_its_scratch_on_success_and_failure(tmp_path, exit_code): import check_python root = tmp_path / "repo" executable = root / ".venv/bin/python" executable.parent.mkdir(parents=True) executable.write_text( f"#!{sys.executable}\n" "import os,pathlib,sys\n" "p=pathlib.Path(os.environ['MYPY_CACHE_DIR']);p.mkdir(parents=True);(p/'data').write_bytes(b'cache')\n" "assert os.environ['RUFF_NO_CACHE']=='true'\n" "assert os.environ['PYTHONDONTWRITEBYTECODE']=='1'\n" f"sys.exit({exit_code})\n" ) executable.chmod(0o700) protected = root / ".runtime/python-checks/another-job" protected.mkdir(parents=True) (protected / "keep").write_text("active") assert check_python.run("mypy", [], root=root) == exit_code assert [p for p in protected.parent.iterdir() if p.is_dir()] == [protected] assert (protected / "keep").read_text() == "active" def test_check_wrapper_refuses_accumulated_crash_directories_without_removing_them(tmp_path): import check_python root = tmp_path / "repo" parent = root / ".runtime/python-checks" for i in range(4): p = parent / str(i) p.mkdir(parents=True) (p / "keep").write_bytes(b"preserve") with pytest.raises(ValueError, match="Four active"): check_python.run("mypy", [], root=root) assert len(list(parent.glob("*/keep"))) == 4