Buckets:

download
raw
82.3 kB
"""Tests for Claude Code artifact regeneration. ``TemplateManager.regenerate_claude_code`` rebuilds a project's ``.claude/`` tree, ``.mcp.json`` and ``CLAUDE.md`` from its ``config.yml``. It runs as a step of ``osprey build`` — there is no standalone regeneration verb — and these tests drive it directly, which is where its contract actually lives: the artifacts it produces, the user files it preserves, the backup it takes, and the safety hooks it must never drop between one render and the next. """ import json import os import re import shutil from pathlib import Path import pytest import yaml from osprey.build.claude_code_resolver import MANAGED_ENV_VARS from osprey.cli.templates import claude_code from osprey.cli.templates.manager import TemplateManager def _bundle_data_root(bundle: str = "control_assistant") -> Path: """The tree these fixtures give ``create_project`` as the profile's ``data:``. A build copies the tree its profile's ``data:`` key names, and that key is required — nothing falls back to a packaged tree any more. These fixtures render straight from a bundle rather than from a profile, so they name the tree that bundle packages, which is the same content the render used to reach for on its own. """ return Path(TemplateManager().template_root) / "apps" / bundle / "data" def _create_project(manager: TemplateManager, **kwargs) -> Path: """``create_project`` plus the manifest stamp a real build writes next. A build stamps ``.osprey-manifest.json`` immediately after the render, and the Claude Code regen reads the preset back out of it to learn which artifacts the project selected. A fixture that renders without stamping is not a project any build produces: it regenerates with an empty artifact selection, and the write-gate lint rightly refuses the result. """ project = manager.create_project(**kwargs) bundle = kwargs.setdefault("data_bundle", "control_assistant") manager.generate_manifest( project, kwargs["project_name"], bundle.replace("_", "-"), {}, # The selection the render was made with, exactly as a build stamps it: # a site that hands `create_project` its own `artifacts=` must get that # selection back on the regen, not the bundle's full list. artifacts=manager._effective_artifacts(bundle, kwargs.get("artifacts")), ) return project # Hook modules that are shipped into .claude/hooks/ as importable support code # rather than as hook entry points. They are deliberately absent from # settings.json and are excluded from the settings <-> hooks parity invariant. HOOK_LIBRARY_MODULES = {"osprey_hook_log.py", "osprey_target_state.py"} _HOOK_BASENAME_RE = re.compile(r"osprey_[A-Za-z0-9_]+\.py") def _referenced_hook_basenames(settings: dict) -> dict[str, list[str]]: """Map each ``osprey_*.py`` basename referenced in settings.json to its events. Hook commands are shell strings whose shape varies by wiring route (quoted absolute interpreter vs. literal ``python3``, trailing ``2>/dev/null || true``), so the basename is extracted by pattern rather than by matching whole commands. """ found: dict[str, list[str]] = {} for event, entries in settings.get("hooks", {}).items(): for entry in entries: for hook in entry.get("hooks", []): for basename in _HOOK_BASENAME_RE.findall(hook.get("command", "")): found.setdefault(basename, []).append(event) return found class TestBuildClaudeCodeContext: """Test build_claude_code_context() reconstructs correct template vars.""" def test_basic_config(self, tmp_path): """Basic config produces correct base context vars.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-basic", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["project_name"] == "ctx-basic" assert ctx["package_name"] == "ctx_basic" assert ctx["project_root"] == str(project_dir.absolute()) assert "current_python_env" in ctx assert ctx["preset"] == "control-assistant" def test_project_root_override(self, tmp_path): """project_root_override replaces project_root in context but keeps file I/O path.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-override", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config, project_root_override="/app/als-assistant", ) # project_root uses the override assert ctx["project_root"] == "/app/als-assistant" # project_name still derived from actual project (file I/O uses project_dir) assert ctx["project_name"] == "ctx-override" def test_control_assistant_config(self, tmp_path): """Control assistant config produces channel_finder context vars.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-control", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Generate manifest so build_claude_code_context can discover the preset manager.generate_manifest(project_dir, "ctx-control", "control-assistant", {}) config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["preset"] == "control-assistant" assert "channel_finder_pipeline" in ctx assert "channel_finder_mode" in ctx def test_uses_manifest_preset(self, tmp_path): """When a manifest exists, the preset stamp is read from it.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-manifest", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Generate manifest manager.generate_manifest(project_dir, "ctx-manifest", "control-assistant", {}) config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["preset"] == "control-assistant" class TestManifestPresetStamp: """What ``creation.template`` means, and what a reader does with an old one.""" def _project(self, tmp_path, name): """A bare project directory with just enough config.yml to read back. The stamp is provenance about the build, not a product of the render, so these pin it without rendering a project: what a full render would add is exactly what must not be able to change the answer. """ project_dir = tmp_path / name project_dir.mkdir() (project_dir / "config.yml").write_text( yaml.safe_dump({"project_name": name}), encoding="utf-8" ) return project_dir def test_a_project_with_no_manifest_reads_no_preset(self, tmp_path): """No manifest is no answer, not a default. The old reader substituted ``control_assistant`` here, which is a guess: it names the common bundle, and for a project built from any other one it was simply wrong. Every real project has a manifest — the build writes it — so the guess only ever hid an incomplete one. """ project_dir = self._project(tmp_path, "no-manifest") manager = TemplateManager() config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["preset"] is None def test_the_stamp_is_the_preset_and_the_bundle_is_not_recorded(self, tmp_path): """The manifest names the preset; the bundle is derivable from it. Recording the bundle beside the preset gives a reader two fields that can disagree — and the one that would be wrong is the one nothing re-derives. """ manager = TemplateManager() project_dir = self._project(tmp_path, "stamp-preset") data = manager.generate_manifest(project_dir, "stamp-preset", "hello-world", {}) assert data["creation"]["template"] == "hello-world" assert "data_bundle" not in data["creation"] assert "data_bundle" not in data["build_args"] on_disk = json.loads((project_dir / ".osprey-manifest.json").read_text()) assert on_disk["creation"]["template"] == "hello-world" assert "data_bundle" not in on_disk["creation"] def test_a_profile_with_no_preset_stamps_none(self, tmp_path): """A hand-written profile records no preset, so neither does its manifest. Substituting a default here would name a preset the operator never chose, and every reader downstream would believe it. """ from osprey.cli.templates import manifest as manifest_mod manager = TemplateManager() project_dir = self._project(tmp_path, "stamp-none") data = manifest_mod.generate_manifest( manager.template_root, manager.jinja_env, project_dir, "stamp-none", None, {}, ) assert data["creation"]["template"] is None def test_the_manager_hands_the_stamp_through_untouched(self, tmp_path): """``TemplateManager`` must not substitute a name of its own. It is the only caller between the build and the manifest, and a default applied here would be indistinguishable, to every later reader, from a preset the operator actually chose. """ manager = TemplateManager() project_dir = self._project(tmp_path, "stamp-through") data = manager.generate_manifest(project_dir, "stamp-through", None, {}) assert data["creation"]["template"] is None def test_a_manifest_from_an_older_build_still_reads(self, tmp_path, caplog): """The retired ``data_bundle`` key is ignored, not refused. Provenance is advisory: a manifest an older build wrote must not break the operation it is annotating, and the reader says so at debug level. """ import logging from osprey.cli.templates import manifest as manifest_mod manager = TemplateManager() project_dir = self._project(tmp_path, "stamp-legacy") manager.generate_manifest(project_dir, "stamp-legacy", "control-assistant", {}) manifest_path = project_dir / ".osprey-manifest.json" stale = json.loads(manifest_path.read_text()) stale["creation"]["data_bundle"] = "control_assistant" manifest_path.write_text(json.dumps(stale), encoding="utf-8") with caplog.at_level(logging.DEBUG, logger="osprey.cli.templates"): loaded = manifest_mod.load_project_manifest(project_dir) assert loaded is not None assert loaded["creation"]["template"] == "control-assistant" assert "data_bundle" in caplog.text # And the context builder reads the preset past it, rather than # preferring the key that is no longer written. config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["preset"] == "control-assistant" assert "data_bundle" not in ctx def test_a_hand_written_profile_stamps_none_and_still_regenerates(self, tmp_path): """The stamp being ``None`` must not cost the project its artifacts. A profile with no ``provenance:``, no ``extends:`` and no artifact lists of its own names no preset, so the manifest honestly records none. Its render still selects the bundle's own declared artifacts — that is what ``create_project`` renders with — so the manifest has to record THAT selection rather than nothing. When it recorded nothing, the regen that runs at the end of the same build found no preset to re-resolve from, selected no artifacts, wired no hook, and the write-gate lint refused the render: a build that worked became a build that could not finish. """ from click.testing import CliRunner from osprey.cli.build_cmd import build repo = tmp_path / "hand-written" repo.mkdir() (repo / "profile.yml").write_text( yaml.safe_dump( { "name": "Hand Written", "data": "data", "provider": "cborg", "model": "haiku", "channel_finder_mode": "in_context", "config": { "control_system.type": "mock", "archiver.type": "mock", "claude_code.telemetry.enabled": False, "hooks.debug": False, }, } ), encoding="utf-8", ) shutil.copytree(_bundle_data_root(), repo / "data", dirs_exist_ok=True) (repo / "data" / "facility_knowledge").mkdir(parents=True, exist_ok=True) result = CliRunner().invoke(build, ["--repo", str(repo), "--skip-deps", "--skip-lifecycle"]) assert result.exit_code == 0, ( f"build failed (exit={result.exit_code})\n{result.output}\n{result.exception}" ) manager = TemplateManager() stamped = json.loads((repo / "build" / ".osprey-manifest.json").read_text()) assert stamped["creation"]["template"] is None # The selection the render was made with, recorded verbatim. assert stamped["artifacts"] == manager._effective_artifacts("control_assistant", None) assert stamped["artifacts"]["hooks"] # And the regen reads it back rather than needing a preset name. config = yaml.safe_load((repo / "build" / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, repo / "build", config ) assert ctx["preset"] is None assert ctx["selected_hooks"] == stamped["artifacts"]["hooks"] def test_a_persona_preset_resolves_its_inherited_artifacts(self): """A preset's artifact fallback follows ``extends:``. The persona presets declare a delta over ``control-assistant``, so reading one preset file alone answers with a fraction of what it selects — ``control-assistant-readonly`` declares no skills and no agents at all. A reader that took that literally would regenerate a readonly deployment with none of the artifacts it inherits. """ from osprey.cli.templates import manifest as manifest_mod base = manifest_mod.load_template_manifest("control-assistant") assert base is not None for persona in ("control-assistant-readonly", "control-assistant-readwrite"): resolved = manifest_mod.load_template_manifest(persona) assert resolved is not None, persona for category in ("hooks", "rules", "skills", "agents"): assert set(base["artifacts"][category]) <= set(resolved["artifacts"][category]), ( f"{persona} lost inherited {category}" ) def test_the_init_render_and_the_regen_name_the_same_preset(self, tmp_path): """The first render must not say "hand-written" about a preset project. The setup-mode skill prints the preset the project was materialized from. It is rendered twice — once by ``create_project`` and again by the regen at the end of the same build — and the two read the name from different places: the render context and the manifest stamp. When only the second was given the name, every fresh render wrote "none — this profile is hand-written" and was silently corrected moments later, which is the wrong text for any reader who looked at the tree in between, and the wrong text permanently for anything that renders without regenerating. """ from osprey.cli.templates import manifest as manifest_mod preset = "control-assistant-admin" manager = TemplateManager() selection = manifest_mod.load_template_manifest(preset)["artifacts"] assert "setup-mode" in selection["skills"] project = manager.create_project( project_name="preset-named", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical", "preset": preset}, artifacts=selection, data_root=_bundle_data_root("control_assistant"), ) manager.generate_manifest(project, "preset-named", preset, {}, artifacts=selection) skill = project / ".claude" / "skills" / "setup-mode" / "SKILL.md" rendered = skill.read_text(encoding="utf-8") assert preset in rendered assert "hand-written" not in rendered manager.regenerate_claude_code(project) assert skill.read_text(encoding="utf-8") == rendered def test_an_unknown_preset_name_resolves_to_nothing(self): """An unknown name is no answer, and never an exception. Every caller of this fallback has a further one, so a preset this installation does not ship must come back as ``None`` rather than aborting the operation it was only annotating. """ from osprey.cli.templates import manifest as manifest_mod assert manifest_mod.load_template_manifest("no-such-preset") is None class TestRegenerationCorrectness: """Test that regeneration produces correct output.""" def test_regen_produces_same_output_as_init(self, tmp_path): """Build → regen with no config changes → identical artifacts. What a build ships is the regenerated tree, not the first render. A project's declarative config is its preset's, and the framework template renders none of it, so a build writes the resolved ``config:`` onto config.yml AFTER ``create_project`` and regenerates from the result. The comparison below is therefore between the artifacts a build leaves behind and a second regeneration of the same config — which is what "no config changes" means for a project on disk. Comparing the first render instead would compare two different configs and fail for a reason that has nothing to do with idempotence. """ from osprey.cli.build_profile import resolve_build_profile from osprey.utils.config_writer import config_update_fields manager = TemplateManager() project_dir = _create_project( manager, project_name="regen-idempotent", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) profile, _profile_dir = resolve_build_profile(None, preset="control-assistant") config_update_fields(project_dir / "config.yml", profile.config) manager.regenerate_claude_code(project_dir) # Capture checksums files_to_check = [".mcp.json", "CLAUDE.md", ".claude/settings.json"] original_checksums = {} for f in files_to_check: fp = project_dir / f if fp.exists(): original_checksums[f] = fp.read_text() # Regen result = manager.regenerate_claude_code(project_dir) # Compare for f, original_content in original_checksums.items(): assert (project_dir / f).read_text() == original_content, f"{f} changed unexpectedly" assert f in result["unchanged"] or not result["changed"] def test_regen_resolves_env_var_in_timezone(self, tmp_path, monkeypatch): """${TZ:-UTC} in config.yml is resolved in timezone.md.""" monkeypatch.delenv("TZ", raising=False) manager = TemplateManager() project_dir = _create_project( manager, project_name="regen-tz", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Set timezone to an env-var pattern in config.yml config = yaml.safe_load((project_dir / "config.yml").read_text()) config.setdefault("system", {})["timezone"] = "${TZ:-UTC}" (project_dir / "config.yml").write_text(yaml.dump(config)) manager.regenerate_claude_code(project_dir) timezone_file = project_dir / ".claude" / "rules" / "timezone.md" assert timezone_file.exists(), "timezone.md should be created when timezone is set" content = timezone_file.read_text() assert "UTC" in content assert "${TZ" not in content, "Env var pattern should be resolved, not literal" def test_regen_resolves_env_var_in_timezone_with_env_set(self, tmp_path, monkeypatch): """${TZ:-...} resolves to actual TZ env value when set.""" monkeypatch.setenv("TZ", "Europe/Berlin") manager = TemplateManager() project_dir = _create_project( manager, project_name="regen-tz-env", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) config.setdefault("system", {})["timezone"] = "${TZ:-UTC}" (project_dir / "config.yml").write_text(yaml.dump(config)) manager.regenerate_claude_code(project_dir) timezone_file = project_dir / ".claude" / "rules" / "timezone.md" assert timezone_file.exists() content = timezone_file.read_text() assert "Europe/Berlin" in content class TestSafetyPreservation: """Test that regeneration always preserves safety layers.""" @pytest.fixture() def regen_project(self, tmp_path): """Create and regenerate a project.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="safety-test", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.regenerate_claude_code(project_dir) return project_dir @pytest.fixture() def regen_project_writes_off(self, tmp_path): """Create a project, disable control-system writes, regenerate.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="safety-writes-off", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config_path = project_dir / "config.yml" config = yaml.safe_load(config_path.read_text()) # The framework template writes no `control_system:` block of its own — # a deployment states its connector in the profile's `config:` — so the # fixture states the one setting it is about. config.setdefault("control_system", {})["writes_enabled"] = False config_path.write_text(yaml.dump(config, default_flow_style=False)) manager.regenerate_claude_code(project_dir) return project_dir def test_writes_off_kill_switch_covers_python_execute(self, regen_project_writes_off): """Kill-switch parity for the python-executor write path. When control-system writes are disabled, neither write entry point may reach Claude Code's ``permissions.ask`` -> ``can_use_tool`` approval path: - ``mcp__controls__channel_write`` is hard-denied via ``permissions.deny``. - ``mcp__python__execute`` cannot be denied wholesale (it has a legitimate read-only path), so it is instead removed from ``permissions.ask``; the ``osprey_writes_check`` PreToolUse hook then denies the read-write case with nothing forcing an approval prompt. Regression guard: under ``claude-agent-sdk==0.2.93`` a static ``permissions.ask`` entry drives a read-write ``execute`` to ``can_use_tool`` even when the writes_check hook denies it in parallel, so leaving ``mcp__python__execute`` in ``ask`` silently bypasses the kill switch (the operator is prompted instead of the call being blocked). """ claude = regen_project_writes_off / ".claude" settings = json.loads((claude / "settings.json").read_text()) perms = settings["permissions"] hook_config = json.loads((claude / "hooks" / "hook_config.json").read_text()) # Anti-vacuous guard: the python executor IS active and write-gated. assert "mcp__python__execute" in hook_config["write_tools"] # channel_write: declarative hard block. assert "mcp__controls__channel_write" in perms["deny"] # python execute: must NOT sit in the ask list while writes are off, # or a read-write execute reaches the approval path and bypasses the # kill switch. assert "mcp__python__execute" not in perms["ask"], ( "mcp__python__execute is in permissions.ask while writes are " "disabled — a read-write execute would reach the can_use_tool " "approval path, bypassing the kill switch." ) def test_always_includes_safety_hooks(self, regen_project): """After regen, settings.json still has PreToolUse/PostToolUse hook chains.""" settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) assert "PreToolUse" in settings["hooks"] assert "PostToolUse" in settings["hooks"] def test_settings_json_has_no_managed_env_block(self, regen_project): """The generated project settings.json must not set any OSPREY-managed provider variable in an ``env`` block. Provider vars are injected into the process environment at launch and must stay there: the project settings scope outranks the process environment, so a value baked into settings.json would pin a stale loopback proxy port or a wrong model ID (issue #355). Provider isolation relies on settings.json staying env-block-free. """ settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) env_block = settings.get("env", {}) leaked = MANAGED_ENV_VARS & set(env_block) assert not leaked, f"settings.json leaks managed provider vars: {sorted(leaked)}" def test_always_denies_dangerous_tools(self, regen_project): """After regen, settings.json denies Bash, Edit, WebFetch, WebSearch. Write is intentionally NOT denied — Claude Code's native auto memory system requires Write access to persist memories across sessions. """ settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) deny = settings["permissions"]["deny"] for tool in ["Bash", "Edit", "WebFetch", "WebSearch"]: assert tool in deny, f"{tool} should be in deny list after regen" assert "Write" not in deny, "Write must not be denied (auto memory needs it)" def test_preserves_writes_check_hook(self, regen_project): """osprey_writes_check.py is in PreToolUse for channel_write after regen.""" settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) pre_tool_use = settings["hooks"]["PreToolUse"] channel_write_hooks = [ h for h in pre_tool_use if h.get("matcher") == "mcp__controls__channel_write" ] assert len(channel_write_hooks) > 0 hook_commands = [ hook["command"] for entry in channel_write_hooks for hook in entry["hooks"] ] assert any("osprey_writes_check.py" in cmd for cmd in hook_commands) def test_has_memory_guard_hook(self, regen_project): """The memory guard survives regen, gating every write tool. The matcher is the guard's frontmatter ``tools:`` copied verbatim, so it is also the exact list of tools the guard can refuse. A regen that narrowed it would leave a rule in place and a tool ungated. """ settings_path = regen_project / ".claude" / "settings.json" data = json.loads(settings_path.read_text()) pre_matchers = [r["matcher"] for r in data["hooks"]["PreToolUse"]] assert "Write|MultiEdit|NotebookEdit" in pre_matchers def test_hooks_remain_executable(self, regen_project): """After regen, all hook .py files retain executable permissions.""" hooks_dir = regen_project / ".claude" / "hooks" for hook in hooks_dir.iterdir(): if hook.is_file() and hook.suffix == ".py": mode = os.stat(hook).st_mode assert mode & 0o111, f"Hook {hook.name} should be executable after regen" def test_framework_hooks_launch_via_resolved_interpreter(self, regen_project): """Framework PreToolUse/PostToolUse hooks must launch via an absolute interpreter path, never bare ``python``/``python3``. Regression guard for the "dark hook layer" bug: framework hook commands were rendered as bare ``python "..."``. On hosts without a ``python`` on PATH (stock macOS, many Linux), the entire approval / writes-kill-switch / feedback hook layer silently failed to launch and the safety tests passed vacuously. The renderer now rewrites the interpreter token to the project's resolved venv python (``current_python_env``), so every framework hook command must invoke a real, absolute interpreter path. """ settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) framework_cmds = [ hook["command"] for event in ("PreToolUse", "PostToolUse") for entry in settings["hooks"].get(event, []) for hook in entry["hooks"] if "/.claude/hooks/osprey_" in hook["command"] ] assert framework_cmds, "expected framework osprey_*.py hook commands after regen" for cmd in framework_cmds: assert not cmd.startswith("python "), ( f"bare `python` re-introduces the dark-hook bug: {cmd}" ) assert not cmd.startswith("python3 "), ( f"PATH-relative `python3` is not the resolved interpreter: {cmd}" ) # Command must launch via a quoted, absolute interpreter path. assert cmd.startswith('"/'), ( f"framework hook must launch via the resolved venv interpreter " f"(absolute path), got: {cmd}" ) def test_every_settings_hook_reference_has_a_shipped_file(self, regen_project): """Direction (a): settings.json never points at a hook that was not shipped. A reference with no file behind it is a silently dead hook — Claude Code runs the command, the interpreter fails to find the script, and (because every framework hook command is fail-open) the event proceeds with the guard absent. Nothing in the rendered project surfaces that, so this invariant is the only place it shows up. Hooks reach settings.json by three different routes, all of which land in the same rendered ``hooks`` block and all of which this direction covers: 1. **Hardcoded template entries** — SessionStart and UserPromptSubmit entries written literally into ``settings.json.j2``. These keep the literal ``python3`` interpreter token and carry a ``2>/dev/null || true`` suffix (the PreToolUse/PostToolUse loops, by contrast, rewrite ``python3`` to the resolved venv interpreter). 2. **Server registry wiring** — ``hooks_pre`` / ``hooks_post`` rules contributed by each enabled MCP server, plus the framework-level pre/post rules. 3. **Frontmatter ``wiring: standalone``** — hooks whose own YAML frontmatter declares the event and matcher tools, from which the renderer builds the rule. Exactly two hooks use this route today: ``osprey_memory_guard`` and ``osprey_notebook_update``. """ settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) hooks_dir = regen_project / ".claude" / "hooks" referenced = _referenced_hook_basenames(settings) assert referenced, "expected settings.json to reference osprey_*.py hooks" missing = { basename: sorted(set(events)) for basename, events in referenced.items() if not (hooks_dir / basename).exists() } assert not missing, ( f"settings.json references hooks that were not shipped into " f"{hooks_dir}: {missing}. A dangling reference fails open — the " f"guard is silently absent at runtime." ) def test_every_shipped_event_hook_is_wired_into_settings(self, regen_project): """Direction (b): no shipped event hook sits in the project unreferenced. The mirror of the test above. A hook file that is deployed but wired into no event is dead weight that reads, to anyone inspecting the project, as an active safety layer. Under the default ``control_assistant`` shape the controls server is enabled and the fixture enables channel-finder, so every event hook is unconditionally wired — there is no configuration in this fixture under which a shipped hook is legitimately unreferenced. ``osprey_hook_log`` and ``osprey_target_state`` are excluded: the other hooks import them as a logging helper and a control-target state reader, and neither is itself a hook entry point (see ``HOOK_LIBRARY_MODULES``). """ settings = json.loads((regen_project / ".claude" / "settings.json").read_text()) hooks_dir = regen_project / ".claude" / "hooks" shipped = {p.name for p in hooks_dir.glob("osprey_*.py")} event_hooks = shipped - HOOK_LIBRARY_MODULES # Anti-vacuous guard: a glob that matched nothing (or only the library # module) would make the subset check below trivially true. assert len(event_hooks) >= 10, ( f"expected at least 10 shipped event hooks, found {sorted(event_hooks)}" ) referenced = set(_referenced_hook_basenames(settings)) unwired = sorted(event_hooks - referenced) assert not unwired, ( f"hooks shipped into {hooks_dir} but referenced by no event in " f"settings.json: {unwired}. Either wire them (template entry, server " f"registry hooks_pre/hooks_post, or `wiring: standalone` frontmatter) " f"or stop shipping them." ) class TestUserFilePreservation: """Test that regeneration preserves user-maintained files.""" def test_claude_md_has_generated_header(self, tmp_path): """CLAUDE.md has the generated-file header comment.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="header-test", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) content = (project_dir / "CLAUDE.md").read_text() assert "GENERATED BY OSPREY" in content assert "claude_md_template" in content class TestErrorHandling: """Test error handling in regeneration.""" def test_no_config_error(self, tmp_path): """Run in directory without config.yml → clear error.""" manager = TemplateManager() with pytest.raises(FileNotFoundError, match="No config.yml found"): manager.regenerate_claude_code(tmp_path) def test_dry_run_no_changes(self, tmp_path): """Dry run does not modify any files.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="dry-run-test", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Record file mtimes mcp_mtime = (project_dir / ".mcp.json").stat().st_mtime manager.regenerate_claude_code(project_dir, dry_run=True) # File should not be modified assert (project_dir / ".mcp.json").stat().st_mtime == mcp_mtime def test_dry_run_clean_after_regen_reports_no_changes(self, tmp_path): """Dry run on a freshly regenerated project reports nothing to change. facility.md is create-only (auto-registered user-owned) — a real regen never rewrites an existing copy, so the dry-run comparison must not report it as drift. A phantom diff here makes regen_if_drift perform a full regen (and churn a backup dir) on every web launch / config write, and makes `osprey status` report permanent false drift. """ manager = TemplateManager() project_dir = _create_project( manager, project_name="dry-clean", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.regenerate_claude_code(project_dir) result = manager.regenerate_claude_code(project_dir, dry_run=True) assert result["changed"] == [] def test_dry_run_skips_user_owned_artifacts(self, tmp_path): """Dry run mirrors real-regen semantics for ejected (user-owned) files. A real regen never rewrites a user-owned artifact, so a customized copy must not show up as drift in the dry-run report. """ manager = TemplateManager() project_dir = _create_project( manager, project_name="dry-owned", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) safety_file = project_dir / ".claude" / "rules" / "safety.md" safety_file.write_text("# My Custom Safety Rules\n") config = yaml.safe_load((project_dir / "config.yml").read_text()) config.setdefault("scaffold", {}).setdefault("user_owned", []).append("rules/safety") (project_dir / "config.yml").write_text(yaml.dump(config)) manager.regenerate_claude_code(project_dir) assert safety_file.read_text() == "# My Custom Safety Rules\n" result = manager.regenerate_claude_code(project_dir, dry_run=True) assert ".claude/rules/safety.md" not in result["changed"] assert result["changed"] == [] def test_dry_run_detects_changes(self, tmp_path): """Dry run correctly detects what would change.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="dry-detect", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Disable a core server in config (will cause .mcp.json to change) config = yaml.safe_load((project_dir / "config.yml").read_text()) config["claude_code"] = {"servers": {"ariel": {"enabled": False}}} (project_dir / "config.yml").write_text(yaml.dump(config)) result = manager.regenerate_claude_code(project_dir, dry_run=True) assert ".mcp.json" in result["changed"] class TestGitignore: """Test that gitignore includes local (personal) settings but NOT shared artifacts.""" def test_gitignore_includes_local_settings(self, tmp_path): """Project .gitignore includes local settings but not shared generated files.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="gitignore-gen-test", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) gitignore = (project_dir / ".gitignore").read_text() # Local/personal settings ARE ignored assert "CLAUDE.local.md" in gitignore assert ".claude/settings.local.json" in gitignore # Shared generated artifacts are NOT ignored (they're committed) lines = [line.strip() for line in gitignore.splitlines()] assert "CLAUDE.md" not in lines assert ".mcp.json" not in lines class TestDisableServers: """Test disable_servers functionality.""" def _create_and_regen( self, tmp_path, disable_servers=None, disable_agents=None, custom_servers=None, template="control_assistant", ): """Helper: create project, set claude_code overrides, regen.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="disable-test", output_dir=tmp_path, data_bundle=template, context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root(template), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) cc = {} servers = {} agents = {} if disable_servers: for name in disable_servers: servers[name] = {"enabled": False} if custom_servers: servers.update(custom_servers) if disable_agents: for name in disable_agents: agents[name] = {"enabled": False} if servers: cc["servers"] = servers if agents: cc["agents"] = agents if cc: config["claude_code"] = cc (project_dir / "config.yml").write_text(yaml.dump(config)) result = manager.regenerate_claude_code(project_dir) return project_dir, result def test_disable_server_removes_from_mcp_json(self, tmp_path): """Disabling ariel removes it from .mcp.json.""" project_dir, _ = self._create_and_regen(tmp_path, disable_servers=["ariel"]) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) assert "ariel" not in mcp_data["mcpServers"] # Core servers should still be present assert "controls" in mcp_data["mcpServers"] def test_disable_server_removes_from_settings_allow(self, tmp_path): """Disabling ariel removes its tools from settings allow list.""" project_dir, _ = self._create_and_regen(tmp_path, disable_servers=["ariel"]) settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) allow = settings["permissions"]["allow"] for entry in allow: assert "ariel" not in entry, f"ariel found in allow: {entry}" def test_disable_server_removes_from_claude_md(self, tmp_path): """Disabling ariel removes ariel row from CLAUDE.md tool table.""" project_dir, _ = self._create_and_regen(tmp_path, disable_servers=["ariel"]) content = (project_dir / "CLAUDE.md").read_text() assert "ariel" not in content.lower() or "ariel" not in content def test_disable_agent_removes_agent_file(self, tmp_path): """Disabling logbook-search produces an empty agent file.""" project_dir, _ = self._create_and_regen(tmp_path, disable_agents=["logbook-search"]) agent_file = project_dir / ".claude" / "agents" / "logbook-search.md" if agent_file.exists(): content = agent_file.read_text().strip() # Disabled agents render to empty (or whitespace-only) files assert content == "", f"Expected empty file, got: {content[:100]}" def test_disable_agent_removes_task_from_settings(self, tmp_path): """Disabling logbook-search removes Task(logbook-search) from allow.""" project_dir, _ = self._create_and_regen(tmp_path, disable_agents=["logbook-search"]) settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) allow = settings["permissions"]["allow"] assert "Task(logbook-search)" not in allow def test_disable_agent_removes_from_claude_md(self, tmp_path): """Disabling logbook-search removes its delegation section from CLAUDE.md.""" project_dir, _ = self._create_and_regen(tmp_path, disable_agents=["logbook-search"]) content = (project_dir / "CLAUDE.md").read_text() # The delegation section should be gone assert "logbook-search` sub-agent" not in content def test_extra_server_added_to_mcp_json(self, tmp_path): """Custom server appears in .mcp.json.""" project_dir, _ = self._create_and_regen( tmp_path, custom_servers={"my-server": {"command": "node", "args": ["server.js"]}}, ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) assert "my-server" in mcp_data["mcpServers"] assert mcp_data["mcpServers"]["my-server"]["command"] == "node" def test_custom_server_permission_in_settings(self, tmp_path): """Custom server with explicit permissions gets them in settings.json.""" project_dir, _ = self._create_and_regen( tmp_path, custom_servers={ "my-server": { "command": "node", "args": ["server.js"], "permissions": {"ask": ["do_stuff"]}, } }, ) settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) ask = settings["permissions"]["ask"] assert "mcp__my-server__do_stuff" in ask def test_regen_preserves_url_servers(self, tmp_path): """URL servers in config.yml survive regen; transport drives .mcp.json's type.""" project_dir, _ = self._create_and_regen( tmp_path, custom_servers={ "remote-api": { "url": "http://remote:8001/mcp", "permissions": {"allow": ["search"]}, }, "legacy-api": { "transport": "sse", "url": "http://remote:8002/sse", }, }, ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) # No transport key → streamable-HTTP default. entry = mcp_data["mcpServers"]["remote-api"] assert entry == {"type": "http", "url": "http://remote:8001/mcp"} # Explicit transport: sse → rendered as an SSE server. entry = mcp_data["mcpServers"]["legacy-api"] assert entry == {"type": "sse", "url": "http://remote:8002/sse"} # Permissions should be in settings.json settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) assert "mcp__remote-api__search" in settings["permissions"]["allow"] def test_custom_server_env_preserves_var_placeholders(self, tmp_path, monkeypatch): """`${VAR}` placeholders in custom stdio server env survive into .mcp.json. Claude Code expands `${VAR}` / `${VAR:-default}` in `.mcp.json` env blocks at MCP server launch time. OSPREY must preserve the literal so the expansion happens at runtime — never bake an expanded (possibly empty) value into the generated artifact at build/regen time. """ # Var is unset at build time — common in CI image builds where # secrets aren't passed to image builds for safety. monkeypatch.delenv("EXAMPLE_SECRET", raising=False) project_dir, _ = self._create_and_regen( tmp_path, custom_servers={ "example-stdio": { "command": "node", "args": ["server.js"], "env": { "EXAMPLE_TOKEN": "${EXAMPLE_SECRET:-}", "EXAMPLE_URL": "https://example.invalid", }, "permissions": {"allow": ["do_stuff"]}, } }, ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) env = mcp_data["mcpServers"]["example-stdio"]["env"] assert env["EXAMPLE_TOKEN"] == "${EXAMPLE_SECRET:-}", ( f"Expected ${{EXAMPLE_SECRET:-}} to survive into .mcp.json verbatim, " f"got {env['EXAMPLE_TOKEN']!r}. Build-time expansion bakes empty secrets " f"into the artifact, blanking the inherited env at MCP launch time." ) # Non-var values should pass through unchanged assert env["EXAMPLE_URL"] == "https://example.invalid" def test_custom_server_env_preserves_placeholder_when_var_set(self, tmp_path, monkeypatch): """`${VAR}` placeholders survive even when VAR is set at build time. Build-time expansion is wrong even when the var IS set: secrets get baked into a build artifact that may be cached, distributed, or committed. Claude Code reads env at MCP launch — that's where expansion belongs. """ monkeypatch.setenv("EXAMPLE_SECRET", "shhh-not-supposed-to-be-baked-in") project_dir, _ = self._create_and_regen( tmp_path, custom_servers={ "example-stdio": { "command": "node", "args": ["server.js"], "env": {"EXAMPLE_TOKEN": "${EXAMPLE_SECRET}"}, "permissions": {"allow": ["do_stuff"]}, } }, ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) env = mcp_data["mcpServers"]["example-stdio"]["env"] assert env["EXAMPLE_TOKEN"] == "${EXAMPLE_SECRET}" assert "shhh" not in json.dumps(mcp_data), ( "Secret leaked into build artifact — env-var expansion happened at " "build time instead of being deferred to MCP server launch." ) def test_regen_with_project_root_override(self, tmp_path): """project_root_override changes paths in rendered output.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="override-test", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.generate_manifest(project_dir, "override-test", "control-assistant", {}) result = manager.regenerate_claude_code( project_dir, project_root_override="/app/als-assistant" ) # Verify the override path appears in rendered files mcp_data = json.loads((project_dir / ".mcp.json").read_text()) # Framework servers use project_root for env vars controls = mcp_data["mcpServers"].get("controls", {}) if "env" in controls: config_path = controls["env"].get("OSPREY_CONFIG", "") assert config_path.startswith("/app/als-assistant") assert "changed" in result or "unchanged" in result def test_disable_does_not_remove_safety_hooks(self, tmp_path): """Disabling a server doesn't remove hook script files.""" project_dir, _ = self._create_and_regen(tmp_path, disable_servers=["ariel"]) hooks_dir = project_dir / ".claude" / "hooks" assert hooks_dir.exists() hook_files = list(hooks_dir.glob("*.py")) assert len(hook_files) > 0 # Safety hooks should still exist hook_names = [f.name for f in hook_files] assert "osprey_writes_check.py" in hook_names assert "osprey_error_guidance.py" in hook_names def test_regen_summary_includes_active_lists(self, tmp_path): """Result dict contains active/disabled lists.""" _, result = self._create_and_regen(tmp_path, disable_servers=["ariel"]) assert "active_servers" in result assert "disabled_servers" in result assert "active_agents" in result assert "disabled_agents" in result assert "ariel" not in result["active_servers"] assert "ariel" in result["disabled_servers"] assert "controls" in result["active_servers"] def test_disable_core_server_allowed(self, tmp_path): """Users can disable any server including core ones.""" project_dir, result = self._create_and_regen(tmp_path, disable_servers=["ariel"]) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) assert "ariel" not in mcp_data["mcpServers"] assert "ariel" in result["disabled_servers"] def test_context_includes_overrides(self, tmp_path): """build_claude_code_context includes enabled_servers and enabled_agents.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-overrides", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) config["claude_code"] = { "servers": {"ariel": {"enabled": False}, "my-srv": {"command": "echo"}}, "agents": {"logbook-search": {"enabled": False}}, } (project_dir / "config.yml").write_text(yaml.dump(config)) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert "ariel" not in ctx["enabled_servers"] assert "logbook-search" not in ctx["enabled_agents"] # Data-driven lists assert any(s["name"] == "my-srv" and s["enabled"] for s in ctx["servers"]) assert any(s["name"] == "ariel" and not s["enabled"] for s in ctx["servers"]) def test_defaults_empty_when_no_claude_code_section(self, tmp_path): """Without claude_code section, core servers are enabled.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="ctx-defaults", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) # Core servers should all be enabled assert {"controls", "osprey_workspace", "ariel"} <= ctx["enabled_servers"] class TestRegenRelocation: """Rendering a project's artifacts against a root it does not live at. ``project_root_override`` is how a project built on a host renders the artifacts a COPY of it will use somewhere else — inside a container image, most of all. Everything below drives :meth:`TemplateManager.regenerate_claude_code` directly, which is the whole of that contract now: the standalone verb that used to wrap it is gone, and rewriting the recorded ``project_root`` in config.yml went with it (the container image's own path contract is Task 3.8's subject). What survives, and is pinned here, is that an override reaches the RENDERED artifacts and never writes to config.yml at all. """ def _create(self, tmp_path, name): manager = TemplateManager() return _create_project( manager, project_name=name, output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) def test_a_relocated_render_records_no_interpreter_path(self, tmp_path): """A render for another machine must name no interpreter at all. Not the one that ran the render, not any other: the interpreter is resolved from the filesystem where the artifacts are USED, and a path baked in here would be a host path that does not exist there. """ import sys project_dir = self._create(tmp_path, "rr-no-interp") config_file = project_dir / "config.yml" TemplateManager().regenerate_claude_code( project_dir, project_root_override="/app/rr-no-interp" ) text = config_file.read_text() config = yaml.safe_load(text) assert "python_env_path" not in config.get("execution", {}) assert sys.executable not in text, ( "a relocated render must not write the rendering interpreter into config.yml" ) def test_a_stale_recorded_interpreter_is_left_alone_and_stays_inert(self, tmp_path): """A legacy config's recorded interpreter is neither healed nor honoured. Older projects may still carry ``execution.python_env_path``. The render does not rewrite it — nothing reads it — and the artifacts it produces must not launch MCP servers with that stale path. """ import sys from osprey.utils.config_writer import config_update_fields stale = "/nonexistent/host/.venv/bin/python" project_dir = self._create(tmp_path, "rr-stale-env") config_file = project_dir / "config.yml" config_update_fields(config_file, {"execution.python_env_path": stale}) TemplateManager().regenerate_claude_code( project_dir, project_root_override=str(project_dir) ) config = yaml.safe_load(config_file.read_text()) assert config["execution"]["python_env_path"] == stale, ( "the render must leave the retired key untouched rather than healing it" ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) commands = {s.get("command") for s in mcp_data["mcpServers"].values()} assert stale not in commands, ( f"a stale recorded interpreter must never reach .mcp.json, got {commands}" ) assert sys.executable in commands, ( "the OSPREY-native servers must launch with the resolved interpreter " f"(this also proves the check above is not vacuous), got {commands}" ) def test_rendered_artifacts_reference_the_override_root(self, tmp_path): """The override has to reach the artifacts, or it changes nothing. ``.mcp.json`` is where it shows: every server's ``OSPREY_CONFIG`` is anchored on the project root, so an override that did not reach here would leave a relocated copy pointing back at the build host. """ project_dir = self._create(tmp_path, "rr-artifacts") TemplateManager().regenerate_claude_code( project_dir, project_root_override="/app/rr-artifacts" ) mcp_data = json.loads((project_dir / ".mcp.json").read_text()) controls = mcp_data["mcpServers"].get("controls", {}) if "env" in controls: config_path = controls["env"].get("OSPREY_CONFIG", "") assert config_path.startswith("/app/rr-artifacts") def test_an_override_never_writes_to_config_yml(self, tmp_path): """config.yml is an INPUT to the render, never an output of it. This is what makes an override safe to run twice, and what keeps a relocated render from silently editing the source it was derived from. """ project_dir = self._create(tmp_path, "rr-no-write") config_file = project_dir / "config.yml" original = config_file.read_text() TemplateManager().regenerate_claude_code( project_dir, project_root_override="/app/rr-no-write" ) assert config_file.read_text() == original class TestFacilityMd: """Test facility.md creation and preservation.""" def test_facility_md_created_on_init(self, tmp_path): """create_project() (osprey build path) creates .claude/rules/facility.md.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="facility-init", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) facility_file = project_dir / ".claude" / "rules" / "facility.md" assert facility_file.exists() content = facility_file.read_text() assert "Facility Identity" in content assert "Example Research Facility" in content def test_facility_md_user_owned_on_init(self, tmp_path): """Init auto-registers facility.md as user-owned in config.yml.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="facility-owned", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) user_owned = config.get("scaffold", {}).get("user_owned", []) assert "rules/facility" in user_owned # No overrides/ directory should exist assert not (project_dir / "overrides").exists() def test_facility_md_preserved_via_user_owned(self, tmp_path): """Regen preserves customized facility.md via user_owned mechanism.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="facility-preserve", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Customize facility.md in-place facility_file = project_dir / ".claude" / "rules" / "facility.md" custom_content = "# My Custom Facility\n\nAdvanced Light Source at LBNL\n" facility_file.write_text(custom_content) # Regen manager.regenerate_claude_code(project_dir) # Verify custom content preserved assert facility_file.read_text() == custom_content def test_facility_md_created_on_regen_if_missing(self, tmp_path): """If facility.md doesn't exist and not user-owned, regen creates it.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="facility-regen-create", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Delete facility.md and remove from user_owned facility_file = project_dir / ".claude" / "rules" / "facility.md" facility_file.unlink() assert not facility_file.exists() # Remove from user_owned so regen will recreate it config = yaml.safe_load((project_dir / "config.yml").read_text()) if "scaffold" in config and "user_owned" in config["scaffold"]: config["scaffold"]["user_owned"] = [ n for n in config["scaffold"]["user_owned"] if n != "rules/facility" ] (project_dir / "config.yml").write_text(yaml.dump(config)) # Regen should recreate it manager.regenerate_claude_code(project_dir) assert facility_file.exists() content = facility_file.read_text() assert "Facility Identity" in content class TestUserOwned: """Test user_owned configuration for skipping files during regen.""" def test_user_owned_default_empty(self, tmp_path): """Without user_owned in config, list is empty.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="owned-defaults", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) # Remove auto-registered facility if "scaffold" in config and "user_owned" in config["scaffold"]: config["scaffold"]["user_owned"] = [] (project_dir / "config.yml").write_text(yaml.dump(config)) ctx = claude_code.build_claude_code_context( manager.template_root, manager.jinja_env, project_dir, config ) assert ctx["user_owned"] == [] def test_user_owned_controls_regen(self, tmp_path): """Adding a file to user_owned prevents overwrite on regen.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="owned-regen", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Customize safety.md safety_file = project_dir / ".claude" / "rules" / "safety.md" custom_safety = "# My Custom Safety Rules\n\nCustom content here.\n" safety_file.write_text(custom_safety) # Add safety to user_owned config = yaml.safe_load((project_dir / "config.yml").read_text()) if "scaffold" not in config: config["scaffold"] = {} user_owned = config["scaffold"].get("user_owned", []) user_owned.append("rules/safety") config["scaffold"]["user_owned"] = user_owned (project_dir / "config.yml").write_text(yaml.dump(config)) # Regen manager.regenerate_claude_code(project_dir) # safety.md should be preserved assert safety_file.read_text() == custom_safety def test_agents_never_user_owned(self, tmp_path): """Agent files are always regenerated even if user_owned list is long.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="owned-agents", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # Regen with some user_owned entries config = yaml.safe_load((project_dir / "config.yml").read_text()) if "scaffold" not in config: config["scaffold"] = {} config["scaffold"]["user_owned"] = ["rules/safety", "rules/error-handling"] (project_dir / "config.yml").write_text(yaml.dump(config)) # Regen manager.regenerate_claude_code(project_dir) # Agent files should still exist (they're auto-managed) agents_dir = project_dir / ".claude" / "agents" if agents_dir.exists(): agent_files = list(agents_dir.glob("*.md")) assert len(agent_files) > 0 class TestSettingsJsonValidity: """Test that settings.json.j2 renders valid JSON across all configurations. Regression test for trailing-comma bug where conditional Jinja2 blocks in the hooks section could leave a trailing comma before a closing bracket, producing invalid JSON (e.g., `},]`). """ @pytest.mark.parametrize("data_bundle", ["control_assistant"]) def test_all_templates_produce_valid_settings_json(self, tmp_path, data_bundle): """Every built-in template produces valid settings.json.""" manager = TemplateManager() project_dir = _create_project( manager, project_name=f"json-valid-{data_bundle}", output_dir=tmp_path, data_bundle=data_bundle, context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root(data_bundle), ) settings_path = project_dir / ".claude" / "settings.json" data = json.loads(settings_path.read_text()) assert "permissions" in data assert "hooks" in data @pytest.mark.parametrize( "disable_servers,label", [ (["controls"], "controls-disabled"), (["ariel"], "ariel-disabled"), (["osprey_workspace"], "workspace-disabled"), (["controls", "osprey_workspace"], "controls-and-workspace-disabled"), ( ["controls", "osprey_workspace", "ariel"], "all-core-disabled", ), ], ids=lambda x: x if isinstance(x, str) else None, ) def test_disable_servers_produces_valid_json(self, tmp_path, disable_servers, label): """Disabling various server combinations still produces valid JSON.""" manager = TemplateManager() project_dir = _create_project( manager, project_name=f"json-{label}", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) servers_override = {name: {"enabled": False} for name in disable_servers} config["claude_code"] = {"servers": servers_override} (project_dir / "config.yml").write_text(yaml.dump(config)) manager.regenerate_claude_code(project_dir) settings_path = project_dir / ".claude" / "settings.json" data = json.loads(settings_path.read_text()) assert "permissions" in data assert "hooks" in data def test_all_optional_features_enabled(self, tmp_path): """Valid JSON when all optional features (channel-finder) are on.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="json-all-features", output_dir=tmp_path, data_bundle="control_assistant", context={ "channel_finder_pipeline": "hierarchical", "channel_finder_mode": "hierarchical", }, data_root=_bundle_data_root("control_assistant"), ) settings_path = project_dir / ".claude" / "settings.json" data = json.loads(settings_path.read_text()) assert "permissions" in data assert "hooks" in data def test_custom_servers_produce_valid_json(self, tmp_path): """Adding custom servers still produces valid JSON.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="json-custom-servers", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config = yaml.safe_load((project_dir / "config.yml").read_text()) config["claude_code"] = { "servers": { "my-server": {"command": "node", "args": ["server.js"]}, }, } (project_dir / "config.yml").write_text(yaml.dump(config)) manager.regenerate_claude_code(project_dir) settings_path = project_dir / ".claude" / "settings.json" data = json.loads(settings_path.read_text()) assert "permissions" in data def test_all_mcp_json_files_are_valid(self, tmp_path): """Every template also produces valid .mcp.json.""" for data_bundle in ["control_assistant"]: project_dir = _create_project( TemplateManager(), project_name=f"mcp-valid-{data_bundle}", output_dir=tmp_path, data_bundle=data_bundle, context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root(data_bundle), ) mcp_path = project_dir / ".mcp.json" data = json.loads(mcp_path.read_text()) assert "mcpServers" in data class TestWritesToggleRegen: """Flipping control_system.writes_enabled re-renders the kill-switch deny entry. This is the GitHub #244 regression: editing config.yml alone leaves settings.json's permissions.deny stale, so a regen must add/remove mcp__controls__channel_write to match the config. """ @staticmethod def _deny(project_dir): settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) return settings["permissions"]["deny"] def test_toggle_writes_updates_deny(self, tmp_path): from osprey.utils.config_writer import config_update_fields manager = TemplateManager() project_dir = _create_project( manager, project_name="writes-toggle", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) config_path = project_dir / "config.yml" # Writes disabled → kill-switch baked into deny. config_update_fields(config_path, {"control_system.writes_enabled": False}) manager.regenerate_claude_code(project_dir) assert "mcp__controls__channel_write" in self._deny(project_dir) # Enable writes → regen drops the deny entry and reports settings.json changed. config_update_fields(config_path, {"control_system.writes_enabled": True}) result = manager.regenerate_claude_code(project_dir) assert "mcp__controls__channel_write" not in self._deny(project_dir) assert any("settings.json" in f for f in result["changed"]), ( f"settings.json should be in changed list, got {result['changed']}" ) def test_regen_if_drift_only_regens_when_changed(self, tmp_path): """regen_if_drift returns [] when in sync and the changed list when drifted.""" from osprey.utils.config_writer import config_update_fields manager = TemplateManager() project_dir = _create_project( manager, project_name="drift-gate", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.regenerate_claude_code(project_dir) # Already in sync → no-op, and crucially NO real regen. Observed on # `.mcp.json`'s mtime: a real regen rewrites it (identical bytes, new # mtime) while the in-sync path returns before writing anything, and # only ever stamps `.claude/settings.json` — so settings.json cannot # serve as this witness and .mcp.json can. mcp_json = project_dir / ".mcp.json" before = mcp_json.stat().st_mtime_ns assert manager.regen_if_drift(project_dir) == [] assert mcp_json.stat().st_mtime_ns == before, ( "in-sync regen_if_drift must not re-render the Claude Code artifacts" ) # Drift the config by flipping writes_enabled → regen_if_drift reports the change. config_path = project_dir / "config.yml" cfg = yaml.safe_load(config_path.read_text()) current = bool(cfg.get("control_system", {}).get("writes_enabled", False)) config_update_fields(config_path, {"control_system.writes_enabled": not current}) changed = manager.regen_if_drift(project_dir) # The other half of the witness above: a real regen DOES move that # mtime, so the equality asserted for the in-sync path is a property of # the no-op and not of the observable. assert mcp_json.stat().st_mtime_ns != before assert any("settings.json" in f for f in changed) def test_regen_if_drift_stamps_settings_mtime_on_cosmetic_edit(self, tmp_path): """An edit that changes no artifact must still clear the mtime drift signal. The SessionStart drift hook compares config.yml's mtime against settings.json's. A cosmetic edit (e.g. a YAML comment, or a runtime-read field) makes config.yml newer while regen_if_drift correctly finds nothing to regenerate — without an mtime stamp the hook would warn at every session start until a full `osprey build`, training operators to ignore the warning. """ manager = TemplateManager() project_dir = _create_project( manager, project_name="mtime-stamp", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.regenerate_claude_code(project_dir) config_path = project_dir / "config.yml" settings_path = project_dir / ".claude" / "settings.json" # Cosmetic edit: a YAML comment changes no rendered artifact. config_path.write_text(config_path.read_text() + "\n# operator note\n") base = 1_700_000_000 os.utime(settings_path, (base, base)) os.utime(config_path, (base + 100, base + 100)) assert manager.regen_if_drift(project_dir) == [] assert settings_path.stat().st_mtime >= config_path.stat().st_mtime, ( "in-sync regen_if_drift must stamp settings.json so the drift hook " "does not warn on an already-verified config" ) def test_regen_if_drift_noops_without_rendered_claude(self, tmp_path): """regen_if_drift is re-sync only — it never bootstraps a .claude/ from scratch.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="no-claude", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) # A project with config.yml but no rendered settings.json (never built/regenerated). settings = project_dir / ".claude" / "settings.json" if settings.exists(): settings.unlink() assert manager.regen_if_drift(project_dir) == [] # The guard must not create the artifact it was guarding against. assert not settings.exists() def test_session_start_drift_hook_wired_in_settings(self, tmp_path): """The rendered settings.json wires the config-drift hook on SessionStart.""" manager = TemplateManager() project_dir = _create_project( manager, project_name="drift-wiring", output_dir=tmp_path, data_bundle="control_assistant", context={"channel_finder_mode": "hierarchical"}, data_root=_bundle_data_root("control_assistant"), ) manager.regenerate_claude_code(project_dir) settings = json.loads((project_dir / ".claude" / "settings.json").read_text()) session_start = settings["hooks"]["SessionStart"] cmds = [h["command"] for entry in session_start for h in entry["hooks"]] assert any("osprey_config_drift.py" in c for c in cmds), cmds # And the hook file is actually deployed alongside the wiring. assert (project_dir / ".claude" / "hooks" / "osprey_config_drift.py").exists() if __name__ == "__main__": pytest.main([__file__, "-v"])
"""Tests for Claude Code artifact regeneration.
``TemplateManager.regenerate_claude_code`` rebuilds a project's ``.claude/``
tree, ``.mcp.json`` and ``CLAUDE.md`` from its ``config.yml``. It runs as a
step of ``osprey build`` — there is no standalone regeneration verb — and these
tests drive it directly, which is where its contract actually lives: the
artifacts it produces, the user files it preserves, the backup it takes, and
the safety hooks it must never drop between one render and the next.
"""
import json
import os
import re
import shutil
from pathlib import Path
import pytest
import yaml
from osprey.build.claude_code_resolver import MANAGED_ENV_VARS
from osprey.cli.templates import claude_code
from osprey.cli.templates.manager import TemplateManager
def _bundle_data_root(bundle: str = "control_assistant") -> Path:
"""The tree these fixtures give ``create_project`` as the profile's ``data:``.
A build copies the tree its profile's ``data:`` key names, and that key is
required — nothing falls back to a packaged tree any more. These fixtures
render straight from a bundle rather than from a profile, so they name the
tree that bundle packages, which is the same content the render used to
reach for on its own.
"""
return Path(TemplateManager().template_root) / "apps" / bundle / "data"
def _create_project(manager: TemplateManager, **kwargs) -> Path:
"""``create_project`` plus the manifest stamp a real build writes next.
A build stamps ``.osprey-manifest.json`` immediately after the render, and
the Claude Code regen reads the preset back out of it to learn which
artifacts the project selected. A fixture that renders without stamping is
not a project any build produces: it regenerates with an empty artifact
selection, and the write-gate lint rightly refuses the result.
"""
project = manager.create_project(**kwargs)
bundle = kwargs.setdefault("data_bundle", "control_assistant")
manager.generate_manifest(
project,
kwargs["project_name"],
bundle.replace("_", "-"),
{},
# The selection the render was made with, exactly as a build stamps it:
# a site that hands `create_project` its own `artifacts=` must get that
# selection back on the regen, not the bundle's full list.
artifacts=manager._effective_artifacts(bundle, kwargs.get("artifacts")),
)
return project
# Hook modules that are shipped into .claude/hooks/ as importable support code
# rather than as hook entry points. They are deliberately absent from
# settings.json and are excluded from the settings <-> hooks parity invariant.
HOOK_LIBRARY_MODULES = {"osprey_hook_log.py", "osprey_target_state.py"}
_HOOK_BASENAME_RE = re.compile(r"osprey_[A-Za-z0-9_]+\.py")
def _referenced_hook_basenames(settings: dict) -> dict[str, list[str]]:
"""Map each ``osprey_*.py`` basename referenced in settings.json to its events.
Hook commands are shell strings whose shape varies by wiring route (quoted
absolute interpreter vs. literal ``python3``, trailing ``2>/dev/null || true``),
so the basename is extracted by pattern rather than by matching whole commands.
"""
found: dict[str, list[str]] = {}
for event, entries in settings.get("hooks", {}).items():
for entry in entries:
for hook in entry.get("hooks", []):
for basename in _HOOK_BASENAME_RE.findall(hook.get("command", "")):
found.setdefault(basename, []).append(event)
return found
class TestBuildClaudeCodeContext:
"""Test build_claude_code_context() reconstructs correct template vars."""
def test_basic_config(self, tmp_path):
"""Basic config produces correct base context vars."""
manager = TemplateManager()
project_dir = _create_project(
manager,
project_name="ctx-basic",
output_dir=tmp_path,
data_bundle="control_assistant",
context={"channel_finder_mode": "hierarchical"},
data_root=_bundle_data_root("control_assistant"),
)
config = yaml.safe_load((project_dir / "config.yml").read_text())

Xet Storage Details

Size:
82.3 kB
·
Xet hash:
6ba39501acf7c8f44e50a75bc06f2528e9a78c058f6633a117d6519f6d558b18

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.