diff --git a/src/specify_cli/agents.py b/src/specify_cli/agents.py index c0401f37ee..a3aec44416 100644 --- a/src/specify_cli/agents.py +++ b/src/specify_cli/agents.py @@ -743,7 +743,9 @@ def register_commands( raise ValueError( "resource_hashes is required when registering commands with skill resources" ) - commands_dir.mkdir(parents=True, exist_ok=True) + from .integrations._file_changes import make_directories + + make_directories(commands_dir) registered = [] source_root = source_dir.resolve() @@ -949,7 +951,7 @@ def register_commands( if agent_name == "generic" and (dest_file.exists() or dest_file.is_symlink()): if not self._generic_owned_output(dest_file, source_id, project_root): continue - dest_file.parent.mkdir(parents=True, exist_ok=True) + make_directories(dest_file.parent) self._write_registered_output( dest_file, output, @@ -1048,7 +1050,7 @@ def register_commands( if agent_name == "generic" and (alias_file.exists() or alias_file.is_symlink()): if not self._generic_owned_output(alias_file, source_id, project_root): continue - alias_file.parent.mkdir(parents=True, exist_ok=True) + make_directories(alias_file.parent) self._write_registered_output( alias_file, alias_output, @@ -1085,7 +1087,7 @@ def _write_registered_output( agent_config: dict[str, Any] | None = None, ) -> None: """Write a rendered agent artifact, optionally as a dev-mode symlink.""" - from .integrations._file_changes import after_file_change, before_file_change + from .integrations._file_changes import after_file_change, before_file_change, make_directories if dest_file.is_symlink(): before_file_change(dest_file, removal=True) @@ -1106,7 +1108,7 @@ def _write_registered_output( try: before_file_change(cache_file) - cache_file.parent.mkdir(parents=True, exist_ok=True) + make_directories(cache_file.parent) cache_file.write_text(content, encoding="utf-8") after_file_change(cache_file) if dest_file.exists() or dest_file.is_symlink(): @@ -1135,12 +1137,12 @@ def write_copilot_prompt(project_root: Path, cmd_name: str) -> None: raise ValueError( f"Invalid Copilot prompt name {cmd_name!r}: {name_reason}" ) + from .integrations._file_changes import after_file_change, before_file_change, make_directories + prompts_dir = project_root / ".github" / "prompts" - prompts_dir.mkdir(parents=True, exist_ok=True) prompt_file = prompts_dir / f"{cmd_name}.prompt.md" CommandRegistrar._ensure_inside(prompt_file, prompts_dir) - prompt_file.parent.mkdir(parents=True, exist_ok=True) - from .integrations._file_changes import after_file_change, before_file_change + make_directories(prompt_file.parent) before_file_change(prompt_file) prompt_file.write_text(f"---\nagent: {cmd_name}\n---\n", encoding="utf-8") diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index dc0ab5a7ee..00b8fa90d5 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -1330,10 +1330,11 @@ def _get_skills_dir(self, *, create: bool = True) -> Optional[Path]: load_init_options, resolve_active_skills_dir, ) + from ..integrations._file_changes import make_directories def _ensure_usable(skills_dir: Path) -> Optional[Path]: try: - skills_dir.mkdir(parents=True, exist_ok=True) + make_directories(skills_dir) if not skills_dir.is_dir(): raise NotADirectoryError(f"{skills_dir} is not a directory") except (OSError, ValueError) as exc: @@ -1608,7 +1609,7 @@ def _register_extension_skills( from ..agents import CommandRegistrar from ..integrations import get_integration from ..integrations.base import IntegrationBase - from ..integrations._file_changes import changing_file, unlink, write_text + from ..integrations._file_changes import changing_file, make_directories, unlink, write_text written: List[str] = [] opts = load_init_options(self.project_root) @@ -1705,7 +1706,7 @@ def _replacement(match: re.Match[str]) -> str: # Create skill directory; track whether we created it so we can clean # up safely if reading the source file subsequently fails. created_now = not skill_subdir.exists() - skill_subdir.mkdir(parents=True, exist_ok=True) + make_directories(skill_subdir) # Parse the command file — guard against IsADirectoryError / decode errors try: @@ -1765,7 +1766,7 @@ def _replacement(match: re.Match[str]) -> str: if use_dev_symlink: try: - cache_file.parent.mkdir(parents=True, exist_ok=True) + make_directories(cache_file.parent) write_text(cache_file, skill_content, encoding="utf-8") if skill_file.exists() or skill_file.is_symlink(): unlink(skill_file) @@ -2667,6 +2668,22 @@ def install_from_directory( # extension (configs stranded in .backup/). did_remove = False if force and self.registry.is_installed(manifest.id): + if not generic_active: + from ..file_helper import FileHelper, FileHelperError + + try: + with FileHelper(self.project_root) as files: + try: + configs = files.iterdir( + dest_dir.relative_to(self.project_root), + select=lambda name: name.endswith(("-config.yml", "-config.local.yml")), + ) + except FileNotFoundError: + configs = () + for config in configs: + files.read_bytes(config) + except (OSError, FileHelperError) as exc: + raise ValidationError(f"Cannot preserve config for '{manifest.id}': {exc}") from exc # Clear any stale backup from a previous remove so that only the # backup produced by the current remove() call is restored later. backup_config_dir = self.extensions_dir / ".backup" / manifest.id @@ -2679,7 +2696,9 @@ def install_from_directory( shutil.rmtree(backup_config_dir) elif backup_config_dir.exists(): backup_config_dir.unlink() - did_remove = self.remove(manifest.id) + # Native installs use the durable kept-config rescue below so + # registration rollback and later retries preserve user edits. + did_remove = self.remove(manifest.id, keep_config=not generic_active) finally: after_file_change(dest_dir) after_file_change(backup_config_dir) @@ -3191,12 +3210,23 @@ def rollback_generic_registration() -> None: registry_started = False from ._skill_resources import resolve_skill_resources, track_skill_resource_writes - write_tracking = contextlib.ExitStack() - attempt_resource_writes = write_tracking.enter_context(track_skill_resource_writes()) - try: - # Register commands with AI agents (active integration only, #2948) - resource_hashes = {} if did_remove else copy.deepcopy(previous_resource_hashes) + from ..integrations._lifecycle import extension_registration_journal + output_journal = contextlib.nullcontext() + if not generic_active: + project = self.project_root.absolute() + home_scopes = [ + directory for directory, root in self._extension_skill_candidate_dirs().items() + if root != project + ] + output_journal = extension_registration_journal(self.project_root, home_scopes) + resource_hashes = {} if did_remove else copy.deepcopy(previous_resource_hashes) + hook_executor = HookExecutor(self.project_root) + + def publish_outputs() -> None: + nonlocal hooks_started, registry_started + + # Register commands with AI agents (active integration only, #2948) for command in manifest.commands: if command.get("resources"): resolve_skill_resources(dest_dir, command["resources"]) @@ -3232,14 +3262,13 @@ def rollback_generic_registration() -> None: ) # Register hooks and update installed list in extensions.yml - hook_executor = HookExecutor(self.project_root) hooks_started = True hook_executor.register_hooks(manifest) - # Restore config files from backup when --force triggered a removal. + # Generic force reinstalls restore config files from their backup. # Only restore *.yml config files to match what remove() backs up, # so unexpected artifacts in .backup/ are not resurrected. - if did_remove: + if did_remove and generic_active: backup_config_dir = self.extensions_dir / ".backup" / manifest.id if backup_config_dir.is_symlink(): backup_config_dir.unlink() @@ -3280,42 +3309,52 @@ def rollback_generic_registration() -> None: registry_entry["skill_resource_hashes"] = resource_hashes if generic_active: registry_entry["generic_artifact_hashes"] = generic_hashes - self.registry.add(manifest.id, registry_entry) - except Exception as exc: - # Any failed commit must retire outputs before the original error - # is re-raised, including errors from hook serialization. - if register_commands and generic_active and manifest.commands: - rollback_errors = [] - if registry_started: + # The native journal restores the registry file, but the + # manager also needs its cached state restored for a plain retry. + registry_snapshot = copy.deepcopy(self.registry.data) if not generic_active else None + try: + self.registry.add(manifest.id, registry_entry) + except BaseException: + if registry_snapshot is not None: + self.registry.data = registry_snapshot + raise + + with output_journal, track_skill_resource_writes() as attempt_resource_writes: + try: + publish_outputs() + except Exception as exc: + # Any failed commit must retire outputs before the original error + # is re-raised, including errors from hook serialization. + if register_commands and generic_active and manifest.commands: + rollback_errors = [] + if registry_started: + try: + self.registry.remove(manifest.id) + except Exception as error: + rollback_errors.append(f"registry: {error}") + if hooks_started: + try: + hook_executor.unregister_hooks(manifest.id) + except Exception as error: + rollback_errors.append(f"hooks: {error}") try: - self.registry.remove(manifest.id) + with changing_file(dest_dir, removal=True): + rollback_generic_registration() except Exception as error: - rollback_errors.append(f"registry: {error}") - if hooks_started: + rollback_errors.append(f"artifacts: {error}") + if rollback_errors: + raise ExtensionError( + f"Generic registration failed ({exc}); rollback failed: " + + "; ".join(rollback_errors) + ) from exc + elif generic_active: try: - hook_executor.unregister_hooks(manifest.id) + rollback_install_resources() except Exception as error: - rollback_errors.append(f"hooks: {error}") - try: - with changing_file(dest_dir, removal=True): - rollback_generic_registration() - except Exception as error: - rollback_errors.append(f"artifacts: {error}") - if rollback_errors: - raise ExtensionError( - f"Generic registration failed ({exc}); rollback failed: " - + "; ".join(rollback_errors) - ) from exc - else: - try: - rollback_install_resources() - except Exception as error: - raise ExtensionError( - f"Extension registration failed ({exc}); resource rollback failed: {error}" - ) from exc - raise - finally: - write_tracking.close() + raise ExtensionError( + f"Extension registration failed ({exc}); resource rollback failed: {error}" + ) from exc + raise if did_remove: backup_config_dir = self.extensions_dir / ".backup" / manifest.id @@ -3699,6 +3738,8 @@ def remove(self, extension_id: str, keep_config: bool = False) -> bool: ) if keep_config: + from ..file_helper import FileHelper + # Preserve config files, only remove non-config files if extension_dir.exists(): for child in extension_dir.iterdir(): @@ -3708,10 +3749,9 @@ def remove(self, extension_id: str, keep_config: bool = False) -> bool: or child.name.endswith("-config.local.yml") ): continue - if child.is_dir(): - shutil.rmtree(child) - else: - child.unlink() + # Delete a link itself and leave its target intact. + with FileHelper(self.project_root, allow_symlinks=True) as files: + files.delete(child.relative_to(self.project_root), recursive=True) # Write a provenance marker so install_from_directory can # distinguish this --keep-config leftover from a directory left # by a partially-failed install (which must not have its diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index d83c55d86d..6f47f462e3 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -252,6 +252,11 @@ def __post_init__(self) -> None: object.__setattr__(self, "_windows_root_handle", windows_root_handle) object.__setattr__(self, "_root_cleanup", finalize(self, resources.pop_all().close)) + @property + def canonical_root(self) -> Path: + """Return the resolved identity of the trusted operation root.""" + return self._canonical_root + def close(self) -> None: """Release retained root handles; closing more than once is harmless.""" self._root_cleanup() diff --git a/src/specify_cli/integrations/_file_changes.py b/src/specify_cli/integrations/_file_changes.py index a9b0888b89..88b6421609 100644 --- a/src/specify_cli/integrations/_file_changes.py +++ b/src/specify_cli/integrations/_file_changes.py @@ -17,6 +17,9 @@ directory_creation_observer: ContextVar[Callable[[Path], None] | None] = ContextVar( "integration_directory_creation_observer", default=None ) +directory_creation_validator: ContextVar[Callable[[Path], None] | None] = ContextVar( + "integration_directory_creation_validator", default=None +) def make_directories(path: Path) -> None: @@ -24,8 +27,12 @@ def make_directories(path: Path) -> None: Only directories this call's own ``mkdir()`` created are reported, so a failed operation's rollback can remove them without touching one that - appeared from elsewhere in the meantime. + appeared from elsewhere in the meantime. An active validator checks the + complete requested path before any directory is created. """ + validator = directory_creation_validator.get() + if validator is not None: + validator(path) observer = directory_creation_observer.get() if observer is None: path.mkdir(parents=True, exist_ok=True) diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index af61010c42..04013fd8b7 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -9,7 +9,7 @@ import shutil import stat import tempfile -from contextlib import ExitStack, contextmanager +from contextlib import ExitStack, contextmanager, nullcontext from contextvars import ContextVar from functools import wraps from pathlib import Path @@ -25,7 +25,11 @@ try_read_integration_json, ) from . import BUILTIN_INTEGRATION_KEYS, INTEGRATION_REGISTRY, installer -from ._file_changes import directory_creation_observer, file_change_observer +from ._file_changes import ( + directory_creation_observer, + directory_creation_validator, + file_change_observer, +) _init_directory: ContextVar[tuple[Path, bool, list[Path]] | None] = ContextVar( "external_integration_init_directory", default=None @@ -33,6 +37,9 @@ _success_messages: ContextVar[list[str] | None] = ContextVar( "external_integration_success_messages", default=None ) +_active_file_journal: ContextVar[_FileJournal | None] = ContextVar( + "active_integration_file_journal", default=None +) _MAX_BACKUP_BYTES = 128 * 1024 * 1024 _MAX_BACKUP_ENTRIES = 4096 @@ -446,10 +453,11 @@ def _journalled( backup = Path(tempfile.mkdtemp(prefix="speckit-integration-rollback-")) try: journal = _FileJournal(root, paths, backup, initial, tuple(home_scopes)) + journal_token = _active_file_journal.set(journal) token = file_change_observer.set(journal.observe) directory_token = directory_creation_observer.set(journal.directory_created) try: - yield + yield journal except BaseException as operation_error: # Keep the snapshots unless restoring them completes cleanly. outcome["retained"] = True @@ -478,6 +486,7 @@ def _journalled( ) from operation_error raise finally: + _active_file_journal.reset(journal_token) if token is not None: file_change_observer.reset(token) if directory_token is not None: @@ -512,6 +521,76 @@ def writable_and_retry(function, path, _exc_info): shutil.rmtree(backup, onerror=writable_and_retry) +@contextmanager +def extension_registration_journal(root: Path, home_scopes: list[Path]): + """Roll back the writes made while publishing an extension's outputs.""" + from ..extensions import ExtensionError + from ..file_helper import FileHelper + + active = _active_file_journal.get() + if active is None and lifecycle_owns_rollback(): + yield + return + + if active is not None: + transaction = nullcontext(active) + project_path = Path.absolute + else: + with FileHelper(root) as project_files: + project = project_files.root + canonical = project_files.canonical_root + home = Path.home().absolute() + canonical_home = home + if home_scopes: + with FileHelper(home) as home_files: + canonical_home = home_files.canonical_root + + def home_path(path: Path) -> Path: + if path.is_relative_to(canonical_home): + return home / path.relative_to(canonical_home) + return path + + def project_path(path: Path) -> Path: + absolute = path.absolute() + if absolute.is_relative_to(project): + return canonical / absolute.relative_to(project) + if absolute.is_relative_to(canonical): + return absolute + return home_path(absolute) + + scopes = [home_path(scope) for scope in home_scopes] + transaction = _journalled(canonical, [], scopes, {"retained": False}, initial={}) + + with transaction as journal: + observe = file_change_observer.get() + created = directory_creation_observer.get() + assert observe is not None and created is not None + + def observe_output(path: Path, before: bool, removal: bool) -> None: + try: + observe(project_path(path), before, removal) + except installer.IntegrationInstallError as exc: + # Registration skips invalid commands. A journal refusal must + # instead fail the installation before committing the registry. + raise ExtensionError(f"Cannot register extension output: {exc}") from exc + + def validate_output_directory(path: Path) -> None: + try: + journal.safe_path(project_path(path), allow_leaf_symlink=False) + except installer.IntegrationInstallError as exc: + raise ExtensionError(f"Cannot register extension output: {exc}") from exc + + writes = file_change_observer.set(observe_output) + directories = directory_creation_observer.set(lambda path: created(project_path(path))) + validation = directory_creation_validator.set(validate_output_directory) + try: + yield + finally: + directory_creation_validator.reset(validation) + directory_creation_observer.reset(directories) + file_change_observer.reset(writes) + + @contextmanager def builtin_journal(root: Path, key: str, manifest_files, discover_folders=lambda: ()) -> Any: """Journal a built-in upgrade or init up to its manifest and state commit. diff --git a/tests/test_extension_skills.py b/tests/test_extension_skills.py index e59686d5f6..ccc22a08d7 100644 --- a/tests/test_extension_skills.py +++ b/tests/test_extension_skills.py @@ -3169,6 +3169,314 @@ def test_force_true_with_preexisting_dir_but_no_skill_file( # ===== Extension Skill Unregistration Tests ===== +class TestFailedInstallRollsBackNativeOutputs: + """A failed ``extension add`` must not strand native skill outputs (#5379). + + When installation fails after command registration (hook registration or + the final registry write), the rollback removed the installed package and + registry entry but left the native ``/speckit-*/SKILL.md`` + outputs behind, unrecorded and unowned by any later lifecycle operation. + The generic route's ``rollback_generic_registration`` already removes its + outputs; these pin the equivalent for the native route. + """ + + def _install_expecting_failure(self, project_dir, temp_dir): + from specify_cli.extensions import ExtensionError + + manager = ExtensionManager(project_dir) + with pytest.raises((ExtensionError, RuntimeError)): + manager.install_from_directory( + _create_extension_dir(temp_dir), "1.0.0", register_commands=True + ) + return manager + + def _assert_no_outputs(self, project_dir, manager): + skills_root = project_dir / ".claude" / "skills" + for name in ("speckit-test-ext-hello", "speckit-test-ext-world"): + assert not (skills_root / name).exists(), ( + f"failed install must not leave {name} behind (#5379)" + ) + assert not manager.registry.is_installed("test-ext") + + def test_hook_registration_failure_removes_native_skill_outputs( + self, project_dir, temp_dir, monkeypatch + ): + from specify_cli.extensions import HookExecutor + + _create_init_options(project_dir, ai="claude", ai_skills=True) + + def boom(self, manifest): + raise RuntimeError("simulated hook-write failure") + + monkeypatch.setattr(HookExecutor, "register_hooks", boom) + manager = self._install_expecting_failure(project_dir, temp_dir) + self._assert_no_outputs(project_dir, manager) + + def test_registry_failure_rolls_back_home_skills_and_project_marker( + self, project_dir, temp_dir, monkeypatch + ): + from specify_cli.extensions import ExtensionRegistry + + home = temp_dir / "home" + home.mkdir() + monkeypatch.setattr(Path, "home", lambda: home) + _create_init_options(project_dir, ai="hermes", ai_skills=True) + skills = home / ".hermes/skills" + existing = skills / "speckit-test-ext-hello/SKILL.md" + created = skills / "speckit-test-ext-world" + unrelated = skills / "user-skill/SKILL.md" + marker = project_dir / ".hermes" + original = b"---\nmetadata:\n source: test-ext:commands/hello.md\n---\nPrior output\n" + for path, content in ((existing, original), (unrelated, b"User skill\n")): + path.parent.mkdir(parents=True) + path.write_bytes(content) + + manager = ExtensionManager(project_dir) + source = _create_extension_dir(temp_dir) + + def fail_registry(registry): + assert existing.read_bytes() != original + assert (created / "SKILL.md").is_file() + assert (marker / "skills").is_dir() + raise RuntimeError("simulated registry-write failure") + + with monkeypatch.context() as patch: + patch.setattr(ExtensionRegistry, "_save", fail_registry) + with pytest.raises(RuntimeError, match="simulated registry-write failure"): + manager.install_from_directory(source, "1.0.0") + + assert existing.read_bytes() == original + assert not created.exists() + assert not marker.exists() + assert unrelated.read_bytes() == b"User skill\n" + assert not manager.registry.is_installed("test-ext") + manager.install_from_directory(source, "1.0.0") + assert existing.read_bytes() != original + assert (created / "SKILL.md").is_file() + + def test_registry_failure_restores_preexisting_native_output( + self, project_dir, temp_dir, monkeypatch + ): + from specify_cli.extensions import ExtensionRegistry + + _create_init_options(project_dir, ai="claude", ai_skills=False) + skill = project_dir / ".claude/skills/speckit-test-ext-hello/SKILL.md" + skill.parent.mkdir(parents=True) + original = "---\nmetadata:\n source: test-ext:commands/hello.md\n---\nPrior output\n" + skill.write_text(original, encoding="utf-8") + + def fail_registry(self, extension_id, entry): + assert skill.read_text(encoding="utf-8") != original + raise RuntimeError("simulated registry-write failure") + + monkeypatch.setattr(ExtensionRegistry, "add", fail_registry) + manager = self._install_expecting_failure(project_dir, temp_dir) + assert skill.read_text(encoding="utf-8") == original + assert not (skill.parent.parent / "speckit-test-ext-world").exists() + assert not manager.registry.is_installed("test-ext") + + @pytest.mark.parametrize("after_write", [False, True]) + def test_registry_write_failure_removes_native_skill_outputs( + self, project_dir, temp_dir, monkeypatch, after_write + ): + from specify_cli.extensions import ExtensionRegistry + + _create_init_options(project_dir, ai="claude", ai_skills=True) + manager = ExtensionManager(project_dir) + source = _create_extension_dir(temp_dir) + save = ExtensionRegistry._save + + def boom(registry): + if after_write: + save(registry) + raise RuntimeError("simulated registry-write failure") + + with monkeypatch.context() as patch: + patch.setattr(ExtensionRegistry, "_save", boom) + with pytest.raises(RuntimeError, match="simulated registry-write failure"): + manager.install_from_directory(source, "1.0.0") + + self._assert_no_outputs(project_dir, manager) + assert not ExtensionManager(project_dir).registry.is_installed("test-ext") + manager.install_from_directory(source, "1.0.0") + assert manager.registry.is_installed("test-ext") + assert (project_dir / ".claude/skills/speckit-test-ext-hello/SKILL.md").is_file() + + def test_plain_retry_preserves_config_after_failed_force_reinstall( + self, project_dir, temp_dir, monkeypatch + ): + from specify_cli.extensions import ExtensionRegistry + + _create_init_options(project_dir, ai="claude", ai_skills=False) + source = _create_extension_dir(temp_dir) + config_name = "test-ext-config.yml" + (source / config_name).write_text("setting: default\n", encoding="utf-8") + manager = ExtensionManager(project_dir) + manager.install_from_directory(source, "1.0.0") + config = manager.extensions_dir / "test-ext" / config_name + config.write_text("setting: custom\n", encoding="utf-8") + + def fail_registry(self, extension_id, entry): + raise RuntimeError("simulated registry-write failure") + + with monkeypatch.context() as patch: + patch.setattr(ExtensionRegistry, "add", fail_registry) + with pytest.raises(RuntimeError, match="simulated registry-write failure"): + manager.install_from_directory(source, "1.0.0", force=True) + + retry = ExtensionManager(project_dir) + retry.install_from_directory(source, "1.0.0") + assert config.read_text(encoding="utf-8") == "setting: custom\n" + assert retry.registry.is_installed("test-ext") + + @pytest.mark.parametrize("relative_root", [False, True]) + def test_force_reinstall_can_clean_a_linked_directory_in_the_old_package( + self, project_dir, temp_dir, monkeypatch, relative_root + ): + if not _can_create_symlink(temp_dir): + pytest.skip("symlinks unavailable") + _create_init_options(project_dir, ai="claude", ai_skills=False) + skills_dir = project_dir / ".claude/skills" + skills_dir.mkdir(parents=True) + source = _create_extension_dir(temp_dir) + with monkeypatch.context() as cwd: + root = project_dir + if relative_root: + cwd.chdir(project_dir.parent) + root = Path(project_dir.name) + manager = ExtensionManager(root) + manager.install_from_directory(source, "1.0.0") + + installed_dir = manager.extensions_dir / "test-ext" + config = installed_dir / "test-ext-config.yml" + config.write_text("setting: custom\n", encoding="utf-8") + shared = project_dir / "shared" + shared.mkdir() + note = shared / "note.txt" + note.write_text("shared content\n", encoding="utf-8") + link = installed_dir / "linked-directory" + link.symlink_to(shared, target_is_directory=True) + + manager.install_from_directory(source, "1.0.0", force=True) + + assert not link.is_symlink() + assert note.read_text(encoding="utf-8") == "shared content\n" + assert config.read_text(encoding="utf-8") == "setting: custom\n" + assert manager.registry.is_installed("test-ext") + assert (skills_dir / "speckit-test-ext-hello/SKILL.md").is_file() + + @pytest.mark.parametrize( + ("agent", "output_dir"), + [("gemini", ".gemini/commands"), ("claude", ".claude/skills")], + ) + @pytest.mark.parametrize("outer_journal", [False, True]) + def test_blocked_native_destination_cannot_commit_registration( + self, project_dir, temp_dir, agent, output_dir, outer_journal + ): + from contextlib import nullcontext + + from specify_cli.extensions import ExtensionError + from specify_cli.integrations._lifecycle import _journalled + + if not _can_create_symlink(temp_dir): + pytest.skip("symlinks unavailable") + project_dir = project_dir.resolve() + _create_init_options(project_dir, ai=agent, ai_skills=False) + shared = project_dir / "shared-commands" + shared.mkdir() + output = project_dir / output_dir + output.parent.mkdir() + output.symlink_to(shared, target_is_directory=True) + + manager = ExtensionManager(project_dir) + source = _create_extension_dir(temp_dir) + journal = ( + _journalled(project_dir, [], [], {"retained": False}, initial={}) + if outer_journal else nullcontext() + ) + with pytest.raises(ExtensionError, match="Cannot register extension output"), journal: + manager.install_from_directory(source, "1.0.0") + + assert not manager.registry.is_installed("test-ext") + assert list(shared.iterdir()) == [] + + def test_native_registration_can_commit_with_an_outer_journal(self, project_dir, temp_dir): + from specify_cli.integrations._lifecycle import _journalled + + project_dir = project_dir.resolve() + _create_init_options(project_dir, ai="claude", ai_skills=False) + skills_dir = project_dir / ".claude/skills" + skills_dir.mkdir(parents=True) + manager = ExtensionManager(project_dir) + + with _journalled(project_dir, [], [], {"retained": False}, initial={}): + manager.install_from_directory(_create_extension_dir(temp_dir), "1.0.0") + + assert manager.registry.is_installed("test-ext") + assert (skills_dir / "speckit-test-ext-hello/SKILL.md").is_file() + + @pytest.mark.parametrize("suffix", ["-config.yml", "-config.local.yml"]) + @pytest.mark.parametrize("relative_root", [False, True]) + def test_force_reinstall_preflights_config_before_removing_old_install( + self, project_dir, temp_dir, monkeypatch, suffix, relative_root + ): + from specify_cli.extensions import HookExecutor, ValidationError + + if not _can_create_symlink(temp_dir): + pytest.skip("symlinks unavailable") + _create_init_options(project_dir, ai="claude", ai_skills=False) + (project_dir / ".claude/skills").mkdir(parents=True) + source = _create_extension_dir(temp_dir) + with monkeypatch.context() as cwd: + root = project_dir + if relative_root: + cwd.chdir(project_dir.parent) + root = Path(project_dir.name) + manager = ExtensionManager(root) + manager.install_from_directory(source, "1.0.0") + + config = manager.extensions_dir / "test-ext" / f"test-ext{suffix}" + saved_settings = project_dir / "settings.yml" + saved_settings.write_text("setting: custom\n", encoding="utf-8") + config.symlink_to(saved_settings) + original_target = config.readlink() + installed = manager.registry.get("test-ext") + hooks = HookExecutor(project_dir).get_project_config() + skill = project_dir / ".claude/skills/speckit-test-ext-hello/SKILL.md" + original = skill.read_bytes() + + with pytest.raises(ValidationError) as failure: + manager.install_from_directory(source, "1.0.0", force=True) + + assert manager.registry.get("test-ext") == installed + assert HookExecutor(project_dir).get_project_config() == hooks + assert skill.read_bytes() == original + assert config.is_symlink() + assert config.readlink() == original_target + assert config.samefile(saved_settings) + assert saved_settings.read_text(encoding="utf-8") == "setting: custom\n" + assert "Cannot preserve config" in str(failure.value) + + def test_rollback_preserves_preexisting_user_skill_dir( + self, project_dir, temp_dir, monkeypatch + ): + """Rollback only removes what the attempt wrote, not user skills.""" + from specify_cli.extensions import HookExecutor + + _create_init_options(project_dir, ai="claude", ai_skills=True) + user_dir = project_dir / ".claude" / "skills" / "speckit-my-own-skill" + user_dir.mkdir(parents=True) + (user_dir / "SKILL.md").write_text("user skill", encoding="utf-8") + + def boom(self, manifest): + raise RuntimeError("simulated hook-write failure") + + monkeypatch.setattr(HookExecutor, "register_hooks", boom) + manager = self._install_expecting_failure(project_dir, temp_dir) + self._assert_no_outputs(project_dir, manager) + assert (user_dir / "SKILL.md").read_text(encoding="utf-8") == "user skill" + + class TestExtensionSkillUnregistration: """Test _unregister_extension_skills() on ExtensionManager.""" diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 77a2a0525e..6249ed20e6 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -1903,44 +1903,50 @@ def test_install_force_config_preserved(self, extension_dir, project_dir): assert new_config.exists() assert new_config.read_text() == "test: config" + @pytest.mark.parametrize("relative_root", [False, True]) def test_reinstall_after_keep_config_preserves_config( - self, extension_dir, project_dir + self, extension_dir, project_dir, monkeypatch, relative_root ): """Reinstalling after `remove --keep-config` must not overwrite preserved config.""" - manager = ExtensionManager(project_dir) + with monkeypatch.context() as cwd: + root = project_dir + if relative_root: + cwd.chdir(project_dir.parent) + root = Path(project_dir.name) + manager = ExtensionManager(root) + + # Add a packaged default config so the reinstall has a file to overwrite. + # Without the fix, the packaged default would silently win on reinstall. + packaged_config = extension_dir / "test-ext-config.yml" + packaged_config.write_text("model: default-model\nmax_iterations: 1\n") + + # Install once (packaged default is copied into the installed directory) + manager.install_from_directory( + extension_dir, "0.1.0", register_commands=False + ) - # Add a packaged default config so the reinstall has a file to overwrite. - # Without the fix, the packaged default would silently win on reinstall. - packaged_config = extension_dir / "test-ext-config.yml" - packaged_config.write_text("model: default-model\nmax_iterations: 1\n") + # Overwrite the installed config with user-customized values + ext_dir = project_dir / ".specify" / "extensions" / "test-ext" + config_file = ext_dir / "test-ext-config.yml" + config_file.write_text("model: custom-model\nmax_iterations: 99\n") - # Install once (packaged default is copied into the installed directory) - manager.install_from_directory( - extension_dir, "0.1.0", register_commands=False - ) + # Remove while preserving config + manager.remove("test-ext", keep_config=True) + assert not manager.registry.is_installed("test-ext") + assert config_file.exists() + assert "custom-model" in config_file.read_text() - # Overwrite the installed config with user-customized values - ext_dir = project_dir / ".specify" / "extensions" / "test-ext" - config_file = ext_dir / "test-ext-config.yml" - config_file.write_text("model: custom-model\nmax_iterations: 99\n") - - # Remove while preserving config - manager.remove("test-ext", keep_config=True) - assert not manager.registry.is_installed("test-ext") - assert config_file.exists() - assert "custom-model" in config_file.read_text() - - # Plain reinstall (no --force) — packaged default is still present in - # extension_dir, so a naive implementation would overwrite the custom values. - manager.install_from_directory( - extension_dir, "0.1.0", register_commands=False - ) + # Plain reinstall (no --force) — packaged default is still present in + # extension_dir, so a naive implementation would overwrite the custom values. + manager.install_from_directory( + extension_dir, "0.1.0", register_commands=False + ) - # Preserved config must survive the reinstall and beat the packaged default - assert config_file.exists() - assert "custom-model" in config_file.read_text() - assert "99" in config_file.read_text() - assert "default-model" not in config_file.read_text() + # Preserved config must survive the reinstall and beat the packaged default + assert config_file.exists() + assert "custom-model" in config_file.read_text() + assert "99" in config_file.read_text() + assert "default-model" not in config_file.read_text() def test_reinstall_after_keep_config_preserves_local_config( self, extension_dir, project_dir @@ -2286,6 +2292,34 @@ def test_extensionignore_load_failure_preserves_kept_config( assert manager.registry.is_installed("test-ext") assert config_file.read_bytes() == newer_bytes + def test_force_reinstall_unreadable_config_preserves_install(self, extension_dir, project_dir, monkeypatch): + from specify_cli.file_helper import FileHelper + + skills = project_dir / ".claude/skills" + skills.mkdir(parents=True) + manager = ExtensionManager(project_dir) + manager.install_from_directory(extension_dir, "0.1.0") + installed = manager.extensions_dir / "test-ext" + config = installed / "test-ext-config.local.yml" + config.write_bytes(b"custom: true") + skill = skills / "speckit-test-ext-hello/SKILL.md" + original_skill = skill.read_bytes() + original_record = manager.registry.get("test-ext") + original_read = FileHelper.read_bytes + + def fail_config_read(helper, path): + if Path(path).name == config.name: + raise PermissionError("config unreadable") + return original_read(helper, path) + + monkeypatch.setattr(FileHelper, "read_bytes", fail_config_read) + with pytest.raises(ValidationError, match="config unreadable"): + manager.install_from_directory(extension_dir, "0.1.0", force=True) + assert manager.registry.get("test-ext") == original_record + assert (installed / "extension.yml").is_file() + assert skill.read_bytes() == original_skill + assert config.read_bytes() == b"custom: true" + def test_force_reinstall_extensionignore_invalid_utf8_preserves_install( self, extension_dir, project_dir ):