From a8a922910e28517499f8c2094209a7b764533153 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:55 +0000 Subject: [PATCH 1/4] fix(presets): recompose or retire a surviving composed skill on removal Removing a preset that is the base, or a middle layer, of another preset's prepend/append/wrap command left the removed preset's text in the active agent's SKILL.md (Claude, Codex, Copilot with --skills). Command-file agents were recomposed onto the new stack, so `specify preset resolve` disagreed with what the skill agent ran. The composed skill is owned by the surviving preset at the top of the chain. _unregister_skills() restores nothing for the removed preset, and _reconcile_skills() only revisited the active skills directory when that restore had touched it, so the recomposed .composed/.md was never rendered into the skill. After a removal: - Recompose the active directory's skill for a command whose winning layer composes, while the skill still carries the winning preset's source marker. A hand-edited skill is left alone. - Write only the skill names the directory manages, so a user-owned legacy (speckit.) sibling is not overwritten. - When no base is left to compose onto, remove the survivor's stale .composed cache and the SKILL.md that still carries its marker, as command-file agents unregister the command. Other files in the skill directory stay. New file reads and removals go through FileHelper and unlink_in_directory. Assisted-by: Claude Code (model: Claude Mythos 5.2, autonomous) --- src/specify_cli/presets/_manager_skills.py | 95 +++++++++- .../presets/test_manager_skills.py | 165 ++++++++++++++++++ 2 files changed, 253 insertions(+), 7 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 03aef5ff11..da32671d77 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -12,6 +12,8 @@ from .._init_options import is_ai_skills_enabled from .._invocation_style import get_invocation_prefix from .._utils import dump_frontmatter +from ..file_helper import FileHelper +from ..integrations._file_changes import unlink_in_directory from ..integrations.base import IntegrationBase from ..integrations._registration import project_registration from ._manager_commands import _substitute_core_template @@ -150,6 +152,10 @@ def _reconcile_skills( # directory-independent, so it's computed once and then applied to # every affected directory below. preset_cmds: Dict[str, List[str]] = {} + composed_winners: Dict[str, str] = {} + # Composing winners whose stack no longer has a base (resolution + # returns None): their .composed cache and skill are stale. + unresolved_winners: Dict[str, str] = {} non_preset_skills: List[tuple] = [] managed_skill_names: set = set() reconciled_skill_commands: set[str] = set() @@ -194,6 +200,17 @@ def _reconcile_skills( pack_dir = self.presets_dir / pack_id if top_path.is_relative_to(pack_dir): preset_cmds.setdefault(pack_id, []).append(cmd_name) + if layers[0]["strategy"] != "replace": + if resolver.resolve_content(cmd_name, "command") is None: + # Nothing left to compose onto: drop the stale + # cache so it can't be rendered back into a skill. + unresolved_winners[cmd_name] = pack_id + unlink_in_directory( + pack_dir / ".composed" / f"{cmd_name}.md", + root=self.project_root, + ) + else: + composed_winners[cmd_name] = pack_id found_preset = True break if not found_preset: @@ -361,7 +378,12 @@ def apply_to_dir( # Preserve exact prior behaviour for the currently # active directory (including the ability to create # brand-new skill subdirectories when ai_skills is on). - written = self._register_skills(filtered_manifest, pack_dir) + # On removal, write only the skill names this directory + # may manage, so a user-owned modern/legacy sibling of a + # recomposed skill is left alone. + written = self._register_skills( + filtered_manifest, pack_dir, only_skill_names=managed_names, + ) else: written = self._register_skills( filtered_manifest, pack_dir, @@ -393,16 +415,40 @@ def apply_to_dir( extra_dirs = extra_skills_dirs or {} if active_skills_dir: active_provenance = extra_dirs.get(active_skills_dir) - if extra_skills_dirs is None or active_provenance: + active_names: Optional[Set[str]] = None + if extra_skills_dirs is not None: + # Removal restores only skills the removed preset still owned, + # but a surviving preset composing over a removed lower layer + # owns its skill: recompose it while it keeps that marker. + active_names = set(active_provenance[1]) if active_provenance else set() + active_names |= self._skills_owned_by_preset( + active_skills_dir, composed_winners + ) + # Command-file agents unregister an uncomposable command; + # retire its skill too while it still carries the marker. + for stale_skill in self._skills_owned_by_preset( + active_skills_dir, unresolved_winners + ): + stale_dir = active_skills_dir / stale_skill + if self._validate_skill_subdir( + stale_dir, create=False, skills_root=active_skills_dir + ): + # Only the generated file: anything else the user + # keeps in the directory stays. + unlink_in_directory( + stale_dir / "SKILL.md", + root=( + self.project_root + if stale_dir.is_relative_to(self.project_root) + else active_skills_dir + ), + ) + if active_names is None or active_names: apply_to_dir( active_skills_dir, active_ai, is_active=True, - managed_names=( - set(active_provenance[1]) - if active_provenance - else None - ), + managed_names=active_names, ) for extra_dir, (extra_agent, extra_names) in extra_dirs.items(): @@ -417,6 +463,33 @@ def apply_to_dir( return reconciled_skill_commands + def _skills_owned_by_preset( + self, skills_dir: Path, owners: Dict[str, str] + ) -> Set[str]: + """Return skills in ``skills_dir`` whose source marker names their preset. + + ``owners`` maps command names to the expected owning preset id. + """ + registrar = self._command_registrar() + owned: Set[str] = set() + for cmd_name, pack_id in owners.items(): + for skill_name in self._skill_names_for_command(cmd_name): + if not self._validate_skill_subdir( + skills_dir / skill_name, create=False, skills_root=skills_dir + ): + continue + try: + # Named from the helper's root, which may be relative. + with FileHelper(skills_dir) as files: + content = files.read_text(Path(skill_name) / "SKILL.md") + except (OSError, ValueError): + # Missing, unreadable, not a regular file or not UTF-8. + continue + metadata = registrar.parse_frontmatter(content)[0].get("metadata") + if isinstance(metadata, dict) and metadata.get("source") == f"preset:{pack_id}": + owned.add(skill_name) + return owned + def _resolve_agent_skills_dir(self, agent_name: str) -> Path: """Resolve the real skill output directory for an integration.""" from .. import _get_skills_dir as _project_skills_dir @@ -627,6 +700,7 @@ def _register_skills( *, target_dir: Optional[Path] = None, target_agent: Optional[str] = None, + only_skill_names: Optional[Set[str]] = None, ) -> Dict[str, List[str]]: """Generate SKILL.md files for preset command overrides. @@ -652,6 +726,9 @@ def _register_skills( subdirectories are never created for a non-active, explicitly targeted directory (that creation path is only meaningful for the currently active agent). + only_skill_names: When given, write only these skill + directory names; any other existing modern or legacy + skill for the same command is left untouched. Returns: ``{agent_name: [skill_name, ...]}`` for the single active @@ -737,6 +814,10 @@ def _register_skills( missing_skill_dir = skills_dir / skill_name if not missing_skill_dir.exists(): target_skill_names.append(skill_name) + if only_skill_names is not None: + target_skill_names = [ + name for name in target_skill_names if name in only_skill_names + ] if not target_skill_names: continue diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index a836286952..18b70d2a1e 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -1917,6 +1917,171 @@ def test_remove_preserves_non_owned_skill_during_reconciliation( "---\nname: speckit-specify\n---\n\nUser-owned body\n" ) + def _install_composed_specify_stack(self, project_dir, temp_dir, layers): + """Install ``(preset_id, body, strategy, priority)`` layers for speckit.specify.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-specify") + (project_dir / ".specify" / "templates" / "commands" / "specify.md").write_text( + "---\ndescription: Core specify\n---\n\nCore specify body\n", + encoding="utf-8", + ) + manager = PresetManager(project_dir) + for preset_id, body, strategy, priority in layers: + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.specify", preset_id, body + ) + if strategy != "replace": + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + return manager, project_dir / ".claude" / "skills" / "speckit-specify" / "SKILL.md" + + def _install_unbacked_custom_stack(self, project_dir, temp_dir): + """Base + append presets for ``speckit.custom``, which has no core template.""" + self._write_init_options(project_dir, ai="claude", ai_skills=True) + self._create_skill(project_dir / ".claude" / "skills", "speckit-custom") + manager = PresetManager(project_dir) + for preset_id, body, strategy, priority in [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ]: + preset_dir = self._create_command_preset( + temp_dir, preset_id, "speckit.custom", preset_id, body + ) + if strategy != "replace": + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text()) + manifest["provides"]["templates"][0]["strategy"] = strategy + manifest_path.write_text(yaml.dump(manifest)) + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + skill_file = project_dir / ".claude" / "skills" / "speckit-custom" / "SKILL.md" + assert "Base preset body" in skill_file.read_text(encoding="utf-8") + return manager, skill_file + + def test_remove_sole_base_preset_retires_stale_composed_skill( + self, project_dir, temp_dir + ): + """With no core or extension fallback, removing the only base leaves + nothing to compose onto: the composed skill and its cache must not + keep serving the removed preset's instructions.""" + manager, skill_file = self._install_unbacked_custom_stack(project_dir, temp_dir) + cache = manager.presets_dir / "append-preset" / ".composed" / "speckit.custom.md" + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert not skill_file.exists() + assert not cache.exists() + + def test_remove_sole_base_preset_keeps_hand_edited_skill( + self, project_dir, temp_dir + ): + manager, skill_file = self._install_unbacked_custom_stack(project_dir, temp_dir) + edited = "---\nname: speckit-custom\n---\n\nUser-owned body\n" + skill_file.write_text(edited, encoding="utf-8") + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert skill_file.read_text(encoding="utf-8") == edited + + def test_remove_base_preset_recomposes_surviving_composed_skill( + self, project_dir, temp_dir + ): + """Removing a composition's base layer must recompose the surviving skill. + + The appending preset owns the composed SKILL.md, so removing the + replace preset beneath it restored nothing in the active skills + directory and reconciliation skipped it: the skill kept the removed + preset's body while command-file agents were recomposed onto core. + """ + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" in content and "Appended body" in content + + assert manager.remove("base-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Core specify body" in content + assert "Appended body" in content + assert "preset:append-preset" in content + + def test_remove_middle_preset_drops_its_layer_from_composed_skill( + self, project_dir, temp_dir + ): + """Removing a middle composing layer must drop its fragment from the skill.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("middle-preset", "Middle body", "append", 7), + ("top-preset", "Top body", "append", 5), + ], + ) + assert "Middle body" in skill_file.read_text(encoding="utf-8") + + assert manager.remove("middle-preset") is True + + content = skill_file.read_text(encoding="utf-8") + assert "Middle body" not in content + assert "Base preset body" in content + assert "Top body" in content + + def test_remove_base_preset_preserves_hand_edited_composed_skill( + self, project_dir, temp_dir + ): + """Recomposition after removal must not overwrite a hand-edited skill.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + edited = "---\nname: speckit-specify\n---\n\nUser-owned body\n" + skill_file.write_text(edited, encoding="utf-8") + + assert manager.remove("base-preset") is True + + assert skill_file.read_text(encoding="utf-8") == edited + + def test_remove_base_preset_preserves_user_owned_legacy_skill( + self, project_dir, temp_dir + ): + """Recomposition writes only the skill name that still carries the + winning preset's marker, not a user-owned legacy sibling.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + legacy_file = skill_file.parent.parent / "speckit.specify" / "SKILL.md" + legacy_file.parent.mkdir(parents=True, exist_ok=True) + legacy = "---\nname: speckit.specify\n---\n\nUser-owned legacy body\n" + legacy_file.write_text(legacy, encoding="utf-8") + + assert manager.remove("base-preset") is True + + assert legacy_file.read_text(encoding="utf-8") == legacy + content = skill_file.read_text(encoding="utf-8") + assert "Base preset body" not in content + assert "Appended body" in content + def test_shared_skills_dir_restored_once_using_active_agent( self, project_dir, temp_dir ): From dcba729fa8d6cce543b00463f80e0329528975fd Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:33:06 +0530 Subject: [PATCH 2/4] fix(presets): preserve skill outputs when surviving layers are unreadable When PresetResolver.resolve_content() returns None for a composing command during _reconcile_skills(), distinguish a genuinely missing replace base from an unreadable or undecodable surviving layer: - Retire the survivor's .composed cache and owned SKILL.md only when no replace layer remains in the stack. - When a replace base still exists, skip reconciliation cleanly without deleting the survivor's cache or owned SKILL.md and without adding the command to preset_cmds. - Add regression tests in test_manager_skills.py covering undecodable base and composing layers, OSError base reads, and removing a higher-priority replace preset over an unreadable composing stack. Assisted-by: Antigravity (model: Gemini 4 Neon (XHigh), autonomous) --- src/specify_cli/presets/_manager_skills.py | 29 +++-- .../presets/test_manager_skills.py | 102 ++++++++++++++++++ 2 files changed, 121 insertions(+), 10 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index da32671d77..0d332cdef8 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -153,8 +153,8 @@ def _reconcile_skills( # every affected directory below. preset_cmds: Dict[str, List[str]] = {} composed_winners: Dict[str, str] = {} - # Composing winners whose stack no longer has a base (resolution - # returns None): their .composed cache and skill are stale. + # Composing winners whose stack no longer has a replace base: + # their .composed cache and skill are stale. unresolved_winners: Dict[str, str] = {} non_preset_skills: List[tuple] = [] managed_skill_names: set = set() @@ -199,18 +199,27 @@ def _reconcile_skills( for pack_id, _meta in presets_by_priority: pack_dir = self.presets_dir / pack_id if top_path.is_relative_to(pack_dir): - preset_cmds.setdefault(pack_id, []).append(cmd_name) if layers[0]["strategy"] != "replace": if resolver.resolve_content(cmd_name, "command") is None: - # Nothing left to compose onto: drop the stale - # cache so it can't be rendered back into a skill. - unresolved_winners[cmd_name] = pack_id - unlink_in_directory( - pack_dir / ".composed" / f"{cmd_name}.md", - root=self.project_root, - ) + if not any( + layer["strategy"] == "replace" + for layer in layers + ): + # Nothing left to compose onto: drop the stale + # cache so it can't be rendered back into a skill. + unresolved_winners[cmd_name] = pack_id + unlink_in_directory( + pack_dir / ".composed" / f"{cmd_name}.md", + root=self.project_root, + ) + # Otherwise a replace base still exists, so resolution + # failed because a surviving layer could not be read + # or decoded: skip reconciliation and keep outputs. else: + preset_cmds.setdefault(pack_id, []).append(cmd_name) composed_winners[cmd_name] = pack_id + else: + preset_cmds.setdefault(pack_id, []).append(cmd_name) found_preset = True break if not found_preset: diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index 18b70d2a1e..bfbea2f3a5 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2082,6 +2082,108 @@ def test_remove_base_preset_preserves_user_owned_legacy_skill( assert "Base preset body" not in content assert "Appended body" in content + @pytest.mark.parametrize( + "corrupt_target", + ["core_base", "composing_layer", "base_oserror"], + ) + def test_remove_preset_preserves_outputs_when_surviving_layer_unreadable( + self, project_dir, temp_dir, monkeypatch, corrupt_target + ): + """An unreadable surviving base or composing layer must not cause + removal of another preset to delete the survivor's cache or SKILL.md.""" + if corrupt_target == "composing_layer": + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("middle-preset", "Middle body", "append", 7), + ("top-preset", "Top body", "append", 5), + ], + ) + winner_id = "top-preset" + removed_id = "middle-preset" + unreadable_path = ( + manager.presets_dir / winner_id / "commands" / "speckit.specify.md" + ) + else: + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 10), + ("append-preset", "Appended body", "append", 5), + ], + ) + winner_id = "append-preset" + removed_id = "base-preset" + unreadable_path = ( + project_dir / ".specify" / "templates" / "commands" / "specify.md" + ) + + cache = manager.presets_dir / winner_id / ".composed" / "speckit.specify.md" + original_skill = skill_file.read_text(encoding="utf-8") + original_cache = cache.read_text(encoding="utf-8") + + if corrupt_target == "base_oserror": + original_read_text = Path.read_text + + def failing_read_text(self_path, *args, **kwargs): + if self_path == unreadable_path: + raise PermissionError(13, "Permission denied") + return original_read_text(self_path, *args, **kwargs) + + monkeypatch.setattr(Path, "read_text", failing_read_text) + else: + unreadable_path.write_bytes( + b"---\ndescription: \xff\xfe invalid utf-8\n---\n\nUnreadable\n" + ) + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove(removed_id) is True + + monkeypatch.undo() + + assert skill_file.read_text(encoding="utf-8") == original_skill + assert cache.read_text(encoding="utf-8") == original_cache + + def test_remove_override_preset_skips_reconciliation_for_unreadable_composing_stack( + self, project_dir, temp_dir + ): + """Removing a higher-priority replace preset over an unreadable + composing stack must preserve the survivor's cache and skip + reconciling its unreadable stack into the restored skill.""" + manager, skill_file = self._install_composed_specify_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 20), + ("append-preset", "Appended body", "append", 10), + ("override-preset", "Override body", "replace", 5), + ], + ) + cache = manager.presets_dir / "append-preset" / ".composed" / "speckit.specify.md" + original_cache = cache.read_text(encoding="utf-8") + assert "Override body" in skill_file.read_text(encoding="utf-8") + + ( + manager.presets_dir / "append-preset" / "commands" / "speckit.specify.md" + ).write_bytes( + b"---\ndescription: \xff\xfe invalid utf-8\n---\n\nAppended\n" + ) + + with pytest.warns(UserWarning, match="no base layer") as caught: + assert manager.remove("override-preset") is True + + assert all( + "Post-removal reconciliation failed" not in str(w.message) + for w in caught + ) + assert cache.read_text(encoding="utf-8") == original_cache + restored = skill_file.read_text(encoding="utf-8") + assert "Core specify body" in restored + assert "Base preset body" not in restored + def test_shared_skills_dir_restored_once_using_active_agent( self, project_dir, temp_dir ): From 5893ee284b8e728a84ac493d05a612d30da62212 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:10:03 +0000 Subject: [PATCH 3/4] fix(presets): render a survivor's cached composition over an unreadable layer dcba729 keeps the .composed cache when a surviving layer cannot be read while a replace base is still installed, but it also dropped the command from reconciliation. Removing a higher-priority replace preset over such a stack then left the skill with the core template, although the base preset is still installed: `main` and the next rescaffold both render the survivor's cached composition instead. Keep the command in reconciliation in that case, so the skill is rendered from the kept cache and removal matches what a rescaffold renders. The test now asserts that result and compares it with a rescaffold. Assisted-by: Claude Code (model: Claude Opus 5.5, autonomous) --- src/specify_cli/presets/_manager_skills.py | 9 ++++++--- .../presets/test_manager_skills.py | 19 ++++++++++++++----- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 0d332cdef8..09ddf60bd9 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -212,9 +212,12 @@ def _reconcile_skills( pack_dir / ".composed" / f"{cmd_name}.md", root=self.project_root, ) - # Otherwise a replace base still exists, so resolution - # failed because a surviving layer could not be read - # or decoded: skip reconciliation and keep outputs. + else: + # A replace base still exists, so a surviving + # layer could not be read or decoded: keep the + # cache and render the skill from it, as a + # rescaffold does. + preset_cmds.setdefault(pack_id, []).append(cmd_name) else: preset_cmds.setdefault(pack_id, []).append(cmd_name) composed_winners[cmd_name] = pack_id diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index bfbea2f3a5..fe7db19205 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2,6 +2,7 @@ import os import shutil +import warnings from pathlib import Path import pytest @@ -2147,12 +2148,13 @@ def failing_read_text(self_path, *args, **kwargs): assert skill_file.read_text(encoding="utf-8") == original_skill assert cache.read_text(encoding="utf-8") == original_cache - def test_remove_override_preset_skips_reconciliation_for_unreadable_composing_stack( + def test_remove_override_preset_keeps_cached_composition_for_unreadable_stack( self, project_dir, temp_dir ): """Removing a higher-priority replace preset over an unreadable - composing stack must preserve the survivor's cache and skip - reconciling its unreadable stack into the restored skill.""" + composing stack must keep the survivor's cache and render the skill + from it, as a rescaffold does, not fall back to the core template + while a replace base is still installed.""" manager, skill_file = self._install_composed_specify_stack( project_dir, temp_dir, @@ -2181,8 +2183,15 @@ def test_remove_override_preset_skips_reconciliation_for_unreadable_composing_st ) assert cache.read_text(encoding="utf-8") == original_cache restored = skill_file.read_text(encoding="utf-8") - assert "Core specify body" in restored - assert "Base preset body" not in restored + assert "Base preset body" in restored + assert "Appended body" in restored + assert "Override body" not in restored + assert "Core specify body" not in restored + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + manager.register_enabled_presets_for_agent("claude") + assert skill_file.read_text(encoding="utf-8") == restored def test_shared_skills_dir_restored_once_using_active_agent( self, project_dir, temp_dir From 802dff63c65d347b6e930ee8750385482f57b657 Mon Sep 17 00:00:00 2001 From: yxshee <84263676+yxshee@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:21:06 +0530 Subject: [PATCH 4/4] fix(presets): invalidate all cached presets in a baseless skill stack In a 3-layer stack such as base (replace) -> middle (append) -> top (append) for a custom command without a core/extension fallback, removing the base preset previously unlinked only the top winner's .composed/.md cache. The intermediate preset's cached composition still embedded the removed base, so the next Copilot skills-mode rescaffold rendered that stale cache while the baseless top preset skipped registration, resurrecting the removed skill. When _reconcile_skills() detects a baseless composing stack (resolve_content() is None and no replace layer remains), unlink .composed/.md for every preset participating in layers while leaving the unreadable-stack fallback (where a replace base remains) untouched. Add regression tests covering 3-layer base removal + Copilot skills-mode rescaffold + base re-install, removing a higher-priority replace overlay over a baseless 3-layer stack, and preserving caches in an unreadable 3-layer stack with a surviving base. Assisted-by: Antigravity (model: unknown, autonomous) --- src/specify_cli/presets/_manager_skills.py | 23 ++- .../presets/test_manager_skills.py | 174 ++++++++++++++++++ 2 files changed, 191 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/presets/_manager_skills.py b/src/specify_cli/presets/_manager_skills.py index 09ddf60bd9..f1a3afe0aa 100644 --- a/src/specify_cli/presets/_manager_skills.py +++ b/src/specify_cli/presets/_manager_skills.py @@ -205,13 +205,24 @@ def _reconcile_skills( layer["strategy"] == "replace" for layer in layers ): - # Nothing left to compose onto: drop the stale - # cache so it can't be rendered back into a skill. + # Nothing left to compose onto: drop stale + # caches across the baseless stack so none can + # be rendered back into a skill. unresolved_winners[cmd_name] = pack_id - unlink_in_directory( - pack_dir / ".composed" / f"{cmd_name}.md", - root=self.project_root, - ) + for layer_pack_id, _layer_meta in presets_by_priority: + if not PresetResolver._is_safe_registry_id( + layer_pack_id + ): + continue + layer_pack_dir = self.presets_dir / layer_pack_id + if any( + layer["path"].is_relative_to(layer_pack_dir) + for layer in layers + ): + unlink_in_directory( + layer_pack_dir / ".composed" / f"{cmd_name}.md", + root=self.project_root, + ) else: # A replace base still exists, so a surviving # layer could not be read or decoded: keep the diff --git a/tests/specify_cli/presets/test_manager_skills.py b/tests/specify_cli/presets/test_manager_skills.py index fe7db19205..3065b2e60c 100644 --- a/tests/specify_cli/presets/test_manager_skills.py +++ b/tests/specify_cli/presets/test_manager_skills.py @@ -2193,6 +2193,180 @@ def test_remove_override_preset_keeps_cached_composition_for_unreadable_stack( manager.register_enabled_presets_for_agent("claude") assert skill_file.read_text(encoding="utf-8") == restored + def _install_custom_command_stack( + self, project_dir, temp_dir, layers, *, ai="copilot", command_name="speckit.custom" + ): + """Install ``(preset_id, body, strategy, priority)`` layers for a custom command.""" + self._write_init_options(project_dir, ai=ai, ai_skills=True) + manager = PresetManager(project_dir) + preset_dirs = {} + for preset_id, body, strategy, priority in layers: + preset_dir = self._create_command_preset( + temp_dir, preset_id, command_name, preset_id, body + ) + if strategy != "replace": + manifest_path = preset_dir / "preset.yml" + manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8")) + manifest["provides"]["templates"][0]["strategy"] = strategy + manifest_path.write_text(yaml.dump(manifest), encoding="utf-8") + manager.install_from_directory(preset_dir, "0.1.5", priority=priority) + preset_dirs[preset_id] = preset_dir + skills_dir = manager._get_skills_dir() + assert skills_dir is not None + skill_name, _legacy = manager._skill_names_for_command(command_name) + return manager, skills_dir / skill_name / "SKILL.md", preset_dirs + + def test_remove_base_in_three_layer_custom_stack_invalidates_all_caches_before_rescaffold( + self, project_dir, temp_dir + ): + """Removing the sole replace base of a 3-layer custom stack must + invalidate every surviving preset's .composed cache so a subsequent + Copilot skills-mode rescaffold cannot resurrect the removed skill.""" + manager, skill_file, preset_dirs = self._install_custom_command_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 20), + ("middle-preset", "Middle body", "append", 10), + ("top-preset", "Top body", "append", 5), + ], + ai="copilot", + ) + middle_cache = ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" + ) + top_cache = ( + manager.presets_dir / "top-preset" / ".composed" / "speckit.custom.md" + ) + unrelated_cache = ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.other.md" + ) + unrelated_cache.write_text("unrelated cached content\n", encoding="utf-8") + + initial_skill = skill_file.read_text(encoding="utf-8") + assert "Base preset body" in initial_skill + assert "Middle body" in initial_skill + assert "Top body" in initial_skill + assert "preset:top-preset" in initial_skill + assert middle_cache.exists() + assert top_cache.exists() + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("base-preset") is True + + assert not skill_file.exists() + assert not top_cache.exists() + assert not middle_cache.exists() + assert unrelated_cache.read_text(encoding="utf-8") == "unrelated cached content\n" + + with pytest.warns(UserWarning, match="no base"): + manager.register_enabled_presets_for_agent("copilot") + + assert not skill_file.exists() + assert not top_cache.exists() + assert not middle_cache.exists() + + # Re-installing a replace base must cleanly re-compose the surviving stack. + manager.install_from_directory(preset_dirs["base-preset"], "0.1.5", priority=20) + reinstalled = skill_file.read_text(encoding="utf-8") + assert "Base preset body" in reinstalled + assert "Middle body" in reinstalled + assert "Top body" in reinstalled + assert "preset:top-preset" in reinstalled + + def test_remove_override_over_baseless_three_layer_stack_invalidates_all_caches( + self, project_dir, temp_dir + ): + """Removing a higher-priority replace overlay after the lower base was + removed must drop stale caches across the entire surviving baseless stack.""" + manager, skill_file, _preset_dirs = self._install_custom_command_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 30), + ("middle-preset", "Middle prepend body", "prepend", 20), + ("top-preset", "Top append body", "append", 10), + ("override-preset", "Override body", "replace", 5), + ], + ai="copilot", + ) + middle_cache = ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" + ) + top_cache = ( + manager.presets_dir / "top-preset" / ".composed" / "speckit.custom.md" + ) + assert middle_cache.exists() + assert top_cache.exists() + assert "Override body" in skill_file.read_text(encoding="utf-8") + + assert manager.remove("base-preset") is True + assert "Override body" in skill_file.read_text(encoding="utf-8") + + with pytest.warns(UserWarning, match="no base layer"): + assert manager.remove("override-preset") is True + + assert not skill_file.exists() + assert not top_cache.exists() + assert not middle_cache.exists() + + with pytest.warns(UserWarning, match="no base"): + manager.register_enabled_presets_for_agent("copilot") + + assert not skill_file.exists() + + def test_remove_override_keeps_caches_in_unreadable_three_layer_stack( + self, project_dir, temp_dir + ): + """When a replace base still exists underneath an unreadable 3-layer + composing stack, removing a higher-priority replace preset must preserve + all caches and render from the winner's cached composition.""" + manager, skill_file, _preset_dirs = self._install_custom_command_stack( + project_dir, + temp_dir, + [ + ("base-preset", "Base preset body", "replace", 30), + ("middle-preset", "Middle body", "append", 20), + ("top-preset", "Top body", "append", 10), + ("override-preset", "Override body", "replace", 5), + ], + ai="copilot", + ) + middle_cache = ( + manager.presets_dir / "middle-preset" / ".composed" / "speckit.custom.md" + ) + top_cache = ( + manager.presets_dir / "top-preset" / ".composed" / "speckit.custom.md" + ) + original_middle_cache = middle_cache.read_text(encoding="utf-8") + original_top_cache = top_cache.read_text(encoding="utf-8") + + ( + manager.presets_dir / "middle-preset" / "commands" / "speckit.custom.md" + ).write_bytes( + b"---\ndescription: \xff\xfe invalid utf-8\n---\n\nMiddle\n" + ) + + with pytest.warns(UserWarning, match="no base layer") as caught: + assert manager.remove("override-preset") is True + + assert all( + "Post-removal reconciliation failed" not in str(w.message) + for w in caught + ) + assert middle_cache.read_text(encoding="utf-8") == original_middle_cache + assert top_cache.read_text(encoding="utf-8") == original_top_cache + restored = skill_file.read_text(encoding="utf-8") + assert "Base preset body" in restored + assert "Middle body" in restored + assert "Top body" in restored + assert "Override body" not in restored + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + manager.register_enabled_presets_for_agent("copilot") + assert skill_file.read_text(encoding="utf-8") == restored + def test_shared_skills_dir_restored_once_using_active_agent( self, project_dir, temp_dir ):