diff --git a/src/specify_cli/extensions/__init__.py b/src/specify_cli/extensions/__init__.py index 6485f80639..dc0ab5a7ee 100644 --- a/src/specify_cli/extensions/__init__.py +++ b/src/specify_cli/extensions/__init__.py @@ -3869,6 +3869,7 @@ def unregister_agent_artifacts( *, enabled_only: bool = False, commands_only: bool = False, + preserve_modified: bool = False, ) -> None: """Remove extension files registered for a specific agent. @@ -3885,6 +3886,9 @@ def unregister_agent_artifacts( skill artifacts are outside the target agent's lifecycle and must not be touched. + Set ``preserve_modified=True`` for an unforced integration switch to + keep edited native skill resources and their hashes (#5366). + Skips cleanup when *agent_name* is not a supported agent to avoid losing registry entries while leaving orphaned files on disk. """ @@ -3925,6 +3929,7 @@ def unregister_agent_artifacts( retire_skill_resources( self.project_root, ext_id, resource_hashes, skill_names, skills_dir=native_dir, + preserve_modified=preserve_modified, ) if not commands_only: owned_skills = set(self._valid_name_list(metadata.get("registered_skills", []))) @@ -3935,6 +3940,7 @@ def unregister_agent_artifacts( self._historical_generic_roots(metadata, owned_skills) if agent_name == "generic" else () ), + preserve_modified=preserve_modified, ) if resource_hashes != metadata.get("skill_resource_hashes", {}): updates["skill_resource_hashes"] = resource_hashes diff --git a/src/specify_cli/extensions/_skill_resources.py b/src/specify_cli/extensions/_skill_resources.py index 86b7807feb..dce9c2f3f4 100644 --- a/src/specify_cli/extensions/_skill_resources.py +++ b/src/specify_cli/extensions/_skill_resources.py @@ -501,6 +501,7 @@ def _authorized_prefixes( def retire_skill_resources( project_root: Path, ext_id: str, hashes: dict, skill_names: set[str], *, skills_dir: Path | None = None, extra_roots: Iterable[Path] = (), + preserve_modified: bool = False, ) -> None: """Remove recorded resources for these skill names and forget their keys. @@ -513,6 +514,9 @@ def retire_skill_resources( larger boundary and is only cleaned under the skills directories of agents that declare ``registrar_config["home_scoped"]``, as their ``SKILL.md`` cleanup does; other records are left untouched. + + Unforced integration switches keep edited copies and their ownership + records so switching back cannot overwrite the user's edits (#5366). """ import warnings @@ -542,6 +546,23 @@ def retire_skill_resources( for prefix in prefixes ) } + if preserve_modified: + for key, digest in list(selected.items()): + try: + path = _validate_record_path(Path(key), trusted) + except (ValueError, OSError): + # A linked or unsafe path can't be compared with its record. + warnings.warn(f"Preserved unverifiable resource {key}", stacklevel=2) + selected.pop(key) + continue + try: + if not path.is_file() or _sha256(path) == digest: + continue + warnings.warn(f"Preserved modified resource {key}", stacklevel=2) + except OSError: + # A copy that can't be read can't be shown to be unmodified. + warnings.warn(f"Preserved unreadable resource {key}", stacklevel=2) + selected.pop(key) if not selected: continue skill_dirs = [trusted / Path(*prefix) for prefix in prefixes] diff --git a/src/specify_cli/integrations/_helpers.py b/src/specify_cli/integrations/_helpers.py index 69dde4903b..c2b882d373 100644 --- a/src/specify_cli/integrations/_helpers.py +++ b/src/specify_cli/integrations/_helpers.py @@ -459,17 +459,18 @@ def _unregister_extensions_for_agent( agent_key: str, *, continuing: str, + preserve_modified: bool = False, ) -> None: """Best-effort removal of ``agent_key``'s extension artifacts. Used by ``switch`` when uninstalling the previous integration so its extension command/skill files don't linger as orphans in the old agent's - directory. + directory. Unforced switches preserve edited native skill resources (#5366). """ _best_effort_extension_op( project_root, agent_key, - lambda mgr, key: mgr.unregister_agent_artifacts(key), + lambda mgr, key: mgr.unregister_agent_artifacts(key, preserve_modified=preserve_modified), phase="clean up extension artifacts for", continuing=continuing, ) diff --git a/src/specify_cli/integrations/command_switch.py b/src/specify_cli/integrations/command_switch.py index feb1c8c2c3..3e450ab044 100644 --- a/src/specify_cli/integrations/command_switch.py +++ b/src/specify_cli/integrations/command_switch.py @@ -218,6 +218,7 @@ def integration_switch( _unregister_extensions_for_agent( project_root, installed_key, + preserve_modified=not force, continuing="Continuing with integration switch; old extension artifacts may need manual cleanup.", ) diff --git a/tests/specify_cli/extensions/test_skill_resources.py b/tests/specify_cli/extensions/test_skill_resources.py index 8b8c1e274a..60935ff7f9 100644 --- a/tests/specify_cli/extensions/test_skill_resources.py +++ b/tests/specify_cli/extensions/test_skill_resources.py @@ -45,6 +45,82 @@ def put(path: Path, content: str = "source") -> Path: return path +def test_retire_skill_resources_preserves_modified_copies_and_hashes(tmp_path): + """A switch can retire package copies without losing edited resources (#5366).""" + skills = tmp_path / ".claude/skills" + name = "speckit-ext-run" + modified = put(skills / name / "edited.md") + unchanged = put(skills / name / "unchanged.md") + unowned = put(skills / name / "user.md", "user file") + records = {p.relative_to(tmp_path).as_posix(): _sha256(p) for p in (modified, unchanged)} + expected = {modified.relative_to(tmp_path).as_posix(): _sha256(modified)} + hashes = {"project": records} + modified.write_text("user edit", encoding="utf-8") + + with pytest.warns(UserWarning, match="Preserved modified resource"): + retire_skill_resources( + tmp_path, "ext", hashes, {name}, skills_dir=skills, preserve_modified=True, + ) + assert modified.read_text(encoding="utf-8") == "user edit" + assert hashes == {"project": expected} + assert not unchanged.exists() + assert unowned.read_text(encoding="utf-8") == "user file" + + retire_skill_resources(tmp_path, "ext", hashes, {name}, skills_dir=skills) + assert not modified.exists() + assert hashes == {} + assert unowned.read_text(encoding="utf-8") == "user file" + + +def test_retire_skill_resources_preserves_unreadable_copies(tmp_path, monkeypatch): + """A copy whose hash can't be read is kept with its record on a switch (#5366).""" + import specify_cli.extensions._skill_resources as skill_resources + + skills = tmp_path / ".claude/skills" + name = "speckit-ext-run" + unreadable = put(skills / name / "unreadable.md") + key = unreadable.relative_to(tmp_path).as_posix() + hashes = {"project": {key: _sha256(unreadable)}} + + def fail_on_unreadable(path): + if Path(path) == unreadable: + raise PermissionError("read denied") + return _sha256(path) + + monkeypatch.setattr(skill_resources, "_sha256", fail_on_unreadable) + with pytest.warns(UserWarning, match="Preserved unreadable resource"): + retire_skill_resources( + tmp_path, "ext", hashes, {name}, skills_dir=skills, preserve_modified=True, + ) + assert unreadable.exists() + assert key in hashes["project"] + + +def test_retire_skill_resources_preserves_symlink_replaced_copies(tmp_path): + """A copy replaced with a link is kept with its record unless forced (#5366).""" + skills = tmp_path / ".claude/skills" + name = "speckit-ext-run" + copy = put(skills / name / "guide.md") + key = copy.relative_to(tmp_path).as_posix() + hashes = {"project": {key: _sha256(copy)}} + expected = {"project": dict(hashes["project"])} + shared = put(tmp_path / "docs/shared-guide.md", "shared guide") + copy.unlink() + link(copy, shared) + + with pytest.warns(UserWarning, match="Preserved unverifiable resource"): + retire_skill_resources( + tmp_path, "ext", hashes, {name}, skills_dir=skills, preserve_modified=True, + ) + assert copy.is_symlink() + assert hashes == expected + + retire_skill_resources(tmp_path, "ext", hashes, {name}, skills_dir=skills) + assert not copy.is_symlink() + assert hashes == {} + assert shared.read_text(encoding="utf-8") == "shared guide" + + def link(path: Path, target: Path, *, directory: bool = False) -> None: path.parent.mkdir(parents=True, exist_ok=True) try: diff --git a/tests/specify_cli/integrations/test_command_switch.py b/tests/specify_cli/integrations/test_command_switch.py index fab2754530..d9237c02a4 100644 --- a/tests/specify_cli/integrations/test_command_switch.py +++ b/tests/specify_cli/integrations/test_command_switch.py @@ -1362,7 +1362,7 @@ def test_integration_switch_cleanup_warning_reports_phase_and_targets( encoding="utf-8", ) - def fail_cleanup(self, integration_key): + def fail_cleanup(self, integration_key, *, preserve_modified=False): raise OSError("cleanup exploded") monkeypatch.setattr(ExtensionManager, "unregister_agent_artifacts", fail_cleanup) @@ -1442,6 +1442,65 @@ def test_switch_writes_skill_resources_for_new_target(tmp_path, installed): assert resource.relative_to(project).as_posix() in hashes +@pytest.mark.parametrize("stale_supplemental", [False, True], ids=["native", "stale-supplemental"]) +@pytest.mark.parametrize("force", [False, True]) +def test_switch_preserves_edited_source_resources_unless_forced( + tmp_path, monkeypatch, force, stale_supplemental +): + """Unforced native-skill switches must retain edited resource copies (#5366). + + ``stale-supplemental`` also lists the native skill names in + ``registered_skills``, as a project that used Copilot skills mode + earlier can, so the supplemental cleanup sees the same copies. + """ + import yaml + from typer.testing import CliRunner + from specify_cli.extensions import ExtensionManager + + project = _init_project(tmp_path, "claude") + source = tmp_path / "resource-ext" + (source / "commands").mkdir(parents=True) + (source / "references").mkdir() + (source / "references/r.md").write_text("package", encoding="utf-8") + (source / "commands/run.md").write_text("Read references/r.md", encoding="utf-8") + (source / "extension.yml").write_text(yaml.safe_dump({ + "schema_version": "1.0", + "extension": {"id": "resource-ext", "name": "Resource", "version": "1.0.0", "description": "test"}, + "requires": {"speckit_version": ">=0.1.0"}, + "provides": {"commands": [{ + "name": "speckit.resource-ext.run", "file": "commands/run.md", + "aliases": ["speckit.resource-ext.rv"], "resources": ["references/r.md"], + }]}, + }), encoding="utf-8") + manager = ExtensionManager(project) + manager.install_from_directory(source, "1.0.0") + if stale_supplemental: + manager.registry.update( + "resource-ext", {"registered_skills": ["speckit-resource-ext-run", "speckit-resource-ext-rv"]} + ) + skills = project / ".claude/skills" + resources = [skills / f"speckit-resource-ext-{name}/references/r.md" for name in ("run", "rv")] + original = {p.relative_to(project).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in resources} + for resource in resources: + resource.write_text("user edit", encoding="utf-8") + unowned = skills / "speckit-resource-ext-run/user.md" + unowned.write_text("user file", encoding="utf-8") + monkeypatch.chdir(project) + args = ["integration", "switch", "codex"] + (["--force"] if force else []) + result = CliRunner().invoke(app, args) + assert result.exit_code == 0, result.output + assert [p.exists() for p in resources] == [not force, not force] + hashes = ExtensionManager(project).registry.get("resource-ext")["skill_resource_hashes"]["project"] + for key, digest in original.items(): + assert (key in hashes) == (not force) + if not force: + assert hashes[key] == digest + result = CliRunner().invoke(app, ["integration", "switch", "claude"]) + assert result.exit_code == 0, result.output + assert all(p.read_text(encoding="utf-8") == ("package" if force else "user edit") for p in resources) + assert unowned.read_text(encoding="utf-8") == "user file" + + def test_unregister_agent_keeps_another_agents_resource_with_same_skill_name(tmp_path): import yaml from specify_cli.extensions import ExtensionManager