| 1 | """The loaded root routes to bounded instructions that survive distribution.""" |
| 2 | |
| 3 | import io |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import re |
| 7 | import shutil |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import zipfile |
| 11 | |
| 12 | import pytest |
| 13 | import yaml |
| 14 | |
| 15 | from tests.skill_contract import ( |
| 16 | ROUTES, SKILL_ROOT, STANDARD_CONDITIONS, reference_text, root_text, routing_table, |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | ROOT = SKILL_ROOT.parents[1] |
| 21 | |
| 22 | |
| 23 | def test_every_reference_has_the_correct_conditional_load_gate(): |
| 24 | assert routing_table() == ROUTES |
| 25 | for names in ROUTES.values(): |
| 26 | for name in names: |
| 27 | assert reference_text(name).strip(), f"empty runtime reference: {name}" |
| 28 | |
| 29 | |
| 30 | def test_core_and_standard_research_fit_the_read_budget(): |
| 31 | core = (SKILL_ROOT / "SKILL.md").read_bytes() |
| 32 | assert len(core.splitlines()) <= 500, "root skill exceeds the 500-line read budget" |
| 33 | assert len(core) <= 32_000, "root skill exceeds the 32,000-byte read budget" |
| 34 | routes = routing_table() |
| 35 | assert routes == ROUTES, "classify new routes before measuring the standard path" |
| 36 | standard = {name for condition in STANDARD_CONDITIONS for name in routes[condition]} |
| 37 | assert standard == {"runtime", "research-runbook", "synthesis"} |
| 38 | total = len(core) + sum(len(reference_text(name).encode("utf-8")) for name in standard) |
| 39 | assert total <= 180_000, f"standard configured research path loads {total} bytes" |
| 40 | |
| 41 | |
| 42 | def test_configured_user_without_global_marker_has_a_bounded_setup_check(): |
| 43 | core = root_text() |
| 44 | gate = core.split("**FIRST-RUN GATE", 1)[1].split("**Onboarding consent", 1)[0] |
| 45 | assert 'grep -q "SETUP_COMPLETE=true" ~/.config/last30days/.env' in gate |
| 46 | assert "FIRST_RUN_DETECTED" in gate |
| 47 | assert "read the setup-wizard reference" in gate |
| 48 | setup = reference_text("setup-wizard") |
| 49 | assert "Skip Step 0" in setup.split("## Step 0: First-Run Setup Wizard", 1)[0] |
| 50 | |
| 51 | names = {"runtime", "setup-wizard", "research-runbook", "synthesis"} |
| 52 | total = len((SKILL_ROOT / "SKILL.md").read_bytes()) + sum( |
| 53 | len(reference_text(name).encode("utf-8")) for name in names |
| 54 | ) |
| 55 | assert total <= 191_500, f"configured path without a global marker loads {total} bytes" |
| 56 | |
| 57 | |
| 58 | def test_existing_users_can_load_repair_without_restarting_onboarding(): |
| 59 | condition = "Source repair requested or indicated by doctor" |
| 60 | assert routing_table().get(condition) == ("setup-wizard",) |
| 61 | assert condition not in STANDARD_CONDITIONS |
| 62 | setup = reference_text("setup-wizard") |
| 63 | entry = setup.split("## Step 0: First-Run Setup Wizard", 1)[0] |
| 64 | assert "including when `SETUP_COMPLETE=true`" in entry |
| 65 | assert "go directly to the applicable **Manual Setup Guide** subsection" in entry |
| 66 | assert "Skip Step 0" in entry |
| 67 | assert "do not write `SETUP_COMPLETE=true`" in entry |
| 68 | assert "do not start research unless it was requested" in entry |
| 69 | assert "explicit browser-cookie consent" in entry |
| 70 | assert "Existing authorization still applies" in entry |
| 71 | assert "a refusal, skip, or no answer is not consent" in entry |
| 72 | assert "only **X on a Grok Bot (repair)**" in entry |
| 73 | assert "never read a browser session or use the Linux / Mac mini repair" in entry |
| 74 | |
| 75 | |
| 76 | def test_doctor_routes_host_specific_repairs_without_authorizing_them(): |
| 77 | runbook = reference_text("research-runbook") |
| 78 | doctor = runbook.split("**Doctor health check:**", 1)[1].split( |
| 79 | "**Grok session expiry handling:**", 1, |
| 80 | )[0] |
| 81 | assert "Source repair requested or indicated by doctor" in doctor |
| 82 | assert "read `references/setup-wizard.md` in full" in doctor |
| 83 | assert "A doctor result is not authorization" in doctor |
| 84 | assert "For a health-check-only request, relay the audit and repair guidance, then stop" in doctor |
| 85 | |
| 86 | |
| 87 | def test_selected_references_are_read_fully_without_loading_every_mode(): |
| 88 | core = root_text() |
| 89 | bootstrap = core.split("## Bootstrap and file reads", 1)[1].split("## Reference routing", 1)[0] |
| 90 | assert "Read only references whose conditions apply" in bootstrap |
| 91 | assert "Read each selected reference in full before its phase" in bootstrap |
| 92 | assert "Do not recursively read every reference" in bootstrap |
| 93 | assert "continue bounded reads until the entire selected reference is loaded" in bootstrap |
| 94 | assert "missing or unreadable" in bootstrap |
| 95 | assert "stop before the affected command/output" in bootstrap |
| 96 | for line in core.splitlines(): |
| 97 | if line.lower().startswith(("read all references", "always read every reference")): |
| 98 | pytest.fail(f"unconditional reference loading defeats disclosure: {line}") |
| 99 | |
| 100 | |
| 101 | def test_paths_stay_bound_to_the_loaded_root_across_hosts(): |
| 102 | core = root_text() |
| 103 | bootstrap = core.split("## Bootstrap and file reads", 1)[1].split("## Reference routing", 1)[0] |
| 104 | assert "root SKILL.md actually loaded by the host" in bootstrap |
| 105 | assert "Never bind it to `references/`, the current directory" in bootstrap |
| 106 | assert "Read or equivalent local file capability" in bootstrap |
| 107 | assert "read that replacement root in full, rebind `SKILL_DIR`" in bootstrap |
| 108 | assert "Paths resolve relative to `SKILL_DIR`" in core |
| 109 | metadata = yaml.safe_load(core.split("---", 2)[1]) |
| 110 | assert "Read" in metadata["allowed-tools"].split(", ") |
| 111 | assert "references/*" in metadata["metadata"]["openclaw"]["files"] |
| 112 | |
| 113 | |
| 114 | def test_json_requests_load_the_structured_contract_without_agent_flag(): |
| 115 | routes = routing_table() |
| 116 | assert routes["--agent mode or explicit machine-readable JSON"] == ("agent-mode",) |
| 117 | output = root_text().split("## Output contract", 1)[1].split("**BADGE", 1)[0] |
| 118 | assert "Explicit machine-readable JSON uses `--emit=json`" in output |
| 119 | assert "verbatim engine stdout" in output |
| 120 | assert "no prose badge, synthesis, footer, or invitation added" in output |
| 121 | contract = reference_text("agent-mode") |
| 122 | assert "--emit=json" in contract |
| 123 | assert "--json-profile=raw" in contract |
| 124 | |
| 125 | |
| 126 | @pytest.fixture(scope="module") |
| 127 | def packaged_skill(tmp_path_factory): |
| 128 | checkout = tmp_path_factory.mktemp("skill package source") |
| 129 | skill = checkout / "skills" / "last30days" |
| 130 | shutil.copytree(SKILL_ROOT, skill, ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) |
| 131 | shutil.copy2(ROOT / ".gitattributes", checkout / ".gitattributes") |
| 132 | git_home = checkout / "git-home" |
| 133 | git_home.mkdir() |
| 134 | env = { |
| 135 | **os.environ, |
| 136 | "HOME": str(git_home), |
| 137 | "GIT_CONFIG_GLOBAL": os.devnull, |
| 138 | "GIT_CONFIG_NOSYSTEM": "1", |
| 139 | } |
| 140 | for command in ( |
| 141 | ["git", "-c", "init.templateDir=", "init", "-q"], |
| 142 | ["git", "add", "--", ".gitattributes", "skills/last30days"], |
| 143 | ["git", "-c", "user.name=Package test", "-c", "user.email=package@example.invalid", |
| 144 | "-c", "commit.gpgsign=false", "commit", "-qm", "Package current skill files"], |
| 145 | ["bash", "skills/last30days/scripts/build-skill.sh"], |
| 146 | ): |
| 147 | result = subprocess.run(command, cwd=checkout, env=env, text=True, capture_output=True) |
| 148 | assert result.returncode == 0, result.stdout + result.stderr |
| 149 | with zipfile.ZipFile(checkout / "dist" / "last30days.skill") as archive: |
| 150 | archive.extractall(checkout / "installed skills") |
| 151 | return checkout, checkout / "installed skills" / "last30days", env |
| 152 | |
| 153 | |
| 154 | def test_skill_archive_keeps_runtime_without_development_assets(packaged_skill): |
| 155 | checkout, _, _ = packaged_skill |
| 156 | with zipfile.ZipFile(checkout / "dist" / "last30days.skill") as archive: |
| 157 | files = {entry.filename for entry in archive.infolist() if not entry.is_dir()} |
| 158 | assert {path.split("/", 1)[0] for path in files} == {"last30days"} |
| 159 | assert sum(path.endswith("/SKILL.md") for path in files) == 1 |
| 160 | assert len(files) <= 200 |
| 161 | assert "last30days/scripts/lib/vendor/bird-search/bird-search.mjs" in files |
| 162 | assert "last30days/scripts/watchlist.py" in files |
| 163 | assert not any(path.startswith("last30days/assets/") for path in files) |
| 164 | assert files.isdisjoint( |
| 165 | f"last30days/scripts/{name}" |
| 166 | for name in ("compare.sh", "verify_v3.py", "test_device_auth.py", "test-v1-vs-v2.sh") |
| 167 | ) |
| 168 | |
| 169 | |
| 170 | @pytest.fixture |
| 171 | def minimal_package_source(tmp_path): |
| 172 | skill = tmp_path / "skills" / "last30days" |
| 173 | scripts = skill / "scripts" |
| 174 | library = scripts / "lib" |
| 175 | library.mkdir(parents=True) |
| 176 | (skill / "SKILL.md").write_text("# Test skill\n", encoding="utf-8") |
| 177 | shutil.copy2(SKILL_ROOT / "scripts" / "build-skill.sh", scripts) |
| 178 | |
| 179 | def run(*command, check=True): |
| 180 | return subprocess.run( |
| 181 | command, cwd=tmp_path, text=True, capture_output=True, check=check, timeout=30, |
| 182 | env={ |
| 183 | "PATH": os.pathsep.join((str(Path(sys.executable).parent), os.defpath)), |
| 184 | "HOME": str(tmp_path), |
| 185 | "GIT_CONFIG_NOSYSTEM": "1", |
| 186 | }, |
| 187 | ) |
| 188 | |
| 189 | def commit_and_build(): |
| 190 | run("git", "add", "--", "skills/last30days") |
| 191 | run( |
| 192 | "git", "-c", "user.name=Package test", "-c", "user.email=package@example.invalid", |
| 193 | "-c", "commit.gpgsign=false", "commit", "-qm", "Package skill files", |
| 194 | ) |
| 195 | return run("bash", "skills/last30days/scripts/build-skill.sh", check=False) |
| 196 | |
| 197 | run("git", "-c", "init.templateDir=", "init", "-q") |
| 198 | return library, commit_and_build |
| 199 | |
| 200 | |
| 201 | def test_skill_archive_accepts_200_files_and_preserves_last_build_when_over_limit( |
| 202 | tmp_path, minimal_package_source, |
| 203 | ): |
| 204 | library, commit_and_build = minimal_package_source |
| 205 | for index in range(197): |
| 206 | (library / f"module_{index}.py").touch() |
| 207 | (library / "additional_runtime.py").write_text("PACKAGED = True\n", encoding="utf-8") |
| 208 | |
| 209 | result = commit_and_build() |
| 210 | assert result.returncode == 0, result.stdout + result.stderr |
| 211 | artifact = tmp_path / "dist" / "last30days.skill" |
| 212 | with zipfile.ZipFile(artifact) as archive: |
| 213 | assert sum(not entry.is_dir() for entry in archive.infolist()) == 200 |
| 214 | assert archive.read("last30days/scripts/lib/additional_runtime.py") == b"PACKAGED = True\n" |
| 215 | |
| 216 | (library / "additional_runtime.py").write_text("PACKAGED = 2\n", encoding="utf-8") |
| 217 | result = commit_and_build() |
| 218 | assert result.returncode == 0, result.stdout + result.stderr |
| 219 | with zipfile.ZipFile(artifact) as archive: |
| 220 | assert archive.read("last30days/scripts/lib/additional_runtime.py") == b"PACKAGED = 2\n" |
| 221 | built = artifact.read_bytes() |
| 222 | |
| 223 | (library / "over_capacity.py").touch() |
| 224 | result = commit_and_build() |
| 225 | assert result.returncode == 1 |
| 226 | assert "201 files in zip" in result.stderr |
| 227 | assert artifact.read_bytes() == built |
| 228 | |
| 229 | |
| 230 | @pytest.mark.parametrize("use_symlink", [False, True], ids=["directory", "symlink"]) |
| 231 | def test_skill_archive_rejects_directory_output(tmp_path, minimal_package_source, use_symlink): |
| 232 | _, commit_and_build = minimal_package_source |
| 233 | artifact = tmp_path / "dist" / "last30days.skill" |
| 234 | target = tmp_path / "output directory" if use_symlink else artifact |
| 235 | artifact.parent.mkdir() |
| 236 | target.mkdir() |
| 237 | if use_symlink: |
| 238 | artifact.symlink_to(target, target_is_directory=True) |
| 239 | |
| 240 | result = commit_and_build() |
| 241 | |
| 242 | assert result.returncode == 1, result.stdout + result.stderr |
| 243 | assert "error: cannot replace dist/last30days.skill: destination is a directory" in result.stderr |
| 244 | assert artifact.is_dir() |
| 245 | assert artifact.is_symlink() == use_symlink |
| 246 | assert list(target.iterdir()) == [] |
| 247 | assert list(artifact.parent.iterdir()) == [artifact] |
| 248 | |
| 249 | |
| 250 | def test_skill_archive_contains_the_actual_routed_reference_bytes(packaged_skill): |
| 251 | checkout, installed, env = packaged_skill |
| 252 | assert (installed / "SKILL.md").read_bytes() == (SKILL_ROOT / "SKILL.md").read_bytes() |
| 253 | for names in ROUTES.values(): |
| 254 | for name in names: |
| 255 | assert reference_text(name, installed) == reference_text(name) |
| 256 | result = subprocess.run( |
| 257 | ["git", "archive", "--format=zip", "HEAD"], cwd=checkout, env=env, |
| 258 | capture_output=True, check=True, |
| 259 | ) |
| 260 | with zipfile.ZipFile(io.BytesIO(result.stdout)) as repository_archive: |
| 261 | for name in {name for names in ROUTES.values() for name in names}: |
| 262 | path = f"skills/last30days/references/{name}.md" |
| 263 | assert path in repository_archive.namelist(), f"plugin archive omits {path}" |
| 264 | assert repository_archive.read(path) == (SKILL_ROOT / "references" / f"{name}.md").read_bytes() |
| 265 | |
| 266 | |
| 267 | def test_packaged_runtime_resolves_from_a_path_with_spaces_outside_cwd(packaged_skill, tmp_path): |
| 268 | _, installed, _ = packaged_skill |
| 269 | assert " " in str(installed) |
| 270 | runtime = reference_text("runtime", installed) |
| 271 | assignment = re.findall(r"^LAST30DAYS_MEMORY_DIR=.*$", runtime, re.M) |
| 272 | assert len(assignment) == 1 |
| 273 | result = subprocess.run( |
| 274 | ["bash", "-ec", assignment[0] + '\nprintf "%s" "$LAST30DAYS_MEMORY_DIR"'], |
| 275 | cwd=tmp_path, |
| 276 | env={ |
| 277 | "PATH": os.defpath, |
| 278 | "HOME": str(tmp_path / "home"), |
| 279 | "SKILL_DIR": str(installed), |
| 280 | "LAST30DAYS_PYTHON": sys.executable, |
| 281 | "LAST30DAYS_CONFIG_DIR": str(tmp_path / "config"), |
| 282 | "LAST30DAYS_CACHE_DIR": str(tmp_path / "cache"), |
| 283 | "LAST30DAYS_MEMORY_DIR": str(tmp_path / "saved research"), |
| 284 | }, |
| 285 | text=True, capture_output=True, timeout=15, |
| 286 | ) |
| 287 | assert result.returncode == 0, result.stderr |
| 288 | assert result.stdout == str(tmp_path / "saved research") |
| 289 | assert not list(installed.rglob("__pycache__")) |
| 290 | assert not list(installed.rglob("*.pyc")) |
| 291 |